From 69ac33d7197ba1f7f8b42ee8bf6742be927c1ec4 Mon Sep 17 00:00:00 2001 From: flash555588 Date: Mon, 15 Jun 2026 17:01:17 +0800 Subject: [PATCH] chore(P2): normalize line endings, add .editorconfig, run lint in CI, sync docs --- .github/workflows/release.yml | 5 +- CHANGELOG.md | 21 + README.md | 1454 ++++++------ README.zh-CN.md | 1474 ++++++------ docs/ai-3d-plugin-design-report.md | 1942 ++++++++-------- docs/development-handoff.md | 6 +- eslint.config.mjs | 12 + main.js | 848 +++---- manifest.json | 20 +- package.json | 96 +- src/i18n/en.ts | 690 +++--- src/i18n/zh-CN.ts | 690 +++--- src/io/conversion/manager.ts | 8 +- src/render/babylon/grid.ts | 1086 ++++----- src/render/babylon/scene.ts | 3417 ++++++++++++++-------------- src/render/three/scene.ts | 3 +- src/settings.ts | 1016 ++++----- src/view/inline/code-block.ts | 1340 +++++------ src/view/inline/helper-buttons.ts | 12 +- tsconfig.json | 48 +- 20 files changed, 7114 insertions(+), 7074 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 8f884df..c9b8c8d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -7,7 +7,7 @@ on: workflow_dispatch: inputs: tag: - description: "Release tag to publish, for example 0.4.0" + description: "Release tag to publish, for example 0.5.5" required: false permissions: @@ -36,6 +36,9 @@ jobs: - name: Typecheck run: npm run typecheck + - name: Lint + run: npm run lint + - name: Verify knowledge index run: npm run verify:knowledge-index diff --git a/CHANGELOG.md b/CHANGELOG.md index 6920831..a48cf49 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,26 @@ # Changelog +## Unreleased + +- Security: sanitize remote draft output and model-derived metadata before writing generated notes. +- Security: validate converter command paths and reject shell metacharacters. +- Stability: flush pending plugin store state on unload and log previously swallowed folder-creation errors. +- Stability: handle WebGL context loss/restoration in Three.js, Babylon.js, and 3dgrid previews. +- Stability: add outer timeout to conversion manager to prevent hung converters from blocking previews. +- Performance: pause Babylon.js preview render loops when the canvas leaves the viewport. +- Performance: skip unchanged cells in Babylon.js 3dgrid rendering. +- Performance: cap annotation pins and batch DOM reads/writes in label avoidance. +- Testing: add Vitest with unit tests for escape-html, remote-draft sanitization, and conversion manager timeout/deduplication. +- Build: remove unused `@babylonjs/gui`, `@babylonjs/materials`, and `@babylonjs/serializers` dependencies. + +## 0.5.5 + +- Align release version metadata. + +## 0.5.3 + +- Address Obsidian review warnings. + ## 0.5.1 - Add annotation bookmark display modes for full snippets, compact surfaces, and dots; keep bookmark popovers open while hovered and hide occluded bookmarks fully. diff --git a/README.md b/README.md index cb26527..a8e725c 100644 --- a/README.md +++ b/README.md @@ -1,727 +1,727 @@ -# AI Model Workbench - -> A local-first Obsidian 3D viewer focused on knowledge workflows. It renders common 3D assets in local WebGL viewports, lets you annotate key parts, and turns models into linked notes. Single-model previews (GLB, GLTF, STL, PLY, OBJ) use a configurable Three.js rendering path across reading surfaces and direct file view; the file-view workbench can opt into an experimental Three.js GLB/GLTF path with Babylon.js fallback, while `3dgrid` and SPLAT stay on the Babylon.js capability path that fits them best. - -[AI Model Workbench](https://community.obsidian.md/plugins/ai-model-workbench) - -**English** | [简体中文](README.zh-CN.md) - -![preview](docs/assets/preview.gif) - ---- -https://community.obsidian.md/plugins/ai-model-workbench -## Table of Contents - -- [Features](#features) -- [Platform Support Matrix](#platform-support-matrix) -- [Quick Start](#quick-start) -- [Installation](#installation) -- [Format Support](#format-support) -- [Usage](#usage) -- [Settings](#settings) -- [External Dependencies](#external-dependencies) -- [Security & Privacy](#security--privacy) -- [Funding](#funding) -- [Technical Details](#technical-details) -- [Known Limitations](#known-limitations) -- [Deployment](#deployment) -- [License](#license) - ---- - -## Features - -- **Direct mesh preview** for GLB/GLTF, STL, OBJ, and PLY (all routed through Three.js by default) -- **Optional conversion** for CAD, FBX, 3MF, and DAE assets -- **Hybrid preview routing**: single-model previews use Three.js for GLB/GLTF/STL/PLY/OBJ with a Babylon.js compatibility fallback in settings -- **Inline and file previews**: Live Preview, code blocks, and direct file view -- **Grid system**: render multiple models in a single viewport with presets -- **3D annotations**: click-to-pin bookmarks with labels, colors, and depth-aware occlusion -- **Knowledge notes**: generate structured Markdown from loaded models and auto-register captured part candidates for cross-model reuse checks -- **Snapshots**: copy, save, or download rendered previews as PNG -- **i18n**: English and Simplified Chinese with auto-detect system locale -- **Desktop support**: Obsidian Desktop on Windows, macOS, and Linux -- **Mobile support**: iOS, iPadOS, and Android support direct formats, inline previews, and direct file view - ---- - -## Platform Support Matrix - -| Capability | Windows / macOS / Linux | iOS / iPadOS / Android | -|------------|--------------------------|-------------------------| -| Direct formats (GLB, GLTF, OBJ, STL, PLY) | Yes | Yes | -| Direct file view | Yes | Yes | -| Inline embed / Live Preview for direct formats | Yes | Yes | -| Local conversion (CAD, FBX, 3MF, DAE, SLDPRT) | Yes | No | -| Converter diagnostics and local CLI checks | Yes | No | -| Already converted `.ai3d-converted.glb` assets | Yes | Yes | - ---- - -## Quick Start - -1. Build the plugin: - -```bash -npm install -npm run build -``` - -2. Open your local Obsidian vault folder on your computer. - -3. Create this folder inside the vault: - -```text -/.obsidian/plugins/ai-model-workbench/ -``` - -4. Copy `main.js`, `manifest.json`, and `styles.css` into that folder. - -5. In Obsidian, open `Settings > Community Plugins` and enable `AI Model Workbench`. - -6. Put a supported model file into the same vault, for example `model.glb`. - -7. In any note inside that vault, embed it like this: - -```markdown -![[model.glb]] -![[model.glb|400x300]] -``` - ---- - -## Installation - -Use [Quick Start](#quick-start) if you only want the fastest setup. - -### Requirements - -- Obsidian 1.5.0 or later -- Obsidian Desktop on Windows, macOS, or Linux for local tool-based conversion -- A local Obsidian vault folder on your computer -- This plugin folder inside the vault: - -```text -/.obsidian/plugins/ai-model-workbench/ -``` - -All install methods place the same three files in that folder: - -| File | Size | Description | -|------|------|-------------| -| `main.js` | ~3.8 MB | Plugin runtime bundle | -| `manifest.json` | ~1 KB | Obsidian plugin manifest | -| `styles.css` | ~10 KB | Plugin styles | - -Direct rendering works on desktop and mobile. Local converter tools for CAD, FBX, 3MF, and DAE require desktop OS access. - -### Option A: Build from Source - -1. Clone the repository and build the plugin: - -```bash -git clone https://github.com/flash555588/ai-model-workbench.git -cd ai-model-workbench -npm install -npm run build -``` - -2. Install the built files into a vault: - -```bash -# Install to the bundled test vault -npm run install:vault - -# Or install to your own vault -npm run install:vault -- --vault "C:\path\to\your-vault" -``` - -The installer copies `main.js`, `manifest.json`, and `styles.css` into `.obsidian/plugins/ai-model-workbench/` and enables `ai-model-workbench` in `community-plugins.json`. - -3. If Obsidian is already open, reload the app or disable and re-enable `AI Model Workbench` in `Settings > Community Plugins`. - -Manual fallback: create `/.obsidian/plugins/ai-model-workbench/`, copy `main.js`, `manifest.json`, and `styles.css` into that folder, then enable `AI Model Workbench` in Obsidian. - -### Option B: Download a Release - -1. Download `main.js`, `manifest.json`, and `styles.css` from [Releases](https://github.com/flash555588/ai-model-workbench/releases). -2. Create `/.obsidian/plugins/ai-model-workbench/` if it does not exist. -3. Put the three files in that folder. -4. In Obsidian, enable `AI Model Workbench` in `Settings > Community Plugins`. - -### Option C: Symlink for Development - -1. Make sure `/.obsidian/plugins/` already exists. -2. Create a symlink named `ai-model-workbench` that points to this repository. - -Windows (PowerShell): - -```powershell -New-Item -ItemType SymbolicLink ` - -Path "C:\path\to\your-vault\.obsidian\plugins\ai-model-workbench" ` - -Target "C:\path\to\ai-model-workbench" -``` - -macOS / Linux: - -```bash -ln -s /path/to/ai-model-workbench \ - /path/to/your-vault/.obsidian/plugins/ai-model-workbench -``` - -3. In this repository, run `npm install` once if needed. -4. Run `npm run dev` while developing. -5. In Obsidian, enable `AI Model Workbench` in `Settings > Community Plugins`. - -### After Install - -1. Put a supported model file into the same vault, for example `model.glb`. -2. In any note inside that vault, embed it like this: - -```markdown -![[model.glb]] -![[model.glb|400x300]] -``` - ---- - -## Security & Privacy - -AI Model Workbench does not collect telemetry, phone home, or run background network sync. Model previews are loaded from files already present in the Obsidian vault, and OBJ material/texture references are resolved from the vault instead of being fetched from the network. - -The bundled Babylon.js runtime contains generic loader utilities that are capable of loading URLs for web applications. This plugin passes vault file bytes to Babylon as data URLs, overrides OBJ MTL loading to avoid remote fetches, and installs a runtime guard that rejects explicit `http(s)` / `ws(s)` asset or script URLs while disabling Babylon retry hooks for those requests. Optional converter diagnostics and conversions run only after a user action and execute local tools on desktop platforms. - -Knowledge-note generation is local-only by default. If you configure an optional remote draft service, the plugin sends only the selected evidence payload to your configured `POST /draft-note` endpoint. The current client refuses raw model upload, and geometry summaries or preview image references must be enabled explicitly before they are included. - -Release assets are limited to the three files Obsidian downloads: `main.js`, `manifest.json`, and `styles.css`. GitHub Actions builds these files from source and publishes artifact attestations for provenance verification. - ---- - -## Funding - -AI Model Workbench does not include donation prompts, payment flows, or cryptocurrency wallet addresses in the plugin bundle. - ---- - -## Format Support - -### Direct Rendering (No External Tools) - -| Format | Extension | Features | -|--------|-----------|----------| -| GLB / GLTF | `.glb` `.gltf` | PBR materials, animations, textures, scene hierarchy; `.gltf` resolves vault-relative `.bin` and texture files | -| STL | `.stl` | Binary format, per-face colors (VisCAM/SolidView) | -| OBJ | `.obj` | MTL materials, vault-relative texture resolution, case-insensitive same-folder texture fallback | -| PLY | `.ply` | ASCII/binary, vertex colors, point cloud support | - -SPLAT preview is temporarily disabled in packaged builds while its loader is replaced with a local-only implementation. - -### SPLAT Status and Roadmap - -- Current status: SPLAT preview is temporarily disabled in community release builds. GLB, GLTF, STL, OBJ, PLY, and the current local conversion routes are unaffected. -- Why: the current Babylon SPLAT/SPZ loader still carries dynamic script and remote module fallback paths. The plugin runtime already rejects remote requests, but the packaged release also aims to remove those paths from the shipped bundle to reduce review and static-scan risk. -- Roadmap: first restore local-only `.splat` loading; then reopen it after idle-render stability is improved for Windows and large scenes; finally evaluate `.spz` separately, and only re-enable it if the decoder dependencies can be bundled locally and reviewed as local assets. - -### Conversion (Requires External Tools) - -| Format | Extension | Converter | Output | -|--------|-----------|-----------|--------| -| STEP | `.step` `.stp` | Python + CadQuery/OCCT | GLB | -| IGES | `.iges` `.igs` | Python + CadQuery/OCCT | GLB | -| BREP | `.brep` | Python + CadQuery/OCCT | GLB | -| SLDPRT | `.sldprt` | FreeCAD | GLB | -| 3MF | `.3mf` | Python + trimesh | GLB | -| DAE | `.dae` | Python + trimesh | GLB | -| FBX | `.fbx` | FBX2glTF | GLB | - -STEP conversion preserves XDE assembly/component labels when available, exporting each component as its own GLB node with `extras.ai3d` identity metadata. PCB STEP files from tools such as EasyEDA can therefore register reference-designator parts like `R1`, `USB1`, and `U4` instead of collapsing the board into one mesh. - -### Format Feature Matrix - -| Feature | GLB/GLTF | STL | OBJ | PLY | FBX (converted) | CAD | -|---------|----------|-----|-----|-----|-----------------|-----| -| Mesh | Yes | Yes | Yes | Yes | Yes | Yes | -| Point Cloud | No | No | No | Yes | No | No | -| Materials | PBR | Basic | MTL | Basic | Basic | No | -| Textures | Embedded | No | External | No | No | No | -| Colors | Vertex | Face | No | Vertex | No | Face (STEP) | -| Animation | Yes | No | No | No | Yes | No | - ---- - -## Usage - -### Syntax Guide - -#### 1. Inline Embed - -Write a wikilink anywhere in your note. Works in Reading and Live Preview. - -```markdown -![[model.glb]] -![[model.glb|400x300]] -``` - -#### 2. `3d` Code Block - -**Quick** — file path only: - -````markdown -```3d model.glb -``` -```` - -**Full config** — camera, lights, scene, multi-model: - -````markdown -```3d -{ - "models": [ - { "path": "model.glb" }, - { "path": "part.stl", "color": "#ff0000", "wireframe": true } - ], - "camera": { "fov": 30, "position": [5, 5, 5] }, - "lights": [ - { "type": "hemisphere", "color": "#fff", "intensity": 1 }, - { "type": "directional", "position": [10, 20, 10] } - ], - "scene": { "autoRotate": true, "grid": true }, - "width": "100%", - "height": 500 -} -``` -```` - -| Section | Key fields | -|---------|------------| -| `models[]` | `path` (required), `color`, `wireframe` | -| `camera` | `fov`, `position`, `lookAt`, `mode` (`"perspective"` / `"orthographic"`) | -| `lights[]` | `type` (`"hemisphere"` `"directional"` `"point"` `"spot"` `"ambient"` `"attachToCam"`), `color`, `intensity`, `position` | -| `scene` | `background`, `autoRotate`, `autoRotateSpeed`, `grid`, `axis`, `groundShadow`, `transparent` | -| `stl` | `color`, `wireframe` (defaults for STL files) | -| top-level | `width`, `height` | - -#### 3. `3dgrid` Code Block - -Render multiple models in one viewport using layout presets. - -````markdown -```3dgrid -{ - "models": [ - { "path": "v1.step" }, - { "path": "v2.step" }, - { "path": "v3.step" } - ], - "preset": "compare" -} -``` -```` - -| Preset | Layout | -|--------|--------| -| `compare` | Side-by-side A/B | -| `showcase` | Multi-angle single model | -| `explode` | Ring arrangement | -| `timeline` | Horizontal strip | -| `gallery` | All in one scene (default) | -| `compose` | Custom sections | - -`3dgrid` accepts the same `camera`, `lights`, `scene` fields as `3d`, plus: `preset`, `params`, `columns`, `rowHeight`, `gapX`, `gapY`, `sections`, `direction`. - -#### 4. Direct File View - -Click any `.glb`/`.gltf`/`.stl`/`.obj`/`.ply` file in the file explorer. - -#### Supported Extensions - -| Type | Formats | -|------|---------| -| Direct | `.glb` `.gltf` `.stl` `.obj` `.ply` | -| Conversion | `.step` `.stp` `.iges` `.igs` `.brep` `.sldprt` `.3mf` `.dae` `.fbx` | - -### Keyboard Shortcuts (in preview) - -| Key | Action | -|-----|--------| -| `R` | Reset view | -| `W` | Toggle wireframe | -| `G` | Toggle orientation gizmo | -| `B` | Toggle bounding box | -| `Space` | Play/pause animation | -| `Esc` | Exit annotation mode | - -### 3D Annotations - -Add labeled bookmarks directly on model surfaces. Annotations persist per model file. - -**Direct View** (edit mode): - -1. Click the **tag icon** in the toolbar -2. A blue overlay indicates annotation mode is active -3. Click anywhere on the model surface to place a pin -4. Enter a label and pick a color in the popup editor -5. Click an existing pin to edit its label/color or delete it -6. Press `Esc` to exit annotation mode - -**Depth-aware occlusion**: Pins behind geometry display blurred and dimmed. During camera movement, occlusion refreshes in small batches so existing bookmarks do not visibly lag behind model rotation; when idle, the overlay catches up with a full refresh cadence. - -**Code blocks & Live Preview**: Saved annotations display as read-only overlays with the same occlusion behavior. - ---- - -### Knowledge Notes - -The workbench `Generate note` action creates an evidence-backed Markdown note rather than a bare template. Each generation pass writes: - -- a model report in `Analysis/3D Reports` -- a JSON analysis sidecar with preview summary, part candidates, knowledge nodes, warnings, and pipeline metadata -- a model knowledge index in `Analysis/3D Reports` that links the report, sidecar, evidence images, annotations, and part notes -- up to 8 first-pass part note drafts in `Parts/3D Components`, linked from the report and sidecar without overwriting existing part notes -- a current viewport evidence snapshot in `Media/3D Previews` -- an editable local draft that turns the captured evidence, annotations, tags, and profile notes into a first-pass knowledge note body, plus local draft metadata for tags and next actions - -The default local pass does not send model data to a remote service. It uses renderer evidence, saved annotations, tags, and profile notes as the grounding layer for later AI-assisted drafting. When a GLB/GLTF file contains named internal groups or assemblies, the renderer registers those groups as higher-confidence part candidates and keeps ungrouped meshes as standalone candidates. GLB/GLTF component metadata in `extras.ai3d` (`partId`, `occurrenceId`, `partNumber`, and `componentPath`) is registered as individual component parts when present. STEP conversion preserves XDE component labels as GLB component metadata, so PCB reference designators and CAD assembly children can become individual registered parts after conversion. Direct file view stores those captured candidates in the model profile immediately after a successful load, preserving source extensions such as STEP, FBX, 3MF, and DAE in the analysis record so later imported models can match reused parts across converted model types even before a full report exists. During note generation, current part candidates are also compared with parts registered in other profiles or analyzed model sidecars, so likely reused components can be linked back to their existing part notes for review. - -After a report has been generated, use the direct workbench `Open index` action or the command palette `Open knowledge index` command to jump back into the model's knowledge map. - -Optional remote drafting can be enabled in settings by choosing `Local evidence + remote draft` or `Remote draft from evidence` and entering a draft service URL. The client sends `POST /draft-note` with sanitized drafting input only. Raw model upload is blocked; geometry summaries and preview image references are controlled by separate privacy toggles. - ---- - -## Settings - -| Setting | Default | Description | -|---------|---------|-------------| -| Language | auto | UI language (English / Simplified Chinese / auto-detect) | -| Annotation preview mode | plain-text | How saved annotation content renders inside readonly previews | -| AI drafting mode | Local evidence only | Keeps knowledge-note drafting local unless an optional remote draft service is configured | -| Draft service URL | empty | Base URL for a service that accepts `POST /draft-note` | -| Preview compatibility mode | Reading + file view | Controls how widely the newer single-model GLB preview path is used | -| Experimental Three workbench | off | Tries the Three.js workbench path for direct GLB/GLTF file views, with automatic Babylon.js fallback | -| Canvas height | 400 | Preview height in pixels | -| Auto-rotate | off | Start with turntable animation | -| Auto-rotate speed | 0.5 | Rotation speed (0.1-2.0) | -| Render quality | high | Quality preset (low/medium/high) | -| Render scale | 1.0 | Resolution multiplier (0.25-2.0) | -| Snapshot folder | Media/3D Previews | Export folder | -| Snapshot naming | model-name | File naming mode for exported PNG snapshots | -| Report folder | Analysis/3D Reports | Knowledge notes folder | -| Part notes folder | Parts/3D Components | Folder for generated part note drafts | -| Log level | warn | Console log verbosity | - -### Converter Settings - -| Setting | Description | -|---------|-------------| -| Enable CAD converter | Enable STEP/IGES/BREP via CadQuery | -| Enable SLDPRT converter | Enable SolidWorks via FreeCAD | -| Enable mesh converter | Enable 3MF/DAE via trimesh | -| Enable OBJ2GLTF converter | Optional OBJ normalization through obj2gltf | -| Enable FBX2glTF converter | Enable FBX conversion through FBX2glTF | -| Python command path (for CAD conversion) | Override the Python executable used for STEP/IGES/BREP conversion | -| FreeCADCmd path (for SLDPRT conversion) | Override the FreeCAD executable used for `.sldprt` conversion | -| obj2gltf command path | Override the obj2gltf CLI path | -| FBX2glTF command path | Override the FBX2glTF CLI path | -| Python command path (for 3MF/DAE conversion) | Override the Python executable used for 3MF/DAE conversion | -| Converter command diagnostics | Show which executable path the plugin will actually use and run lightweight self-checks for Python environments and converter CLIs | - -### Portability and diagnostics - -The rendering layer is cross-platform: direct formats like GLB, OBJ, STL, PLY, and already-converted `.ai3d-converted.glb` assets can render anywhere Obsidian Desktop can provide WebGL. - -On iOS, iPadOS, and Android, the plugin now supports direct formats such as GLB, GLTF, OBJ, STL, and PLY. Local conversion routes for CAD, FBX, 3MF, DAE, and SLDPRT remain desktop-only because they depend on external CLI tools and Python environments. - -The conversion layer is less portable because it depends on local tools and Python environments that vary by machine. Use the converter diagnostics panel in plugin settings as the first check when a CAD or mesh format fails. It verifies both the executable path the plugin resolved and whether the selected Python environment can import the required packages or the native converter CLI can launch. - -For repository-level implementation rules, see [docs/cross-platform-development.md](docs/cross-platform-development.md). - -On macOS in particular, the system Python at `/usr/bin/python3` often exists but does not include CAD packages. If diagnostics show that path and the self-check fails, install a separate Python environment and point the plugin setting to that interpreter explicitly. - ---- - -## External Dependencies - -Only needed for CAD, FBX, and mesh conversion. Direct formats work without any external tools. - -### Python + CadQuery (STEP, IGES, BREP) - -```bash -# Install -pip install cadquery trimesh -``` - -Verify with the Python command your OS uses: - -- Windows: `py -c "import cadquery; print('OK')"` -- macOS / Linux: `python3 -c "import cadquery; print('OK')"` - -If diagnostics resolve to `/usr/bin/python3` on macOS and the import check fails, install a separate Python (for example Homebrew Python), install `cadquery` and `trimesh` there, then set that interpreter path in plugin settings. - -### FreeCAD (SLDPRT) - -Install FreeCAD for your platform: - -- Windows: install from [freecad.org/downloads](https://www.freecad.org/downloads.php) -- macOS: install the app bundle or use `brew install --cask freecad` -- Linux: install your distro's FreeCAD package and make sure `freecadcmd` is available - -The plugin prefers the explicit setting and environment variable first, then checks common user-managed install locations, then PATH, and finally system fallback hints such as: -- Windows: `%LOCALAPPDATA%\Programs\FreeCAD*\bin\FreeCADCmd.exe` -- macOS: `/Applications/FreeCAD.app/Contents/MacOS/FreeCADCmd`, `/usr/local/bin/FreeCADCmd`, `/opt/homebrew/bin/FreeCADCmd` -- Linux: `/usr/bin/freecadcmd` - -### Python + trimesh (3MF, DAE) - -```bash -pip install trimesh numpy networkx pycollada -``` - -**Auto-discovery**: Same Python as CadQuery (see above). - -**Override**: Environment variable `AI3D_ASSIMP_CMD`. - -### obj2gltf (OBJ, optional) - -The plugin already has a built-in OBJ loader. obj2gltf is an optional alternative that can produce higher-fidelity GLB output. - -**Install**: - -```bash -npm install -g obj2gltf -``` - -**Resolution order**: The plugin prefers the explicit setting and environment variable first, then checks common user-managed install locations, then PATH, and finally system fallback hints such as `obj2gltf.cmd` on Windows and `obj2gltf` in standard macOS/Linux locations like `/usr/local/bin/obj2gltf` and `/opt/homebrew/bin/obj2gltf`. - -**Enable**: Settings > Enable OBJ2GLTF converter, or set "obj2gltf path". - -### FBX2glTF (FBX) - -FBX files are converted to GLB through the local FBX2glTF binary. The older community FBX loader is not bundled because its current release targets Babylon.js 8, while this plugin uses Babylon.js 9. - -**Install**: - -Download or build [FBX2glTF](https://github.com/godotengine/FBX2glTF) for your platform and place the binary in a known location. - -**Resolution order**: The plugin prefers the explicit setting and environment variable first, then checks common user-managed install locations, then PATH, and finally system fallback hints such as: - -```text -C:\Program Files\FBX2glTF\FBX2glTF-windows-x64.exe -C:\Program Files\FBX2glTF\FBX2glTF.exe -/usr/local/bin/FBX2glTF -/opt/homebrew/bin/FBX2glTF -/usr/local/bin/fbx2gltf -``` - -**Enable**: Settings > Enable FBX2glTF converter, or set "FBX2glTF path". - -### Environment Variables - -| Variable | Purpose | -|----------|---------| -| `AI3D_FREECAD_CMD` | Python command for CadQuery | -| `AI3D_FREECADCMD` | FreeCADCmd path | -| `AI3D_ASSIMP_CMD` | Python command for trimesh | -| `AI3D_OBJ2GLTF_CMD` | obj2gltf command path | -| `AI3D_FBX2GLTF_CMD` | FBX2glTF command path | - -The legacy alias `AI3D_FREECMDCMD` is still accepted for compatibility, but new setups should use `AI3D_FREECADCMD`. - ---- - -## Technical Details - -### Architecture - -``` -src/ -├── main.ts # Plugin lifecycle, commands -├── domain/ -│ ├── models.ts # Shared interfaces -│ └── constants.ts # Default settings, extensions -├── store/ -│ ├── create-store.ts # Custom store primitive -│ └── plugin-store.ts # Obsidian saveData bridge -├── render/ -│ ├── preview/ # Renderer-agnostic abstraction layer -│ │ ├── types.ts # ModelPreview, AnnotationPreview, WorkbenchPreview interfaces -│ │ ├── routing.ts # Three/Babylon route decision logic -│ │ ├── factory.ts # Dynamic import factory for renderers -│ │ ├── selection.ts # Preview selection with logging -│ │ ├── annotations.ts # AnnotationManager (pin overlay + occlusion) -│ │ ├── geometry.ts # Renderer-agnostic vector math -│ │ ├── bounds.ts # Bounding box utilities -│ │ ├── camera-fit.ts # Camera fitting algorithms -│ │ ├── disassembly.ts # Disassembly controller (adapter pattern) -│ │ ├── explode.ts # Explode view (adapter pattern) -│ │ ├── report.ts # Markdown report generation -│ │ └── summary.ts # Model/part summary creation -│ ├── three/ # Three.js renderer -│ │ ├── scene.ts # ThreeModelPreview class (GLB/GLTF/STL/PLY/OBJ) -│ │ ├── loaders.ts # Format-specific loaders with vault MTL resolution -│ │ ├── disassembly.ts # ThreeDisassemblyAdapter -│ │ └── explode.ts # ThreeExplodeAdapter -│ ├── babylon/ # Babylon.js renderer -│ │ ├── scene.ts # BabylonModelPreview class -│ │ ├── grid.ts # GridRenderer class -│ │ ├── picking.ts # Click-to-pick with highlight -│ │ ├── loaders/ -│ │ │ ├── stl-loader.ts # Custom binary STL parser -│ │ │ ├── ply-loader.ts # Custom ASCII/binary PLY parser -│ │ │ └── register.ts # Babylon SceneLoader plugins -│ │ └── presets/ # Grid layout presets -├── io/ -│ ├── formats/ -│ │ └── registry.ts # Format capability registry -│ ├── conversion/ -│ │ ├── manager.ts # Conversion orchestration -│ │ └── adapters/ # Converter implementations -│ └── model-pipeline.ts # Format routing logic -└── view/ - ├── workbench/ # Knowledge-note helpers - ├── inline/ # Code blocks, live preview - └── direct-view.ts # Direct file opening -``` - -### Model Import Pipeline - -``` -┌─────────────────────────────────────────────────────────────┐ -│ 1. Format Detection │ -│ └─ getFormatCapability(ext) → { family, strategy } │ -│ │ -│ 2. Route Decision │ -│ ├─ strategy: "direct" → prepareDirectLoad() │ -│ └─ strategy: "convert" → convertForPreview() │ -│ │ -│ 3. Data Loading │ -│ ├─ readBinaryPath() → ArrayBuffer │ -│ └─ [if converted] → read converted .glb │ -│ │ -│ 4. Babylon Rendering │ -│ ├─ GLB/GLTF/OBJ → SceneLoader.ImportMeshAsync() │ -│ ├─ STL → loadSTLBuffer() (direct parse) │ -│ └─ PLY → loadPLYBuffer() (direct parse) │ -└─────────────────────────────────────────────────────────────┘ -``` - -### Why Direct Buffer Loading for STL/PLY - -Babylon.js v9 SceneLoader has a bug where custom plugins receive data URL strings instead of ArrayBuffer when loading via `SceneLoader.ImportMeshAsync()`. Built-in loaders (GLTF and OBJ) are unaffected. - -**Workaround**: STL and PLY parsers are called directly with the raw ArrayBuffer, bypassing SceneLoader entirely. - -### Conversion Caching - -- **Location**: Same directory as source file -- **Format**: `{filename}.ai3d-converted.glb` -- **Validation**: Checks converter identity, cache key, file existence -- **Invalidation**: Automatic when converter settings change -- **Manual clear**: Command palette > "Clear Conversion Cache" - ---- - -## Known Limitations - -| Issue | Affected Formats | Workaround | -|-------|-----------------|------------| -| External converter required | FBX | Install and enable FBX2glTF | -| External tools required | STEP/IGES/BREP/SLDPRT | Install Python + CadQuery or FreeCAD | -| Texture path resolution | OBJ | Place textures beside the OBJ/MTL; missing textures show a non-blocking asset warning | -| External resource path resolution | GLTF | Keep `.bin` and textures in the vault beside the `.gltf` or in referenced relative folders | -| Conversion timeout | SLDPRT | 10-minute timeout for complex assemblies | - ---- - -## Deployment - -### Prerequisites - -- Node.js >= 18 -- npm >= 9 -- Obsidian >= 1.5.0 - -### Build Commands - -```bash -npm install # Install dependencies -npm run dev # Development build with watch -npm run build # Production build -npm run typecheck # TypeScript type check -npm run verify:preview # Targeted browser preview smoke test -npm run verify:preview:success # Full preview routing success suite -npm run verify:obsidian # End-to-end Obsidian app smoke test -npm run verify:release # Release asset version/hash/size check -npm run verify:settings # Legacy data.json/default-settings migration check -npm run verify:remote-draft # Remote draft privacy/client behavior check -npm run verify:knowledge-index # Knowledge index link and refresh regression check -npm run verify:diagnostics # Sanitized diagnostics report regression check -``` - -### Preview Verification - -Run `npm run verify:preview:success` before shipping preview changes. For a focused default-route check, `npm run verify:preview` still works. The harness auto-detects common Chrome, Edge, Chromium, and Brave installs on Windows, macOS, and Linux; set `PLAYWRIGHT_CHROMIUM_EXECUTABLE` only when using a custom browser path. The success suite launches a temporary Playwright harness, loads `models/rubiks-cube-3x3.glb`, and verifies: - -- default simple `GLB` preview -- default direct-edit `GLB` preview -- default readonly saved-pin `GLB` preview -- reading-surfaces-only rollout behavior -- compatibility-mode rollback behavior -- workbench Babylon fallback routing and experimental Three.js workbench probe -- direct-format `STL`, `PLY`, and `OBJ` preview routing -- helper toolbar interactions, focus mode, moving-pin occlusion, selected-part export, performance snapshots, and wheel-scroll containment - -If verification fails, the script saves a screenshot and a log with preview state plus browser messages under `.tmp/preview-failures/`. - -### Obsidian Verification - -Run `npm run verify:obsidian` on macOS before release when Obsidian is installed. The script builds a temporary test vault under `/tmp/ai-model-workbench-verify-vault`, installs the packaged plugin, opens a note in Obsidian through a remote debugging port, trusts the temporary vault when prompted, confirms that GLB/STL preview canvases are loaded, checks converter feedback for an FBX route without FBX2glTF enabled, then opens the real GLB file view with Experimental Three workbench enabled and checks backend selection, focus/disassembly controls, panel explode controls, annotation mode, and knowledge-note generation. - -Use `npm run verify:obsidian -- --clean` when you want the temporary vault removed after the run. On macOS, the clean path quits Obsidian and unregisters the temporary vault before deleting it so the developer console does not keep reporting stale `ENOENT` reads from `/tmp`. - -### Knowledge Note Verification - -Run `npm run verify:knowledge-index` after changing generated reports, part drafts, or model index behavior. The script bundles the knowledge-note helpers with a small Obsidian shim, builds a representative model index, refreshes the AI-managed block, and confirms user-written notes remain intact. - -### Build Output - -``` -ai-model-workbench/ -├── main.js # ~3.8 MB (minified plugin runtime bundle) -├── manifest.json # Plugin manifest -├── styles.css # Plugin styles -└── src/ # Source code -``` - -### Release Publishing - -Releases are published by the GitHub Actions `Release` workflow. Push a tag that matches `manifest.json`, for example `0.4.0`, or run the workflow manually. The workflow uploads only `main.js`, `manifest.json`, and `styles.css`, removes unsupported release assets, verifies asset sizes and SHA-256 hashes, and generates GitHub artifact attestations for the published files. After a release is published, run `npm run verify:obsidian -- --release-tag 0.4.0` to install the assets downloaded from GitHub into the temporary Obsidian vault. - -### Release Token Safety - -Prefer GitHub Actions or GitHub CLI browser login for publishing. See `SECURITY.md` for the token safety checklist and PAT leak response. - -### Platform Support - -| Platform | Status | -|----------|--------| -| Windows | Full support | -| macOS | Full support | -| Linux | Full support | -| Obsidian Mobile | Supported (reduced resolution) | - -### Bundle Size Optimization - -The rendering runtimes dominate the bundle size. The project keeps the output in check with: - -- Subpath imports (`@babylonjs/core/Engines/engine.js`) instead of barrel imports -- Tree-shaking to remove unused features -- esbuild for fast, optimized bundling - -Because the shipped preview mix now includes both Babylon and Three paths, the exact bundle size moves as routing coverage changes. Treat the build output above as the current reference point rather than a fixed ceiling. - ---- - -## Acknowledgments - -Thanks to the LinuxDo community (https://linux.do) for their support. +# AI Model Workbench + +> A local-first Obsidian 3D viewer focused on knowledge workflows. It renders common 3D assets in local WebGL viewports, lets you annotate key parts, and turns models into linked notes. Single-model previews (GLB, GLTF, STL, PLY, OBJ) use a configurable Three.js rendering path across reading surfaces and direct file view; the file-view workbench can opt into an experimental Three.js GLB/GLTF path with Babylon.js fallback, while `3dgrid` and SPLAT stay on the Babylon.js capability path that fits them best. + +[AI Model Workbench](https://community.obsidian.md/plugins/ai-model-workbench) + +**English** | [简体中文](README.zh-CN.md) + +![preview](docs/assets/preview.gif) + +--- +https://community.obsidian.md/plugins/ai-model-workbench +## Table of Contents + +- [Features](#features) +- [Platform Support Matrix](#platform-support-matrix) +- [Quick Start](#quick-start) +- [Installation](#installation) +- [Format Support](#format-support) +- [Usage](#usage) +- [Settings](#settings) +- [External Dependencies](#external-dependencies) +- [Security & Privacy](#security--privacy) +- [Funding](#funding) +- [Technical Details](#technical-details) +- [Known Limitations](#known-limitations) +- [Deployment](#deployment) +- [License](#license) + +--- + +## Features + +- **Direct mesh preview** for GLB/GLTF, STL, OBJ, and PLY (all routed through Three.js by default) +- **Optional conversion** for CAD, FBX, 3MF, and DAE assets +- **Hybrid preview routing**: single-model previews use Three.js for GLB/GLTF/STL/PLY/OBJ with a Babylon.js compatibility fallback in settings +- **Inline and file previews**: Live Preview, code blocks, and direct file view +- **Grid system**: render multiple models in a single viewport with presets +- **3D annotations**: click-to-pin bookmarks with labels, colors, and depth-aware occlusion +- **Knowledge notes**: generate structured Markdown from loaded models and auto-register captured part candidates for cross-model reuse checks +- **Snapshots**: copy, save, or download rendered previews as PNG +- **i18n**: English and Simplified Chinese with auto-detect system locale +- **Desktop support**: Obsidian Desktop on Windows, macOS, and Linux +- **Mobile support**: iOS, iPadOS, and Android support direct formats, inline previews, and direct file view + +--- + +## Platform Support Matrix + +| Capability | Windows / macOS / Linux | iOS / iPadOS / Android | +|------------|--------------------------|-------------------------| +| Direct formats (GLB, GLTF, OBJ, STL, PLY) | Yes | Yes | +| Direct file view | Yes | Yes | +| Inline embed / Live Preview for direct formats | Yes | Yes | +| Local conversion (CAD, FBX, 3MF, DAE, SLDPRT) | Yes | No | +| Converter diagnostics and local CLI checks | Yes | No | +| Already converted `.ai3d-converted.glb` assets | Yes | Yes | + +--- + +## Quick Start + +1. Build the plugin: + +```bash +npm install +npm run build +``` + +2. Open your local Obsidian vault folder on your computer. + +3. Create this folder inside the vault: + +```text +/.obsidian/plugins/ai-model-workbench/ +``` + +4. Copy `main.js`, `manifest.json`, and `styles.css` into that folder. + +5. In Obsidian, open `Settings > Community Plugins` and enable `AI Model Workbench`. + +6. Put a supported model file into the same vault, for example `model.glb`. + +7. In any note inside that vault, embed it like this: + +```markdown +![[model.glb]] +![[model.glb|400x300]] +``` + +--- + +## Installation + +Use [Quick Start](#quick-start) if you only want the fastest setup. + +### Requirements + +- Obsidian 1.5.0 or later +- Obsidian Desktop on Windows, macOS, or Linux for local tool-based conversion +- A local Obsidian vault folder on your computer +- This plugin folder inside the vault: + +```text +/.obsidian/plugins/ai-model-workbench/ +``` + +All install methods place the same three files in that folder: + +| File | Size | Description | +|------|------|-------------| +| `main.js` | ~3.8 MB | Plugin runtime bundle | +| `manifest.json` | ~1 KB | Obsidian plugin manifest | +| `styles.css` | ~10 KB | Plugin styles | + +Direct rendering works on desktop and mobile. Local converter tools for CAD, FBX, 3MF, and DAE require desktop OS access. + +### Option A: Build from Source + +1. Clone the repository and build the plugin: + +```bash +git clone https://github.com/flash555588/ai-model-workbench.git +cd ai-model-workbench +npm install +npm run build +``` + +2. Install the built files into a vault: + +```bash +# Install to the bundled test vault +npm run install:vault + +# Or install to your own vault +npm run install:vault -- --vault "C:\path\to\your-vault" +``` + +The installer copies `main.js`, `manifest.json`, and `styles.css` into `.obsidian/plugins/ai-model-workbench/` and enables `ai-model-workbench` in `community-plugins.json`. + +3. If Obsidian is already open, reload the app or disable and re-enable `AI Model Workbench` in `Settings > Community Plugins`. + +Manual fallback: create `/.obsidian/plugins/ai-model-workbench/`, copy `main.js`, `manifest.json`, and `styles.css` into that folder, then enable `AI Model Workbench` in Obsidian. + +### Option B: Download a Release + +1. Download `main.js`, `manifest.json`, and `styles.css` from [Releases](https://github.com/flash555588/ai-model-workbench/releases). +2. Create `/.obsidian/plugins/ai-model-workbench/` if it does not exist. +3. Put the three files in that folder. +4. In Obsidian, enable `AI Model Workbench` in `Settings > Community Plugins`. + +### Option C: Symlink for Development + +1. Make sure `/.obsidian/plugins/` already exists. +2. Create a symlink named `ai-model-workbench` that points to this repository. + +Windows (PowerShell): + +```powershell +New-Item -ItemType SymbolicLink ` + -Path "C:\path\to\your-vault\.obsidian\plugins\ai-model-workbench" ` + -Target "C:\path\to\ai-model-workbench" +``` + +macOS / Linux: + +```bash +ln -s /path/to/ai-model-workbench \ + /path/to/your-vault/.obsidian/plugins/ai-model-workbench +``` + +3. In this repository, run `npm install` once if needed. +4. Run `npm run dev` while developing. +5. In Obsidian, enable `AI Model Workbench` in `Settings > Community Plugins`. + +### After Install + +1. Put a supported model file into the same vault, for example `model.glb`. +2. In any note inside that vault, embed it like this: + +```markdown +![[model.glb]] +![[model.glb|400x300]] +``` + +--- + +## Security & Privacy + +AI Model Workbench does not collect telemetry, phone home, or run background network sync. Model previews are loaded from files already present in the Obsidian vault, and OBJ material/texture references are resolved from the vault instead of being fetched from the network. + +The bundled Babylon.js runtime contains generic loader utilities that are capable of loading URLs for web applications. This plugin passes vault file bytes to Babylon as data URLs, overrides OBJ MTL loading to avoid remote fetches, and installs a runtime guard that rejects explicit `http(s)` / `ws(s)` asset or script URLs while disabling Babylon retry hooks for those requests. Optional converter diagnostics and conversions run only after a user action and execute local tools on desktop platforms. + +Knowledge-note generation is local-only by default. If you configure an optional remote draft service, the plugin sends only the selected evidence payload to your configured `POST /draft-note` endpoint. The current client refuses raw model upload, and geometry summaries or preview image references must be enabled explicitly before they are included. + +Release assets are limited to the three files Obsidian downloads: `main.js`, `manifest.json`, and `styles.css`. GitHub Actions builds these files from source and publishes artifact attestations for provenance verification. + +--- + +## Funding + +AI Model Workbench does not include donation prompts, payment flows, or cryptocurrency wallet addresses in the plugin bundle. + +--- + +## Format Support + +### Direct Rendering (No External Tools) + +| Format | Extension | Features | +|--------|-----------|----------| +| GLB / GLTF | `.glb` `.gltf` | PBR materials, animations, textures, scene hierarchy; `.gltf` resolves vault-relative `.bin` and texture files | +| STL | `.stl` | Binary format, per-face colors (VisCAM/SolidView) | +| OBJ | `.obj` | MTL materials, vault-relative texture resolution, case-insensitive same-folder texture fallback | +| PLY | `.ply` | ASCII/binary, vertex colors, point cloud support | + +SPLAT preview is temporarily disabled in packaged builds while its loader is replaced with a local-only implementation. + +### SPLAT Status and Roadmap + +- Current status: SPLAT preview is temporarily disabled in community release builds. GLB, GLTF, STL, OBJ, PLY, and the current local conversion routes are unaffected. +- Why: the current Babylon SPLAT/SPZ loader still carries dynamic script and remote module fallback paths. The plugin runtime already rejects remote requests, but the packaged release also aims to remove those paths from the shipped bundle to reduce review and static-scan risk. +- Roadmap: first restore local-only `.splat` loading; then reopen it after idle-render stability is improved for Windows and large scenes; finally evaluate `.spz` separately, and only re-enable it if the decoder dependencies can be bundled locally and reviewed as local assets. + +### Conversion (Requires External Tools) + +| Format | Extension | Converter | Output | +|--------|-----------|-----------|--------| +| STEP | `.step` `.stp` | Python + CadQuery/OCCT | GLB | +| IGES | `.iges` `.igs` | Python + CadQuery/OCCT | GLB | +| BREP | `.brep` | Python + CadQuery/OCCT | GLB | +| SLDPRT | `.sldprt` | FreeCAD | GLB | +| 3MF | `.3mf` | Python + trimesh | GLB | +| DAE | `.dae` | Python + trimesh | GLB | +| FBX | `.fbx` | FBX2glTF | GLB | + +STEP conversion preserves XDE assembly/component labels when available, exporting each component as its own GLB node with `extras.ai3d` identity metadata. PCB STEP files from tools such as EasyEDA can therefore register reference-designator parts like `R1`, `USB1`, and `U4` instead of collapsing the board into one mesh. + +### Format Feature Matrix + +| Feature | GLB/GLTF | STL | OBJ | PLY | FBX (converted) | CAD | +|---------|----------|-----|-----|-----|-----------------|-----| +| Mesh | Yes | Yes | Yes | Yes | Yes | Yes | +| Point Cloud | No | No | No | Yes | No | No | +| Materials | PBR | Basic | MTL | Basic | Basic | No | +| Textures | Embedded | No | External | No | No | No | +| Colors | Vertex | Face | No | Vertex | No | Face (STEP) | +| Animation | Yes | No | No | No | Yes | No | + +--- + +## Usage + +### Syntax Guide + +#### 1. Inline Embed + +Write a wikilink anywhere in your note. Works in Reading and Live Preview. + +```markdown +![[model.glb]] +![[model.glb|400x300]] +``` + +#### 2. `3d` Code Block + +**Quick** — file path only: + +````markdown +```3d model.glb +``` +```` + +**Full config** — camera, lights, scene, multi-model: + +````markdown +```3d +{ + "models": [ + { "path": "model.glb" }, + { "path": "part.stl", "color": "#ff0000", "wireframe": true } + ], + "camera": { "fov": 30, "position": [5, 5, 5] }, + "lights": [ + { "type": "hemisphere", "color": "#fff", "intensity": 1 }, + { "type": "directional", "position": [10, 20, 10] } + ], + "scene": { "autoRotate": true, "grid": true }, + "width": "100%", + "height": 500 +} +``` +```` + +| Section | Key fields | +|---------|------------| +| `models[]` | `path` (required), `color`, `wireframe` | +| `camera` | `fov`, `position`, `lookAt`, `mode` (`"perspective"` / `"orthographic"`) | +| `lights[]` | `type` (`"hemisphere"` `"directional"` `"point"` `"spot"` `"ambient"` `"attachToCam"`), `color`, `intensity`, `position` | +| `scene` | `background`, `autoRotate`, `autoRotateSpeed`, `grid`, `axis`, `groundShadow`, `transparent` | +| `stl` | `color`, `wireframe` (defaults for STL files) | +| top-level | `width`, `height` | + +#### 3. `3dgrid` Code Block + +Render multiple models in one viewport using layout presets. + +````markdown +```3dgrid +{ + "models": [ + { "path": "v1.step" }, + { "path": "v2.step" }, + { "path": "v3.step" } + ], + "preset": "compare" +} +``` +```` + +| Preset | Layout | +|--------|--------| +| `compare` | Side-by-side A/B | +| `showcase` | Multi-angle single model | +| `explode` | Ring arrangement | +| `timeline` | Horizontal strip | +| `gallery` | All in one scene (default) | +| `compose` | Custom sections | + +`3dgrid` accepts the same `camera`, `lights`, `scene` fields as `3d`, plus: `preset`, `params`, `columns`, `rowHeight`, `gapX`, `gapY`, `sections`, `direction`. + +#### 4. Direct File View + +Click any `.glb`/`.gltf`/`.stl`/`.obj`/`.ply` file in the file explorer. + +#### Supported Extensions + +| Type | Formats | +|------|---------| +| Direct | `.glb` `.gltf` `.stl` `.obj` `.ply` | +| Conversion | `.step` `.stp` `.iges` `.igs` `.brep` `.sldprt` `.3mf` `.dae` `.fbx` | + +### Keyboard Shortcuts (in preview) + +| Key | Action | +|-----|--------| +| `R` | Reset view | +| `W` | Toggle wireframe | +| `G` | Toggle orientation gizmo | +| `B` | Toggle bounding box | +| `Space` | Play/pause animation | +| `Esc` | Exit annotation mode | + +### 3D Annotations + +Add labeled bookmarks directly on model surfaces. Annotations persist per model file. + +**Direct View** (edit mode): + +1. Click the **tag icon** in the toolbar +2. A blue overlay indicates annotation mode is active +3. Click anywhere on the model surface to place a pin +4. Enter a label and pick a color in the popup editor +5. Click an existing pin to edit its label/color or delete it +6. Press `Esc` to exit annotation mode + +**Depth-aware occlusion**: Pins behind geometry display blurred and dimmed. During camera movement, occlusion refreshes in small batches so existing bookmarks do not visibly lag behind model rotation; when idle, the overlay catches up with a full refresh cadence. + +**Code blocks & Live Preview**: Saved annotations display as read-only overlays with the same occlusion behavior. + +--- + +### Knowledge Notes + +The workbench `Generate note` action creates an evidence-backed Markdown note rather than a bare template. Each generation pass writes: + +- a model report in `Analysis/3D Reports` +- a JSON analysis sidecar with preview summary, part candidates, knowledge nodes, warnings, and pipeline metadata +- a model knowledge index in `Analysis/3D Reports` that links the report, sidecar, evidence images, annotations, and part notes +- up to 8 first-pass part note drafts in `Parts/3D Components`, linked from the report and sidecar without overwriting existing part notes +- a current viewport evidence snapshot in `Media/3D Previews` +- an editable local draft that turns the captured evidence, annotations, tags, and profile notes into a first-pass knowledge note body, plus local draft metadata for tags and next actions + +The default local pass does not send model data to a remote service. It uses renderer evidence, saved annotations, tags, and profile notes as the grounding layer for later AI-assisted drafting. When a GLB/GLTF file contains named internal groups or assemblies, the renderer registers those groups as higher-confidence part candidates and keeps ungrouped meshes as standalone candidates. GLB/GLTF component metadata in `extras.ai3d` (`partId`, `occurrenceId`, `partNumber`, and `componentPath`) is registered as individual component parts when present. STEP conversion preserves XDE component labels as GLB component metadata, so PCB reference designators and CAD assembly children can become individual registered parts after conversion. Direct file view stores those captured candidates in the model profile immediately after a successful load, preserving source extensions such as STEP, FBX, 3MF, and DAE in the analysis record so later imported models can match reused parts across converted model types even before a full report exists. During note generation, current part candidates are also compared with parts registered in other profiles or analyzed model sidecars, so likely reused components can be linked back to their existing part notes for review. + +After a report has been generated, use the direct workbench `Open index` action or the command palette `Open knowledge index` command to jump back into the model's knowledge map. + +Optional remote drafting can be enabled in settings by choosing `Local evidence + remote draft` or `Remote draft from evidence` and entering a draft service URL. The client sends `POST /draft-note` with sanitized drafting input only. Raw model upload is blocked; geometry summaries and preview image references are controlled by separate privacy toggles. + +--- + +## Settings + +| Setting | Default | Description | +|---------|---------|-------------| +| Language | auto | UI language (English / Simplified Chinese / auto-detect) | +| Annotation preview mode | plain-text | How saved annotation content renders inside readonly previews | +| AI drafting mode | Local evidence only | Keeps knowledge-note drafting local unless an optional remote draft service is configured | +| Draft service URL | empty | Base URL for a service that accepts `POST /draft-note` | +| Preview compatibility mode | Reading + file view | Controls how widely the newer single-model GLB preview path is used | +| Experimental Three workbench | off | Tries the Three.js workbench path for direct GLB/GLTF file views, with automatic Babylon.js fallback | +| Canvas height | 400 | Preview height in pixels | +| Auto-rotate | off | Start with turntable animation | +| Auto-rotate speed | 0.5 | Rotation speed (0.1-2.0) | +| Render quality | high | Quality preset (low/medium/high) | +| Render scale | 1.0 | Resolution multiplier (0.25-2.0) | +| Snapshot folder | Media/3D Previews | Export folder | +| Snapshot naming | model-name | File naming mode for exported PNG snapshots | +| Report folder | Analysis/3D Reports | Knowledge notes folder | +| Part notes folder | Parts/3D Components | Folder for generated part note drafts | +| Log level | warn | Console log verbosity | + +### Converter Settings + +| Setting | Description | +|---------|-------------| +| Enable CAD converter | Enable STEP/IGES/BREP via CadQuery | +| Enable SLDPRT converter | Enable SolidWorks via FreeCAD | +| Enable mesh converter | Enable 3MF/DAE via trimesh | +| Enable OBJ2GLTF converter | Optional OBJ normalization through obj2gltf | +| Enable FBX2glTF converter | Enable FBX conversion through FBX2glTF | +| Python command path (for CAD conversion) | Override the Python executable used for STEP/IGES/BREP conversion | +| FreeCADCmd path (for SLDPRT conversion) | Override the FreeCAD executable used for `.sldprt` conversion | +| obj2gltf command path | Override the obj2gltf CLI path | +| FBX2glTF command path | Override the FBX2glTF CLI path | +| Python command path (for 3MF/DAE conversion) | Override the Python executable used for 3MF/DAE conversion | +| Converter command diagnostics | Show which executable path the plugin will actually use and run lightweight self-checks for Python environments and converter CLIs | + +### Portability and diagnostics + +The rendering layer is cross-platform: direct formats like GLB, OBJ, STL, PLY, and already-converted `.ai3d-converted.glb` assets can render anywhere Obsidian Desktop can provide WebGL. + +On iOS, iPadOS, and Android, the plugin now supports direct formats such as GLB, GLTF, OBJ, STL, and PLY. Local conversion routes for CAD, FBX, 3MF, DAE, and SLDPRT remain desktop-only because they depend on external CLI tools and Python environments. + +The conversion layer is less portable because it depends on local tools and Python environments that vary by machine. Use the converter diagnostics panel in plugin settings as the first check when a CAD or mesh format fails. It verifies both the executable path the plugin resolved and whether the selected Python environment can import the required packages or the native converter CLI can launch. + +For repository-level implementation rules, see [docs/cross-platform-development.md](docs/cross-platform-development.md). + +On macOS in particular, the system Python at `/usr/bin/python3` often exists but does not include CAD packages. If diagnostics show that path and the self-check fails, install a separate Python environment and point the plugin setting to that interpreter explicitly. + +--- + +## External Dependencies + +Only needed for CAD, FBX, and mesh conversion. Direct formats work without any external tools. + +### Python + CadQuery (STEP, IGES, BREP) + +```bash +# Install +pip install cadquery trimesh +``` + +Verify with the Python command your OS uses: + +- Windows: `py -c "import cadquery; print('OK')"` +- macOS / Linux: `python3 -c "import cadquery; print('OK')"` + +If diagnostics resolve to `/usr/bin/python3` on macOS and the import check fails, install a separate Python (for example Homebrew Python), install `cadquery` and `trimesh` there, then set that interpreter path in plugin settings. + +### FreeCAD (SLDPRT) + +Install FreeCAD for your platform: + +- Windows: install from [freecad.org/downloads](https://www.freecad.org/downloads.php) +- macOS: install the app bundle or use `brew install --cask freecad` +- Linux: install your distro's FreeCAD package and make sure `freecadcmd` is available + +The plugin prefers the explicit setting and environment variable first, then checks common user-managed install locations, then PATH, and finally system fallback hints such as: +- Windows: `%LOCALAPPDATA%\Programs\FreeCAD*\bin\FreeCADCmd.exe` +- macOS: `/Applications/FreeCAD.app/Contents/MacOS/FreeCADCmd`, `/usr/local/bin/FreeCADCmd`, `/opt/homebrew/bin/FreeCADCmd` +- Linux: `/usr/bin/freecadcmd` + +### Python + trimesh (3MF, DAE) + +```bash +pip install trimesh numpy networkx pycollada +``` + +**Auto-discovery**: Same Python as CadQuery (see above). + +**Override**: Environment variable `AI3D_ASSIMP_CMD`. + +### obj2gltf (OBJ, optional) + +The plugin already has a built-in OBJ loader. obj2gltf is an optional alternative that can produce higher-fidelity GLB output. + +**Install**: + +```bash +npm install -g obj2gltf +``` + +**Resolution order**: The plugin prefers the explicit setting and environment variable first, then checks common user-managed install locations, then PATH, and finally system fallback hints such as `obj2gltf.cmd` on Windows and `obj2gltf` in standard macOS/Linux locations like `/usr/local/bin/obj2gltf` and `/opt/homebrew/bin/obj2gltf`. + +**Enable**: Settings > Enable OBJ2GLTF converter, or set "obj2gltf path". + +### FBX2glTF (FBX) + +FBX files are converted to GLB through the local FBX2glTF binary. The older community FBX loader is not bundled because its current release targets Babylon.js 8, while this plugin uses Babylon.js 9. + +**Install**: + +Download or build [FBX2glTF](https://github.com/godotengine/FBX2glTF) for your platform and place the binary in a known location. + +**Resolution order**: The plugin prefers the explicit setting and environment variable first, then checks common user-managed install locations, then PATH, and finally system fallback hints such as: + +```text +C:\Program Files\FBX2glTF\FBX2glTF-windows-x64.exe +C:\Program Files\FBX2glTF\FBX2glTF.exe +/usr/local/bin/FBX2glTF +/opt/homebrew/bin/FBX2glTF +/usr/local/bin/fbx2gltf +``` + +**Enable**: Settings > Enable FBX2glTF converter, or set "FBX2glTF path". + +### Environment Variables + +| Variable | Purpose | +|----------|---------| +| `AI3D_FREECAD_CMD` | Python command for CadQuery | +| `AI3D_FREECADCMD` | FreeCADCmd path | +| `AI3D_ASSIMP_CMD` | Python command for trimesh | +| `AI3D_OBJ2GLTF_CMD` | obj2gltf command path | +| `AI3D_FBX2GLTF_CMD` | FBX2glTF command path | + +The legacy alias `AI3D_FREECMDCMD` is still accepted for compatibility, but new setups should use `AI3D_FREECADCMD`. + +--- + +## Technical Details + +### Architecture + +``` +src/ +├── main.ts # Plugin lifecycle, commands +├── domain/ +│ ├── models.ts # Shared interfaces +│ └── constants.ts # Default settings, extensions +├── store/ +│ ├── create-store.ts # Custom store primitive +│ └── plugin-store.ts # Obsidian saveData bridge +├── render/ +│ ├── preview/ # Renderer-agnostic abstraction layer +│ │ ├── types.ts # ModelPreview, AnnotationPreview, WorkbenchPreview interfaces +│ │ ├── routing.ts # Three/Babylon route decision logic +│ │ ├── factory.ts # Dynamic import factory for renderers +│ │ ├── selection.ts # Preview selection with logging +│ │ ├── annotations.ts # AnnotationManager (pin overlay + occlusion) +│ │ ├── geometry.ts # Renderer-agnostic vector math +│ │ ├── bounds.ts # Bounding box utilities +│ │ ├── camera-fit.ts # Camera fitting algorithms +│ │ ├── disassembly.ts # Disassembly controller (adapter pattern) +│ │ ├── explode.ts # Explode view (adapter pattern) +│ │ ├── report.ts # Markdown report generation +│ │ └── summary.ts # Model/part summary creation +│ ├── three/ # Three.js renderer +│ │ ├── scene.ts # ThreeModelPreview class (GLB/GLTF/STL/PLY/OBJ) +│ │ ├── loaders.ts # Format-specific loaders with vault MTL resolution +│ │ ├── disassembly.ts # ThreeDisassemblyAdapter +│ │ └── explode.ts # ThreeExplodeAdapter +│ ├── babylon/ # Babylon.js renderer +│ │ ├── scene.ts # BabylonModelPreview class +│ │ ├── grid.ts # GridRenderer class +│ │ ├── picking.ts # Click-to-pick with highlight +│ │ ├── loaders/ +│ │ │ ├── stl-loader.ts # Custom binary STL parser +│ │ │ ├── ply-loader.ts # Custom ASCII/binary PLY parser +│ │ │ └── register.ts # Babylon SceneLoader plugins +│ │ └── presets/ # Grid layout presets +├── io/ +│ ├── formats/ +│ │ └── registry.ts # Format capability registry +│ ├── conversion/ +│ │ ├── manager.ts # Conversion orchestration +│ │ └── adapters/ # Converter implementations +│ └── model-pipeline.ts # Format routing logic +└── view/ + ├── workbench/ # Knowledge-note helpers + ├── inline/ # Code blocks, live preview + └── direct-view.ts # Direct file opening +``` + +### Model Import Pipeline + +``` +┌─────────────────────────────────────────────────────────────┐ +│ 1. Format Detection │ +│ └─ getFormatCapability(ext) → { family, strategy } │ +│ │ +│ 2. Route Decision │ +│ ├─ strategy: "direct" → prepareDirectLoad() │ +│ └─ strategy: "convert" → convertForPreview() │ +│ │ +│ 3. Data Loading │ +│ ├─ readBinaryPath() → ArrayBuffer │ +│ └─ [if converted] → read converted .glb │ +│ │ +│ 4. Babylon Rendering │ +│ ├─ GLB/GLTF/OBJ → SceneLoader.ImportMeshAsync() │ +│ ├─ STL → loadSTLBuffer() (direct parse) │ +│ └─ PLY → loadPLYBuffer() (direct parse) │ +└─────────────────────────────────────────────────────────────┘ +``` + +### Why Direct Buffer Loading for STL/PLY + +Babylon.js v9 SceneLoader has a bug where custom plugins receive data URL strings instead of ArrayBuffer when loading via `SceneLoader.ImportMeshAsync()`. Built-in loaders (GLTF and OBJ) are unaffected. + +**Workaround**: STL and PLY parsers are called directly with the raw ArrayBuffer, bypassing SceneLoader entirely. + +### Conversion Caching + +- **Location**: Same directory as source file +- **Format**: `{filename}.ai3d-converted.glb` +- **Validation**: Checks converter identity, cache key, file existence +- **Invalidation**: Automatic when converter settings change +- **Manual clear**: Command palette > "Clear Conversion Cache" + +--- + +## Known Limitations + +| Issue | Affected Formats | Workaround | +|-------|-----------------|------------| +| External converter required | FBX | Install and enable FBX2glTF | +| External tools required | STEP/IGES/BREP/SLDPRT | Install Python + CadQuery or FreeCAD | +| Texture path resolution | OBJ | Place textures beside the OBJ/MTL; missing textures show a non-blocking asset warning | +| External resource path resolution | GLTF | Keep `.bin` and textures in the vault beside the `.gltf` or in referenced relative folders | +| Conversion timeout | SLDPRT | 10-minute timeout for complex assemblies | + +--- + +## Deployment + +### Prerequisites + +- Node.js >= 18 +- npm >= 9 +- Obsidian >= 1.5.0 + +### Build Commands + +```bash +npm install # Install dependencies +npm run dev # Development build with watch +npm run build # Production build +npm run typecheck # TypeScript type check +npm run verify:preview # Targeted browser preview smoke test +npm run verify:preview:success # Full preview routing success suite +npm run verify:obsidian # End-to-end Obsidian app smoke test +npm run verify:release # Release asset version/hash/size check +npm run verify:settings # Legacy data.json/default-settings migration check +npm run verify:remote-draft # Remote draft privacy/client behavior check +npm run verify:knowledge-index # Knowledge index link and refresh regression check +npm run verify:diagnostics # Sanitized diagnostics report regression check +``` + +### Preview Verification + +Run `npm run verify:preview:success` before shipping preview changes. For a focused default-route check, `npm run verify:preview` still works. The harness auto-detects common Chrome, Edge, Chromium, and Brave installs on Windows, macOS, and Linux; set `PLAYWRIGHT_CHROMIUM_EXECUTABLE` only when using a custom browser path. The success suite launches a temporary Playwright harness, loads `models/rubiks-cube-3x3.glb`, and verifies: + +- default simple `GLB` preview +- default direct-edit `GLB` preview +- default readonly saved-pin `GLB` preview +- reading-surfaces-only rollout behavior +- compatibility-mode rollback behavior +- workbench Babylon fallback routing and experimental Three.js workbench probe +- direct-format `STL`, `PLY`, and `OBJ` preview routing +- helper toolbar interactions, focus mode, moving-pin occlusion, selected-part export, performance snapshots, and wheel-scroll containment + +If verification fails, the script saves a screenshot and a log with preview state plus browser messages under `.tmp/preview-failures/`. + +### Obsidian Verification + +Run `npm run verify:obsidian` on macOS before release when Obsidian is installed. The script builds a temporary test vault under `/tmp/ai-model-workbench-verify-vault`, installs the packaged plugin, opens a note in Obsidian through a remote debugging port, trusts the temporary vault when prompted, confirms that GLB/STL preview canvases are loaded, checks converter feedback for an FBX route without FBX2glTF enabled, then opens the real GLB file view with Experimental Three workbench enabled and checks backend selection, focus/disassembly controls, panel explode controls, annotation mode, and knowledge-note generation. + +Use `npm run verify:obsidian -- --clean` when you want the temporary vault removed after the run. On macOS, the clean path quits Obsidian and unregisters the temporary vault before deleting it so the developer console does not keep reporting stale `ENOENT` reads from `/tmp`. + +### Knowledge Note Verification + +Run `npm run verify:knowledge-index` after changing generated reports, part drafts, or model index behavior. The script bundles the knowledge-note helpers with a small Obsidian shim, builds a representative model index, refreshes the AI-managed block, and confirms user-written notes remain intact. + +### Build Output + +``` +ai-model-workbench/ +├── main.js # ~3.8 MB (minified plugin runtime bundle) +├── manifest.json # Plugin manifest +├── styles.css # Plugin styles +└── src/ # Source code +``` + +### Release Publishing + +Releases are published by the GitHub Actions `Release` workflow. Push a tag that matches `manifest.json`, for example `0.5.5`, or run the workflow manually. The workflow uploads only `main.js`, `manifest.json`, and `styles.css`, removes unsupported release assets, verifies asset sizes and SHA-256 hashes, and generates GitHub artifact attestations for the published files. After a release is published, run `npm run verify:obsidian -- --release-tag 0.5.5` to install the assets downloaded from GitHub into the temporary Obsidian vault. + +### Release Token Safety + +Prefer GitHub Actions or GitHub CLI browser login for publishing. See `SECURITY.md` for the token safety checklist and PAT leak response. + +### Platform Support + +| Platform | Status | +|----------|--------| +| Windows | Full support | +| macOS | Full support | +| Linux | Full support | +| Obsidian Mobile | Supported (reduced resolution) | + +### Bundle Size Optimization + +The rendering runtimes dominate the bundle size. The project keeps the output in check with: + +- Subpath imports (`@babylonjs/core/Engines/engine.js`) instead of barrel imports +- Tree-shaking to remove unused features +- esbuild for fast, optimized bundling + +Because the shipped preview mix now includes both Babylon and Three paths, the exact bundle size moves as routing coverage changes. Treat the build output above as the current reference point rather than a fixed ceiling. + +--- + +## Acknowledgments + +Thanks to the LinuxDo community (https://linux.do) for their support. diff --git a/README.zh-CN.md b/README.zh-CN.md index 85dc60e..4736f5b 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -1,737 +1,737 @@ -# AI Model Workbench - -> 一个以本地优先和知识库整合为核心的 Obsidian 3D 查看插件,可在本地 WebGL 视口中查看常见 3D 资产、标注关键部位,并将模型整理为可链接的知识笔记。单模型预览(GLB、GLTF、STL、PLY、OBJ)现在默认走 Three.js 渲染路径,可通过“预览兼容模式”回退到 Babylon.js;文件视图 workbench 可以选择启用实验性 Three.js GLB/GLTF 路径,并保留 Babylon.js 自动回退;`3dgrid` 与 SPLAT 仍保留在 Babylon.js 能力路径上。 - -[AI Model Workbench](https://community.obsidian.md/plugins/ai-model-workbench) - -[English](README.md) | **简体中文** - -![preview](docs/assets/preview.gif) - ---- - -## 目录 - -- [功能特性](#功能特性) -- [平台支持矩阵](#平台支持矩阵) -- [快速入门](#快速入门) -- [安装](#安装) -- [格式支持](#格式支持) -- [使用方法](#使用方法) -- [设置选项](#设置选项) -- [外部依赖](#外部依赖) -- [安全与隐私](#安全与隐私) -- [资金与赞助](#资金与赞助) -- [技术细节](#技术细节) -- [已知限制](#已知限制) -- [部署指南](#部署指南) -- [许可证](#许可证) - ---- - -## 功能特性 - -- **直接预览** GLB/GLTF、STL、OBJ、PLY(默认全部走 Three.js 渲染路径) -- **可选转换** CAD、FBX、3MF、DAE 等资产到 GLB -- **混合预览路由**:单模型预览(GLB/GLTF/STL/PLY/OBJ)默认走 Three.js,可在设置中回退到 Babylon.js -- **内联与文件视图**:实时预览、代码块、直接文件查看 -- **网格系统**:在单个视口中渲染多个模型,支持预设布局 -- **3D 标注**:点击模型表面添加带标签和颜色的书签,支持深度遮挡 -- **知识笔记**:从已加载的模型生成结构化 Markdown,并自动注册捕获到的零件候选用于跨模型复用识别 -- **快照功能**:复制、保存或下载渲染预览为 PNG -- **国际化**:英文和简体中文,自动检测系统语言 -- **桌面端支持**:Windows、macOS、Linux 上的 Obsidian Desktop -- **移动端支持**:iOS、iPadOS、Android 支持直读格式和简化后的工作台布局 - ---- - -## 平台支持矩阵 - -| 能力 | Windows / macOS / Linux | iOS / iPadOS / Android | -|------|--------------------------|-------------------------| -| 直读格式(GLB、GLTF、OBJ、STL、PLY) | 支持 | 支持 | -| 直接文件查看 | 支持 | 支持 | -| 直读格式的内联嵌入 / 实时预览 | 支持 | 支持 | -| 工作台布局 | 完整桌面布局 | 简化单列移动布局 | -| 本地转换(CAD、FBX、3MF、DAE、SLDPRT) | 支持 | 不支持 | -| 转换器诊断与本地 CLI 自检 | 支持 | 不支持 | -| 已生成的 `.ai3d-converted.glb` 资产 | 支持 | 支持 | - ---- - -## 快速入门 - -1. 构建插件: - -```bash -npm install -npm run build -``` - -2. 打开你电脑上的本地 Obsidian vault 文件夹。 - -3. 在该 vault 里创建这个文件夹: - -```text -/.obsidian/plugins/ai-model-workbench/ -``` - -4. 把 `main.js`、`manifest.json`、`styles.css` 复制到这个文件夹里。 - -5. 在 Obsidian 中打开“设置 > 社区插件”,启用 `AI Model Workbench`。 - -6. 把一个受支持的模型文件放进同一个 vault,例如 `model.glb`。 - -7. 在该 vault 的任意笔记中这样嵌入: - -```markdown -![[model.glb]] -![[model.glb|400x300]] -``` - ---- - -## 安装 - -如果你只想最快跑起来,直接看上面的 [快速入门](#快速入门)。 - -### 前提 - -- Obsidian 1.5.0 或更高版本 -- 需要 Windows、macOS 或 Linux 上的 Obsidian Desktop 才能使用本地转换工具 -- 你电脑上的本地 Obsidian vault 文件夹 -- vault 里的插件目录: - -```text -/.obsidian/plugins/ai-model-workbench/ -``` - -无论用哪种方式安装,最终都要把下面这三个文件放进这个目录: - -| 文件 | 大小 | 说明 | -|------|------|------| -| `main.js` | ~3.8 MB | 插件运行时 bundle | -| `manifest.json` | ~1 KB | Obsidian 插件清单 | -| `styles.css` | ~5 KB | 插件样式 | - -直接渲染在桌面端和移动端都可用。CAD、FBX、3MF、DAE 的本地转换工具只适用于桌面系统。 - -### 方式 A:从源码构建 - -1. 克隆仓库并构建插件: - -```bash -git clone https://github.com/flash555588/ai-model-workbench.git -cd ai-model-workbench -npm install -npm run build -``` - -2. 把构建产物安装到 vault: - -```bash -# 安装到仓库自带的测试 vault -npm run install:vault - -# 或安装到你自己的 vault -npm run install:vault -- --vault "C:\path\to\your-vault" -``` - -安装脚本会把 `main.js`、`manifest.json`、`styles.css` 复制到 `.obsidian/plugins/ai-model-workbench/`,并在 `community-plugins.json` 中启用 `ai-model-workbench`。 - -3. 如果 Obsidian 已经打开,重新加载应用,或在“设置 > 社区插件”中禁用再启用 `AI Model Workbench`。 - -手动备选:创建 `/.obsidian/plugins/ai-model-workbench/`,把 `main.js`、`manifest.json`、`styles.css` 复制进去,然后在 Obsidian 中启用 `AI Model Workbench`。 - -### 方式 B:下载发布版 - -1. 从 [Releases](https://github.com/flash555588/ai-model-workbench/releases) 下载 `main.js`、`manifest.json` 和 `styles.css`。 -2. 如果 `/.obsidian/plugins/ai-model-workbench/` 还不存在,先创建它。 -3. 把这三个文件放进这个文件夹里。 -4. 在 Obsidian 的“设置 > 社区插件”中启用 `AI Model Workbench`。 - -### 方式 C:开发用符号链接 - -1. 先确认 `/.obsidian/plugins/` 已经存在。 -2. 创建一个名为 `ai-model-workbench` 的符号链接,指向当前仓库。 - -Windows(PowerShell): - -```powershell -New-Item -ItemType SymbolicLink ` - -Path "C:\path\to\your-vault\.obsidian\plugins\ai-model-workbench" ` - -Target "C:\path\to\ai-model-workbench" -``` - -macOS / Linux: - -```bash -ln -s /path/to/ai-model-workbench \ - /path/to/your-vault/.obsidian/plugins/ai-model-workbench -``` - -3. 如果还没装依赖,先在当前仓库运行一次 `npm install`。 -4. 开发时运行 `npm run dev`。 -5. 在 Obsidian 的“设置 > 社区插件”中启用 `AI Model Workbench`。 - -### 安装后 - -1. 先把一个受支持的模型文件放进同一个 vault,例如 `model.glb`。 -2. 然后在该 vault 的任意笔记中这样嵌入: - -```markdown -![[model.glb]] -![[model.glb|400x300]] -``` - ---- - -## 安全与隐私 - -AI Model Workbench 不收集遥测数据,不会主动回传,也不会运行后台网络同步。模型预览读取的是已经存在于 Obsidian vault 中的本地文件;OBJ 的 MTL 材质和纹理引用会从 vault 内解析,而不是从网络下载。 - -打包后的 Babylon.js 运行时包含面向 Web 应用的通用 URL 加载工具。该插件会把 vault 文件字节以 data URL 传给 Babylon,覆盖 OBJ MTL 加载逻辑以避免远程请求,并在运行时显式拒绝 `http(s)` / `ws(s)` 资产与脚本 URL,同时关闭 Babylon 对这类请求的重试钩子。可选的转换器诊断和格式转换只会在用户主动操作后运行,并且只在桌面端调用本地工具。 - -知识笔记生成默认保持本地-only。如果你配置了可选远程草稿服务,插件只会向你填写的 `POST /draft-note` 端点发送被允许的证据 payload。当前客户端拒绝上传原始模型;几何摘要和预览图引用必须分别显式开启后才会包含在请求中。 - -发布资产仅限 Obsidian 会下载的三个文件:`main.js`、`manifest.json` 和 `styles.css`。GitHub Actions 会从源码构建这些文件,并为它们发布 artifact attestation,便于验证来源。 - ---- - -## 资金与赞助 - -AI Model Workbench 的插件包中不包含赞助提示、付款流程或加密货币钱包地址。 - ---- - -## 格式支持 - -### 直接渲染(无需外部工具) - -| 格式 | 扩展名 | 特性 | -|------|--------|------| -| GLB / GLTF | `.glb` `.gltf` | PBR 材质、动画、纹理、场景层级;`.gltf` 会解析 vault 内相对路径的 `.bin` 与纹理 | -| STL | `.stl` | 二进制格式、逐面颜色(VisCAM/SolidView) | -| OBJ | `.obj` | MTL 材质、库内相对路径纹理解析、同目录大小写兜底 | -| PLY | `.ply` | ASCII/二进制、顶点颜色、点云支持 | - -当前打包版本临时关闭 SPLAT 预览,直到其加载器替换为纯本地实现。 - -### SPLAT 说明与规划 - -- 当前状态:社区发布版暂时关闭 SPLAT 预览,GLB、GLTF、STL、OBJ、PLY 以及现有本地转换路线不受影响。 -- 原因:现阶段 Babylon 上游 SPLAT/SPZ loader 仍带有动态脚本与远程模块回退路径。插件运行时已经拒绝远程请求,但发布版希望进一步把这类加载路径从最终产物中剥离,降低审核和静态扫描风险。 -- 未来规划:第一步恢复纯本地 `.splat` 直读;第二步在 Windows 和大场景下完成静止/空闲渲染稳定性优化后再重新开放;第三步再单独评估 `.spz`,只有在解码依赖可以完整本地打包并通过审查时才会重新启用。 - -### 转换(需要外部工具) - -| 格式 | 扩展名 | 转换器 | 输出 | -|------|--------|--------|------| -| STEP | `.step` `.stp` | Python + CadQuery/OCCT | GLB | -| IGES | `.iges` `.igs` | Python + CadQuery/OCCT | GLB | -| BREP | `.brep` | Python + CadQuery/OCCT | GLB | -| SLDPRT | `.sldprt` | FreeCAD | GLB | -| 3MF | `.3mf` | Python + trimesh | GLB | -| DAE | `.dae` | Python + trimesh | GLB | -| FBX | `.fbx` | FBX2glTF | GLB | - -### 格式特性矩阵 - -| 特性 | GLB/GLTF | STL | OBJ | PLY | FBX(转换后) | CAD | -|------|----------|-----|-----|-----|---------------|-----| -| 网格 | 是 | 是 | 是 | 是 | 是 | 是 | -| 点云 | 否 | 否 | 否 | 是 | 否 | 否 | -| 材质 | PBR | 基础 | MTL | 基础 | 基础 | 否 | -| 纹理 | 嵌入式 | 否 | 外部 | 否 | 否 | 否 | -| 颜色 | 顶点 | 面 | 否 | 顶点 | 否 | 面(STEP) | -| 动画 | 是 | 否 | 否 | 否 | 是 | 否 | - ---- - -## 使用方法 - -### 语法指南 - -#### 1. 内联嵌入 - -在笔记中写 Wikilink 即可。阅读模式和实时预览均支持。 - -```markdown -![[model.glb]] -![[model.glb|400x300]] -``` - -#### 2. `3d` 代码块 - -**简单写法** — 只写文件路径: - -````markdown -```3d model.glb -``` -```` -ai-model-workbench/ -**完整配置** — 相机、灯光、场景、多模型: - -````markdown -```3d -{ - "models": [ - { "path": "model.glb" }, - { "path": "part.stl", "color": "#ff0000", "wireframe": true } - ], - "camera": { "fov": 30, "position": [5, 5, 5] }, - "lights": [ - { "type": "hemisphere", "color": "#fff", "intensity": 1 }, - { "type": "directional", "position": [10, 20, 10] } - ], - "scene": { "autoRotate": true, "grid": true }, - "width": "100%", - "height": 500 -} -``` -```` - -| 配置项 | 常用字段 | -|--------|----------| -| `models[]` | `path`(必填)、`color`、`wireframe` | -| `camera` | `fov`、`position`、`lookAt`、`mode`(`"perspective"` / `"orthographic"`) | -| `lights[]` | `type`(`"hemisphere"` `"directional"` `"point"` `"spot"` `"ambient"` `"attachToCam"`)、`color`、`intensity`、`position` | -| `scene` | `background`、`autoRotate`、`autoRotateSpeed`、`grid`、`axis`、`groundShadow`、`transparent` | -| `stl` | `color`、`wireframe`(STL 文件默认值) | -| 顶层 | `width`、`height` | - -#### 3. `3dgrid` 代码块 - -在一个视口中用预设布局渲染多个模型。 - -````markdown -```3dgrid -{ - "models": [ - { "path": "v1.step" }, - { "path": "v2.step" }, - { "path": "v3.step" } - ], - "preset": "compare" -} -``` -```` - -| 预设 | 布局 | -|------|------| -| `compare` | 并排 A/B 对比 | -| `showcase` | 单模型多角度 | -| `explode` | 环形排列 | -| `timeline` | 水平条带 | -| `gallery` | 全部同场景(默认) | -| `compose` | 自定义分区 | - -`3dgrid` 支持与 `3d` 相同的 `camera`、`lights`、`scene`,另有:`preset`、`params`、`columns`、`rowHeight`、`gapX`、`gapY`、`sections`、`direction`。 - -#### 4. 直接打开 - -在文件资源管理器中点击 `.glb`/`.gltf`/`.stl`/`.obj`/`.ply` 文件即可。 - -#### 支持的格式 - -| 类型 | 格式 | -|------|------| -| 直接渲染 | `.glb` `.gltf` `.stl` `.obj` `.ply` | -| 需转换 | `.step` `.stp` `.iges` `.igs` `.brep` `.sldprt` `.3mf` `.dae` `.fbx` | - -### 预览工具栏 - -模型加载完成后,预览区域的工具栏提供以下检查和导出操作: - -| 按钮 | 用途 | -|------|------| -| 复制模型信息 | 将当前模型的网格、三角面、顶点和边界尺寸复制为 Markdown | -| 复制选中部件信息 | 先点击模型中的一个部件,再复制该部件的名称、面数、顶点、材质和包围盒信息 | -| 聚焦选中部件 | 开启后点击部件会弱化其他网格,方便检查类似 `cubie` 这类独立部件 | -| 标签图标 | 进入标注模式,在模型表面添加可持久化的标签 | -| 快照按钮 | 将当前视口复制、保存或下载为 PNG | - -### 键盘快捷键(预览中) - -| 按键 | 功能 | -|------|------| -| `R` | 重置视图 | -| `W` | 切换线框模式 | -| `G` | 切换方向指示器 | -| `B` | 切换包围盒 | -| `空格` | 播放/暂停动画 | -| `Esc` | 退出标注模式 | - -### 3D 标注 - -在模型表面添加带标签的书签。标注按模型文件持久化保存。 - -**直接查看 & 工作台**(编辑模式): - -1. 点击工具栏的 **标签图标**(或工作台面板中的"标注"按钮) -2. 蓝色半透明遮罩表示标注模式已激活 -3. 点击模型表面放置标注点 -4. 在弹出编辑器中输入标签并选择颜色 -5. 点击已有标注可编辑标签/颜色或删除 -6. 点击工作台面板中的标签文字,相机自动平滑旋转到该位置 -7. 按 `Esc` 退出标注模式 - -**深度遮挡**:被模型遮挡的标注显示为半透明模糊状态。相机移动时遮挡会分批刷新,避免已有书签在旋转模型时明显延迟;空闲后叠层会按完整刷新节奏补齐。 - -**代码块 & 实时预览**:已保存的标注以只读方式显示,具有相同的遮挡效果。 - ---- - -### 知识笔记 - -工作台里的“生成笔记”会生成基于证据的 Markdown,而不是单纯模板。每次生成会写入: - -- `Analysis/3D Reports` 下的模型报告 -- 一个 JSON analysis sidecar,包含预览摘要、部件候选、知识节点、资源警告和 pipeline 元数据 -- `Analysis/3D Reports` 下的模型知识索引,把报告、sidecar、证据截图、标注和部件笔记集中到一个入口 -- `Parts/3D Components` 下最多 8 个第一版部件笔记草稿,并从报告和 sidecar 中建立链接;已有部件笔记不会被覆盖 -- `Media/3D Previews` 下的当前视口证据截图 -- 一个可直接编辑的本地草稿,把捕获到的证据、标注、标签和 profile notes 组织成第一版知识笔记正文,并附带本地草稿元数据、建议标签和下一步动作 - -默认本地分析不会把模型数据发送到远程服务。它会先用渲染器证据、已保存标注、标签和 profile notes 建立后续 AI 草稿所需的 grounding 层。对于带有命名内部 group/assembly 的 GLB/GLTF,渲染器会自动把这些分组注册为更高置信度的部件候选,同时保留未归组 mesh 作为独立候选。直接文件视图在模型加载成功后会立刻把捕获到的候选零件写入模型 profile,所以后续导入的模型即使还没生成完整报告,也能识别疑似复用零件。生成笔记时,当前部件候选还会和其他 profile 或已分析模型 sidecar 中注册过的部件做本地相似度匹配,把疑似复用组件链接回已有部件笔记,方便人工复核。 - -报告生成后,可以在 direct workbench 使用“打开索引”,或在命令面板执行“打开知识索引”,直接回到该模型的知识地图入口。 - -如需接入可选远程草稿,可在设置里选择“本地证据 + 远程草稿”或“基于证据的远程草稿”,并填写草稿服务 URL。客户端会向 `POST /draft-note` 发送经过裁剪的 drafting input。原始模型上传会被阻止;几何摘要和预览图引用都由单独的隐私开关控制。 - ---- - -## 设置选项 - -| 设置项 | 默认值 | 说明 | -|--------|--------|------| -| 语言 | 自动 | 界面语言(英文 / 简体中文 / 自动检测) | -| 标注预览模式 | plain-text | 控制已保存标注内容在只读预览中的渲染方式 | -| AI 草稿模式 | 仅本地证据 | 默认保持本地生成;配置远程服务后才请求远程草稿 | -| 草稿服务 URL | 空 | 接收 `POST /draft-note` 的服务基础地址 | -| 预览兼容模式 | 阅读 + 文件视图 | 控制新的单模型 GLB 预览路径启用范围 | -| 实验性 Three 工作台 | 关 | 仅对直读 GLB/GLTF 文件视图尝试 Three.js workbench,失败时自动回退 Babylon.js | -| 画布高度 | 400 | 预览高度(像素) | -| 自动旋转 | 关 | 启动时启用旋转动画 | -| 自动旋转速度 | 0.5 | 旋转速度(0.1-2.0) | -| 渲染质量 | 高 | 质量预设(低/中/高) | -| 渲染缩放 | 1.0 | 分辨率倍数(0.25-2.0) | -| 快照文件夹 | Media/3D Previews | 导出文件夹 | -| 快照命名 | model-name | 导出 PNG 快照时的文件命名方式 | -| 报告文件夹 | Analysis/3D Reports | 知识笔记文件夹 | -| 部件笔记文件夹 | Parts/3D Components | 保存生成的部件笔记草稿 | -| 日志级别 | warn | 控制台日志详细程度 | - -### 转换器设置 - -| 设置项 | 说明 | -|--------|------| -| 启用 CAD 转换器 | 通过 CadQuery 启用 STEP/IGES/BREP | -| 启用 SLDPRT 转换器 | 通过 FreeCAD 启用 SolidWorks | -| 启用网格转换器 | 通过 trimesh 启用 3MF/DAE | -| 启用 OBJ2GLTF 转换器 | 可选,通过 obj2gltf 标准化 OBJ | -| 启用 FBX2glTF 转换器 | 通过 FBX2glTF 启用 FBX 转换 | -| Python 命令路径(CAD 用) | 覆盖 STEP/IGES/BREP 转换使用的 Python 可执行文件 | -| FreeCADCmd 路径(SLDPRT 用) | 覆盖 `.sldprt` 转换使用的 FreeCAD 可执行文件 | -| obj2gltf 命令路径 | 覆盖 obj2gltf CLI 路径 | -| FBX2glTF 命令路径 | 覆盖 FBX2glTF CLI 路径 | -| Python 命令路径(3MF/DAE 用) | 覆盖 3MF/DAE 转换使用的 Python 可执行文件 | -| 转换器命令诊断 | 显示插件当前实际会使用的可执行文件路径,并为 Python 环境和转换器命令运行轻量自检 | - -### 可移植性与诊断 - -渲染层本身具备较好的跨平台可移植性:GLB、OBJ、STL、PLY 以及已经生成好的 `.ai3d-converted.glb`,只要 Obsidian Desktop 能提供 WebGL 就可以显示。 - -在 iOS、iPadOS 和 Android 上,插件现已支持 GLB、GLTF、OBJ、STL、PLY 等直读格式。CAD、FBX、3MF、DAE、SLDPRT 这类需要本地转换器的路线仍然只支持桌面端,因为它们依赖外部 CLI 工具和 Python 环境。 - -转换层的可移植性较弱,因为它依赖每台机器本地安装的工具和 Python 环境。当 CAD 或网格格式加载失败时,优先看插件设置里的转换器诊断面板。它会同时检查插件最终解析到的可执行文件路径,以及当前 Python 环境能否导入所需依赖,或原生命令行转换器是否能够启动。 - -如果你是在这个仓库里继续开发,请先看 [docs/cross-platform-development.md](docs/cross-platform-development.md) 里的项目级实现准则。 - -尤其在 macOS 上,系统自带的 `/usr/bin/python3` 往往存在,但并不包含 CAD 依赖。如果诊断面板显示使用的是这个路径且自检失败,应安装一个独立的 Python 环境,并在插件设置里显式填入那个解释器路径。 - ---- - -## 外部依赖 - -仅 CAD、FBX 和网格转换需要外部工具。直接格式无需任何外部工具。 - -### Python + CadQuery(STEP、IGES、BREP) - -```bash -# 安装 -pip install cadquery trimesh -``` - -按你的系统使用对应的 Python 命令验证: - -- Windows:`py -c "import cadquery; print('OK')"` -- macOS / Linux:`python3 -c "import cadquery; print('OK')"` - -如果诊断面板在 macOS 上解析到 `/usr/bin/python3` 且导入检查失败,请安装独立 Python(例如 Homebrew Python),在那个环境里安装 `cadquery` 和 `trimesh`,然后把该解释器路径填入插件设置。 - -### FreeCAD(SLDPRT) - -按平台安装 FreeCAD: - -- Windows:从 [freecad.org/downloads](https://www.freecad.org/downloads.php) 安装 -- macOS:安装官方 app,或使用 `brew install --cask freecad` -- Linux:安装发行版提供的 FreeCAD 包,并确保 `freecadcmd` 可用 - -插件会优先使用显式设置值和环境变量,其次检查常见的用户管理安装位置,再检查 PATH,最后再回退到下面这些系统级安装位置提示: -- Windows:`%LOCALAPPDATA%\Programs\FreeCAD*\bin\FreeCADCmd.exe` -- macOS:`/Applications/FreeCAD.app/Contents/MacOS/FreeCADCmd`、`/usr/local/bin/FreeCADCmd`、`/opt/homebrew/bin/FreeCADCmd` -- Linux:`/usr/bin/freecadcmd` - -### Python + trimesh(3MF、DAE) - -```bash -pip install trimesh numpy networkx pycollada -``` - -**自动发现**:使用与 CadQuery 相同的 Python 发现逻辑。 - -**覆盖方式**:环境变量 `AI3D_ASSIMP_CMD`。 - -### obj2gltf(OBJ,可选) - -插件已经内置 OBJ 加载器。obj2gltf 是可选替代方案,可用于生成更标准的 GLB 输出。 - -**安装**: - -```bash -npm install -g obj2gltf -``` - -**解析顺序**:插件会优先使用显式设置值和环境变量,其次检查常见的用户管理安装位置,再检查 PATH,最后再回退到系统级提示位置,例如 Windows 下的 `obj2gltf.cmd`,以及 macOS / Linux 下标准位置中的 `obj2gltf`,如 `/usr/local/bin/obj2gltf`、`/opt/homebrew/bin/obj2gltf`。 - -**启用**:设置 > 启用 OBJ2GLTF 转换器,或设置 obj2gltf 命令路径。 - -### FBX2glTF(FBX) - -FBX 文件通过本地 FBX2glTF 二进制转换为 GLB。旧的社区 FBX 加载器没有打包进插件,因为它当前版本面向 Babylon.js 8,而本插件使用 Babylon.js 9。 - -**安装**: - -下载或自行构建适用于你平台的 [FBX2glTF](https://github.com/godotengine/FBX2glTF),并将二进制文件放到可发现的位置。 - -**解析顺序**:插件会优先使用显式设置值和环境变量,其次检查常见的用户管理安装位置,再检查 PATH,最后再回退到下面这些系统级安装位置提示: - -```text -C:\Program Files\FBX2glTF\FBX2glTF-windows-x64.exe -C:\Program Files\FBX2glTF\FBX2glTF.exe -/usr/local/bin/FBX2glTF -/opt/homebrew/bin/FBX2glTF -/usr/local/bin/fbx2gltf -``` - -**启用**:设置 > 启用 FBX2glTF 转换器,或设置 FBX2glTF 命令路径。 - -### 环境变量 - -| 变量 | 用途 | -|------|------| -| `AI3D_FREECAD_CMD` | CadQuery 的 Python 命令 | -| `AI3D_FREECADCMD` | FreeCADCmd 路径 | -| `AI3D_ASSIMP_CMD` | trimesh 的 Python 命令 | -| `AI3D_OBJ2GLTF_CMD` | obj2gltf 命令路径 | -| `AI3D_FBX2GLTF_CMD` | FBX2glTF 命令路径 | - -兼容旧配置时仍接受历史别名 `AI3D_FREECMDCMD`,但新配置应统一使用 `AI3D_FREECADCMD`。 - ---- - -## 技术细节 - -### 架构 - -``` -src/ -├── main.ts # 插件生命周期、命令 -├── domain/ -│ ├── models.ts # 共享接口 -│ └── constants.ts # 默认设置、扩展名 -├── store/ -│ ├── create-store.ts # 自定义 store 原语 -│ └── plugin-store.ts # Obsidian saveData 桥接 -├── render/ -│ ├── preview/ # 渲染器无关抽象层 -│ │ ├── types.ts # ModelPreview、AnnotationPreview、WorkbenchPreview 接口 -│ │ ├── routing.ts # Three/Babylon 路由决策 -│ │ ├── factory.ts # 渲染器动态导入工厂 -│ │ ├── selection.ts # 预览选择与日志 -│ │ ├── annotations.ts # AnnotationManager(标注叠层 + 遮挡) -│ │ ├── geometry.ts # 渲染器无关向量运算 -│ │ ├── bounds.ts # 包围盒工具 -│ │ ├── camera-fit.ts # 相机适配算法 -│ │ ├── disassembly.ts # 拆解控制器(适配器模式) -│ │ ├── explode.ts # 爆炸视图(适配器模式) -│ │ ├── report.ts # Markdown 报告生成 -│ │ └── summary.ts # 模型/零件摘要创建 -│ ├── three/ # Three.js 渲染器 -│ │ ├── scene.ts # ThreeModelPreview 类(GLB/GLTF/STL/PLY/OBJ) -│ │ ├── loaders.ts # 格式专用加载器,含 vault MTL 解析 -│ │ ├── disassembly.ts # ThreeDisassemblyAdapter -│ │ └── explode.ts # ThreeExplodeAdapter -│ ├── babylon/ # Babylon.js 渲染器 -│ │ ├── scene.ts # BabylonModelPreview 类 -│ │ ├── grid.ts # GridRenderer 类 -│ │ ├── loaders/ -│ │ │ ├── stl-loader.ts # 自定义二进制 STL 解析器 -│ │ │ ├── ply-loader.ts # 自定义 ASCII/二进制 PLY 解析器 -│ │ │ └── register.ts # Babylon SceneLoader 插件 -│ │ └── presets/ # 网格布局预设 -├── io/ -│ ├── formats/ -│ │ └── registry.ts # 格式能力注册表 -│ ├── conversion/ -│ │ ├── manager.ts # 转换编排 -│ │ └── adapters/ # 转换器实现 -│ └── model-pipeline.ts # 格式路由逻辑 -└── view/ - ├── workbench/ # 主工作台 UI - ├── inline/ # 代码块、实时预览 - └── direct-view.ts # 直接文件打开 -``` - -### 模型导入管线 - -``` -┌─────────────────────────────────────────────────────────────┐ -│ 1. 格式检测 │ -│ └─ getFormatCapability(ext) → { family, strategy } │ -│ │ -│ 2. 路由决策 │ -│ ├─ strategy: "direct" → prepareDirectLoad() │ -│ └─ strategy: "convert" → convertForPreview() │ -│ │ -│ 3. 数据加载 │ -│ ├─ readBinaryPath() → ArrayBuffer │ -│ └─ [如已转换] → 读取转换后的 .glb │ -│ │ -│ 4. Babylon 渲染 │ -│ ├─ GLB/GLTF/OBJ → SceneLoader.ImportMeshAsync() │ -│ ├─ STL → loadSTLBuffer()(直接解析) │ -│ └─ PLY → loadPLYBuffer()(直接解析) │ -└─────────────────────────────────────────────────────────────┘ -``` - -### 为什么 STL/PLY 使用直接缓冲区加载 - -Babylon.js v9 的 SceneLoader 存在一个 bug:自定义插件在通过 `SceneLoader.ImportMeshAsync()` 加载时,接收到的是 data URL 字符串而非 ArrayBuffer。内置加载器(GLTF、OBJ)不受影响。 - -**解决方案**:STL 和 PLY 解析器直接使用原始 ArrayBuffer 调用,完全绕过 SceneLoader。 - -### 转换缓存 - -- **位置**:与源文件相同目录 -- **格式**:`{filename}.ai3d-converted.glb` -- **验证**:检查转换器身份、缓存键、文件存在性 -- **失效**:转换器设置更改时自动失效 -- **手动清除**:命令面板 > "Clear Conversion Cache" - ---- - -## 已知限制 - -| 问题 | 受影响格式 | 解决方法 | -|------|-----------|---------| -| 需要外部转换器 | FBX | 安装并启用 FBX2glTF | -| 需要外部工具 | STEP/IGES/BREP/SLDPRT | 安装 Python + CadQuery 或 FreeCAD | -| 纹理路径解析 | OBJ | 将纹理放在 OBJ/MTL 同一目录;缺失纹理会显示非阻塞资源提示 | -| 外部资源路径解析 | GLTF | 将 `.bin` 和纹理保留在 vault 中,并按 `.gltf` 引用的相对路径放置 | -| 转换超时 | SLDPRT | 复杂装配体有 10 分钟超时 | - ---- - -## 部署指南 - -### 前置要求 - -- Node.js >= 18 -- npm >= 9 -- Obsidian >= 1.5.0 - -### 构建命令 - -```bash -npm install # 安装依赖 -npm run dev # 开发构建(监听模式) -npm run build # 生产构建 -npm run typecheck # TypeScript 类型检查 -npm run verify:preview # 定向浏览器预览冒烟验证 -npm run verify:preview:success # 完整预览路由成功套件 -npm run verify:obsidian # Obsidian 应用端到端冒烟验证 -npm run verify:release # 发布资产版本/hash/体积检查 -npm run verify:settings # 旧 data.json/default settings 迁移检查 -npm run verify:remote-draft # 远程草稿隐私/客户端行为检查 -npm run verify:knowledge-index # 知识索引链接和刷新回归检查 -npm run verify:diagnostics # 脱敏诊断报告回归检查 -``` - -### 预览验证 - -在提交预览相关改动前,建议运行 `npm run verify:preview:success`。如果只想检查当前默认路径,`npm run verify:preview` 仍然可用。验证脚本会自动识别 Windows、macOS 和 Linux 上常见的 Chrome、Edge、Chromium 与 Brave;只有使用自定义浏览器路径时才需要设置 `PLAYWRIGHT_CHROMIUM_EXECUTABLE`。完整成功套件会启动一个临时的 Playwright 验证页面,加载 `models/rubiks-cube-3x3.glb`,并验证: - -- 默认 simple `GLB` 预览 -- 默认 direct-edit `GLB` 预览 -- 默认 readonly saved-pin `GLB` 预览 -- “仅阅读场景”档位的路由行为 -- “兼容优先”回退档位的路由行为 -- workbench Babylon 回退路由和实验性 Three.js workbench 能力探针 -- `STL`、`PLY`、`OBJ` 直读格式预览路由 -- helper toolbar 交互、聚焦模式、旋转时标注遮挡刷新、选中部件导出、性能快照,以及滚轮不带动页面滚动 - -如果验证失败,脚本会把截图以及包含预览状态和浏览器消息的日志保存到 `.tmp/preview-failures/`。 - -### Obsidian 验证 - -在 macOS 且已安装 Obsidian 时,发布前运行 `npm run verify:obsidian`。脚本会在 `/tmp/ai-model-workbench-verify-vault` 下创建临时测试库,安装当前打包插件,通过远程调试端口打开测试笔记,按需信任临时 vault,确认 GLB/STL 预览 canvas 已加载,检查未启用 FBX2glTF 时的 FBX 转换反馈,然后打开真实 GLB 文件视图并启用实验性 Three workbench,检查 backend 选择、聚焦/分解控件、面板爆炸控件、标注模式和知识笔记生成。 - -如果想在验证结束后删除临时库,使用 `npm run verify:obsidian -- --clean`。在 macOS 上,clean 流程会先退出 Obsidian,并从 Obsidian 配置中注销该临时库,再删除 `/tmp` 目录,避免开发者控制台继续刷旧路径的 `ENOENT`。 - -### 知识笔记验证 - -修改生成报告、零件草稿或模型索引行为后,运行 `npm run verify:knowledge-index`。脚本会用一个极小的 Obsidian shim 打包知识笔记 helper,构建代表性的模型索引,刷新 AI 托管区,并确认用户手写笔记不会被覆盖。 - -### 构建输出 - -``` -ai-model-workbench/ -├── main.js # ~3.8 MB(压缩后的插件运行时 bundle) -├── manifest.json # 插件清单 -├── styles.css # 插件样式 -└── src/ # 源代码 -``` - -### 发布流程 - -发布由 GitHub Actions 的 `Release` workflow 完成。推送一个与 `manifest.json` 版本匹配的 tag,例如 `0.4.0`,或手动运行该 workflow。它只上传 `main.js`、`manifest.json` 和 `styles.css`,会删除不受支持的 release asset,校验资产体积与 SHA-256 hash,并为发布文件生成 GitHub artifact attestation。发布完成后可运行 `npm run verify:obsidian -- --release-tag 0.4.0`,从 GitHub release 下载资产并安装到临时 Obsidian vault 做实机验证。 - -### 发布 Token 安全 - -发布优先使用 GitHub Actions 或 GitHub CLI 浏览器登录。Token 安全清单和 PAT 泄露处理流程见 `SECURITY.md`。 - -### 平台支持 - -| 平台 | 状态 | -|------|------| -| Windows | 完全支持 | -| macOS | 完全支持 | -| Linux | 完全支持 | -| Obsidian Mobile | 支持(降低分辨率) | - -### 包体积优化 - -渲染运行时是当前包体积的主要来源。项目通过以下方式控制输出体积: - -- 子路径导入(`@babylonjs/core/Engines/engine.js`)而非桶导入 -- Tree-shaking 移除未使用的功能 -- esbuild 进行快速、优化的打包 - -由于当前发布包同时包含 Babylon 和 Three 的预览路径,最终体积会随着路由覆盖面变化而波动。以上构建输出更适合作为当前参考值,而不是固定上限。 - ---- -## 致谢 - -感谢 LinuxDo 社区(https://linux.do)的支持。 +# AI Model Workbench + +> 一个以本地优先和知识库整合为核心的 Obsidian 3D 查看插件,可在本地 WebGL 视口中查看常见 3D 资产、标注关键部位,并将模型整理为可链接的知识笔记。单模型预览(GLB、GLTF、STL、PLY、OBJ)现在默认走 Three.js 渲染路径,可通过“预览兼容模式”回退到 Babylon.js;文件视图 workbench 可以选择启用实验性 Three.js GLB/GLTF 路径,并保留 Babylon.js 自动回退;`3dgrid` 与 SPLAT 仍保留在 Babylon.js 能力路径上。 + +[AI Model Workbench](https://community.obsidian.md/plugins/ai-model-workbench) + +[English](README.md) | **简体中文** + +![preview](docs/assets/preview.gif) + +--- + +## 目录 + +- [功能特性](#功能特性) +- [平台支持矩阵](#平台支持矩阵) +- [快速入门](#快速入门) +- [安装](#安装) +- [格式支持](#格式支持) +- [使用方法](#使用方法) +- [设置选项](#设置选项) +- [外部依赖](#外部依赖) +- [安全与隐私](#安全与隐私) +- [资金与赞助](#资金与赞助) +- [技术细节](#技术细节) +- [已知限制](#已知限制) +- [部署指南](#部署指南) +- [许可证](#许可证) + +--- + +## 功能特性 + +- **直接预览** GLB/GLTF、STL、OBJ、PLY(默认全部走 Three.js 渲染路径) +- **可选转换** CAD、FBX、3MF、DAE 等资产到 GLB +- **混合预览路由**:单模型预览(GLB/GLTF/STL/PLY/OBJ)默认走 Three.js,可在设置中回退到 Babylon.js +- **内联与文件视图**:实时预览、代码块、直接文件查看 +- **网格系统**:在单个视口中渲染多个模型,支持预设布局 +- **3D 标注**:点击模型表面添加带标签和颜色的书签,支持深度遮挡 +- **知识笔记**:从已加载的模型生成结构化 Markdown,并自动注册捕获到的零件候选用于跨模型复用识别 +- **快照功能**:复制、保存或下载渲染预览为 PNG +- **国际化**:英文和简体中文,自动检测系统语言 +- **桌面端支持**:Windows、macOS、Linux 上的 Obsidian Desktop +- **移动端支持**:iOS、iPadOS、Android 支持直读格式和简化后的工作台布局 + +--- + +## 平台支持矩阵 + +| 能力 | Windows / macOS / Linux | iOS / iPadOS / Android | +|------|--------------------------|-------------------------| +| 直读格式(GLB、GLTF、OBJ、STL、PLY) | 支持 | 支持 | +| 直接文件查看 | 支持 | 支持 | +| 直读格式的内联嵌入 / 实时预览 | 支持 | 支持 | +| 工作台布局 | 完整桌面布局 | 简化单列移动布局 | +| 本地转换(CAD、FBX、3MF、DAE、SLDPRT) | 支持 | 不支持 | +| 转换器诊断与本地 CLI 自检 | 支持 | 不支持 | +| 已生成的 `.ai3d-converted.glb` 资产 | 支持 | 支持 | + +--- + +## 快速入门 + +1. 构建插件: + +```bash +npm install +npm run build +``` + +2. 打开你电脑上的本地 Obsidian vault 文件夹。 + +3. 在该 vault 里创建这个文件夹: + +```text +/.obsidian/plugins/ai-model-workbench/ +``` + +4. 把 `main.js`、`manifest.json`、`styles.css` 复制到这个文件夹里。 + +5. 在 Obsidian 中打开“设置 > 社区插件”,启用 `AI Model Workbench`。 + +6. 把一个受支持的模型文件放进同一个 vault,例如 `model.glb`。 + +7. 在该 vault 的任意笔记中这样嵌入: + +```markdown +![[model.glb]] +![[model.glb|400x300]] +``` + +--- + +## 安装 + +如果你只想最快跑起来,直接看上面的 [快速入门](#快速入门)。 + +### 前提 + +- Obsidian 1.5.0 或更高版本 +- 需要 Windows、macOS 或 Linux 上的 Obsidian Desktop 才能使用本地转换工具 +- 你电脑上的本地 Obsidian vault 文件夹 +- vault 里的插件目录: + +```text +/.obsidian/plugins/ai-model-workbench/ +``` + +无论用哪种方式安装,最终都要把下面这三个文件放进这个目录: + +| 文件 | 大小 | 说明 | +|------|------|------| +| `main.js` | ~3.8 MB | 插件运行时 bundle | +| `manifest.json` | ~1 KB | Obsidian 插件清单 | +| `styles.css` | ~5 KB | 插件样式 | + +直接渲染在桌面端和移动端都可用。CAD、FBX、3MF、DAE 的本地转换工具只适用于桌面系统。 + +### 方式 A:从源码构建 + +1. 克隆仓库并构建插件: + +```bash +git clone https://github.com/flash555588/ai-model-workbench.git +cd ai-model-workbench +npm install +npm run build +``` + +2. 把构建产物安装到 vault: + +```bash +# 安装到仓库自带的测试 vault +npm run install:vault + +# 或安装到你自己的 vault +npm run install:vault -- --vault "C:\path\to\your-vault" +``` + +安装脚本会把 `main.js`、`manifest.json`、`styles.css` 复制到 `.obsidian/plugins/ai-model-workbench/`,并在 `community-plugins.json` 中启用 `ai-model-workbench`。 + +3. 如果 Obsidian 已经打开,重新加载应用,或在“设置 > 社区插件”中禁用再启用 `AI Model Workbench`。 + +手动备选:创建 `/.obsidian/plugins/ai-model-workbench/`,把 `main.js`、`manifest.json`、`styles.css` 复制进去,然后在 Obsidian 中启用 `AI Model Workbench`。 + +### 方式 B:下载发布版 + +1. 从 [Releases](https://github.com/flash555588/ai-model-workbench/releases) 下载 `main.js`、`manifest.json` 和 `styles.css`。 +2. 如果 `/.obsidian/plugins/ai-model-workbench/` 还不存在,先创建它。 +3. 把这三个文件放进这个文件夹里。 +4. 在 Obsidian 的“设置 > 社区插件”中启用 `AI Model Workbench`。 + +### 方式 C:开发用符号链接 + +1. 先确认 `/.obsidian/plugins/` 已经存在。 +2. 创建一个名为 `ai-model-workbench` 的符号链接,指向当前仓库。 + +Windows(PowerShell): + +```powershell +New-Item -ItemType SymbolicLink ` + -Path "C:\path\to\your-vault\.obsidian\plugins\ai-model-workbench" ` + -Target "C:\path\to\ai-model-workbench" +``` + +macOS / Linux: + +```bash +ln -s /path/to/ai-model-workbench \ + /path/to/your-vault/.obsidian/plugins/ai-model-workbench +``` + +3. 如果还没装依赖,先在当前仓库运行一次 `npm install`。 +4. 开发时运行 `npm run dev`。 +5. 在 Obsidian 的“设置 > 社区插件”中启用 `AI Model Workbench`。 + +### 安装后 + +1. 先把一个受支持的模型文件放进同一个 vault,例如 `model.glb`。 +2. 然后在该 vault 的任意笔记中这样嵌入: + +```markdown +![[model.glb]] +![[model.glb|400x300]] +``` + +--- + +## 安全与隐私 + +AI Model Workbench 不收集遥测数据,不会主动回传,也不会运行后台网络同步。模型预览读取的是已经存在于 Obsidian vault 中的本地文件;OBJ 的 MTL 材质和纹理引用会从 vault 内解析,而不是从网络下载。 + +打包后的 Babylon.js 运行时包含面向 Web 应用的通用 URL 加载工具。该插件会把 vault 文件字节以 data URL 传给 Babylon,覆盖 OBJ MTL 加载逻辑以避免远程请求,并在运行时显式拒绝 `http(s)` / `ws(s)` 资产与脚本 URL,同时关闭 Babylon 对这类请求的重试钩子。可选的转换器诊断和格式转换只会在用户主动操作后运行,并且只在桌面端调用本地工具。 + +知识笔记生成默认保持本地-only。如果你配置了可选远程草稿服务,插件只会向你填写的 `POST /draft-note` 端点发送被允许的证据 payload。当前客户端拒绝上传原始模型;几何摘要和预览图引用必须分别显式开启后才会包含在请求中。 + +发布资产仅限 Obsidian 会下载的三个文件:`main.js`、`manifest.json` 和 `styles.css`。GitHub Actions 会从源码构建这些文件,并为它们发布 artifact attestation,便于验证来源。 + +--- + +## 资金与赞助 + +AI Model Workbench 的插件包中不包含赞助提示、付款流程或加密货币钱包地址。 + +--- + +## 格式支持 + +### 直接渲染(无需外部工具) + +| 格式 | 扩展名 | 特性 | +|------|--------|------| +| GLB / GLTF | `.glb` `.gltf` | PBR 材质、动画、纹理、场景层级;`.gltf` 会解析 vault 内相对路径的 `.bin` 与纹理 | +| STL | `.stl` | 二进制格式、逐面颜色(VisCAM/SolidView) | +| OBJ | `.obj` | MTL 材质、库内相对路径纹理解析、同目录大小写兜底 | +| PLY | `.ply` | ASCII/二进制、顶点颜色、点云支持 | + +当前打包版本临时关闭 SPLAT 预览,直到其加载器替换为纯本地实现。 + +### SPLAT 说明与规划 + +- 当前状态:社区发布版暂时关闭 SPLAT 预览,GLB、GLTF、STL、OBJ、PLY 以及现有本地转换路线不受影响。 +- 原因:现阶段 Babylon 上游 SPLAT/SPZ loader 仍带有动态脚本与远程模块回退路径。插件运行时已经拒绝远程请求,但发布版希望进一步把这类加载路径从最终产物中剥离,降低审核和静态扫描风险。 +- 未来规划:第一步恢复纯本地 `.splat` 直读;第二步在 Windows 和大场景下完成静止/空闲渲染稳定性优化后再重新开放;第三步再单独评估 `.spz`,只有在解码依赖可以完整本地打包并通过审查时才会重新启用。 + +### 转换(需要外部工具) + +| 格式 | 扩展名 | 转换器 | 输出 | +|------|--------|--------|------| +| STEP | `.step` `.stp` | Python + CadQuery/OCCT | GLB | +| IGES | `.iges` `.igs` | Python + CadQuery/OCCT | GLB | +| BREP | `.brep` | Python + CadQuery/OCCT | GLB | +| SLDPRT | `.sldprt` | FreeCAD | GLB | +| 3MF | `.3mf` | Python + trimesh | GLB | +| DAE | `.dae` | Python + trimesh | GLB | +| FBX | `.fbx` | FBX2glTF | GLB | + +### 格式特性矩阵 + +| 特性 | GLB/GLTF | STL | OBJ | PLY | FBX(转换后) | CAD | +|------|----------|-----|-----|-----|---------------|-----| +| 网格 | 是 | 是 | 是 | 是 | 是 | 是 | +| 点云 | 否 | 否 | 否 | 是 | 否 | 否 | +| 材质 | PBR | 基础 | MTL | 基础 | 基础 | 否 | +| 纹理 | 嵌入式 | 否 | 外部 | 否 | 否 | 否 | +| 颜色 | 顶点 | 面 | 否 | 顶点 | 否 | 面(STEP) | +| 动画 | 是 | 否 | 否 | 否 | 是 | 否 | + +--- + +## 使用方法 + +### 语法指南 + +#### 1. 内联嵌入 + +在笔记中写 Wikilink 即可。阅读模式和实时预览均支持。 + +```markdown +![[model.glb]] +![[model.glb|400x300]] +``` + +#### 2. `3d` 代码块 + +**简单写法** — 只写文件路径: + +````markdown +```3d model.glb +``` +```` +ai-model-workbench/ +**完整配置** — 相机、灯光、场景、多模型: + +````markdown +```3d +{ + "models": [ + { "path": "model.glb" }, + { "path": "part.stl", "color": "#ff0000", "wireframe": true } + ], + "camera": { "fov": 30, "position": [5, 5, 5] }, + "lights": [ + { "type": "hemisphere", "color": "#fff", "intensity": 1 }, + { "type": "directional", "position": [10, 20, 10] } + ], + "scene": { "autoRotate": true, "grid": true }, + "width": "100%", + "height": 500 +} +``` +```` + +| 配置项 | 常用字段 | +|--------|----------| +| `models[]` | `path`(必填)、`color`、`wireframe` | +| `camera` | `fov`、`position`、`lookAt`、`mode`(`"perspective"` / `"orthographic"`) | +| `lights[]` | `type`(`"hemisphere"` `"directional"` `"point"` `"spot"` `"ambient"` `"attachToCam"`)、`color`、`intensity`、`position` | +| `scene` | `background`、`autoRotate`、`autoRotateSpeed`、`grid`、`axis`、`groundShadow`、`transparent` | +| `stl` | `color`、`wireframe`(STL 文件默认值) | +| 顶层 | `width`、`height` | + +#### 3. `3dgrid` 代码块 + +在一个视口中用预设布局渲染多个模型。 + +````markdown +```3dgrid +{ + "models": [ + { "path": "v1.step" }, + { "path": "v2.step" }, + { "path": "v3.step" } + ], + "preset": "compare" +} +``` +```` + +| 预设 | 布局 | +|------|------| +| `compare` | 并排 A/B 对比 | +| `showcase` | 单模型多角度 | +| `explode` | 环形排列 | +| `timeline` | 水平条带 | +| `gallery` | 全部同场景(默认) | +| `compose` | 自定义分区 | + +`3dgrid` 支持与 `3d` 相同的 `camera`、`lights`、`scene`,另有:`preset`、`params`、`columns`、`rowHeight`、`gapX`、`gapY`、`sections`、`direction`。 + +#### 4. 直接打开 + +在文件资源管理器中点击 `.glb`/`.gltf`/`.stl`/`.obj`/`.ply` 文件即可。 + +#### 支持的格式 + +| 类型 | 格式 | +|------|------| +| 直接渲染 | `.glb` `.gltf` `.stl` `.obj` `.ply` | +| 需转换 | `.step` `.stp` `.iges` `.igs` `.brep` `.sldprt` `.3mf` `.dae` `.fbx` | + +### 预览工具栏 + +模型加载完成后,预览区域的工具栏提供以下检查和导出操作: + +| 按钮 | 用途 | +|------|------| +| 复制模型信息 | 将当前模型的网格、三角面、顶点和边界尺寸复制为 Markdown | +| 复制选中部件信息 | 先点击模型中的一个部件,再复制该部件的名称、面数、顶点、材质和包围盒信息 | +| 聚焦选中部件 | 开启后点击部件会弱化其他网格,方便检查类似 `cubie` 这类独立部件 | +| 标签图标 | 进入标注模式,在模型表面添加可持久化的标签 | +| 快照按钮 | 将当前视口复制、保存或下载为 PNG | + +### 键盘快捷键(预览中) + +| 按键 | 功能 | +|------|------| +| `R` | 重置视图 | +| `W` | 切换线框模式 | +| `G` | 切换方向指示器 | +| `B` | 切换包围盒 | +| `空格` | 播放/暂停动画 | +| `Esc` | 退出标注模式 | + +### 3D 标注 + +在模型表面添加带标签的书签。标注按模型文件持久化保存。 + +**直接查看 & 工作台**(编辑模式): + +1. 点击工具栏的 **标签图标**(或工作台面板中的"标注"按钮) +2. 蓝色半透明遮罩表示标注模式已激活 +3. 点击模型表面放置标注点 +4. 在弹出编辑器中输入标签并选择颜色 +5. 点击已有标注可编辑标签/颜色或删除 +6. 点击工作台面板中的标签文字,相机自动平滑旋转到该位置 +7. 按 `Esc` 退出标注模式 + +**深度遮挡**:被模型遮挡的标注显示为半透明模糊状态。相机移动时遮挡会分批刷新,避免已有书签在旋转模型时明显延迟;空闲后叠层会按完整刷新节奏补齐。 + +**代码块 & 实时预览**:已保存的标注以只读方式显示,具有相同的遮挡效果。 + +--- + +### 知识笔记 + +工作台里的“生成笔记”会生成基于证据的 Markdown,而不是单纯模板。每次生成会写入: + +- `Analysis/3D Reports` 下的模型报告 +- 一个 JSON analysis sidecar,包含预览摘要、部件候选、知识节点、资源警告和 pipeline 元数据 +- `Analysis/3D Reports` 下的模型知识索引,把报告、sidecar、证据截图、标注和部件笔记集中到一个入口 +- `Parts/3D Components` 下最多 8 个第一版部件笔记草稿,并从报告和 sidecar 中建立链接;已有部件笔记不会被覆盖 +- `Media/3D Previews` 下的当前视口证据截图 +- 一个可直接编辑的本地草稿,把捕获到的证据、标注、标签和 profile notes 组织成第一版知识笔记正文,并附带本地草稿元数据、建议标签和下一步动作 + +默认本地分析不会把模型数据发送到远程服务。它会先用渲染器证据、已保存标注、标签和 profile notes 建立后续 AI 草稿所需的 grounding 层。对于带有命名内部 group/assembly 的 GLB/GLTF,渲染器会自动把这些分组注册为更高置信度的部件候选,同时保留未归组 mesh 作为独立候选。直接文件视图在模型加载成功后会立刻把捕获到的候选零件写入模型 profile,所以后续导入的模型即使还没生成完整报告,也能识别疑似复用零件。生成笔记时,当前部件候选还会和其他 profile 或已分析模型 sidecar 中注册过的部件做本地相似度匹配,把疑似复用组件链接回已有部件笔记,方便人工复核。 + +报告生成后,可以在 direct workbench 使用“打开索引”,或在命令面板执行“打开知识索引”,直接回到该模型的知识地图入口。 + +如需接入可选远程草稿,可在设置里选择“本地证据 + 远程草稿”或“基于证据的远程草稿”,并填写草稿服务 URL。客户端会向 `POST /draft-note` 发送经过裁剪的 drafting input。原始模型上传会被阻止;几何摘要和预览图引用都由单独的隐私开关控制。 + +--- + +## 设置选项 + +| 设置项 | 默认值 | 说明 | +|--------|--------|------| +| 语言 | 自动 | 界面语言(英文 / 简体中文 / 自动检测) | +| 标注预览模式 | plain-text | 控制已保存标注内容在只读预览中的渲染方式 | +| AI 草稿模式 | 仅本地证据 | 默认保持本地生成;配置远程服务后才请求远程草稿 | +| 草稿服务 URL | 空 | 接收 `POST /draft-note` 的服务基础地址 | +| 预览兼容模式 | 阅读 + 文件视图 | 控制新的单模型 GLB 预览路径启用范围 | +| 实验性 Three 工作台 | 关 | 仅对直读 GLB/GLTF 文件视图尝试 Three.js workbench,失败时自动回退 Babylon.js | +| 画布高度 | 400 | 预览高度(像素) | +| 自动旋转 | 关 | 启动时启用旋转动画 | +| 自动旋转速度 | 0.5 | 旋转速度(0.1-2.0) | +| 渲染质量 | 高 | 质量预设(低/中/高) | +| 渲染缩放 | 1.0 | 分辨率倍数(0.25-2.0) | +| 快照文件夹 | Media/3D Previews | 导出文件夹 | +| 快照命名 | model-name | 导出 PNG 快照时的文件命名方式 | +| 报告文件夹 | Analysis/3D Reports | 知识笔记文件夹 | +| 部件笔记文件夹 | Parts/3D Components | 保存生成的部件笔记草稿 | +| 日志级别 | warn | 控制台日志详细程度 | + +### 转换器设置 + +| 设置项 | 说明 | +|--------|------| +| 启用 CAD 转换器 | 通过 CadQuery 启用 STEP/IGES/BREP | +| 启用 SLDPRT 转换器 | 通过 FreeCAD 启用 SolidWorks | +| 启用网格转换器 | 通过 trimesh 启用 3MF/DAE | +| 启用 OBJ2GLTF 转换器 | 可选,通过 obj2gltf 标准化 OBJ | +| 启用 FBX2glTF 转换器 | 通过 FBX2glTF 启用 FBX 转换 | +| Python 命令路径(CAD 用) | 覆盖 STEP/IGES/BREP 转换使用的 Python 可执行文件 | +| FreeCADCmd 路径(SLDPRT 用) | 覆盖 `.sldprt` 转换使用的 FreeCAD 可执行文件 | +| obj2gltf 命令路径 | 覆盖 obj2gltf CLI 路径 | +| FBX2glTF 命令路径 | 覆盖 FBX2glTF CLI 路径 | +| Python 命令路径(3MF/DAE 用) | 覆盖 3MF/DAE 转换使用的 Python 可执行文件 | +| 转换器命令诊断 | 显示插件当前实际会使用的可执行文件路径,并为 Python 环境和转换器命令运行轻量自检 | + +### 可移植性与诊断 + +渲染层本身具备较好的跨平台可移植性:GLB、OBJ、STL、PLY 以及已经生成好的 `.ai3d-converted.glb`,只要 Obsidian Desktop 能提供 WebGL 就可以显示。 + +在 iOS、iPadOS 和 Android 上,插件现已支持 GLB、GLTF、OBJ、STL、PLY 等直读格式。CAD、FBX、3MF、DAE、SLDPRT 这类需要本地转换器的路线仍然只支持桌面端,因为它们依赖外部 CLI 工具和 Python 环境。 + +转换层的可移植性较弱,因为它依赖每台机器本地安装的工具和 Python 环境。当 CAD 或网格格式加载失败时,优先看插件设置里的转换器诊断面板。它会同时检查插件最终解析到的可执行文件路径,以及当前 Python 环境能否导入所需依赖,或原生命令行转换器是否能够启动。 + +如果你是在这个仓库里继续开发,请先看 [docs/cross-platform-development.md](docs/cross-platform-development.md) 里的项目级实现准则。 + +尤其在 macOS 上,系统自带的 `/usr/bin/python3` 往往存在,但并不包含 CAD 依赖。如果诊断面板显示使用的是这个路径且自检失败,应安装一个独立的 Python 环境,并在插件设置里显式填入那个解释器路径。 + +--- + +## 外部依赖 + +仅 CAD、FBX 和网格转换需要外部工具。直接格式无需任何外部工具。 + +### Python + CadQuery(STEP、IGES、BREP) + +```bash +# 安装 +pip install cadquery trimesh +``` + +按你的系统使用对应的 Python 命令验证: + +- Windows:`py -c "import cadquery; print('OK')"` +- macOS / Linux:`python3 -c "import cadquery; print('OK')"` + +如果诊断面板在 macOS 上解析到 `/usr/bin/python3` 且导入检查失败,请安装独立 Python(例如 Homebrew Python),在那个环境里安装 `cadquery` 和 `trimesh`,然后把该解释器路径填入插件设置。 + +### FreeCAD(SLDPRT) + +按平台安装 FreeCAD: + +- Windows:从 [freecad.org/downloads](https://www.freecad.org/downloads.php) 安装 +- macOS:安装官方 app,或使用 `brew install --cask freecad` +- Linux:安装发行版提供的 FreeCAD 包,并确保 `freecadcmd` 可用 + +插件会优先使用显式设置值和环境变量,其次检查常见的用户管理安装位置,再检查 PATH,最后再回退到下面这些系统级安装位置提示: +- Windows:`%LOCALAPPDATA%\Programs\FreeCAD*\bin\FreeCADCmd.exe` +- macOS:`/Applications/FreeCAD.app/Contents/MacOS/FreeCADCmd`、`/usr/local/bin/FreeCADCmd`、`/opt/homebrew/bin/FreeCADCmd` +- Linux:`/usr/bin/freecadcmd` + +### Python + trimesh(3MF、DAE) + +```bash +pip install trimesh numpy networkx pycollada +``` + +**自动发现**:使用与 CadQuery 相同的 Python 发现逻辑。 + +**覆盖方式**:环境变量 `AI3D_ASSIMP_CMD`。 + +### obj2gltf(OBJ,可选) + +插件已经内置 OBJ 加载器。obj2gltf 是可选替代方案,可用于生成更标准的 GLB 输出。 + +**安装**: + +```bash +npm install -g obj2gltf +``` + +**解析顺序**:插件会优先使用显式设置值和环境变量,其次检查常见的用户管理安装位置,再检查 PATH,最后再回退到系统级提示位置,例如 Windows 下的 `obj2gltf.cmd`,以及 macOS / Linux 下标准位置中的 `obj2gltf`,如 `/usr/local/bin/obj2gltf`、`/opt/homebrew/bin/obj2gltf`。 + +**启用**:设置 > 启用 OBJ2GLTF 转换器,或设置 obj2gltf 命令路径。 + +### FBX2glTF(FBX) + +FBX 文件通过本地 FBX2glTF 二进制转换为 GLB。旧的社区 FBX 加载器没有打包进插件,因为它当前版本面向 Babylon.js 8,而本插件使用 Babylon.js 9。 + +**安装**: + +下载或自行构建适用于你平台的 [FBX2glTF](https://github.com/godotengine/FBX2glTF),并将二进制文件放到可发现的位置。 + +**解析顺序**:插件会优先使用显式设置值和环境变量,其次检查常见的用户管理安装位置,再检查 PATH,最后再回退到下面这些系统级安装位置提示: + +```text +C:\Program Files\FBX2glTF\FBX2glTF-windows-x64.exe +C:\Program Files\FBX2glTF\FBX2glTF.exe +/usr/local/bin/FBX2glTF +/opt/homebrew/bin/FBX2glTF +/usr/local/bin/fbx2gltf +``` + +**启用**:设置 > 启用 FBX2glTF 转换器,或设置 FBX2glTF 命令路径。 + +### 环境变量 + +| 变量 | 用途 | +|------|------| +| `AI3D_FREECAD_CMD` | CadQuery 的 Python 命令 | +| `AI3D_FREECADCMD` | FreeCADCmd 路径 | +| `AI3D_ASSIMP_CMD` | trimesh 的 Python 命令 | +| `AI3D_OBJ2GLTF_CMD` | obj2gltf 命令路径 | +| `AI3D_FBX2GLTF_CMD` | FBX2glTF 命令路径 | + +兼容旧配置时仍接受历史别名 `AI3D_FREECMDCMD`,但新配置应统一使用 `AI3D_FREECADCMD`。 + +--- + +## 技术细节 + +### 架构 + +``` +src/ +├── main.ts # 插件生命周期、命令 +├── domain/ +│ ├── models.ts # 共享接口 +│ └── constants.ts # 默认设置、扩展名 +├── store/ +│ ├── create-store.ts # 自定义 store 原语 +│ └── plugin-store.ts # Obsidian saveData 桥接 +├── render/ +│ ├── preview/ # 渲染器无关抽象层 +│ │ ├── types.ts # ModelPreview、AnnotationPreview、WorkbenchPreview 接口 +│ │ ├── routing.ts # Three/Babylon 路由决策 +│ │ ├── factory.ts # 渲染器动态导入工厂 +│ │ ├── selection.ts # 预览选择与日志 +│ │ ├── annotations.ts # AnnotationManager(标注叠层 + 遮挡) +│ │ ├── geometry.ts # 渲染器无关向量运算 +│ │ ├── bounds.ts # 包围盒工具 +│ │ ├── camera-fit.ts # 相机适配算法 +│ │ ├── disassembly.ts # 拆解控制器(适配器模式) +│ │ ├── explode.ts # 爆炸视图(适配器模式) +│ │ ├── report.ts # Markdown 报告生成 +│ │ └── summary.ts # 模型/零件摘要创建 +│ ├── three/ # Three.js 渲染器 +│ │ ├── scene.ts # ThreeModelPreview 类(GLB/GLTF/STL/PLY/OBJ) +│ │ ├── loaders.ts # 格式专用加载器,含 vault MTL 解析 +│ │ ├── disassembly.ts # ThreeDisassemblyAdapter +│ │ └── explode.ts # ThreeExplodeAdapter +│ ├── babylon/ # Babylon.js 渲染器 +│ │ ├── scene.ts # BabylonModelPreview 类 +│ │ ├── grid.ts # GridRenderer 类 +│ │ ├── loaders/ +│ │ │ ├── stl-loader.ts # 自定义二进制 STL 解析器 +│ │ │ ├── ply-loader.ts # 自定义 ASCII/二进制 PLY 解析器 +│ │ │ └── register.ts # Babylon SceneLoader 插件 +│ │ └── presets/ # 网格布局预设 +├── io/ +│ ├── formats/ +│ │ └── registry.ts # 格式能力注册表 +│ ├── conversion/ +│ │ ├── manager.ts # 转换编排 +│ │ └── adapters/ # 转换器实现 +│ └── model-pipeline.ts # 格式路由逻辑 +└── view/ + ├── workbench/ # 主工作台 UI + ├── inline/ # 代码块、实时预览 + └── direct-view.ts # 直接文件打开 +``` + +### 模型导入管线 + +``` +┌─────────────────────────────────────────────────────────────┐ +│ 1. 格式检测 │ +│ └─ getFormatCapability(ext) → { family, strategy } │ +│ │ +│ 2. 路由决策 │ +│ ├─ strategy: "direct" → prepareDirectLoad() │ +│ └─ strategy: "convert" → convertForPreview() │ +│ │ +│ 3. 数据加载 │ +│ ├─ readBinaryPath() → ArrayBuffer │ +│ └─ [如已转换] → 读取转换后的 .glb │ +│ │ +│ 4. Babylon 渲染 │ +│ ├─ GLB/GLTF/OBJ → SceneLoader.ImportMeshAsync() │ +│ ├─ STL → loadSTLBuffer()(直接解析) │ +│ └─ PLY → loadPLYBuffer()(直接解析) │ +└─────────────────────────────────────────────────────────────┘ +``` + +### 为什么 STL/PLY 使用直接缓冲区加载 + +Babylon.js v9 的 SceneLoader 存在一个 bug:自定义插件在通过 `SceneLoader.ImportMeshAsync()` 加载时,接收到的是 data URL 字符串而非 ArrayBuffer。内置加载器(GLTF、OBJ)不受影响。 + +**解决方案**:STL 和 PLY 解析器直接使用原始 ArrayBuffer 调用,完全绕过 SceneLoader。 + +### 转换缓存 + +- **位置**:与源文件相同目录 +- **格式**:`{filename}.ai3d-converted.glb` +- **验证**:检查转换器身份、缓存键、文件存在性 +- **失效**:转换器设置更改时自动失效 +- **手动清除**:命令面板 > "Clear Conversion Cache" + +--- + +## 已知限制 + +| 问题 | 受影响格式 | 解决方法 | +|------|-----------|---------| +| 需要外部转换器 | FBX | 安装并启用 FBX2glTF | +| 需要外部工具 | STEP/IGES/BREP/SLDPRT | 安装 Python + CadQuery 或 FreeCAD | +| 纹理路径解析 | OBJ | 将纹理放在 OBJ/MTL 同一目录;缺失纹理会显示非阻塞资源提示 | +| 外部资源路径解析 | GLTF | 将 `.bin` 和纹理保留在 vault 中,并按 `.gltf` 引用的相对路径放置 | +| 转换超时 | SLDPRT | 复杂装配体有 10 分钟超时 | + +--- + +## 部署指南 + +### 前置要求 + +- Node.js >= 18 +- npm >= 9 +- Obsidian >= 1.5.0 + +### 构建命令 + +```bash +npm install # 安装依赖 +npm run dev # 开发构建(监听模式) +npm run build # 生产构建 +npm run typecheck # TypeScript 类型检查 +npm run verify:preview # 定向浏览器预览冒烟验证 +npm run verify:preview:success # 完整预览路由成功套件 +npm run verify:obsidian # Obsidian 应用端到端冒烟验证 +npm run verify:release # 发布资产版本/hash/体积检查 +npm run verify:settings # 旧 data.json/default settings 迁移检查 +npm run verify:remote-draft # 远程草稿隐私/客户端行为检查 +npm run verify:knowledge-index # 知识索引链接和刷新回归检查 +npm run verify:diagnostics # 脱敏诊断报告回归检查 +``` + +### 预览验证 + +在提交预览相关改动前,建议运行 `npm run verify:preview:success`。如果只想检查当前默认路径,`npm run verify:preview` 仍然可用。验证脚本会自动识别 Windows、macOS 和 Linux 上常见的 Chrome、Edge、Chromium 与 Brave;只有使用自定义浏览器路径时才需要设置 `PLAYWRIGHT_CHROMIUM_EXECUTABLE`。完整成功套件会启动一个临时的 Playwright 验证页面,加载 `models/rubiks-cube-3x3.glb`,并验证: + +- 默认 simple `GLB` 预览 +- 默认 direct-edit `GLB` 预览 +- 默认 readonly saved-pin `GLB` 预览 +- “仅阅读场景”档位的路由行为 +- “兼容优先”回退档位的路由行为 +- workbench Babylon 回退路由和实验性 Three.js workbench 能力探针 +- `STL`、`PLY`、`OBJ` 直读格式预览路由 +- helper toolbar 交互、聚焦模式、旋转时标注遮挡刷新、选中部件导出、性能快照,以及滚轮不带动页面滚动 + +如果验证失败,脚本会把截图以及包含预览状态和浏览器消息的日志保存到 `.tmp/preview-failures/`。 + +### Obsidian 验证 + +在 macOS 且已安装 Obsidian 时,发布前运行 `npm run verify:obsidian`。脚本会在 `/tmp/ai-model-workbench-verify-vault` 下创建临时测试库,安装当前打包插件,通过远程调试端口打开测试笔记,按需信任临时 vault,确认 GLB/STL 预览 canvas 已加载,检查未启用 FBX2glTF 时的 FBX 转换反馈,然后打开真实 GLB 文件视图并启用实验性 Three workbench,检查 backend 选择、聚焦/分解控件、面板爆炸控件、标注模式和知识笔记生成。 + +如果想在验证结束后删除临时库,使用 `npm run verify:obsidian -- --clean`。在 macOS 上,clean 流程会先退出 Obsidian,并从 Obsidian 配置中注销该临时库,再删除 `/tmp` 目录,避免开发者控制台继续刷旧路径的 `ENOENT`。 + +### 知识笔记验证 + +修改生成报告、零件草稿或模型索引行为后,运行 `npm run verify:knowledge-index`。脚本会用一个极小的 Obsidian shim 打包知识笔记 helper,构建代表性的模型索引,刷新 AI 托管区,并确认用户手写笔记不会被覆盖。 + +### 构建输出 + +``` +ai-model-workbench/ +├── main.js # ~3.8 MB(压缩后的插件运行时 bundle) +├── manifest.json # 插件清单 +├── styles.css # 插件样式 +└── src/ # 源代码 +``` + +### 发布流程 + +发布由 GitHub Actions 的 `Release` workflow 完成。推送一个与 `manifest.json` 版本匹配的 tag,例如 `0.5.5`,或手动运行该 workflow。它只上传 `main.js`、`manifest.json` 和 `styles.css`,会删除不受支持的 release asset,校验资产体积与 SHA-256 hash,并为发布文件生成 GitHub artifact attestation。发布完成后可运行 `npm run verify:obsidian -- --release-tag 0.5.5`,从 GitHub release 下载资产并安装到临时 Obsidian vault 做实机验证。 + +### 发布 Token 安全 + +发布优先使用 GitHub Actions 或 GitHub CLI 浏览器登录。Token 安全清单和 PAT 泄露处理流程见 `SECURITY.md`。 + +### 平台支持 + +| 平台 | 状态 | +|------|------| +| Windows | 完全支持 | +| macOS | 完全支持 | +| Linux | 完全支持 | +| Obsidian Mobile | 支持(降低分辨率) | + +### 包体积优化 + +渲染运行时是当前包体积的主要来源。项目通过以下方式控制输出体积: + +- 子路径导入(`@babylonjs/core/Engines/engine.js`)而非桶导入 +- Tree-shaking 移除未使用的功能 +- esbuild 进行快速、优化的打包 + +由于当前发布包同时包含 Babylon 和 Three 的预览路径,最终体积会随着路由覆盖面变化而波动。以上构建输出更适合作为当前参考值,而不是固定上限。 + +--- +## 致谢 + +感谢 LinuxDo 社区(https://linux.do)的支持。 diff --git a/docs/ai-3d-plugin-design-report.md b/docs/ai-3d-plugin-design-report.md index c708052..ab5de30 100644 --- a/docs/ai-3d-plugin-design-report.md +++ b/docs/ai-3d-plugin-design-report.md @@ -1,972 +1,972 @@ -# Obsidian AI 3D 模型拆解插件设计报告 - -## 1. 文档信息 - -- 文档版本: v0.1 -- 文档日期: 2026-05-06 -- 目标形态: Obsidian 社区插件 + 可选本地/远程分析服务 -- 设计原则: 以知识沉淀为中心,而不是把 Obsidian 变成 DCC 工具 - -## 2. 执行摘要 - -本插件的目标,是把 3D 模型转换为可拆解、可解释、可链接、可复用的知识资产。插件本体负责导入、预览、组织、索引、生成笔记与交互纠错,复杂的几何分析和 AI 推理通过可切换的分析服务完成。 - -首版推荐采用混合架构: - -- Obsidian 插件负责用户交互、笔记写入、知识图谱链接、结果缓存 -- 本地预处理负责格式归一化、基础几何统计、多视角渲染 -- AI 服务负责部件语义识别、知识点映射、说明文本生成 - -这样设计有三个直接收益: - -- 符合 Obsidian 插件能力边界与社区插件政策 -- 把高成本、高不确定性的 AI 能力与主插件解耦 -- 允许后续替换分析引擎而不破坏用户已沉淀的知识库结构 - -## 3. 产品定位 - -### 3.1 产品定义 - -这是一个面向知识工作流的 3D 解析插件,不做完整建模编辑,不取代 Blender、Maya、3ds Max、CAD 等专业工具。 - -插件将围绕以下三层对象工作: - -- 资产层: 一个完整 3D 模型 -- 部件层: 模型拆分后的结构单元、功能单元或语义单元 -- 知识层: 与部件和资产关联的可学习知识点 - -### 3.2 核心价值 - -- 把 3D 模型从文件资产转成知识资产 -- 自动提炼结构、语义、工艺、优化等知识点 -- 自动建立资产、部件、知识点之间的双向链接 -- 支持用户审阅和修正,让 AI 输出逐渐变成用户自己的知识网络 - -### 3.3 目标用户 - -- 3D 初学者,希望边看模型边学知识点 -- 技术美术,需要把资产经验沉淀为方法库 -- 游戏美术,需要对模型做结构化复盘 -- 工业设计和产品设计从业者,需要从结构和工艺角度解读模型 -- 教学人员,需要把模型拆成课程讲解内容 - -## 4. 目标与非目标 - -### 4.1 目标 - -- 支持导入常见 3D 模型并在 Obsidian 中预览 -- 自动生成结构树、部件列表和模型统计信息 -- 自动产出知识点建议,并写入 Markdown 笔记 -- 支持用户修正拆解结果并持久化 -- 构建可检索、可链接、可复用的知识图谱 - -### 4.2 非目标 - -- 不在首版提供高阶网格编辑能力 -- 不在首版支持重型 FBX 工作流 -- 不在首版支持复杂骨骼动画编辑 -- 不在首版覆盖所有 3D 文件格式 -- 不在首版保证通用级高精度语义分割 - -## 5. 官方能力边界与约束 - -以下约束来自 Obsidian 官方开发文档和社区插件政策,是技术方案必须遵守的边界。 - -### 5.1 插件能力边界 - -社区插件以 TypeScript 开发,插件主类基于 Plugin 生命周期运作。可直接利用的能力包括: - -- 命令注册: addCommand -- Ribbon 入口: addRibbonIcon -- 设置页: addSettingTab -- 状态栏: addStatusBarItem -- 自定义视图: registerView -- Markdown 扩展: registerMarkdownCodeBlockProcessor, registerMarkdownPostProcessor -- 编辑器扩展: registerEditorExtension -- 数据持久化: loadData, saveData -- Vault 文件读写: create, modify, read, process, getMarkdownFiles -- MetadataCache 索引与链接解析: getFileCache, resolvedLinks, unresolvedLinks - -### 5.2 视图能力边界 - -自定义视图建议基于 ItemView,用于承载: - -- 主面板 3D 预览 -- 部件树和知识侧栏 -- 自定义操作按钮 -- 状态恢复和视图状态保存 - -### 5.3 社区插件政策边界 - -如果要进入官方插件目录,需要满足以下要求: - -- 不得包含客户端遥测 -- 不得混淆代码来隐藏用途 -- 不得自带插件自更新机制 -- 若使用网络服务,必须在 README 中明确披露服务内容与用途 -- 若需要登录、付费或访问库外文件,也必须明确披露 - -结论: - -首版必须把“是否联网分析”“传输什么数据”“是否访问库外文件”做成用户显式可控的开关,而不是隐式行为。 - -## 6. 总体架构 - -### 6.1 推荐部署形态 - -推荐混合架构: - -1. Obsidian 插件 -2. 本地预处理服务 -3. 可切换 AI 分析后端 - -### 6.2 逻辑架构 - -```text -+---------------------------+ -| Obsidian Plugin | -| - Commands | -| - ItemView UI | -| - Vault Writer | -| - Cache Manager | -| - Markdown Renderer | -+-------------+-------------+ - | - | HTTP / Local IPC - v -+---------------------------+ -| Analysis Coordinator | -| - Format Normalize | -| - Mesh Stats | -| - Multi-view Render | -| - Rule-based Split | -| - AI Prompt Builder | -+-------------+-------------+ - | - | Adapter - v -+---------------------------+ -| AI Provider | -| - Local Model | -| - Cloud API | -| - Hybrid Pipeline | -+---------------------------+ -``` - -### 6.3 分层责任 - -插件层职责: - -- 文件选择与导入 -- 任务发起、轮询、取消 -- 3D 预览与交互 -- 分析结果展示 -- 结果写回 Obsidian 笔记和 JSON -- 用户修正与再次分析 - -分析服务职责: - -- 模型格式解析 -- 多视角渲染 -- 规则拆分和统计 -- AI 提示构造与输出规整 -- 知识点映射 - -AI 提供方职责: - -- 多模态理解或文本推理 -- 对部件语义和知识点给出候选结果 - -### 6.4 双层 Agent 路线 - -为了兼顾 Obsidian 插件边界、长时任务稳定性和后续工程建模扩展,推荐引入双层 Agent 架构: - -1. 插件内嵌轻 Agent,作为默认主路径 -2. 插件外接重 Agent,作为备用执行路径 - -插件内嵌轻 Agent 的职责: - -- 需求拆解 -- Prompt 组装 -- 参数补全 -- 结果展示 -- 人工确认 -- 知识写回 - -外接重 Agent 的职责: - -- 长时任务执行 -- 脚本运行 -- 外部软件自动化 -- 失败重试与纠错 -- 执行日志回传 - -这样设计的原因是: - -- 插件内先完成计划层和审阅层,避免 Obsidian 进程直接承担重执行器角色 -- 当任务进入 SolidWorks、COMSOL 等桌面软件自动化阶段时,可转交本地 Agent Bridge、Claude Code、Codex 或自定义执行器 -- 对用户来说,工作台仍然只暴露一个统一任务模型,不把底层执行器差异直接暴露成碎片化 UI - -推荐的运行顺序是: - -1. 轻 Agent 先生成结构化建模计划 -2. 用户在插件内确认参数与约束 -3. 只有需要真实自动化执行时,才切换到备用外接 Agent -4. 外接执行结果再回流到插件进行审阅、沉淀和知识写回 - -## 7. 功能设计 - -### 7.1 功能清单 - -MVP 范围内的功能: - -- 导入 GLB、GLTF、STL -- 3D 模型预览 -- 模型基本统计信息 -- 资产总览笔记生成 -- 部件树展示 -- 首轮知识点建议生成 -- 部件笔记与知识点笔记生成 -- 用户手动修正并保存 -- 基于 frontmatter 和链接的索引管理 - -后续版本功能: - -- OBJ 支持 -- 批量导入与批量分析 -- 课程模板输出 -- 部件差异对比 -- Markdown 内联 3D 嵌入块 -- 仅截图分析模式 - -### 7.2 关键用户流程 - -#### 流程 A: 导入并分析模型 - -1. 用户执行“导入 3D 模型”命令 -2. 插件校验格式和大小 -3. 插件将模型交给分析服务 -4. 预处理阶段返回基础统计信息,先展示给用户 -5. AI 分析完成后返回部件、知识点、说明和置信度 -6. 插件生成资产笔记、部件笔记和知识点链接 -7. 自定义视图展示 3D 视图与知识面板 - -#### 流程 B: 审阅与修正 - -1. 用户选择某个部件 -2. 用户可执行重命名、合并、拆分、标记错误 -3. 插件将修正写入 sidecar JSON 和 Markdown frontmatter -4. 用户可重新执行知识点映射,而不必重跑全量分析 - -#### 流程 C: 回看和复用 - -1. 用户打开已有资产笔记 -2. 插件根据 asset_id 定位 sidecar JSON -3. 自定义视图恢复历史分析状态 -4. 用户继续浏览、修正和追加笔记 - -#### 流程 D: AI 辅助工程建模 - -1. 用户在工作台中选择目标软件,例如 SolidWorks 或 COMSOL -2. 插件内嵌轻 Agent 根据当前模型、需求和约束生成结构化建模计划 -3. 用户审阅计划、参数表和预期输出 -4. 若仅需建议和脚本草稿,则直接写回 Obsidian -5. 若需要真实执行,则任务转交给备用外接 Agent -6. 外接 Agent 调用桥接层与目标软件 API,并把执行日志、脚本和结果回传工作台 - -## 8. 模块设计 - -### 8.1 插件启动模块 - -职责: - -- 注册命令 -- 注册 Ribbon 图标 -- 注册设置页 -- 注册自定义视图 -- 加载插件设置与本地索引 - -建议命令: - -- 导入 3D 模型 -- 重新分析当前资产 -- 仅重建知识点映射 -- 打开 3D 分析工作台 -- 清理缓存 -- 导出分析报告 - -### 8.2 模型导入模块 - -职责: - -- 接收文件路径或复制到指定库目录 -- 生成 asset_id -- 校验格式、大小和重复导入 -- 建立资产记录 - -### 8.3 Agent 编排模块 - -职责: - -- 维护统一任务协议 -- 在插件内生成轻量计划和参数草稿 -- 管理主执行器与备用执行器切换 -- 记录执行日志和用户确认 -- 把外接执行结果转换为可写回笔记的结构化结果 - -建议的统一任务字段: - -- target_app -- task_type -- user_intent -- constraints -- deliverable -- primary_backend -- fallback_backend -- status -- steps -- logs -- artifacts - -推荐约束: - -- 插件内默认只运行轻推理和短回合建议 -- 任何外部软件调用都必须经过显式确认 -- 任何远程或本地桥接调用都必须在设置和 README 中披露 - -关键决策: - -- 是否复制原始模型进库目录由设置控制 -- 默认保留原始文件路径引用,但可选复制入库 - -### 8.3 3D 预览模块 - -建议使用 Three.js 承载。 - -职责: - -- 加载模型并显示基础材质 -- 支持旋转、缩放、平移 -- 支持部件高亮、隔离、隐藏 -- 支持根据分析结果着色 -- 支持导出视角截图 - -### 8.4 分析协调模块 - -职责: - -- 组装分析请求 -- 发起任务和轮询状态 -- 接收中间进度 -- 处理失败、超时和取消 -- 缓存成功结果 - -### 8.5 知识映射模块 - -职责: - -- 将分析结果映射为知识点本体 -- 规整 tag、分类、置信度 -- 生成标准化 Markdown 模板 - -### 8.6 笔记写入模块 - -职责: - -- 创建资产主笔记 -- 创建部件笔记 -- 创建知识点引用或新知识点笔记 -- 更新 frontmatter -- 保持链接稳定 - -### 8.7 审阅与修正模块 - -职责: - -- 保存用户对部件的修正 -- 记录被用户拒绝的 AI 标签 -- 支持增量重分析 - -### 8.8 缓存与索引模块 - -职责: - -- 保存 sidecar JSON -- 维护 asset_id 到文件路径的映射 -- 恢复上次视图状态 - -## 9. 数据模型 - -### 9.1 插件设置 - -```ts -interface PluginSettings { - analysisMode: 'local' | 'remote' | 'hybrid'; - serviceBaseUrl: string; - copySourceModelToVault: boolean; - sourceModelFolder: string; - reportFolder: string; - partFolder: string; - previewFolder: string; - maxFileSizeMb: number; - autoGenerateKnowledgeNotes: boolean; - sendRawModelToRemote: boolean; - sendPreviewImagesToRemote: boolean; - sendGeometrySummaryToRemote: boolean; - defaultKnowledgeTaxonomy: string; -} -``` - -### 9.2 资产记录 - -```ts -interface AssetRecord { - assetId: string; - title: string; - sourcePath: string; - vaultPath?: string; - format: 'glb' | 'gltf' | 'stl' | 'obj'; - importedAt: string; - updatedAt: string; - status: 'idle' | 'processing' | 'ready' | 'error'; - vertexCount?: number; - triangleCount?: number; - materialCount?: number; - boundingBox?: [number, number, number]; - analysisVersion?: string; - reportNotePath?: string; - sidecarPath?: string; -} -``` - -### 9.3 部件记录 - -```ts -interface PartRecord { - partId: string; - assetId: string; - parentPartId?: string; - name: string; - category?: string; - meshRefs: string[]; - materialRefs: string[]; - bbox?: [number, number, number]; - confidence: number; - observations: string[]; - inferredFunctions: string[]; - knowledgeTags: string[]; - notePath?: string; - reviewed: boolean; -} -``` - -### 9.4 知识点记录 - -```ts -interface KnowledgeNode { - id: string; - title: string; - domain: - | 'geometry' - | 'topology' - | 'material' - | 'rigging' - | 'rendering' - | 'manufacturing' - | 'assembly'; - summary: string; - relatedPartIds: string[]; - relatedAssetIds: string[]; - confidence: number; - source: 'rule' | 'ai' | 'user'; -} -``` - -### 9.5 分析任务结果 - -```ts -interface AnalysisResult { - asset: AssetRecord; - parts: PartRecord[]; - knowledgeNodes: KnowledgeNode[]; - previewImages: string[]; - warnings: string[]; - pipeline: - | { - stage: 'normalize' | 'stats' | 'render' | 'split' | 'reason' | 'map'; - durationMs: number; - status: 'success' | 'failed' | 'skipped'; - }[]; -} -``` - -## 10. 知识本体设计 - -首版建议固定本体,避免 AI 自行扩散类别导致后续笔记不可维护。 - -### 10.1 一级分类 - -- geometry: 几何与比例 -- topology: 拓扑与边流 -- material: 材质与贴图 -- rigging: 骨骼与变形 -- rendering: 实时渲染与优化 -- manufacturing: 制造与打印 -- assembly: 装配与运动关系 - -### 10.2 AI 输出约束 - -每条部件解释必须拆成三层: - -- observation: 从模型中观察到的事实 -- inference: 基于事实做出的判断 -- learningPoint: 对用户有价值的知识点 - -这样做的好处: - -- 便于用户判断 AI 是否幻觉 -- 便于后续只重跑知识映射,而不重做视觉推理 -- 便于把用户修正回写为结构化数据 - -## 11. 库内文件组织 - -建议默认目录结构如下: - -```text -Assets/3D/ -Analysis/3D Reports/ -Analysis/3D Reports/.cache/ -Parts/3D Components/ -Knowledge/3D Concepts/ -Media/3D Previews/ -``` - -### 11.1 资产主笔记模板 - -```md ---- -asset_id: asset-xxxx -format: glb -source_model: Assets/3D/example.glb -analysis_version: v1 -status: ready -knowledge_tags: - - hard-surface - - topology -updated_at: 2026-05-06T12:00:00Z ---- - -# Example Model - -## Summary - -## Key Parts - -## Suggested Knowledge Points - -## Review Notes -``` - -### 11.2 部件笔记模板 - -```md ---- -part_id: part-001 -asset_id: asset-xxxx -parent_part: part-root -category: hinge -confidence: 0.82 -reviewed: false -knowledge_tags: - - assembly - - topology ---- - -# Hinge Part - -## Observation - -## Inference - -## Learning Points - -## Related Links -``` - -## 12. 分析服务接口设计 - -### 12.1 原则 - -- 插件与分析服务通过稳定 JSON 协议通信 -- 分析服务可以是本地 HTTP 服务,也可以是远程 API -- 插件不依赖某个单一 AI 厂商 - -### 12.2 API 列表 - -#### 健康检查 - -```http -GET /health -``` - -响应: - -```json -{ - "status": "ok", - "version": "0.1.0", - "capabilities": ["glb", "gltf", "stl", "multiview", "knowledge-map"] -} -``` - -#### 创建分析任务 - -```http -POST /analyze -Content-Type: application/json -``` - -请求: - -```json -{ - "assetId": "asset-123", - "sourcePath": "C:/models/demo.glb", - "format": "glb", - "mode": "hybrid", - "options": { - "generatePreviewImages": true, - "maxParts": 50, - "knowledgeTaxonomy": "default-v1", - "sendRawModelToRemote": false, - "sendPreviewImagesToRemote": true, - "sendGeometrySummaryToRemote": true - } -} -``` - -响应: - -```json -{ - "jobId": "job-123", - "status": "queued" -} -``` - -#### 查询任务状态 - -```http -GET /jobs/{jobId} -``` - -响应: - -```json -{ - "jobId": "job-123", - "status": "running", - "stage": "render", - "progress": 42 -} -``` - -#### 获取分析结果 - -```http -GET /jobs/{jobId}/result -``` - -返回 AnalysisResult。 - -#### 仅重建知识映射 - -```http -POST /knowledge/remap -``` - -用途: - -- 用户修正部件后,只重跑知识层而不重跑几何层 - -## 13. AI 与规则混合策略 - -### 13.1 为什么不能只靠 AI - -3D 模型拆解存在强结构性。若直接把全量模型交给 AI,问题通常出在: - -- 部件边界不稳定 -- 相同零件无法可靠聚类 -- 缺少几何事实依据 -- 输出不可复现 - -### 13.2 推荐策略 - -先规则,后 AI。 - -#### 规则阶段 - -- 基于节点层级拆分 -- 基于材质分组拆分 -- 基于连通域拆分 -- 统计顶点、面数、法线方向、对称性、重复件 -- 生成多视角截图和部件摘要 - -#### AI 阶段 - -- 对部件候选执行语义命名 -- 推测功能和学习点 -- 输出 observation / inference / learningPoint 三段式说明 - -#### 映射阶段 - -- 将 AI 自由文本规整为固定知识分类 -- 计算置信度 -- 标出需要人工复核的条目 - -## 14. UI 设计 - -### 14.1 工作台布局 - -推荐四区布局: - -- 左侧: 资产信息和部件树 -- 中央: 3D 视图 -- 右侧上部: AI 说明和知识点 -- 右侧下部: 审阅、修正和任务日志 - -### 14.2 核心交互 - -- 点击部件树,高亮 3D 模型中的对应区域 -- 在 3D 视图中点击部件,联动右侧知识面板 -- 右侧每个知识点支持“一键创建笔记” -- 对 AI 条目支持“接受 / 拒绝 / 改名 / 重新分类” -- 视图可恢复上次打开状态 - -### 14.3 状态设计 - -- idle: 未选择资产 -- loading: 模型加载中 -- preprocessing: 统计和预渲染中 -- analyzing: AI 分析中 -- reviewing: 用户审阅中 -- error: 失败态 - -### 14.4 错误态要求 - -- 必须给出可执行的错误提示 -- 必须区分格式不支持、文件过大、服务不可用、AI 响应失败 -- 必须支持保留已完成的中间结果 - -## 15. 缓存与一致性策略 - -### 15.1 缓存对象 - -- 模型预览图 -- 分析 sidecar JSON -- 视图状态 -- 任务中间阶段结果 - -### 15.2 缓存键 - -推荐由以下信息组合: - -- sourcePath -- 文件修改时间 -- 文件大小 -- analysisVersion -- taxonomyVersion - -### 15.3 一致性策略 - -- 资产源文件变化后,旧分析结果标记为 stale -- 用户修正优先级高于 AI 输出 -- 重新分析时,保留用户已确认的标签,除非用户选择覆盖 - -## 16. 安全、隐私与合规 - -### 16.1 默认隐私策略 - -- 默认关闭远程分析 -- 默认不上传原始模型 -- 默认不采集遥测 -- 明确显示传输内容 - -### 16.2 网络披露要求 - -若启用远程分析,README 和设置页都应明确说明: - -- 使用了哪些远程服务 -- 上传了哪些数据 -- 为什么需要上传 -- 数据保留多久 -- 如何关闭网络功能 - -### 16.3 库外文件访问 - -如果支持分析库外模型,必须在文档中说明原因,并允许用户切换为“复制模型入库后再分析”。 - -## 17. 性能设计 - -### 17.1 首版性能目标 - -- 50MB 以内模型可稳定导入 -- 中小模型首轮分析时间控制在 1 到 3 分钟 -- 视图切换不阻塞主线程超过 200ms - -### 17.2 性能策略 - -- 预处理与 AI 分析异步化 -- 3D 预览与 Markdown 写入分离 -- 大模型时先展示包围盒和统计信息 -- 预览图和 sidecar 先行写入,文本生成稍后补全 - -## 18. 测试策略 - -### 18.1 单元测试 - -- 设置解析 -- 路径生成 -- 数据映射 -- 笔记模板渲染 -- 置信度规整逻辑 - -### 18.2 集成测试 - -- 模型导入到笔记生成的完整链路 -- 分析服务异常处理 -- 缓存命中与失效 -- 用户修正后的增量重分析 - -### 18.3 手动验收 - -- 至少验证一个机械件模型 -- 至少验证一个角色或游戏资产模型 -- 至少验证一个 3D 打印场景模型 - -### 18.4 发布前检查 - -- 关闭所有遥测与调试输出 -- 检查 README 披露项完整 -- 检查网络开关默认值 -- 检查移动端降级行为是否可接受 - -## 19. 里程碑规划 - -### 阶段 0: 原型验证,1 周 - -- 完成插件脚手架 -- 完成 ItemView 工作台 -- 完成 GLB 预览 -- 完成资产主笔记最小写入 - -### 阶段 1: MVP,2 到 3 周 - -- 完成模型导入流程 -- 完成基础统计和预览截图 -- 完成分析服务对接 -- 完成资产、部件、知识点笔记生成 -- 完成基础修正流程 - -### 阶段 2: 可用版,2 到 4 周 - -- 完成知识点重映射 -- 完成缓存和 stale 策略 -- 完成设置页和隐私开关 -- 完成 README 和提交目录要求 - -### 阶段 3: 增强版 - -- 批量分析 -- 内联 Markdown 代码块渲染 -- OBJ 支持 -- 教学模板和导出方案 - -## 20. 关键风险与应对 - -### 风险 1: 语义拆解准确率不足 - -应对: - -- 先规则后 AI -- 增加人工修正入口 -- 把输出拆成观察、判断、知识点三层 - -### 风险 2: 模型格式复杂度过高 - -应对: - -- 首版只收敛到 GLB、GLTF、STL -- OBJ 作为后续增强 -- FBX 延后到分析链路稳定后再评估 - -### 风险 3: 远程分析引发隐私顾虑 - -应对: - -- 默认本地模式 -- 显示上传内容级别 -- 提供只传截图或只传摘要模式 - -### 风险 4: Obsidian 内主线程压力大 - -应对: - -- 把重计算放到外部服务 -- 渐进渲染 UI -- 先展示轻量结果,再补全详细结果 - -## 21. 开发建议 - -建议的首版仓库结构: - -```text -plugin/ - manifest.json - package.json - src/ - main.ts - settings.ts - view/ - analysis-view.ts - components/ - domain/ - models.ts - taxonomy.ts - services/ - analysis-client.ts - vault-writer.ts - cache-manager.ts - render/ - three-scene.ts - loaders/ - templates/ - asset-note.ts - part-note.ts -``` - -推荐优先顺序: - -1. 先把导入、视图、笔记写入打通 -2. 再接基础预处理服务 -3. 最后接 AI 知识映射 - -不要反过来做。先做 AI 容易得到一堆不可维护的结果,最后发现没有稳定容器承接这些输出。 - -## 22. 结论 - -这个插件最合理的产品路径,是做“3D 模型知识化工作台”。 - -它的关键不是在 Obsidian 里完成重型 3D 计算,而是: - -- 让模型分析结果可被审阅 -- 让知识点被写成结构化笔记 -- 让资产、部件、知识形成稳定链接 - -如果按本报告推进,首版完全可以在不突破 Obsidian 官方能力边界的前提下,做出一个真正有学习价值和复用价值的插件。 - -下一步最适合做的不是继续泛化方案,而是直接进入脚手架阶段,验证三件事: - -- 自定义视图里的 3D 预览是否顺畅 -- 分析服务协议是否足够稳定 +# Obsidian AI 3D 模型拆解插件设计报告 + +## 1. 文档信息 + +- 文档版本: v0.1 +- 文档日期: 2026-05-06 +- 目标形态: Obsidian 社区插件 + 可选本地/远程分析服务 +- 设计原则: 以知识沉淀为中心,而不是把 Obsidian 变成 DCC 工具 + +## 2. 执行摘要 + +本插件的目标,是把 3D 模型转换为可拆解、可解释、可链接、可复用的知识资产。插件本体负责导入、预览、组织、索引、生成笔记与交互纠错,复杂的几何分析和 AI 推理通过可切换的分析服务完成。 + +首版推荐采用混合架构: + +- Obsidian 插件负责用户交互、笔记写入、知识图谱链接、结果缓存 +- 本地预处理负责格式归一化、基础几何统计、多视角渲染 +- AI 服务负责部件语义识别、知识点映射、说明文本生成 + +这样设计有三个直接收益: + +- 符合 Obsidian 插件能力边界与社区插件政策 +- 把高成本、高不确定性的 AI 能力与主插件解耦 +- 允许后续替换分析引擎而不破坏用户已沉淀的知识库结构 + +## 3. 产品定位 + +### 3.1 产品定义 + +这是一个面向知识工作流的 3D 解析插件,不做完整建模编辑,不取代 Blender、Maya、3ds Max、CAD 等专业工具。 + +插件将围绕以下三层对象工作: + +- 资产层: 一个完整 3D 模型 +- 部件层: 模型拆分后的结构单元、功能单元或语义单元 +- 知识层: 与部件和资产关联的可学习知识点 + +### 3.2 核心价值 + +- 把 3D 模型从文件资产转成知识资产 +- 自动提炼结构、语义、工艺、优化等知识点 +- 自动建立资产、部件、知识点之间的双向链接 +- 支持用户审阅和修正,让 AI 输出逐渐变成用户自己的知识网络 + +### 3.3 目标用户 + +- 3D 初学者,希望边看模型边学知识点 +- 技术美术,需要把资产经验沉淀为方法库 +- 游戏美术,需要对模型做结构化复盘 +- 工业设计和产品设计从业者,需要从结构和工艺角度解读模型 +- 教学人员,需要把模型拆成课程讲解内容 + +## 4. 目标与非目标 + +### 4.1 目标 + +- 支持导入常见 3D 模型并在 Obsidian 中预览 +- 自动生成结构树、部件列表和模型统计信息 +- 自动产出知识点建议,并写入 Markdown 笔记 +- 支持用户修正拆解结果并持久化 +- 构建可检索、可链接、可复用的知识图谱 + +### 4.2 非目标 + +- 不在首版提供高阶网格编辑能力 +- 不在首版支持重型 FBX 工作流 +- 不在首版支持复杂骨骼动画编辑 +- 不在首版覆盖所有 3D 文件格式 +- 不在首版保证通用级高精度语义分割 + +## 5. 官方能力边界与约束 + +以下约束来自 Obsidian 官方开发文档和社区插件政策,是技术方案必须遵守的边界。 + +### 5.1 插件能力边界 + +社区插件以 TypeScript 开发,插件主类基于 Plugin 生命周期运作。可直接利用的能力包括: + +- 命令注册: addCommand +- Ribbon 入口: addRibbonIcon +- 设置页: addSettingTab +- 状态栏: addStatusBarItem +- 自定义视图: registerView +- Markdown 扩展: registerMarkdownCodeBlockProcessor, registerMarkdownPostProcessor +- 编辑器扩展: registerEditorExtension +- 数据持久化: loadData, saveData +- Vault 文件读写: create, modify, read, process, getMarkdownFiles +- MetadataCache 索引与链接解析: getFileCache, resolvedLinks, unresolvedLinks + +### 5.2 视图能力边界 + +自定义视图建议基于 ItemView,用于承载: + +- 主面板 3D 预览 +- 部件树和知识侧栏 +- 自定义操作按钮 +- 状态恢复和视图状态保存 + +### 5.3 社区插件政策边界 + +如果要进入官方插件目录,需要满足以下要求: + +- 不得包含客户端遥测 +- 不得混淆代码来隐藏用途 +- 不得自带插件自更新机制 +- 若使用网络服务,必须在 README 中明确披露服务内容与用途 +- 若需要登录、付费或访问库外文件,也必须明确披露 + +结论: + +首版必须把“是否联网分析”“传输什么数据”“是否访问库外文件”做成用户显式可控的开关,而不是隐式行为。 + +## 6. 总体架构 + +### 6.1 推荐部署形态 + +推荐混合架构: + +1. Obsidian 插件 +2. 本地预处理服务 +3. 可切换 AI 分析后端 + +### 6.2 逻辑架构 + +```text ++---------------------------+ +| Obsidian Plugin | +| - Commands | +| - ItemView UI | +| - Vault Writer | +| - Cache Manager | +| - Markdown Renderer | ++-------------+-------------+ + | + | HTTP / Local IPC + v ++---------------------------+ +| Analysis Coordinator | +| - Format Normalize | +| - Mesh Stats | +| - Multi-view Render | +| - Rule-based Split | +| - AI Prompt Builder | ++-------------+-------------+ + | + | Adapter + v ++---------------------------+ +| AI Provider | +| - Local Model | +| - Cloud API | +| - Hybrid Pipeline | ++---------------------------+ +``` + +### 6.3 分层责任 + +插件层职责: + +- 文件选择与导入 +- 任务发起、轮询、取消 +- 3D 预览与交互 +- 分析结果展示 +- 结果写回 Obsidian 笔记和 JSON +- 用户修正与再次分析 + +分析服务职责: + +- 模型格式解析 +- 多视角渲染 +- 规则拆分和统计 +- AI 提示构造与输出规整 +- 知识点映射 + +AI 提供方职责: + +- 多模态理解或文本推理 +- 对部件语义和知识点给出候选结果 + +### 6.4 双层 Agent 路线 + +为了兼顾 Obsidian 插件边界、长时任务稳定性和后续工程建模扩展,推荐引入双层 Agent 架构: + +1. 插件内嵌轻 Agent,作为默认主路径 +2. 插件外接重 Agent,作为备用执行路径 + +插件内嵌轻 Agent 的职责: + +- 需求拆解 +- Prompt 组装 +- 参数补全 +- 结果展示 +- 人工确认 +- 知识写回 + +外接重 Agent 的职责: + +- 长时任务执行 +- 脚本运行 +- 外部软件自动化 +- 失败重试与纠错 +- 执行日志回传 + +这样设计的原因是: + +- 插件内先完成计划层和审阅层,避免 Obsidian 进程直接承担重执行器角色 +- 当任务进入 SolidWorks、COMSOL 等桌面软件自动化阶段时,可转交本地 Agent Bridge、Claude Code、Codex 或自定义执行器 +- 对用户来说,工作台仍然只暴露一个统一任务模型,不把底层执行器差异直接暴露成碎片化 UI + +推荐的运行顺序是: + +1. 轻 Agent 先生成结构化建模计划 +2. 用户在插件内确认参数与约束 +3. 只有需要真实自动化执行时,才切换到备用外接 Agent +4. 外接执行结果再回流到插件进行审阅、沉淀和知识写回 + +## 7. 功能设计 + +### 7.1 功能清单 + +MVP 范围内的功能: + +- 导入 GLB、GLTF、STL +- 3D 模型预览 +- 模型基本统计信息 +- 资产总览笔记生成 +- 部件树展示 +- 首轮知识点建议生成 +- 部件笔记与知识点笔记生成 +- 用户手动修正并保存 +- 基于 frontmatter 和链接的索引管理 + +后续版本功能: + +- OBJ 支持 +- 批量导入与批量分析 +- 课程模板输出 +- 部件差异对比 +- Markdown 内联 3D 嵌入块 +- 仅截图分析模式 + +### 7.2 关键用户流程 + +#### 流程 A: 导入并分析模型 + +1. 用户执行“导入 3D 模型”命令 +2. 插件校验格式和大小 +3. 插件将模型交给分析服务 +4. 预处理阶段返回基础统计信息,先展示给用户 +5. AI 分析完成后返回部件、知识点、说明和置信度 +6. 插件生成资产笔记、部件笔记和知识点链接 +7. 自定义视图展示 3D 视图与知识面板 + +#### 流程 B: 审阅与修正 + +1. 用户选择某个部件 +2. 用户可执行重命名、合并、拆分、标记错误 +3. 插件将修正写入 sidecar JSON 和 Markdown frontmatter +4. 用户可重新执行知识点映射,而不必重跑全量分析 + +#### 流程 C: 回看和复用 + +1. 用户打开已有资产笔记 +2. 插件根据 asset_id 定位 sidecar JSON +3. 自定义视图恢复历史分析状态 +4. 用户继续浏览、修正和追加笔记 + +#### 流程 D: AI 辅助工程建模 + +1. 用户在工作台中选择目标软件,例如 SolidWorks 或 COMSOL +2. 插件内嵌轻 Agent 根据当前模型、需求和约束生成结构化建模计划 +3. 用户审阅计划、参数表和预期输出 +4. 若仅需建议和脚本草稿,则直接写回 Obsidian +5. 若需要真实执行,则任务转交给备用外接 Agent +6. 外接 Agent 调用桥接层与目标软件 API,并把执行日志、脚本和结果回传工作台 + +## 8. 模块设计 + +### 8.1 插件启动模块 + +职责: + +- 注册命令 +- 注册 Ribbon 图标 +- 注册设置页 +- 注册自定义视图 +- 加载插件设置与本地索引 + +建议命令: + +- 导入 3D 模型 +- 重新分析当前资产 +- 仅重建知识点映射 +- 打开 3D 分析工作台 +- 清理缓存 +- 导出分析报告 + +### 8.2 模型导入模块 + +职责: + +- 接收文件路径或复制到指定库目录 +- 生成 asset_id +- 校验格式、大小和重复导入 +- 建立资产记录 + +### 8.3 Agent 编排模块 + +职责: + +- 维护统一任务协议 +- 在插件内生成轻量计划和参数草稿 +- 管理主执行器与备用执行器切换 +- 记录执行日志和用户确认 +- 把外接执行结果转换为可写回笔记的结构化结果 + +建议的统一任务字段: + +- target_app +- task_type +- user_intent +- constraints +- deliverable +- primary_backend +- fallback_backend +- status +- steps +- logs +- artifacts + +推荐约束: + +- 插件内默认只运行轻推理和短回合建议 +- 任何外部软件调用都必须经过显式确认 +- 任何远程或本地桥接调用都必须在设置和 README 中披露 + +关键决策: + +- 是否复制原始模型进库目录由设置控制 +- 默认保留原始文件路径引用,但可选复制入库 + +### 8.3 3D 预览模块 + +建议使用 Three.js 承载。 + +职责: + +- 加载模型并显示基础材质 +- 支持旋转、缩放、平移 +- 支持部件高亮、隔离、隐藏 +- 支持根据分析结果着色 +- 支持导出视角截图 + +### 8.4 分析协调模块 + +职责: + +- 组装分析请求 +- 发起任务和轮询状态 +- 接收中间进度 +- 处理失败、超时和取消 +- 缓存成功结果 + +### 8.5 知识映射模块 + +职责: + +- 将分析结果映射为知识点本体 +- 规整 tag、分类、置信度 +- 生成标准化 Markdown 模板 + +### 8.6 笔记写入模块 + +职责: + +- 创建资产主笔记 +- 创建部件笔记 +- 创建知识点引用或新知识点笔记 +- 更新 frontmatter +- 保持链接稳定 + +### 8.7 审阅与修正模块 + +职责: + +- 保存用户对部件的修正 +- 记录被用户拒绝的 AI 标签 +- 支持增量重分析 + +### 8.8 缓存与索引模块 + +职责: + +- 保存 sidecar JSON +- 维护 asset_id 到文件路径的映射 +- 恢复上次视图状态 + +## 9. 数据模型 + +### 9.1 插件设置 + +```ts +interface PluginSettings { + analysisMode: 'local' | 'remote' | 'hybrid'; + serviceBaseUrl: string; + copySourceModelToVault: boolean; + sourceModelFolder: string; + reportFolder: string; + partFolder: string; + previewFolder: string; + maxFileSizeMb: number; + autoGenerateKnowledgeNotes: boolean; + sendRawModelToRemote: boolean; + sendPreviewImagesToRemote: boolean; + sendGeometrySummaryToRemote: boolean; + defaultKnowledgeTaxonomy: string; +} +``` + +### 9.2 资产记录 + +```ts +interface AssetRecord { + assetId: string; + title: string; + sourcePath: string; + vaultPath?: string; + format: 'glb' | 'gltf' | 'stl' | 'obj'; + importedAt: string; + updatedAt: string; + status: 'idle' | 'processing' | 'ready' | 'error'; + vertexCount?: number; + triangleCount?: number; + materialCount?: number; + boundingBox?: [number, number, number]; + analysisVersion?: string; + reportNotePath?: string; + sidecarPath?: string; +} +``` + +### 9.3 部件记录 + +```ts +interface PartRecord { + partId: string; + assetId: string; + parentPartId?: string; + name: string; + category?: string; + meshRefs: string[]; + materialRefs: string[]; + bbox?: [number, number, number]; + confidence: number; + observations: string[]; + inferredFunctions: string[]; + knowledgeTags: string[]; + notePath?: string; + reviewed: boolean; +} +``` + +### 9.4 知识点记录 + +```ts +interface KnowledgeNode { + id: string; + title: string; + domain: + | 'geometry' + | 'topology' + | 'material' + | 'rigging' + | 'rendering' + | 'manufacturing' + | 'assembly'; + summary: string; + relatedPartIds: string[]; + relatedAssetIds: string[]; + confidence: number; + source: 'rule' | 'ai' | 'user'; +} +``` + +### 9.5 分析任务结果 + +```ts +interface AnalysisResult { + asset: AssetRecord; + parts: PartRecord[]; + knowledgeNodes: KnowledgeNode[]; + previewImages: string[]; + warnings: string[]; + pipeline: + | { + stage: 'normalize' | 'stats' | 'render' | 'split' | 'reason' | 'map'; + durationMs: number; + status: 'success' | 'failed' | 'skipped'; + }[]; +} +``` + +## 10. 知识本体设计 + +首版建议固定本体,避免 AI 自行扩散类别导致后续笔记不可维护。 + +### 10.1 一级分类 + +- geometry: 几何与比例 +- topology: 拓扑与边流 +- material: 材质与贴图 +- rigging: 骨骼与变形 +- rendering: 实时渲染与优化 +- manufacturing: 制造与打印 +- assembly: 装配与运动关系 + +### 10.2 AI 输出约束 + +每条部件解释必须拆成三层: + +- observation: 从模型中观察到的事实 +- inference: 基于事实做出的判断 +- learningPoint: 对用户有价值的知识点 + +这样做的好处: + +- 便于用户判断 AI 是否幻觉 +- 便于后续只重跑知识映射,而不重做视觉推理 +- 便于把用户修正回写为结构化数据 + +## 11. 库内文件组织 + +建议默认目录结构如下: + +```text +Assets/3D/ +Analysis/3D Reports/ +Analysis/3D Reports/.cache/ +Parts/3D Components/ +Knowledge/3D Concepts/ +Media/3D Previews/ +``` + +### 11.1 资产主笔记模板 + +```md +--- +asset_id: asset-xxxx +format: glb +source_model: Assets/3D/example.glb +analysis_version: v1 +status: ready +knowledge_tags: + - hard-surface + - topology +updated_at: 2026-05-06T12:00:00Z +--- + +# Example Model + +## Summary + +## Key Parts + +## Suggested Knowledge Points + +## Review Notes +``` + +### 11.2 部件笔记模板 + +```md +--- +part_id: part-001 +asset_id: asset-xxxx +parent_part: part-root +category: hinge +confidence: 0.82 +reviewed: false +knowledge_tags: + - assembly + - topology +--- + +# Hinge Part + +## Observation + +## Inference + +## Learning Points + +## Related Links +``` + +## 12. 分析服务接口设计 + +### 12.1 原则 + +- 插件与分析服务通过稳定 JSON 协议通信 +- 分析服务可以是本地 HTTP 服务,也可以是远程 API +- 插件不依赖某个单一 AI 厂商 + +### 12.2 API 列表 + +#### 健康检查 + +```http +GET /health +``` + +响应: + +```json +{ + "status": "ok", + "version": "0.1.0", + "capabilities": ["glb", "gltf", "stl", "multiview", "knowledge-map"] +} +``` + +#### 创建分析任务 + +```http +POST /analyze +Content-Type: application/json +``` + +请求: + +```json +{ + "assetId": "asset-123", + "sourcePath": "C:/models/demo.glb", + "format": "glb", + "mode": "hybrid", + "options": { + "generatePreviewImages": true, + "maxParts": 50, + "knowledgeTaxonomy": "default-v1", + "sendRawModelToRemote": false, + "sendPreviewImagesToRemote": true, + "sendGeometrySummaryToRemote": true + } +} +``` + +响应: + +```json +{ + "jobId": "job-123", + "status": "queued" +} +``` + +#### 查询任务状态 + +```http +GET /jobs/{jobId} +``` + +响应: + +```json +{ + "jobId": "job-123", + "status": "running", + "stage": "render", + "progress": 42 +} +``` + +#### 获取分析结果 + +```http +GET /jobs/{jobId}/result +``` + +返回 AnalysisResult。 + +#### 仅重建知识映射 + +```http +POST /knowledge/remap +``` + +用途: + +- 用户修正部件后,只重跑知识层而不重跑几何层 + +## 13. AI 与规则混合策略 + +### 13.1 为什么不能只靠 AI + +3D 模型拆解存在强结构性。若直接把全量模型交给 AI,问题通常出在: + +- 部件边界不稳定 +- 相同零件无法可靠聚类 +- 缺少几何事实依据 +- 输出不可复现 + +### 13.2 推荐策略 + +先规则,后 AI。 + +#### 规则阶段 + +- 基于节点层级拆分 +- 基于材质分组拆分 +- 基于连通域拆分 +- 统计顶点、面数、法线方向、对称性、重复件 +- 生成多视角截图和部件摘要 + +#### AI 阶段 + +- 对部件候选执行语义命名 +- 推测功能和学习点 +- 输出 observation / inference / learningPoint 三段式说明 + +#### 映射阶段 + +- 将 AI 自由文本规整为固定知识分类 +- 计算置信度 +- 标出需要人工复核的条目 + +## 14. UI 设计 + +### 14.1 工作台布局 + +推荐四区布局: + +- 左侧: 资产信息和部件树 +- 中央: 3D 视图 +- 右侧上部: AI 说明和知识点 +- 右侧下部: 审阅、修正和任务日志 + +### 14.2 核心交互 + +- 点击部件树,高亮 3D 模型中的对应区域 +- 在 3D 视图中点击部件,联动右侧知识面板 +- 右侧每个知识点支持“一键创建笔记” +- 对 AI 条目支持“接受 / 拒绝 / 改名 / 重新分类” +- 视图可恢复上次打开状态 + +### 14.3 状态设计 + +- idle: 未选择资产 +- loading: 模型加载中 +- preprocessing: 统计和预渲染中 +- analyzing: AI 分析中 +- reviewing: 用户审阅中 +- error: 失败态 + +### 14.4 错误态要求 + +- 必须给出可执行的错误提示 +- 必须区分格式不支持、文件过大、服务不可用、AI 响应失败 +- 必须支持保留已完成的中间结果 + +## 15. 缓存与一致性策略 + +### 15.1 缓存对象 + +- 模型预览图 +- 分析 sidecar JSON +- 视图状态 +- 任务中间阶段结果 + +### 15.2 缓存键 + +推荐由以下信息组合: + +- sourcePath +- 文件修改时间 +- 文件大小 +- analysisVersion +- taxonomyVersion + +### 15.3 一致性策略 + +- 资产源文件变化后,旧分析结果标记为 stale +- 用户修正优先级高于 AI 输出 +- 重新分析时,保留用户已确认的标签,除非用户选择覆盖 + +## 16. 安全、隐私与合规 + +### 16.1 默认隐私策略 + +- 默认关闭远程分析 +- 默认不上传原始模型 +- 默认不采集遥测 +- 明确显示传输内容 + +### 16.2 网络披露要求 + +若启用远程分析,README 和设置页都应明确说明: + +- 使用了哪些远程服务 +- 上传了哪些数据 +- 为什么需要上传 +- 数据保留多久 +- 如何关闭网络功能 + +### 16.3 库外文件访问 + +如果支持分析库外模型,必须在文档中说明原因,并允许用户切换为“复制模型入库后再分析”。 + +## 17. 性能设计 + +### 17.1 首版性能目标 + +- 50MB 以内模型可稳定导入 +- 中小模型首轮分析时间控制在 1 到 3 分钟 +- 视图切换不阻塞主线程超过 200ms + +### 17.2 性能策略 + +- 预处理与 AI 分析异步化 +- 3D 预览与 Markdown 写入分离 +- 大模型时先展示包围盒和统计信息 +- 预览图和 sidecar 先行写入,文本生成稍后补全 + +## 18. 测试策略 + +### 18.1 单元测试 + +- 设置解析 +- 路径生成 +- 数据映射 +- 笔记模板渲染 +- 置信度规整逻辑 + +### 18.2 集成测试 + +- 模型导入到笔记生成的完整链路 +- 分析服务异常处理 +- 缓存命中与失效 +- 用户修正后的增量重分析 + +### 18.3 手动验收 + +- 至少验证一个机械件模型 +- 至少验证一个角色或游戏资产模型 +- 至少验证一个 3D 打印场景模型 + +### 18.4 发布前检查 + +- 关闭所有遥测与调试输出 +- 检查 README 披露项完整 +- 检查网络开关默认值 +- 检查移动端降级行为是否可接受 + +## 19. 里程碑规划 + +### 阶段 0: 原型验证,1 周 + +- 完成插件脚手架 +- 完成 ItemView 工作台 +- 完成 GLB 预览 +- 完成资产主笔记最小写入 + +### 阶段 1: MVP,2 到 3 周 + +- 完成模型导入流程 +- 完成基础统计和预览截图 +- 完成分析服务对接 +- 完成资产、部件、知识点笔记生成 +- 完成基础修正流程 + +### 阶段 2: 可用版,2 到 4 周 + +- 完成知识点重映射 +- 完成缓存和 stale 策略 +- 完成设置页和隐私开关 +- 完成 README 和提交目录要求 + +### 阶段 3: 增强版 + +- 批量分析 +- 内联 Markdown 代码块渲染 +- OBJ 支持 +- 教学模板和导出方案 + +## 20. 关键风险与应对 + +### 风险 1: 语义拆解准确率不足 + +应对: + +- 先规则后 AI +- 增加人工修正入口 +- 把输出拆成观察、判断、知识点三层 + +### 风险 2: 模型格式复杂度过高 + +应对: + +- 首版只收敛到 GLB、GLTF、STL +- OBJ 作为后续增强 +- FBX 延后到分析链路稳定后再评估 + +### 风险 3: 远程分析引发隐私顾虑 + +应对: + +- 默认本地模式 +- 显示上传内容级别 +- 提供只传截图或只传摘要模式 + +### 风险 4: Obsidian 内主线程压力大 + +应对: + +- 把重计算放到外部服务 +- 渐进渲染 UI +- 先展示轻量结果,再补全详细结果 + +## 21. 开发建议 + +建议的首版仓库结构: + +```text +plugin/ + manifest.json + package.json + src/ + main.ts + settings.ts + view/ + analysis-view.ts + components/ + domain/ + models.ts + taxonomy.ts + services/ + analysis-client.ts + vault-writer.ts + cache-manager.ts + render/ + three-scene.ts + loaders/ + templates/ + asset-note.ts + part-note.ts +``` + +推荐优先顺序: + +1. 先把导入、视图、笔记写入打通 +2. 再接基础预处理服务 +3. 最后接 AI 知识映射 + +不要反过来做。先做 AI 容易得到一堆不可维护的结果,最后发现没有稳定容器承接这些输出。 + +## 22. 结论 + +这个插件最合理的产品路径,是做“3D 模型知识化工作台”。 + +它的关键不是在 Obsidian 里完成重型 3D 计算,而是: + +- 让模型分析结果可被审阅 +- 让知识点被写成结构化笔记 +- 让资产、部件、知识形成稳定链接 + +如果按本报告推进,首版完全可以在不突破 Obsidian 官方能力边界的前提下,做出一个真正有学习价值和复用价值的插件。 + +下一步最适合做的不是继续泛化方案,而是直接进入脚手架阶段,验证三件事: + +- 自定义视图里的 3D 预览是否顺畅 +- 分析服务协议是否足够稳定 - 资产/部件/知识点三层笔记结构是否好用 \ No newline at end of file diff --git a/docs/development-handoff.md b/docs/development-handoff.md index 912bcf7..4315748 100644 --- a/docs/development-handoff.md +++ b/docs/development-handoff.md @@ -8,7 +8,7 @@ README, implementation, verification scripts, and release/security docs. AI Model Workbench is an Obsidian plugin that renders 3D model files inside a vault, adds 3D annotations/bookmarks, and generates linked knowledge notes from model evidence. -The current package version is `0.4.0`. +The current package version is `0.5.5`. Important runtime files: @@ -216,11 +216,11 @@ npm run verify:preview -- --model "models/resource-fixtures/grouped-parts/groupe 2. Run `npm run build`. 3. Run `npm run verify:release`. 4. Scan for tokens as described in `SECURITY.md`. -5. Publish through GitHub Actions with a tag such as `0.4.0` (no `v` prefix). +5. Publish through GitHub Actions with a tag such as `0.5.5` (no `v` prefix). ## Current Follow-Up Direction -Short-term product direction after `0.4.0`: +Short-term product direction after `0.5.5`: - Tighten auto part registration and cross-model part reuse feedback. - Keep improving direct workbench UX without prematurely moving all workbench routes. diff --git a/eslint.config.mjs b/eslint.config.mjs index b75d669..93d1b7c 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -24,6 +24,18 @@ export default defineConfig([ parserOptions: { project: "./tsconfig.json" }, }, }, + { + files: ["src/**/*.test.ts"], + languageOptions: { + globals: { + setTimeout: "readonly", + clearTimeout: "readonly", + }, + }, + rules: { + "obsidianmd/prefer-active-window-timers": "off", + }, + }, { files: ["scripts/**/*.{js,mjs,ts}", "*.config.mjs"], languageOptions: { diff --git a/main.js b/main.js index 18cd53f..a16c41e 100644 --- a/main.js +++ b/main.js @@ -1,10 +1,10 @@ -"use strict";var Ob=Object.defineProperty;var Pq=Object.getOwnPropertyDescriptor;var Dq=Object.getOwnPropertyNames;var Lq=Object.prototype.hasOwnProperty;var C=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(i){throw t=[i],i}};var tt=(n,e)=>{for(var t in e)Ob(n,t,{get:e[t],enumerable:!0})},Oq=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Dq(e))!Lq.call(n,r)&&r!==t&&Ob(n,r,{get:()=>e[r],enumerable:!(i=Pq(e,r))||i.enumerable});return n};var Nq=n=>Oq(Ob({},"__esModule",{value:!0}),n);function yd(n,e,t){return`${n}::${e}::${t}`}function wq(n,e){return!!(n.cacheVersion===2&&n.converterId&&n.converterCacheKey&&n.sourcePath&&n.sourceExt&&n.targetExt==="glb"&&n.outputPath&&n.outputExt==="glb"&&Number.isFinite(n.createdAt)&&e-n.createdAt<=2592e6)}function UN(n,e=Date.now()){let t=new Map;for(let i of n){if(!wq(i,e))continue;let r=yd(i.sourcePath,i.sourceExt,i.targetExt),s=t.get(r);(!s||i.createdAt>s.createdAt)&&t.set(r,i)}return[...t.values()].sort((i,r)=>r.createdAt-i.createdAt).slice(0,200)}function Fq(n,e){return!!n&&!!e&&n.cacheVersion===e.cacheVersion&&n.converterId===e.converterId&&n.converterCacheKey===e.converterCacheKey&&n.sourcePath===e.sourcePath&&n.sourceExt===e.sourceExt&&n.targetExt===e.targetExt&&n.outputPath===e.outputPath&&n.outputExt===e.outputExt&&n.createdAt===e.createdAt&&n.warnings.join(` +"use strict";var Ob=Object.defineProperty;var Pq=Object.getOwnPropertyDescriptor;var Dq=Object.getOwnPropertyNames;var Lq=Object.prototype.hasOwnProperty;var C=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(i){throw t=[i],i}};var tt=(n,e)=>{for(var t in e)Ob(n,t,{get:e[t],enumerable:!0})},Oq=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Dq(e))!Lq.call(n,r)&&r!==t&&Ob(n,r,{get:()=>e[r],enumerable:!(i=Pq(e,r))||i.enumerable});return n};var Nq=n=>Oq(Ob({},"__esModule",{value:!0}),n);function Cd(n,e,t){return`${n}::${e}::${t}`}function wq(n,e){return!!(n.cacheVersion===2&&n.converterId&&n.converterCacheKey&&n.sourcePath&&n.sourceExt&&n.targetExt==="glb"&&n.outputPath&&n.outputExt==="glb"&&Number.isFinite(n.createdAt)&&e-n.createdAt<=2592e6)}function UN(n,e=Date.now()){let t=new Map;for(let i of n){if(!wq(i,e))continue;let r=Cd(i.sourcePath,i.sourceExt,i.targetExt),s=t.get(r);(!s||i.createdAt>s.createdAt)&&t.set(r,i)}return[...t.values()].sort((i,r)=>r.createdAt-i.createdAt).slice(0,200)}function Fq(n,e){return!!n&&!!e&&n.cacheVersion===e.cacheVersion&&n.converterId===e.converterId&&n.converterCacheKey===e.converterCacheKey&&n.sourcePath===e.sourcePath&&n.sourceExt===e.sourceExt&&n.targetExt===e.targetExt&&n.outputPath===e.outputPath&&n.outputExt===e.outputExt&&n.createdAt===e.createdAt&&n.warnings.join(` `)===e.warnings.join(` -`)}function VN(n=[],e){function t(){return UN([...s.values()])}function i(l){s.clear();for(let c of l)s.set(yd(c.sourcePath,c.sourceExt,c.targetExt),c)}let r=UN(n),s=new Map(r.map(l=>[yd(l.sourcePath,l.sourceExt,l.targetExt),l]));function a(){let l=t();i(l),e==null||e(l)}return(n.length!==r.length||r.some((l,c)=>!Fq(l,n[c])))&&(e==null||e(r)),{get(l,c,f){return s.get(yd(l,c,f))},set(l){s.set(yd(l.sourcePath,l.sourceExt,l.targetExt),l),a()},delete(l,c,f){let h=s.delete(yd(l,c,f));return h&&a(),h},clear(){s.size!==0&&(s.clear(),a())},entries(){return t()}}}var Nb=C(()=>{"use strict"});function Ba(n){return n.trim().toLowerCase().replace(/^\./,"")}function wb(n){return Bq.get(Ba(n))}function gl(n){let e=wb(n);return!!(e!=null&&e.enabled)}function Ap(n){return["splat","spz","sog"].includes(Ba(n))}function vl(){return GN.filter(n=>n.enabled).map(n=>n.ext)}var GN,Bq,Io=C(()=>{"use strict";GN=[{ext:"glb",family:"mesh",strategy:"direct",directLoader:"babylon",enabled:!0},{ext:"gltf",family:"mesh",strategy:"direct",directLoader:"babylon",enabled:!0},{ext:"stl",family:"mesh",strategy:"direct",directLoader:"custom-stl",enabled:!0},{ext:"obj",family:"mesh",strategy:"direct",directLoader:"babylon",converterId:"obj2gltf",outputFormat:"glb",enabled:!0},{ext:"ply",family:"mesh",strategy:"direct",directLoader:"custom-ply",enabled:!0},{ext:"fbx",family:"mesh",strategy:"convert",converterId:"fbx2gltf",outputFormat:"glb",enabled:!0},{ext:"step",family:"cad",strategy:"convert",converterId:"freecad",outputFormat:"glb",enabled:!0},{ext:"stp",family:"cad",strategy:"convert",converterId:"freecad",outputFormat:"glb",enabled:!0},{ext:"iges",family:"cad",strategy:"convert",converterId:"freecad",outputFormat:"glb",enabled:!0},{ext:"igs",family:"cad",strategy:"convert",converterId:"freecad",outputFormat:"glb",enabled:!0},{ext:"brep",family:"cad",strategy:"convert",converterId:"freecad",outputFormat:"glb",enabled:!0},{ext:"sldprt",family:"cad",strategy:"convert",converterId:"sldprt",outputFormat:"glb",enabled:!0},{ext:"3mf",family:"mesh",strategy:"convert",converterId:"assimp",outputFormat:"glb",enabled:!0},{ext:"dae",family:"mesh",strategy:"convert",converterId:"assimp",outputFormat:"glb",enabled:!0}],Bq=new Map(GN.map(n=>[n.ext,n]))});var Fb,zN=C(()=>{"use strict";Fb={"settings.title":"AI 3d model workbench","settings.folders":"Folders","settings.behavior":"Behavior","settings.converters":"Converters","settings.converterMenu":"Model converters","settings.converterMenu.desc":"Closed by default. Open this section only when you want to manually enable an optional local conversion route.","settings.environmentInspector":"Environment inspector","settings.environmentInspector.desc":"Closed by default. Open this section when you need to configure command paths or run environment checks.","settings.paths":"Converter paths","settings.diagnostics":"Converter command diagnostics","settings.performance":"Performance & display","settings.mobileSupport":"Mobile support","settings.knowledgeGeneration":"Knowledge generation","settings.sourceModelFolder":"Source model folder","settings.sourceModelFolder.desc":"Vault folder where source model files are stored.","settings.reportFolder":"Report folder","settings.reportFolder.desc":"Vault folder where generated knowledge notes are saved.","settings.partFolder":"Part notes folder","settings.partFolder.desc":"Vault folder where generated part note drafts are saved.","settings.snapshotFolder":"Snapshot folder","settings.snapshotFolder.desc":"Vault folder where exported snapshots are saved.","settings.autoGenerateKnowledgeNotes":"Auto-generate knowledge notes","settings.autoGenerateKnowledgeNotes.desc":"Reserved for a future automation flow. For now, generate notes manually from the command palette.","settings.annotationPreviewMode":"Annotation preview mode","settings.annotationPreviewMode.desc":"Choose how bound note previews render in annotation popovers and the editor.","settings.annotationPreviewMode.plainText":"Plain text","settings.annotationPreviewMode.markdown":"Markdown","settings.annotationDisplayMode":"Annotation display mode","settings.annotationDisplayMode.desc":"Choose how bookmark pins appear over the model.","settings.annotationDisplayMode.snippet":"Full snippet","settings.annotationDisplayMode.surface":"Single surface","settings.annotationDisplayMode.dot":"Single dot","settings.previewRendererRollout":"Preview compatibility mode","settings.previewRendererRollout.desc":"Controls how widely the Three.js preview path is used for single-model previews (GLB, GLTF, STL, PLY, OBJ). Switch back to Compatibility mode if pin projection, occlusion, edit pins, snapshots, or toolbar behavior regress. 3dgrid is not affected by this setting.","settings.previewRendererRollout.babylonSafe":"Compatibility mode","settings.previewRendererRollout.readonly":"Reading surfaces only","settings.previewRendererRollout.direct":"Reading + file view (Recommended)","settings.useThreeRenderer":"Use Three.js renderer","settings.useThreeRenderer.desc":"Toggle between Three.js (faster, lighter) and Babylon.js (full compatibility) for single-model previews. Three.js supports GLB/GLTF/STL/PLY/OBJ. 3dgrid always uses Babylon.js.","settings.experimentalThreeWorkbench":"Experimental Three workbench","settings.experimentalThreeWorkbench.desc":"Try the Three.js workbench path for direct GLB/GLTF files only. If loading fails, the file view falls back to Babylon.js automatically.","settings.autoRotateDefault":"Auto-rotate by default","settings.autoRotateDefault.desc":"Start model previews with auto-rotation enabled.","settings.snapshotNaming":"Snapshot naming","settings.snapshotNaming.desc":"How exported snapshot files are named.","settings.snapshotNaming.modelName":"Model name + timestamp","settings.snapshotNaming.timestamp":"Timestamp only","settings.logLevel":"Log level","settings.logLevel.desc":"Controls plugin runtime log verbosity in the developer console.","settings.language":"Language","settings.language.desc":"Display language for plugin settings. Takes effect immediately.","settings.analysisMode":"AI drafting mode","settings.analysisMode.desc":"Controls whether knowledge-note generation stays local or also requests a sanitized remote draft. Raw model upload is blocked by the current client.","settings.analysisMode.local":"Local evidence only","settings.analysisMode.hybrid":"Local evidence + remote draft","settings.analysisMode.remote":"Remote draft from evidence","settings.serviceBaseUrl":"Draft service URL","settings.serviceBaseUrl.desc":"Optional base URL for a service that accepts POST /draft-note. Leave empty to keep all drafting local.","settings.sendGeometrySummaryToRemote":"Send geometry summary","settings.sendGeometrySummaryToRemote.desc":"Allow sanitized mesh counts, bounds, part candidates, annotation coordinates, and nearest-part links to be included in remote draft input.","settings.sendPreviewImagesToRemote":"Send preview image references","settings.sendPreviewImagesToRemote.desc":"Allow generated preview image paths to be listed in the remote draft input. Image bytes are not uploaded by this client.","settings.sendRawModelToRemote":"Send raw model file","settings.sendRawModelToRemote.desc":"Reserved for future explicit upload support. If enabled manually, remote draft requests are blocked instead of uploading the model.","settings.enableCad":"Enable cad conversion for step, iges, and brep files","settings.enableCad.desc":"Enable cad conversion for step, iges, and brep formats. Requires cadquery and trimesh in your python environment.","settings.enableObj2gltf":"Enable obj2gltf converter (experimental)","settings.enableObj2gltf.desc":"Keep obj direct loading as the default. Enable this only if you want an optional local normalization route through obj2gltf.","settings.preferObj2gltf":"Prefer obj2gltf for obj","settings.preferObj2gltf.desc":"Recommended default is off. Turn this on only when you want normalized output files or direct obj loading is not good enough.","settings.enableFbx2gltf":"Enable FBX2glTF converter","settings.enableFbx2gltf.desc":"Enable conversion for fbx files via FBX2glTF. Requires the FBX2glTF binary installed locally.","settings.enableMesh":"Enable mesh conversion for 3mf and dae files","settings.enableMesh.desc":"Enable conversion for 3mf and dae formats via python trimesh. Requires trimesh, numpy, networkx, and pycollada in your python environment.","settings.enableSldprt":"Enable sldprt conversion for SolidWorks files","settings.enableSldprt.desc":"Enable conversion for SolidWorks sldprt files via FreeCAD. Requires FreeCAD installed locally.","settings.mobileSupport.desc":"On iOS, iPadOS, and Android, direct formats like GLB, GLTF, STL, OBJ, and PLY are supported. Local converter settings and diagnostics remain desktop-only.","settings.pythonCmd":"Path to the python command for cad conversion","settings.pythonCmd.desc":"Optional path to the python command used for cad conversion. Windows usually uses py. macOS and Linux usually use python3. Overrides auto-discovery when set.","settings.freecadCmd":"Path to the FreeCAD command for sldprt conversion","settings.freecadCmd.desc":"Optional path to the FreeCAD command used for SolidWorks file conversion. Windows usually uses FreeCADCmd.exe, macOS usually uses FreeCADCmd, and Linux usually uses freecadcmd. Overrides auto-discovery when set.","settings.obj2gltfCmd":"Path to the obj2gltf command","settings.obj2gltfCmd.desc":"Optional path to the obj2gltf command. Windows usually uses obj2gltf.cmd, and macOS and Linux usually use obj2gltf. Overrides auto-discovery when set.","settings.fbx2gltfCmd":"FBX2glTF command path","settings.fbx2gltfCmd.desc":"Optional path to the FBX2glTF command. Windows usually uses FBX2glTF.exe, and macOS and Linux usually use FBX2glTF. Overrides auto-discovery when set.","settings.assimpCmd":"Path to the python command for 3mf and dae conversion","settings.assimpCmd.desc":"Optional path to the python command used for 3mf and dae conversion. Windows usually uses py. macOS and Linux usually use python3. Overrides auto-discovery when set.","settings.diagnostics.desc":"Shows the exact executable path the plugin would use right now and runs lightweight self-checks for Python environments and converter CLIs.","settings.diagnostics.idle":"Diagnostics are off by default. Click Check now to run them manually.","settings.diagnostics.checkNow":"Check now","settings.diagnostics.checking":"Checking...","settings.diagnostics.refreshed":"Converter command diagnostics refreshed.","settings.diagnostics.checkingAvailability":"Checking converter command availability...","settings.diagnostics.available":"available","settings.diagnostics.notFound":"not found","settings.diagnostics.sourceLabel":"Source","settings.diagnostics.commandLabel":"Command","settings.diagnostics.resolvedPathLabel":"Resolved path","settings.diagnostics.selfCheckLabel":"Self-check","settings.diagnostics.selfCheckOk":"passed","settings.diagnostics.selfCheckFailed":"failed","settings.diagnostics.cadPythonCheck":"Python packages (cadquery, trimesh)","settings.diagnostics.meshPythonCheck":"Python packages (trimesh, numpy, networkx, collada)","settings.diagnostics.freecadCmdCheck":"FreeCADCmd launch probe","settings.diagnostics.obj2gltfCheck":"obj2gltf launch probe","settings.diagnostics.fbx2gltfCheck":"FBX2glTF launch probe","settings.canvasHeight":"Default canvas height","settings.canvasHeight.desc":"Default height (px) for inline model previews. Range: 200\u2013800.","settings.autoRotateSpeed":"Auto-rotate speed","settings.autoRotateSpeed.desc":"Rotation speed when auto-rotate is enabled. Range: 0.1\u20132.0.","settings.renderQuality":"Render quality","settings.renderQuality.desc":"Higher quality uses more GPU resources. Affects anti-aliasing and resolution.","settings.renderScale":"Resolution scale","settings.renderScale.desc":"Render resolution multiplier. 1.0 = native, 0.5 = half, 2.0 = double (supersampling). Range: 0.25\u20132.0.","modelLoad.warningTitle":"Model preview unavailable","modelLoad.warningMessage":"{ext} files need the {converterName} converter enabled in plugin settings before they can load.","modelLoad.warningHint":"Enable the matching converter in plugin settings, then reload this file.","modelLoad.mobileWarningMessage":"{ext} files need local conversion tools that are unavailable on iOS, iPadOS, and Android.","modelLoad.mobileWarningHint":"Open this file on desktop, or convert it to GLB, GLTF, OBJ, STL, or PLY first.","modelLoad.errorTitle":"Couldn't display this model","modelLoad.errorMessage":"Failed to load: {reason}","modelLoad.errorHint":"Check the file format or open the developer console for details.","headingPin.showSingle":"Show linked pin","headingPin.showMultiple":"Show linked pins","headingPin.linkedTo":"Pin linked to: {models}","helper.resetViewLabel":"Reset view","helper.resetViewDone":"Reset","helper.copyModelInfoLabel":"Copy model info as Markdown","helper.copySelectedPartInfoLabel":"Copy selected part info","helper.noSelectedPart":"Select a part first","helper.copied":"Copied!","helper.failed":"Failed","helper.toggleWireframeLabel":"Toggle wireframe","helper.wireframeOn":"Wireframe","helper.wireframeOff":"Solid","helper.toggleAxesLabel":"Toggle orientation axes","helper.axesOn":"Axes on","helper.axesOff":"Axes off","helper.toggleBoundingBoxLabel":"Toggle bounding box","helper.boundingBoxOn":"Bounding box on","helper.boundingBoxOff":"Bounding box off","helper.toggleFocusSelectionLabel":"Focus selected part","helper.focusSelectionOn":"Focus mode on","helper.focusSelectionOff":"Focus mode off","helper.toggleDisassemblyLabel":"Toggle disassembly mode","helper.disassemblyOn":"Disassembly on","helper.disassemblyOff":"Disassembly off","helper.resetPartsLabel":"Reset disassembled parts","helper.partsReset":"Parts reset","helper.changeResolutionLabel":"Change resolution","helper.resolutionValue":"Resolution: {value}","helper.toggleAnimationLabel":"Play or pause animation","helper.playing":"Playing","helper.paused":"Paused","helper.toggleMeasurementLabel":"Toggle distance measurement","helper.measurementOn":"Measurement on","helper.measurementOff":"Measurement off","helper.clearMeasurementsLabel":"Clear measurements","helper.measurementsCleared":"Cleared","helper.calibrateLabel":"Calibrate measurement scale","helper.calibrateTitle":"Measurement Calibration","helper.calibrateCurrent":"Current size:","helper.calibrateReal":"Real size:","helper.calibrateLock":"Lock ratio","helper.calibrateApply":"Apply","helper.calibrateReset":"Reset","helper.calibrated":"Scale applied","helper.calibrateResetDone":"Scale reset","helper.calibrateOpen":"Calibration panel opened","helper.calibrateClose":"Calibration panel closed","helper.removePreviewLabel":"Remove preview","helper.copySnapshotLabel":"Copy snapshot","helper.saveSnapshotLabel":"Save snapshot to vault","helper.saved":"Saved!","helper.downloadSnapshotLabel":"Download snapshot","helper.downloaded":"Downloaded!","helper.toggleAnnotationLabel":"Toggle annotation mode","helper.toggleAnnotationsVisibilityLabel":"Show or hide annotations","helper.annotateOn":"Annotation mode on","helper.annotateOff":"Annotation mode off","helper.annotationsVisible":"Annotations shown","helper.annotationsHidden":"Annotations hidden","helper.enableInteractionLabel":"Enable touch interaction","helper.disableInteractionLabel":"Return to scroll mode","helper.interactionOn":"Model interaction on","helper.interactionOff":"Scroll mode on","helper.showMoreActionsLabel":"Show more actions","helper.hideMoreActionsLabel":"Hide extra actions","helper.moreActionsShown":"More actions shown","helper.moreActionsHidden":"Extra actions hidden","helper.interactAction":"Interact","helper.scrollAction":"Scroll","workbench.emptyTitle":"No model","workbench.emptyText":'Use the "import 3D model" command to load a GLB, GLTF, STL, OBJ, or PLY file.',"workbench.modelTitle":"Model","workbench.studioTitle":"AI Model Workbench","workbench.studioTagline":"Inspect, annotate, and turn 3D assets into linked notes.","workbench.navLabel":"Workbench sections","workbench.navGallery":"Gallery","workbench.navLibrary":"Library","workbench.navNotebooks":"Notebooks","workbench.navSettings":"Settings","workbench.sourcesTitle":"Model sources","workbench.layersTitle":"Review layers","workbench.viewModeTitle":"View mode","workbench.modeMesh":"Mesh view","workbench.modeFocus":"Focus selection","workbench.modeMeshShort":"Mesh","workbench.modeFocusShort":"Focus","workbench.previewViewsTitle":"Preview views","workbench.connectionsTitle":"Knowledge connections","workbench.currentModelLabel":"Current model","workbench.noReportYet":"No report note yet","workbench.noIndexYet":"No knowledge index yet. Generate a knowledge note first.","workbench.noModelLoaded":"No model loaded","workbench.disassemblyTitle":"Disassembly","workbench.explodeLabel":"Explode","workbench.summaryTitle":"Summary","workbench.meshesLabel":"Meshes","workbench.splatsLabel":"Splats","workbench.trianglesLabel":"Triangles","workbench.verticesLabel":"Vertices","workbench.materialsLabel":"Materials","workbench.boundingSizeLabel":"Bounds","workbench.centerLabel":"Center","workbench.selectedPartTitle":"Selected Part","workbench.partMeshLabel":"Mesh","workbench.noSelectedPart":"Click a model part to inspect it here.","workbench.tagsTitle":"Tags","workbench.noTagsYet":"No tags yet","workbench.addTagPlaceholder":"Add tag...","workbench.addTagAction":"Add","workbench.annotationsTitle":"Annotations","workbench.exitAnnotate":"Exit annotate","workbench.annotate":"Annotate","workbench.annotateHintActive":"Click the model to add a label \xB7 press Esc to exit","workbench.annotateHintActiveMobile":"Tap the model to add a label. Switch back to Scroll when you want to move through the note again.","workbench.pinCount":"{count} pin(s)","workbench.editAction":"Edit","workbench.deleteAction":"Delete","workbench.resetViewAction":"Reset view","workbench.insertInfoAction":"Insert info","workbench.insertGalleryAction":"Insert Gallery","workbench.insertCompareAction":"Insert Compare","workbench.playAction":"Play","workbench.pauseAction":"Pause","workbench.saveProfileAction":"Save profile","workbench.generateNoteAction":"Generate note","workbench.openNoteAction":"Open note","workbench.openIndexAction":"Open index","workbench.recordTitle":"Specimen card","workbench.recordSubtitle":"Current asset profile","workbench.notesTitle":"Analysis notes","workbench.whereTitle":"Where it connects","workbench.noteReady":"Linked note ready","workbench.indexReady":"Knowledge index ready","workbench.notePending":"Linked note pending","workbench.analysisLabel":"Analysis","workbench.settingsUnavailable":"Open this plugin from Obsidian settings to change workbench options.","workbench.profileSaved":"Profile saved","workbench.viewReset":"View reset","workbench.infoInserted":"Model info inserted","workbench.infoCopied":"Model info copied","workbench.templateInserted":"Template inserted","workbench.templateCopied":"Template copied","workbench.mobileHint":"Mobile tip: tap Interact to move the model, then switch back to Scroll to keep reading the note.","workbench.mobileHintInteractive":"Interaction mode is on. Switch back to Scroll when you want to move through the note again.","directView.mobileHint":"Mobile tip: use the toolbar Interact button to switch between model interaction and note scrolling.","directWorkbench.modelLoadInterrupted":"Model load was interrupted by a newer request.","directWorkbench.backendLabel":"Backend","directWorkbench.routeLabel":"Route","directWorkbench.performanceLabel":"Performance","directWorkbench.partCandidatesLabel":"Part candidates","directWorkbench.knowledgeTitle":"Knowledge","directWorkbench.registeredTitle":"Registered part matches","directWorkbench.registeredLoading":"Checking...","directWorkbench.registeredCount":"{count} match(es)","directWorkbench.registeredEmpty":"No cross-model part match yet","directWorkbench.registeredUnavailable":"Part evidence unavailable","directWorkbench.registeredOpen":"Open","directWorkbench.registeredOpenNote":"Note","directWorkbench.registeredOpenModel":"Model","directWorkbench.registeredSourceModel":"From {model}","directWorkbench.registeredTargetPartNote":"Opens matched part note","directWorkbench.registeredTargetSourceModel":"Opens source model","directWorkbench.registeredTargetUnavailable":"No linked target","workbench.fileNotFound":"File not found: {path}","annotation.selectColor":"Select color {color}","annotation.sectionEmpty":"Section is empty.","modal.selectModel":"Select a 3D model...","main.commandImportModel":"Import a 3D model","main.commandGenerateNote":"Generate knowledge note","main.commandOpenKnowledgeIndex":"Open knowledge index","main.commandClearConversionCache":"Clear conversion cache","main.commandCheckConverters":"Check converters","main.commandCopyDiagnostics":"Copy diagnostics report","main.converterDiagnosticsMobileUnavailable":"Converter diagnostics are only available on desktop. On iOS, iPadOS, and Android, direct formats can still load.","main.diagnosticsCopied":"AI Model Workbench diagnostics copied to clipboard.","main.diagnosticsCopyFailed":"Couldn't copy diagnostics. A sanitized diagnostics note was created instead.","codeBlock.noModelPathOrConfig":"No model path or config specified.","codeBlock.jsonParseError":"JSON parse error: {error}","codeBlock.jsonParseLine":" (line {line})","codeBlock.noModelsInConfig":"No models specified in config.","codeBlock.unsupportedFormat":"Unsupported format: {ext}. Supported: {formats}","codeBlock.splatDisabled":"SPLAT preview is disabled in packaged builds. Local-only .splat support is planned first; .spz/.sog need locally bundled decoders before reevaluation.","codeBlock.noConfigSpecified":"No config specified.","codeBlock.noModelsSpecified":"No models specified.","codeBlock.mobileHint":"Mobile tip: use Interact to manipulate the model, then switch back to Scroll to keep moving through the note.","codeBlock.renderingGrid":"Rendering grid...","codeBlock.composeRequiresSections":'"compose" preset requires a "sections" array.',"codeBlock.composeNoValidSections":"Compose: no valid sections.","codeBlock.unknownPreset":'Unknown preset: "{preset}". Available: compare, showcase, explode, timeline, compose',"codeBlock.presetRequiresModels":'Preset "{preset}" requires {min}-{max} models, got {count}.',"codeBlock.gridFailed":"Grid failed: {reason}","livePreview.mobileHint":"Mobile tip: switch between Interact and Scroll depending on whether you want to move the model or keep reading.","loading.default":"Loading...","loading.preparingModel":"Preparing model...","loading.loadingModel":"Loading model..."}});var XN,YN=C(()=>{"use strict";XN={"settings.title":"AI 3D \u6A21\u578B\u5DE5\u4F5C\u53F0","settings.folders":"\u6587\u4EF6\u5939","settings.behavior":"\u884C\u4E3A","settings.converters":"\u8F6C\u6362\u5668","settings.converterMenu":"\u6A21\u578B\u8F6C\u6362\u5668","settings.converterMenu.desc":"\u9ED8\u8BA4\u6536\u8D77\u3002\u4EC5\u5728\u4F60\u9700\u8981\u624B\u52A8\u542F\u7528\u67D0\u6761\u672C\u5730\u8F6C\u6362\u8DEF\u7EBF\u65F6\u518D\u5C55\u5F00\u3002","settings.environmentInspector":"\u73AF\u5883\u68C0\u67E5\u5668","settings.environmentInspector.desc":"\u9ED8\u8BA4\u6536\u8D77\u3002\u4EC5\u5728\u9700\u8981\u914D\u7F6E\u547D\u4EE4\u8DEF\u5F84\u6216\u624B\u52A8\u6267\u884C\u73AF\u5883\u68C0\u67E5\u65F6\u518D\u5C55\u5F00\u3002","settings.paths":"\u8F6C\u6362\u5668\u8DEF\u5F84","settings.diagnostics":"\u8F6C\u6362\u5668\u547D\u4EE4\u8BCA\u65AD","settings.performance":"\u6027\u80FD\u4E0E\u663E\u793A","settings.mobileSupport":"\u79FB\u52A8\u7AEF\u652F\u6301","settings.knowledgeGeneration":"\u77E5\u8BC6\u751F\u6210","settings.sourceModelFolder":"\u6E90\u6A21\u578B\u6587\u4EF6\u5939","settings.sourceModelFolder.desc":"\u5B58\u653E\u6E90 3D \u6A21\u578B\u7684\u5E93\u6587\u4EF6\u5939\u3002","settings.reportFolder":"\u62A5\u544A\u6587\u4EF6\u5939","settings.reportFolder.desc":"\u4FDD\u5B58\u751F\u6210\u7684\u77E5\u8BC6\u7B14\u8BB0\u7684\u5E93\u6587\u4EF6\u5939\u3002","settings.partFolder":"\u90E8\u4EF6\u7B14\u8BB0\u6587\u4EF6\u5939","settings.partFolder.desc":"\u4FDD\u5B58\u751F\u6210\u7684\u90E8\u4EF6\u7B14\u8BB0\u8349\u7A3F\u7684\u5E93\u6587\u4EF6\u5939\u3002","settings.snapshotFolder":"\u5FEB\u7167\u6587\u4EF6\u5939","settings.snapshotFolder.desc":"\u4FDD\u5B58\u5BFC\u51FA\u5FEB\u7167\u7684\u5E93\u6587\u4EF6\u5939\u3002","settings.autoGenerateKnowledgeNotes":"\u81EA\u52A8\u751F\u6210\u77E5\u8BC6\u7B14\u8BB0","settings.autoGenerateKnowledgeNotes.desc":"\u9884\u7559\u7ED9\u540E\u7EED\u81EA\u52A8\u5316\u6D41\u7A0B\u3002\u5F53\u524D\u8BF7\u901A\u8FC7\u547D\u4EE4\u6216\u5DE5\u4F5C\u53F0\u6309\u94AE\u624B\u52A8\u751F\u6210\u77E5\u8BC6\u7B14\u8BB0\u3002","settings.annotationPreviewMode":"\u6807\u6CE8\u9884\u89C8\u6A21\u5F0F","settings.annotationPreviewMode.desc":"\u9009\u62E9\u6807\u6CE8\u7ED1\u5B9A\u7B14\u8BB0\u5728\u60AC\u6D6E\u9884\u89C8\u548C\u7F16\u8F91\u5668\u4E2D\u7684\u663E\u793A\u65B9\u5F0F\u3002","settings.annotationPreviewMode.plainText":"\u7EAF\u6587\u672C","settings.annotationPreviewMode.markdown":"Markdown","settings.annotationDisplayMode":"\u6807\u6CE8\u663E\u793A\u6A21\u5F0F","settings.annotationDisplayMode.desc":"\u9009\u62E9\u6A21\u578B\u4E0A\u4E66\u7B7E\u6807\u6CE8\u7684\u663E\u793A\u65B9\u5F0F\u3002","settings.annotationDisplayMode.snippet":"\u5B8C\u6574\u7247\u6BB5","settings.annotationDisplayMode.surface":"\u5355\u4E2A\u6807\u7B7E\u9762","settings.annotationDisplayMode.dot":"\u5355\u4E2A\u5706\u70B9","settings.previewRendererRollout":"\u9884\u89C8\u517C\u5BB9\u6A21\u5F0F","settings.previewRendererRollout.desc":"\u63A7\u5236\u5355\u6A21\u578B\u9884\u89C8\uFF08GLB\u3001GLTF\u3001STL\u3001PLY\u3001OBJ\uFF09\u4E2D Three.js \u6E32\u67D3\u8DEF\u5F84\u7684\u542F\u7528\u8303\u56F4\u3002\u53EA\u8981\u51FA\u73B0 pin \u6295\u5F71\u3001\u906E\u6321\u3001\u7F16\u8F91\u6001 pin\u3001\u5FEB\u7167\u6216\u5DE5\u5177\u680F\u884C\u4E3A\u56DE\u9000\uFF0C\u5C31\u5207\u56DE\u201C\u517C\u5BB9\u4F18\u5148\u201D\u3002workbench \u548C 3dgrid \u4E0D\u53D7\u8FD9\u4E2A\u8BBE\u7F6E\u5F71\u54CD\u3002","settings.previewRendererRollout.babylonSafe":"\u517C\u5BB9\u4F18\u5148","settings.previewRendererRollout.readonly":"\u4EC5\u9605\u8BFB\u573A\u666F","settings.previewRendererRollout.direct":"\u9605\u8BFB + \u6587\u4EF6\u89C6\u56FE\uFF08\u63A8\u8350\uFF09","settings.useThreeRenderer":"\u4F7F\u7528 Three.js \u6E32\u67D3\u5668","settings.useThreeRenderer.desc":"\u5728 Three.js\uFF08\u66F4\u5FEB\u3001\u66F4\u8F7B\u91CF\uFF09\u548C Babylon.js\uFF08\u5B8C\u5168\u517C\u5BB9\uFF09\u4E4B\u95F4\u5207\u6362\u5355\u6A21\u578B\u9884\u89C8\u6E32\u67D3\u5668\u3002Three.js \u652F\u6301 GLB/GLTF/STL/PLY/OBJ\u3002\u5DE5\u4F5C\u53F0\u548C 3dgrid \u59CB\u7EC8\u4F7F\u7528 Babylon.js\u3002","settings.experimentalThreeWorkbench":"\u5B9E\u9A8C\u6027 Three \u5DE5\u4F5C\u53F0","settings.experimentalThreeWorkbench.desc":"\u4EC5\u5BF9\u76F4\u8BFB GLB/GLTF \u6587\u4EF6\u5C1D\u8BD5\u4F7F\u7528 Three.js \u5DE5\u4F5C\u53F0\u8DEF\u5F84\u3002\u52A0\u8F7D\u5931\u8D25\u65F6\uFF0C\u6587\u4EF6\u89C6\u56FE\u4F1A\u81EA\u52A8\u56DE\u9000\u5230 Babylon.js\u3002","settings.autoRotateDefault":"\u9ED8\u8BA4\u81EA\u52A8\u65CB\u8F6C","settings.autoRotateDefault.desc":"\u542F\u52A8 3D \u9884\u89C8\u65F6\u9ED8\u8BA4\u5F00\u542F\u81EA\u52A8\u65CB\u8F6C\u3002","settings.snapshotNaming":"\u5FEB\u7167\u547D\u540D","settings.snapshotNaming.desc":"\u5BFC\u51FA\u5FEB\u7167\u6587\u4EF6\u7684\u547D\u540D\u65B9\u5F0F\u3002","settings.snapshotNaming.modelName":"\u6A21\u578B\u540D + \u65F6\u95F4\u6233","settings.snapshotNaming.timestamp":"\u4EC5\u65F6\u95F4\u6233","settings.logLevel":"\u65E5\u5FD7\u7EA7\u522B","settings.logLevel.desc":"\u63A7\u5236\u63D2\u4EF6\u5728\u5F00\u53D1\u8005\u63A7\u5236\u53F0\u4E2D\u7684\u65E5\u5FD7\u8BE6\u7EC6\u7A0B\u5EA6\u3002","settings.language":"\u8BED\u8A00","settings.language.desc":"\u63D2\u4EF6\u8BBE\u7F6E\u754C\u9762\u7684\u663E\u793A\u8BED\u8A00\u3002\u7ACB\u5373\u751F\u6548\u3002","settings.analysisMode":"AI \u8349\u7A3F\u6A21\u5F0F","settings.analysisMode.desc":"\u63A7\u5236\u77E5\u8BC6\u7B14\u8BB0\u751F\u6210\u4FDD\u6301\u672C\u5730\uFF0C\u8FD8\u662F\u989D\u5916\u8BF7\u6C42\u7ECF\u8FC7\u88C1\u526A\u7684\u8FDC\u7A0B\u8349\u7A3F\u3002\u5F53\u524D\u5BA2\u6237\u7AEF\u4F1A\u963B\u6B62\u539F\u59CB\u6A21\u578B\u4E0A\u4F20\u3002","settings.analysisMode.local":"\u4EC5\u672C\u5730\u8BC1\u636E","settings.analysisMode.hybrid":"\u672C\u5730\u8BC1\u636E + \u8FDC\u7A0B\u8349\u7A3F","settings.analysisMode.remote":"\u57FA\u4E8E\u8BC1\u636E\u7684\u8FDC\u7A0B\u8349\u7A3F","settings.serviceBaseUrl":"\u8349\u7A3F\u670D\u52A1 URL","settings.serviceBaseUrl.desc":"\u53EF\u9009\u7684\u8349\u7A3F\u670D\u52A1\u57FA\u7840\u5730\u5740\uFF0C\u670D\u52A1\u9700\u63A5\u6536 POST /draft-note\u3002\u7559\u7A7A\u65F6\u6240\u6709\u8349\u7A3F\u8F93\u5165\u90FD\u4FDD\u7559\u5728\u672C\u5730\u3002","settings.sendGeometrySummaryToRemote":"\u53D1\u9001\u51E0\u4F55\u6458\u8981","settings.sendGeometrySummaryToRemote.desc":"\u5141\u8BB8\u628A\u7ECF\u8FC7\u88C1\u526A\u7684\u7F51\u683C\u6570\u91CF\u3001\u5305\u56F4\u76D2\u3001\u90E8\u4EF6\u5019\u9009\u3001\u6807\u6CE8\u5750\u6807\u548C\u6700\u8FD1\u90E8\u4EF6\u5173\u8054\u52A0\u5165\u8FDC\u7A0B\u8349\u7A3F\u8F93\u5165\u3002","settings.sendPreviewImagesToRemote":"\u53D1\u9001\u9884\u89C8\u56FE\u5F15\u7528","settings.sendPreviewImagesToRemote.desc":"\u5141\u8BB8\u5728\u8FDC\u7A0B\u8349\u7A3F\u8F93\u5165\u4E2D\u5217\u51FA\u751F\u6210\u7684\u9884\u89C8\u56FE\u8DEF\u5F84\u3002\u5F53\u524D\u5BA2\u6237\u7AEF\u4E0D\u4F1A\u4E0A\u4F20\u56FE\u7247\u5B57\u8282\u3002","settings.sendRawModelToRemote":"\u53D1\u9001\u539F\u59CB\u6A21\u578B\u6587\u4EF6","settings.sendRawModelToRemote.desc":"\u9884\u7559\u7ED9\u672A\u6765\u663E\u5F0F\u4E0A\u4F20\u652F\u6301\u3002\u82E5\u624B\u52A8\u5F00\u542F\uFF0C\u8FDC\u7A0B\u8349\u7A3F\u8BF7\u6C42\u4F1A\u88AB\u963B\u6B62\uFF0C\u4E0D\u4F1A\u4E0A\u4F20\u6A21\u578B\u3002","settings.enableCad":"\u542F\u7528 CAD \u8F6C\u6362\u5668 (STEP/IGES/BREP)","settings.enableCad.desc":"\u542F\u7528 STEP/IGES/BREP \u683C\u5F0F\u7684 CAD \u8F6C\u6362\u8DEF\u7EBF\uFF0C\u901A\u8FC7 Python CadQuery (OpenCASCADE)\u3002\u9700\u8981\uFF1Apip install cadquery trimesh","settings.enableObj2gltf":"\u542F\u7528 obj2gltf \u8F6C\u6362\u5668\uFF08\u5B9E\u9A8C\u6027\uFF09","settings.enableObj2gltf.desc":"\u9ED8\u8BA4\u4F7F\u7528 OBJ \u76F4\u63A5\u52A0\u8F7D\u3002\u4EC5\u5728\u9700\u8981\u672C\u5730\u6807\u51C6\u5316 GLB \u8F93\u51FA\u65F6\u542F\u7528\u3002","settings.preferObj2gltf":"OBJ \u4F18\u5148\u4F7F\u7528 obj2gltf","settings.preferObj2gltf.desc":"\u9ED8\u8BA4\u5173\u95ED\u3002\u4EC5\u5728\u9700\u8981\u6807\u51C6\u5316 GLB \u8F93\u51FA\u6216\u76F4\u63A5 OBJ \u52A0\u8F7D\u6548\u679C\u4E0D\u4F73\u65F6\u5F00\u542F\u3002","settings.enableFbx2gltf":"\u542F\u7528 FBX2glTF \u8F6C\u6362\u5668","settings.enableFbx2gltf.desc":"\u542F\u7528 FBX \u6587\u4EF6\u901A\u8FC7 FBX2glTF \u8F6C\u6362\u3002\u9700\u8981\u672C\u5730\u5B89\u88C5 FBX2glTF \u4E8C\u8FDB\u5236\u6587\u4EF6\u3002","settings.enableMesh":"\u542F\u7528\u7F51\u683C\u8F6C\u6362\u5668 (3MF/DAE)","settings.enableMesh.desc":"\u542F\u7528 3MF \u548C DAE (Collada) \u683C\u5F0F\u7684\u8F6C\u6362\u8DEF\u7EBF\uFF0C\u901A\u8FC7 Python trimesh\u3002\u9700\u8981\u5B89\u88C5 Python \u548C trimesh (pip install trimesh numpy networkx pycollada)\u3002","settings.enableSldprt":"\u542F\u7528 SLDPRT \u8F6C\u6362\u5668 (SolidWorks)","settings.enableSldprt.desc":"\u542F\u7528 SolidWorks .sldprt \u6587\u4EF6\u901A\u8FC7 FreeCAD \u8F6C\u6362\u3002\u9700\u8981\u5B89\u88C5 FreeCAD (https://www.freecad.org/downloads.php)\u3002","settings.mobileSupport.desc":"\u5728 iOS\u3001iPadOS \u548C Android \u4E0A\uFF0CGLB\u3001GLTF\u3001STL\u3001OBJ\u3001PLY \u8FD9\u7C7B\u76F4\u8BFB\u683C\u5F0F\u53EF\u7528\u3002\u672C\u5730\u8F6C\u6362\u5668\u8BBE\u7F6E\u548C\u547D\u4EE4\u8BCA\u65AD\u4ECD\u4EC5\u652F\u6301\u684C\u9762\u7AEF\u3002","settings.pythonCmd":"Python \u547D\u4EE4\u8DEF\u5F84\uFF08CAD \u7528\uFF09","settings.pythonCmd.desc":"\u53EF\u9009\u7684 Python \u547D\u4EE4\u8DEF\u5F84\uFF0C\u7528\u4E8E CAD \u8F6C\u6362\u3002Windows \u901A\u5E38\u7528 py\uFF0CmacOS \u548C Linux \u901A\u5E38\u7528 python3\u3002\u8BBE\u7F6E\u540E\u8986\u76D6\u81EA\u52A8\u53D1\u73B0\u548C AI3D_FREECAD_CMD\u3002","settings.freecadCmd":"FreeCAD \u547D\u4EE4\u8DEF\u5F84\uFF08SLDPRT \u7528\uFF09","settings.freecadCmd.desc":"\u53EF\u9009\u7684 FreeCAD \u547D\u4EE4\u8DEF\u5F84\uFF0C\u7528\u4E8E SolidWorks \u6587\u4EF6\u8F6C\u6362\u3002Windows \u901A\u5E38\u7528 FreeCADCmd.exe\uFF0CmacOS \u901A\u5E38\u7528 FreeCADCmd\uFF0CLinux \u901A\u5E38\u7528 freecadcmd\u3002\u8BBE\u7F6E\u540E\u8986\u76D6\u81EA\u52A8\u53D1\u73B0\u548C AI3D_FREECADCMD\u3002","settings.obj2gltfCmd":"obj2gltf \u547D\u4EE4\u8DEF\u5F84","settings.obj2gltfCmd.desc":"\u53EF\u9009\u7684 obj2gltf \u547D\u4EE4\u8DEF\u5F84\u3002Windows \u901A\u5E38\u7528 obj2gltf.cmd\uFF0CmacOS \u548C Linux \u901A\u5E38\u7528 obj2gltf\u3002\u8BBE\u7F6E\u540E\u8986\u76D6\u81EA\u52A8\u53D1\u73B0\u548C AI3D_OBJ2GLTF_CMD\u3002","settings.fbx2gltfCmd":"FBX2glTF \u547D\u4EE4\u8DEF\u5F84","settings.fbx2gltfCmd.desc":"\u53EF\u9009\u7684 FBX2glTF \u547D\u4EE4\u8DEF\u5F84\u3002Windows \u901A\u5E38\u7528 FBX2glTF.exe\uFF0CmacOS \u548C Linux \u901A\u5E38\u7528 FBX2glTF\u3002\u8BBE\u7F6E\u540E\u8986\u76D6\u81EA\u52A8\u53D1\u73B0\u548C AI3D_FBX2GLTF_CMD\u3002","settings.assimpCmd":"Python \u547D\u4EE4\u8DEF\u5F84\uFF083MF/DAE \u7528\uFF09","settings.assimpCmd.desc":"\u53EF\u9009\u7684 Python \u547D\u4EE4\u8DEF\u5F84\uFF0C\u7528\u4E8E 3MF \u548C DAE \u8F6C\u6362\u3002Windows \u901A\u5E38\u7528 py\uFF0CmacOS \u548C Linux \u901A\u5E38\u7528 python3\u3002\u8BBE\u7F6E\u540E\u8986\u76D6\u81EA\u52A8\u53D1\u73B0\u548C AI3D_ASSIMP_CMD\u3002","settings.diagnostics.desc":"\u663E\u793A\u63D2\u4EF6\u5F53\u524D\u5B9E\u9645\u4F7F\u7528\u7684\u53EF\u6267\u884C\u6587\u4EF6\u8DEF\u5F84\uFF0C\u5E76\u4E3A Python \u73AF\u5883\u548C\u8F6C\u6362\u5668\u547D\u4EE4\u6267\u884C\u8F7B\u91CF\u81EA\u68C0\u3002","settings.diagnostics.idle":"\u73AF\u5883\u68C0\u67E5\u9ED8\u8BA4\u5173\u95ED\u3002\u70B9\u51FB\u201C\u7ACB\u5373\u68C0\u67E5\u201D\u540E\u624D\u4F1A\u6267\u884C\u3002","settings.diagnostics.checkNow":"\u7ACB\u5373\u68C0\u67E5","settings.diagnostics.checking":"\u68C0\u67E5\u4E2D...","settings.diagnostics.refreshed":"AI 3D \u8F6C\u6362\u5668\u547D\u4EE4\u8BCA\u65AD\u5DF2\u5237\u65B0\u3002","settings.diagnostics.checkingAvailability":"\u6B63\u5728\u68C0\u67E5\u8F6C\u6362\u5668\u547D\u4EE4\u53EF\u7528\u6027...","settings.diagnostics.available":"\u53EF\u7528","settings.diagnostics.notFound":"\u672A\u627E\u5230","settings.diagnostics.sourceLabel":"\u6765\u6E90","settings.diagnostics.commandLabel":"\u547D\u4EE4","settings.diagnostics.resolvedPathLabel":"\u89E3\u6790\u8DEF\u5F84","settings.diagnostics.selfCheckLabel":"\u81EA\u68C0","settings.diagnostics.selfCheckOk":"\u901A\u8FC7","settings.diagnostics.selfCheckFailed":"\u5931\u8D25","settings.diagnostics.cadPythonCheck":"Python \u5305\uFF08cadquery\u3001trimesh\uFF09","settings.diagnostics.meshPythonCheck":"Python \u5305\uFF08trimesh\u3001numpy\u3001networkx\u3001collada\uFF09","settings.diagnostics.freecadCmdCheck":"FreeCADCmd \u542F\u52A8\u63A2\u6D4B","settings.diagnostics.obj2gltfCheck":"obj2gltf \u542F\u52A8\u63A2\u6D4B","settings.diagnostics.fbx2gltfCheck":"FBX2glTF \u542F\u52A8\u63A2\u6D4B","settings.canvasHeight":"\u9ED8\u8BA4\u753B\u5E03\u9AD8\u5EA6","settings.canvasHeight.desc":"\u5185\u8054 3D \u9884\u89C8\u7684\u9ED8\u8BA4\u9AD8\u5EA6\uFF08\u50CF\u7D20\uFF09\u3002\u8303\u56F4\uFF1A200\u2013800\u3002","settings.autoRotateSpeed":"\u81EA\u52A8\u65CB\u8F6C\u901F\u5EA6","settings.autoRotateSpeed.desc":"\u542F\u7528\u81EA\u52A8\u65CB\u8F6C\u65F6\u7684\u65CB\u8F6C\u901F\u5EA6\u3002\u8303\u56F4\uFF1A0.1\u20132.0\u3002","settings.renderQuality":"\u6E32\u67D3\u8D28\u91CF","settings.renderQuality.desc":"\u66F4\u9AD8\u8D28\u91CF\u4F7F\u7528\u66F4\u591A GPU \u8D44\u6E90\u3002\u5F71\u54CD\u6297\u952F\u9F7F\u548C\u5206\u8FA8\u7387\u3002","settings.renderScale":"\u6E32\u67D3\u7F29\u653E","settings.renderScale.desc":"\u6E32\u67D3\u5206\u8FA8\u7387\u500D\u6570\u30021.0 = \u539F\u59CB\uFF0C0.5 = \u4E00\u534A\uFF0C2.0 = \u53CC\u500D\uFF08\u8D85\u91C7\u6837\uFF09\u3002\u8303\u56F4\uFF1A0.25\u20132.0\u3002","modelLoad.warningTitle":"\u6682\u65F6\u65E0\u6CD5\u9884\u89C8\u6A21\u578B","modelLoad.warningMessage":"{ext} \u6587\u4EF6\u9700\u8981\u5148\u5728\u63D2\u4EF6\u8BBE\u7F6E\u4E2D\u542F\u7528 {converterName} \u8F6C\u6362\u5668\uFF0C\u624D\u80FD\u52A0\u8F7D\u3002","modelLoad.warningHint":"\u8BF7\u5148\u5728\u63D2\u4EF6\u8BBE\u7F6E\u4E2D\u542F\u7528\u5BF9\u5E94\u8F6C\u6362\u5668\uFF0C\u7136\u540E\u91CD\u65B0\u52A0\u8F7D\u5F53\u524D\u6587\u4EF6\u3002","modelLoad.mobileWarningMessage":"{ext} \u6587\u4EF6\u9700\u8981\u672C\u5730\u8F6C\u6362\u5DE5\u5177\uFF0C\u4F46\u8FD9\u4E9B\u5DE5\u5177\u5728 iOS\u3001iPadOS \u548C Android \u4E0A\u4E0D\u53EF\u7528\u3002","modelLoad.mobileWarningHint":"\u8BF7\u5728\u684C\u9762\u7AEF\u6253\u5F00\u6B64\u6587\u4EF6\uFF0C\u6216\u5148\u5C06\u5B83\u8F6C\u6362\u4E3A GLB\u3001GLTF\u3001OBJ\u3001STL \u6216 PLY\u3002","modelLoad.errorTitle":"\u65E0\u6CD5\u663E\u793A\u8FD9\u4E2A\u6A21\u578B","modelLoad.errorMessage":"\u52A0\u8F7D\u5931\u8D25\uFF1A{reason}","modelLoad.errorHint":"\u8BF7\u68C0\u67E5\u6587\u4EF6\u683C\u5F0F\uFF0C\u6216\u6253\u5F00\u5F00\u53D1\u8005\u63A7\u5236\u53F0\u67E5\u770B\u8BE6\u7EC6\u4FE1\u606F\u3002","headingPin.showSingle":"\u663E\u793A\u5173\u8054\u6807\u6CE8","headingPin.showMultiple":"\u663E\u793A\u5173\u8054\u6807\u6CE8","headingPin.linkedTo":"\u5173\u8054\u5230\uFF1A{models}","helper.resetViewLabel":"\u91CD\u7F6E\u89C6\u56FE","helper.resetViewDone":"\u5DF2\u91CD\u7F6E","helper.copyModelInfoLabel":"\u590D\u5236\u6A21\u578B\u4FE1\u606F\u4E3A Markdown","helper.copySelectedPartInfoLabel":"\u590D\u5236\u9009\u4E2D\u90E8\u4EF6\u4FE1\u606F","helper.noSelectedPart":"\u8BF7\u5148\u70B9\u51FB\u4E00\u4E2A\u90E8\u4EF6","helper.copied":"\u5DF2\u590D\u5236","helper.failed":"\u5931\u8D25","helper.toggleWireframeLabel":"\u5207\u6362\u7EBF\u6846\u663E\u793A","helper.wireframeOn":"\u7EBF\u6846","helper.wireframeOff":"\u5B9E\u4F53","helper.toggleAxesLabel":"\u5207\u6362\u65B9\u5411\u5750\u6807\u8F74","helper.axesOn":"\u5750\u6807\u8F74\u5DF2\u5F00\u542F","helper.axesOff":"\u5750\u6807\u8F74\u5DF2\u5173\u95ED","helper.toggleBoundingBoxLabel":"\u5207\u6362\u5305\u56F4\u76D2","helper.boundingBoxOn":"\u5305\u56F4\u76D2\u5DF2\u5F00\u542F","helper.boundingBoxOff":"\u5305\u56F4\u76D2\u5DF2\u5173\u95ED","helper.toggleFocusSelectionLabel":"\u805A\u7126\u9009\u4E2D\u90E8\u4EF6","helper.focusSelectionOn":"\u805A\u7126\u6A21\u5F0F\u5DF2\u5F00\u542F","helper.focusSelectionOff":"\u805A\u7126\u6A21\u5F0F\u5DF2\u5173\u95ED","helper.toggleDisassemblyLabel":"\u5207\u6362\u5206\u89E3\u6A21\u5F0F","helper.disassemblyOn":"\u5206\u89E3\u6A21\u5F0F\u5DF2\u5F00\u542F","helper.disassemblyOff":"\u5206\u89E3\u6A21\u5F0F\u5DF2\u5173\u95ED","helper.resetPartsLabel":"\u91CD\u7F6E\u5206\u89E3\u90E8\u4EF6","helper.partsReset":"\u90E8\u4EF6\u5DF2\u91CD\u7F6E","helper.changeResolutionLabel":"\u5207\u6362\u5206\u8FA8\u7387","helper.resolutionValue":"\u5206\u8FA8\u7387\uFF1A{value}","helper.toggleAnimationLabel":"\u64AD\u653E\u6216\u6682\u505C\u52A8\u753B","helper.playing":"\u64AD\u653E\u4E2D","helper.paused":"\u5DF2\u6682\u505C","helper.toggleMeasurementLabel":"\u5207\u6362\u8DDD\u79BB\u6D4B\u91CF","helper.measurementOn":"\u6D4B\u91CF\u5DF2\u5F00\u542F","helper.measurementOff":"\u6D4B\u91CF\u5DF2\u5173\u95ED","helper.clearMeasurementsLabel":"\u6E05\u9664\u6D4B\u91CF","helper.measurementsCleared":"\u5DF2\u6E05\u9664","helper.calibrateLabel":"\u6821\u51C6\u6D4B\u91CF\u6BD4\u4F8B","helper.calibrateTitle":"\u6D4B\u91CF\u6821\u51C6","helper.calibrateCurrent":"\u5F53\u524D\u5C3A\u5BF8\uFF1A","helper.calibrateReal":"\u771F\u5B9E\u5C3A\u5BF8\uFF1A","helper.calibrateLock":"\u9501\u5B9A\u6BD4\u4F8B","helper.calibrateApply":"\u5E94\u7528","helper.calibrateReset":"\u91CD\u7F6E","helper.calibrated":"\u6BD4\u4F8B\u5DF2\u5E94\u7528","helper.calibrateResetDone":"\u6BD4\u4F8B\u5DF2\u91CD\u7F6E","helper.calibrateOpen":"\u6821\u51C6\u9762\u677F\u5DF2\u6253\u5F00","helper.calibrateClose":"\u6821\u51C6\u9762\u677F\u5DF2\u5173\u95ED","helper.removePreviewLabel":"\u79FB\u9664\u9884\u89C8","helper.copySnapshotLabel":"\u590D\u5236\u5FEB\u7167","helper.saveSnapshotLabel":"\u4FDD\u5B58\u5FEB\u7167\u5230\u4ED3\u5E93","helper.saved":"\u5DF2\u4FDD\u5B58","helper.downloadSnapshotLabel":"\u4E0B\u8F7D\u5FEB\u7167","helper.downloaded":"\u5DF2\u4E0B\u8F7D","helper.toggleAnnotationLabel":"\u5207\u6362\u6807\u6CE8\u6A21\u5F0F","helper.toggleAnnotationsVisibilityLabel":"\u663E\u793A\u6216\u9690\u85CF\u6807\u6CE8","helper.annotateOn":"\u6807\u6CE8\u6A21\u5F0F\u5DF2\u5F00\u542F","helper.annotateOff":"\u6807\u6CE8\u6A21\u5F0F\u5DF2\u5173\u95ED","helper.annotationsVisible":"\u6807\u6CE8\u5DF2\u663E\u793A","helper.annotationsHidden":"\u6807\u6CE8\u5DF2\u9690\u85CF","helper.enableInteractionLabel":"\u542F\u7528\u89E6\u63A7\u4EA4\u4E92","helper.disableInteractionLabel":"\u5207\u56DE\u6EDA\u52A8\u6A21\u5F0F","helper.interactionOn":"\u6A21\u578B\u4EA4\u4E92\u5DF2\u5F00\u542F","helper.interactionOff":"\u6EDA\u52A8\u6A21\u5F0F\u5DF2\u5F00\u542F","helper.showMoreActionsLabel":"\u663E\u793A\u66F4\u591A\u64CD\u4F5C","helper.hideMoreActionsLabel":"\u6536\u8D77\u989D\u5916\u64CD\u4F5C","helper.moreActionsShown":"\u5DF2\u5C55\u5F00\u66F4\u591A\u64CD\u4F5C","helper.moreActionsHidden":"\u5DF2\u6536\u8D77\u989D\u5916\u64CD\u4F5C","helper.interactAction":"\u4EA4\u4E92","helper.scrollAction":"\u6EDA\u52A8","workbench.emptyTitle":"\u6682\u65E0\u6A21\u578B","workbench.emptyText":"\u4F7F\u7528\u201C\u5BFC\u5165 3D \u6A21\u578B\u201D\u547D\u4EE4\u52A0\u8F7D GLB\u3001GLTF\u3001STL\u3001OBJ \u6216 PLY \u6587\u4EF6\u3002","workbench.modelTitle":"3D \u6A21\u578B","workbench.studioTitle":"AI \u6A21\u578B\u5DE5\u4F5C\u53F0","workbench.studioTagline":"\u68C0\u67E5\u3001\u6807\u6CE8\uFF0C\u5E76\u628A 3D \u8D44\u4EA7\u6574\u7406\u6210\u53CC\u94FE\u7B14\u8BB0\u3002","workbench.navLabel":"\u5DE5\u4F5C\u53F0\u5206\u533A","workbench.navGallery":"\u753B\u5ECA","workbench.navLibrary":"\u8D44\u6599\u5E93","workbench.navNotebooks":"\u7B14\u8BB0\u672C","workbench.navSettings":"\u8BBE\u7F6E","workbench.sourcesTitle":"\u6A21\u578B\u6765\u6E90","workbench.layersTitle":"\u5BA1\u9605\u5C42","workbench.viewModeTitle":"\u89C6\u56FE\u6A21\u5F0F","workbench.modeMesh":"\u7F51\u683C\u89C6\u56FE","workbench.modeFocus":"\u805A\u7126\u9009\u533A","workbench.modeMeshShort":"\u7F51\u683C","workbench.modeFocusShort":"\u805A\u7126","workbench.previewViewsTitle":"\u9884\u89C8\u89C6\u56FE","workbench.connectionsTitle":"\u77E5\u8BC6\u8FDE\u63A5","workbench.currentModelLabel":"\u5F53\u524D\u6A21\u578B","workbench.noReportYet":"\u8FD8\u6CA1\u6709\u62A5\u544A\u7B14\u8BB0","workbench.noIndexYet":"\u8FD8\u6CA1\u6709\u77E5\u8BC6\u7D22\u5F15\u3002\u8BF7\u5148\u751F\u6210\u77E5\u8BC6\u7B14\u8BB0\u3002","workbench.noModelLoaded":"\u5C1A\u672A\u52A0\u8F7D\u6A21\u578B","workbench.disassemblyTitle":"\u5206\u89E3","workbench.explodeLabel":"\u7206\u70B8","workbench.summaryTitle":"\u6458\u8981","workbench.meshesLabel":"\u7F51\u683C","workbench.splatsLabel":"\u70B9\u4E91","workbench.trianglesLabel":"\u4E09\u89D2\u5F62","workbench.verticesLabel":"\u9876\u70B9","workbench.materialsLabel":"\u6750\u8D28","workbench.boundingSizeLabel":"\u5305\u56F4\u76D2","workbench.centerLabel":"\u4E2D\u5FC3","workbench.selectedPartTitle":"\u5F53\u524D\u9009\u4E2D\u90E8\u4EF6","workbench.partMeshLabel":"\u7F51\u683C","workbench.noSelectedPart":"\u70B9\u51FB\u6A21\u578B\u4E2D\u7684\u90E8\u4EF6\u540E\u4F1A\u663E\u793A\u8BE6\u7EC6\u4FE1\u606F\u3002","workbench.tagsTitle":"\u6807\u7B7E","workbench.noTagsYet":"\u8FD8\u6CA1\u6709\u6807\u7B7E","workbench.addTagPlaceholder":"\u6DFB\u52A0\u6807\u7B7E...","workbench.addTagAction":"\u6DFB\u52A0","workbench.annotationsTitle":"\u6807\u6CE8","workbench.exitAnnotate":"\u9000\u51FA\u6807\u6CE8","workbench.annotate":"\u6807\u6CE8","workbench.annotateHintActive":"\u70B9\u51FB\u6A21\u578B\u6DFB\u52A0\u6807\u7B7E \xB7 \u6309 Esc \u9000\u51FA","workbench.annotateHintActiveMobile":"\u70B9\u6309\u6A21\u578B\u6DFB\u52A0\u6807\u7B7E\u3002\u9700\u8981\u7EE7\u7EED\u9605\u8BFB\u65F6\u5207\u56DE\u201C\u6EDA\u52A8\u201D\u3002","workbench.pinCount":"{count} \u4E2A\u6807\u6CE8","workbench.editAction":"\u7F16\u8F91","workbench.deleteAction":"\u5220\u9664","workbench.resetViewAction":"\u91CD\u7F6E\u89C6\u56FE","workbench.insertInfoAction":"\u63D2\u5165\u4FE1\u606F","workbench.insertGalleryAction":"\u63D2\u5165 Gallery","workbench.insertCompareAction":"\u63D2\u5165\u5BF9\u6BD4","workbench.playAction":"\u64AD\u653E","workbench.pauseAction":"\u6682\u505C","workbench.saveProfileAction":"\u4FDD\u5B58\u914D\u7F6E","workbench.generateNoteAction":"\u751F\u6210\u7B14\u8BB0","workbench.openNoteAction":"\u6253\u5F00\u7B14\u8BB0","workbench.openIndexAction":"\u6253\u5F00\u7D22\u5F15","workbench.recordTitle":"\u6807\u672C\u5361","workbench.recordSubtitle":"\u5F53\u524D\u8D44\u4EA7\u6863\u6848","workbench.notesTitle":"\u5206\u6790\u672D\u8BB0","workbench.whereTitle":"\u5173\u8054\u4F4D\u7F6E","workbench.noteReady":"\u5173\u8054\u7B14\u8BB0\u5DF2\u5C31\u7EEA","workbench.indexReady":"\u77E5\u8BC6\u7D22\u5F15\u5DF2\u5C31\u7EEA","workbench.notePending":"\u5173\u8054\u7B14\u8BB0\u5F85\u751F\u6210","workbench.analysisLabel":"\u5206\u6790","workbench.settingsUnavailable":"\u8BF7\u4ECE Obsidian \u8BBE\u7F6E\u4E2D\u6253\u5F00\u672C\u63D2\u4EF6\u6765\u8C03\u6574\u5DE5\u4F5C\u53F0\u9009\u9879\u3002","workbench.profileSaved":"\u914D\u7F6E\u5DF2\u4FDD\u5B58","workbench.viewReset":"\u89C6\u56FE\u5DF2\u91CD\u7F6E","workbench.infoInserted":"\u6A21\u578B\u4FE1\u606F\u5DF2\u63D2\u5165","workbench.infoCopied":"\u6A21\u578B\u4FE1\u606F\u5DF2\u590D\u5236","workbench.templateInserted":"\u6A21\u677F\u5DF2\u63D2\u5165","workbench.templateCopied":"\u6A21\u677F\u5DF2\u590D\u5236","workbench.mobileHint":"\u79FB\u52A8\u7AEF\u63D0\u793A\uFF1A\u9700\u8981\u64CD\u4F5C\u6A21\u578B\u65F6\u70B9\u201C\u4EA4\u4E92\u201D\uFF0C\u7EE7\u7EED\u9605\u8BFB\u7B14\u8BB0\u65F6\u5207\u56DE\u201C\u6EDA\u52A8\u201D\u3002","workbench.mobileHintInteractive":"\u5F53\u524D\u4E3A\u4EA4\u4E92\u6A21\u5F0F\u3002\u9700\u8981\u7EE7\u7EED\u6EDA\u52A8\u7B14\u8BB0\u65F6\uFF0C\u8BF7\u5207\u56DE\u201C\u6EDA\u52A8\u201D\u3002","directView.mobileHint":"\u79FB\u52A8\u7AEF\u63D0\u793A\uFF1A\u4F7F\u7528\u4E0B\u65B9\u5DE5\u5177\u680F\u91CC\u7684\u201C\u4EA4\u4E92\u201D\u6309\u94AE\uFF0C\u5728\u6A21\u578B\u64CD\u4F5C\u548C\u7B14\u8BB0\u6EDA\u52A8\u4E4B\u95F4\u5207\u6362\u3002","directWorkbench.modelLoadInterrupted":"\u6A21\u578B\u52A0\u8F7D\u88AB\u65B0\u8BF7\u6C42\u4E2D\u65AD\u3002","directWorkbench.backendLabel":"\u540E\u7AEF","directWorkbench.routeLabel":"\u8DEF\u7531","directWorkbench.performanceLabel":"\u6027\u80FD","directWorkbench.partCandidatesLabel":"\u5019\u9009\u96F6\u4EF6","directWorkbench.knowledgeTitle":"\u77E5\u8BC6","directWorkbench.registeredTitle":"\u5DF2\u6CE8\u518C\u96F6\u4EF6\u5339\u914D","directWorkbench.registeredLoading":"\u68C0\u67E5\u4E2D...","directWorkbench.registeredCount":"{count} \u4E2A\u5339\u914D","directWorkbench.registeredEmpty":"\u6682\u65E0\u8DE8\u6A21\u578B\u96F6\u4EF6\u5339\u914D","directWorkbench.registeredUnavailable":"\u6682\u65E0\u96F6\u4EF6\u8BC1\u636E","directWorkbench.registeredOpen":"\u6253\u5F00","directWorkbench.registeredOpenNote":"\u7B14\u8BB0","directWorkbench.registeredOpenModel":"\u6A21\u578B","directWorkbench.registeredSourceModel":"\u6765\u81EA {model}","directWorkbench.registeredTargetPartNote":"\u6253\u5F00\u5339\u914D\u96F6\u4EF6\u7B14\u8BB0","directWorkbench.registeredTargetSourceModel":"\u6253\u5F00\u6765\u6E90\u6A21\u578B","directWorkbench.registeredTargetUnavailable":"\u6682\u65E0\u53EF\u6253\u5F00\u76EE\u6807","workbench.fileNotFound":"\u672A\u627E\u5230\u6587\u4EF6\uFF1A{path}","annotation.selectColor":"\u9009\u62E9\u989C\u8272 {color}","annotation.sectionEmpty":"\u8BE5\u6BB5\u5185\u5BB9\u4E3A\u7A7A\u3002","modal.selectModel":"\u9009\u62E9\u4E00\u4E2A 3D \u6A21\u578B...","main.commandImportModel":"\u5BFC\u5165 3D \u6A21\u578B","main.commandGenerateNote":"\u751F\u6210\u77E5\u8BC6\u7B14\u8BB0","main.commandOpenKnowledgeIndex":"\u6253\u5F00\u77E5\u8BC6\u7D22\u5F15","main.commandClearConversionCache":"\u6E05\u9664\u8F6C\u6362\u7F13\u5B58","main.commandCheckConverters":"\u68C0\u67E5\u8F6C\u6362\u5668","main.commandCopyDiagnostics":"\u590D\u5236\u8BCA\u65AD\u62A5\u544A","main.converterDiagnosticsMobileUnavailable":"\u8F6C\u6362\u5668\u8BCA\u65AD\u4EC5\u652F\u6301\u684C\u9762\u7AEF\u3002\u5728 iOS\u3001iPadOS \u548C Android \u4E0A\uFF0C\u76F4\u8BFB\u683C\u5F0F\u4ECD\u53EF\u52A0\u8F7D\u3002","main.diagnosticsCopied":"AI Model Workbench \u8BCA\u65AD\u62A5\u544A\u5DF2\u590D\u5236\u5230\u526A\u8D34\u677F\u3002","main.diagnosticsCopyFailed":"\u65E0\u6CD5\u590D\u5236\u8BCA\u65AD\u62A5\u544A\uFF0C\u5DF2\u6539\u4E3A\u521B\u5EFA\u4E00\u4EFD\u8131\u654F\u8BCA\u65AD\u7B14\u8BB0\u3002","codeBlock.noModelPathOrConfig":"\u672A\u6307\u5B9A\u6A21\u578B\u8DEF\u5F84\u6216\u914D\u7F6E\u3002","codeBlock.jsonParseError":"JSON \u89E3\u6790\u9519\u8BEF\uFF1A{error}","codeBlock.jsonParseLine":"\uFF08\u7B2C {line} \u884C\uFF09","codeBlock.noModelsInConfig":"\u914D\u7F6E\u4E2D\u672A\u6307\u5B9A\u6A21\u578B\u3002","codeBlock.unsupportedFormat":"\u4E0D\u652F\u6301\u7684\u683C\u5F0F\uFF1A{ext}\u3002\u652F\u6301\uFF1A{formats}","codeBlock.splatDisabled":"\u5F53\u524D\u6253\u5305\u7248\u672C\u6682\u672A\u542F\u7528 SPLAT \u9884\u89C8\u3002\u540E\u7EED\u4F1A\u4F18\u5148\u6062\u590D\u672C\u5730-only .splat\uFF1B.spz/.sog \u9700\u8981\u672C\u5730\u6253\u5305\u89E3\u7801\u5668\u540E\u518D\u8BC4\u4F30\u3002","codeBlock.noConfigSpecified":"\u672A\u6307\u5B9A\u914D\u7F6E\u3002","codeBlock.noModelsSpecified":"\u672A\u6307\u5B9A\u6A21\u578B\u3002","codeBlock.mobileHint":"\u79FB\u52A8\u7AEF\u63D0\u793A\uFF1A\u9700\u8981\u64CD\u4F5C\u6A21\u578B\u65F6\u70B9\u201C\u4EA4\u4E92\u201D\uFF0C\u7EE7\u7EED\u9605\u8BFB\u7B14\u8BB0\u65F6\u5207\u56DE\u201C\u6EDA\u52A8\u201D\u3002","codeBlock.renderingGrid":"\u6B63\u5728\u6E32\u67D3\u7F51\u683C...","codeBlock.composeRequiresSections":"\u201Ccompose\u201D \u9884\u8BBE\u9700\u8981\u63D0\u4F9B \u201Csections\u201D \u6570\u7EC4\u3002","codeBlock.composeNoValidSections":"Compose\uFF1A\u6CA1\u6709\u6709\u6548\u7684\u5206\u6BB5\u3002","codeBlock.unknownPreset":"\u672A\u77E5\u9884\u8BBE\uFF1A\u201C{preset}\u201D\u3002\u53EF\u7528\uFF1Acompare\u3001showcase\u3001explode\u3001timeline\u3001compose","codeBlock.presetRequiresModels":"\u9884\u8BBE \u201C{preset}\u201D \u9700\u8981 {min}-{max} \u4E2A\u6A21\u578B\uFF0C\u5F53\u524D\u4E3A {count} \u4E2A\u3002","codeBlock.gridFailed":"\u7F51\u683C\u6E32\u67D3\u5931\u8D25\uFF1A{reason}","livePreview.mobileHint":"\u79FB\u52A8\u7AEF\u63D0\u793A\uFF1A\u9700\u8981\u62D6\u52A8\u6A21\u578B\u65F6\u5207\u5230\u201C\u4EA4\u4E92\u201D\uFF0C\u7EE7\u7EED\u9605\u8BFB\u65F6\u5207\u56DE\u201C\u6EDA\u52A8\u201D\u3002","loading.default":"\u52A0\u8F7D\u4E2D...","loading.preparingModel":"\u6B63\u5728\u51C6\u5907\u6A21\u578B...","loading.loadingModel":"\u6B63\u5728\u52A0\u8F7D\u6A21\u578B..."}});function Rp(n){KN=n;for(let e of Bb)e()}function J(n){var e,t,i;return(i=(t=(e=Wq[KN])==null?void 0:e[n])!=null?t:Fb[n])!=null?i:n}function jN(n){return Bb.add(n),()=>{Bb.delete(n)}}function Hq(n,e){return n.replace(/\{(\w+)\}/g,(t,i)=>{var r;return(r=e[i])!=null?r:""})}function dr(n,e){return Hq(J(n),e)}var Wq,KN,Bb,ra=C(()=>{"use strict";zN();YN();Wq={en:Fb,"zh-CN":XN},KN="en",Bb=new Set});function zq(){if("require"in activeWindow)return activeWindow.require}function dv(){if("process"in activeWindow)return activeWindow.process}function bp(n){let e=zq();if(!e)return null;try{return e(n)}catch(t){return null}}function ls(n,e){if(n===null)throw new Error(`${e} is not available in this environment (mobile or web).`);return n}function cs(n,e){return ls(Dd,"node:fs/promises").access(n,e)}function na(n){return ls(Dd,"node:fs/promises").readFile(n)}function Ld(n,e,t){return ls(Dd,"node:fs/promises").writeFile(n,e,{encoding:t})}function Od(n,e){return ls(Dd,"node:fs/promises").mkdir(n,e)}function Nd(n,e){return ls(Dd,"node:fs/promises").rm(n,e)}function $N(n){return ls(Dd,"node:fs/promises").stat(n)}function zi(...n){return ls(El,"node:path").join(...n)}function Mo(n){return ls(El,"node:path").dirname(n)}function Co(n,e){return ls(El,"node:path").basename(n,e)}function sa(n){return ls(El,"node:path").extname(n)}function Ub(n){return ls(El,"node:path").normalize(n)}function Yn(n){return ls(El,"node:path").isAbsolute(n)}function aa(n,e,t,i){ls(Xq,"node:child_process").execFile(n,e,t,i)}function wd(){return ls(Yq,"node:os").tmpdir()}var Dd,Pd,El,Xq,Yq,qN,fs,ZN,JN,QN,ew,ar=C(()=>{"use strict";Dd=bp("node:fs/promises"),Pd=bp("node:fs"),El=bp("node:path"),Xq=bp("node:child_process"),Yq=bp("node:os");fs=(qN=Pd==null?void 0:Pd.constants.F_OK)!=null?qN:0,JN=(ZN=Pd==null?void 0:Pd.constants.X_OK)!=null?ZN:0;ew=(QN=El==null?void 0:El.delimiter)!=null?QN:":"});function Vb(n){return n.replace(/\\/g,"/")}function uv(n){let e=Vb(n),t=[];for(let i of e.split("/"))if(!(!i||i===".")){if(i===".."){t.pop();continue}t.push(i)}return t.join("/")}function tw(n){try{return decodeURIComponent(n)}catch(e){return n}}function ws(n,e){var r;let t=tw((r=e.split(/[?#]/,1)[0])!=null?r:e),i=uv(t);return n?uv(`${n}/${i}`):i}function Ip(n){let e=Vb(n).replace(/\/+$/,""),t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function oa(n){let e=Vb(n).replace(/\/+$/,""),t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}function jr(n){return oa(n).replace(/\.[^.]+$/,"")}async function Kq(n,e){let t=uv(e);if(!t)return null;let i=t.split("/"),r="",s=n.vault.getRoot().children;for(let a of i){let o=s.find(c=>c.name===a),l=o!=null?o:s.find(c=>c.name.toLowerCase()===a.toLowerCase());if(!l)return null;if(r=r?`${r}/${l.name}`:l.name,l instanceof Fd.TFile)return r;if(!(l instanceof Fd.TFolder))return null;s=l.children}return null}function jq(n){return Uint8Array.from(n).buffer}function qq(n){let e=n.vault.adapter;return typeof e.getBasePath=="function"?e.getBasePath():typeof e.basePath=="string"&&e.basePath.length>0?e.basePath:null}function Bd(n,e){var r,s;let t=n.vault.getAbstractFileByPath(e);if(t)return t.path;let i=(s=(r=n.metadataCache)==null?void 0:r.getFirstLinkpathDest)==null?void 0:s.call(r,e,"");return i?i.path:null}function eh(n,e){if(Yn(e))return Ub(e);let t=qq(n);return t?Ub(zi(t,e)):null}async function Ua(n,e){if(Yn(e)){let r=await na(e);return jq(r)}let t=uv(tw(e)),i=n.vault.getAbstractFileByPath(t);if(!(i instanceof Fd.TFile)){let r=await Kq(n,t);if(r){let s=n.vault.getAbstractFileByPath(r);if(s instanceof Fd.TFile)return n.vault.readBinary(s)}throw new Error(`File not found: ${t}`)}return n.vault.readBinary(i)}var Fd,la=C(()=>{"use strict";Fd=require("obsidian");ar();ar()});function Ht(n){return{x:n.x,y:n.y,z:n.z}}function qr(n){return{x:n.x,y:n.y,z:n.z}}function Ud(n,e){return{x:n.x-e.x,y:n.y-e.y,z:n.z-e.z}}function Mp(n,e){return{x:n.x*e,y:n.y*e,z:n.z*e}}function nw(n,e){let t=Ud(n,e);return Math.hypot(t.x,t.y,t.z)}function Gb(n){let e=Math.hypot(n.x,n.y,n.z);return e<=Number.EPSILON?null:Mp(n,1/e)}function th(n,e){return{x:n.x+e.x,y:n.y+e.y,z:n.z+e.z}}function iw(n,e){return n.x*e.x+n.y*e.y+n.z*e.z}function sw(n,e,t){return{x:e==="x"?n.x+t:n.x,y:e==="y"?n.y+t:n.y,z:e==="z"?n.z+t:n.z}}function aw(n){return Math.max(n*.01,.01)}function Nc(n,e,t=aw(e)){return n{"use strict"});function iZ(){return`pin-${Date.now()}-${$q++}`}function fw(n){return qr(n)}function rZ(n,e,t){return n.lefte.left-t&&n.tope.top-t}var Cp,Gd,$q,kb,Jq,eZ,ow,lw,tZ,cw,kd,Fc,vv=C(()=>{"use strict";Cp=require("obsidian");ra();la();Fs();Gd=["#4a9eff","#ff6b6b","#51cf66","#ffd43b","#845ef7","#ff922b","#22b8cf","#f06595","#94d82d","#ffa8a8"],$q=1,kb=4,Jq=2,eZ=6,ow=6,lw=72,tZ=80,cw=200;kd=class kd{constructor(e,t,i,r,s,a,o,l={}){this.provider=e;this.hostEl=t;this.mode=i;this.onChange=s;this.noteReader=a;this.headingSearch=o;this.pinEls=new Map;this.observer=null;this.resizeObs=null;this.annotations=[];this.editorEl=null;this.disposeCallbacks=[];this.frameCount=0;this.lastCamState="";this.idleFrames=0;this.cameraIdle=!1;this.movingOcclusionCursor=0;this.hoverPopover=null;this.hoverTimeout=null;this.hoverCloseTimeout=null;this.hoverRequestId=0;this._highlightHandler=null;this._pulseTimeout=null;this._headingDropdown=null;this._headingDebounce=null;this._selectedHeading=null;this.previewRenderRoot=new Cp.Component;this.previewRenderChildren=new WeakMap;var c,f;this.previewApp=l.app,this.previewMode=(c=l.previewMode)!=null?c:"plain-text",this.displayMode=(f=l.displayMode)!=null?f:"surface",this.previewRenderRoot.load(),this.overlay=this.hostEl.createDiv({cls:"ai3d-annotation-overlay"}),this.setAnnotations(r),this._highlightHandler=h=>{let d=h.detail,u=d==null?void 0:d.pinId;u&&this.pulsePin(u)},activeDocument.addEventListener("ai3d-pin-highlight",this._highlightHandler),this.disposeCallbacks.push(()=>activeDocument.removeEventListener("ai3d-pin-highlight",this._highlightHandler)),this.disposeCallbacks.push(()=>this.previewRenderRoot.unload()),this.startProjectionLoop()}setAnnotations(e){for(let[,t]of this.pinEls)this.removePinElement(t.el);this.pinEls.clear(),this.annotations=[...e];for(let t of e)this.createPinElement(t);this.updateProjections()}addPin(e,t,i){var s;if(this.annotations.length>=cw)return console.warn(`[AI3D] Pin limit (${cw}) reached; ignoring new pin.`),this.annotations[this.annotations.length-1];let r={id:iZ(),position:[e.x,e.y,e.z],label:t,color:i!=null?i:Gd[this.annotations.length%Gd.length],createdAt:new Date().toISOString()};return this.annotations.push(r),this.createPinElement(r),this.updateProjections(),(s=this.onChange)==null||s.call(this,this.annotations),r}removePin(e){var i;let t=this.pinEls.get(e);t&&(this.removePinElement(t.el),this.pinEls.delete(e)),this.annotations=this.annotations.filter(r=>r.id!==e),(i=this.onChange)==null||i.call(this,this.annotations)}updatePin(e,t){var s;let i=this.annotations.find(a=>a.id===e);if(!i)return;Object.assign(i,t);let r=this.pinEls.get(e);if(r){t.position&&(r.worldPos={x:t.position[0],y:t.position[1],z:t.position[2]});let a=r.el.querySelector(".ai3d-pin-label");a&&t.label!==void 0&&(a.textContent=t.label);let o=r.el.querySelector(".ai3d-pin-dot");o&&t.color!==void 0&&o.style.setProperty("--pin-color",t.color),(t.notePath!==void 0||t.headingRef!==void 0||t.label!==void 0)&&this.renderPinDisplay(r.el,i)}this.updateProjections(),(s=this.onChange)==null||s.call(this,this.annotations)}showEditor(e,t,i){this.showEditorInternal(e,t,i)}editPin(e){let t=this.annotations.find(o=>o.id===e);if(!t)return;let i=this.pinEls.get(e);if(!i)return;let r=i.el.getBoundingClientRect(),s=r.left+r.width/2,a=r.top;this.showEditorInternal(s,a,fw(i.worldPos),t)}getPinPosition(e){let t=this.pinEls.get(e);return t?fw(t.worldPos):null}getAnnotations(){return this.annotations}showEditorInternal(e,t,i,r){var O,V;this.hideEditor(),this._selectedHeading=null;let s=this.overlay.createDiv({cls:"ai3d-annotation-editor"}),a=s.createDiv({cls:"ai3d-editor-input-wrap"}),o=a.createEl("input",{cls:"ai3d-annotation-editor-input"});o.type="text",o.placeholder=this.headingSearch?"Label or search heading...":"Label...",r&&(o.value=r.label);let l=a.createSpan({cls:"ai3d-editor-binding-tag is-hidden"}),c=l.createEl("button",{cls:"ai3d-editor-binding-clear"});c.textContent="\xD7",c.addEventListener("click",N=>{N.stopPropagation(),this._selectedHeading=null,l.classList.add("is-hidden"),f.classList.add("is-hidden"),f.textContent="",o.value="",o.focus()});let f=s.createDiv({cls:"ai3d-editor-content-preview is-hidden"}),h=s.createDiv({cls:"ai3d-heading-dropdown is-hidden"});this._headingDropdown=h;let d=-1,u=[],m=N=>{let F=h.querySelectorAll(".ai3d-heading-dropdown-item");F.forEach(U=>U.classList.remove("active")),d=N,N>=0&&N{var k;this._selectedHeading=N,o.value=N.heading;let F=jr(N.notePath);(k=l.querySelector(".ai3d-editor-binding-text"))==null||k.remove();let U=l.createSpan({cls:"ai3d-editor-binding-text"});U.textContent=`\u{1F4C4} ${F}`,l.classList.remove("is-hidden"),_(),o.focus(),this.loadContentPreview(f,N.notePath,N.heading)},_=()=>{h.classList.add("is-hidden"),h.replaceChildren(),d=-1},g=N=>{if(h.replaceChildren(),d=-1,u=N,N.length===0){h.classList.add("is-hidden");return}for(let F=0;F{Q.preventDefault(),Q.stopPropagation(),p(U)}),k.addEventListener("mouseenter",()=>m(F))}h.classList.remove("is-hidden")};o.addEventListener("input",()=>{if(!this.headingSearch)return;this._headingDebounce&&window.clearTimeout(this._headingDebounce);let N=o.value.trim();if(N.length<1){_();return}this._headingDebounce=window.setTimeout(()=>{let F=this.headingSearch(N);g(F)},150)}),o.addEventListener("keydown",N=>{if(h.classList.contains("is-hidden")){N.key==="Enter"?(N.preventDefault(),R.click()):N.key==="Escape"&&(N.preventDefault(),this.hideEditor());return}let F=h.querySelectorAll(".ai3d-heading-dropdown-item");N.key==="ArrowDown"?(N.preventDefault(),m(Math.min(d+1,F.length-1))):N.key==="ArrowUp"?(N.preventDefault(),m(Math.max(d-1,0))):N.key==="Enter"?(N.preventDefault(),d>=0&&d{window.setTimeout(_,150)});let v=s.createDiv({cls:"ai3d-annotation-editor-colors"}),x=(O=r==null?void 0:r.color)==null?void 0:O.trim(),A=x||Gd[0],S=x&&!Gd.includes(x)?[x,...Gd]:Gd;for(let N of S){let F=v.createEl("button",{cls:"ai3d-pin-color-swatch"});F.type="button",F.title=N,F.setAttribute("aria-label",dr("annotation.selectColor",{color:N})),F.style.setProperty("--swatch-color",N),F.style.backgroundColor=N,N===A&&F.classList.add("is-selected"),F.addEventListener("click",U=>{U.stopPropagation(),A=N,v.querySelectorAll(".ai3d-pin-color-swatch").forEach(k=>k.classList.remove("is-selected")),F.classList.add("is-selected")})}let E=s.createDiv({cls:"ai3d-annotation-editor-actions"});if(r){let N=E.createEl("button",{cls:"ai3d-annotation-editor-btn ai3d-annotation-editor-delete"});N.textContent="Delete",N.addEventListener("click",F=>{F.stopPropagation(),this.removePin(r.id),this.hideEditor()})}let R=E.createEl("button",{cls:"ai3d-annotation-editor-btn ai3d-annotation-editor-confirm"});R.textContent=r?"Save":"OK",R.addEventListener("click",N=>{N.stopPropagation();let F=o.value.trim()||"Pin",U=this._selectedHeading;if(r){let k={label:F,color:A};U&&(k.notePath=U.notePath,k.headingRef=U.heading,k.headingLevel=U.level),this.updatePin(r.id,k)}else{let k=this.addPin(i,F,A);U&&this.updatePin(k.id,{notePath:U.notePath,headingRef:U.heading,headingLevel:U.level})}this.hideEditor()});let I=E.createEl("button",{cls:"ai3d-annotation-editor-btn ai3d-annotation-editor-cancel"});I.textContent="Cancel",I.addEventListener("click",N=>{N.stopPropagation(),this.hideEditor()});let y=this.overlay.getBoundingClientRect(),M=e-y.left,D=t-y.top;if(s.style.setProperty("--editor-left",`${Math.max(0,Math.min(M,y.width-220))}px`),s.style.setProperty("--editor-top",`${Math.max(0,Math.min(D-10,y.height-160))}px`),this.editorEl=s,r!=null&&r.notePath&&(r!=null&&r.headingRef)){let N=jr(r.notePath),F=l.createSpan({cls:"ai3d-editor-binding-text"});F.textContent=`\u{1F4C4} ${N}`,l.classList.remove("is-hidden"),this._selectedHeading={notePath:r.notePath,heading:r.headingRef,level:(V=r.headingLevel)!=null?V:2},this.loadContentPreview(f,r.notePath,r.headingRef)}window.requestAnimationFrame(()=>o.focus()),s.addEventListener("pointerdown",N=>N.stopPropagation()),s.addEventListener("mousedown",N=>N.stopPropagation())}hideEditor(){if(this._headingDebounce&&(window.clearTimeout(this._headingDebounce),this._headingDebounce=null),this._headingDropdown=null,this._selectedHeading=null,this.editorEl){let e=this.editorEl.querySelector(".ai3d-editor-content-preview");e&&this.clearRenderedPreview(e),this.editorEl.remove(),this.editorEl=null}}async loadContentPreview(e,t,i){if(!this.noteReader)return;this.clearRenderedPreview(e),e.classList.add("is-hidden");let r=await this.noteReader(t,i);if(!r){e.textContent=J("annotation.sectionEmpty"),e.className="ai3d-editor-content-preview ai3d-editor-content-preview--empty",e.classList.remove("is-hidden");return}await this.renderPreviewContent(e,r,t,"editor")}async showHoverPopover(e,t,i){if(!this.noteReader||!i.notePath||!i.headingRef)return;this.hideHoverPopover();let r=await this.noteReader(i.notePath,i.headingRef);if(!r||e!==this.hoverRequestId||!t.isConnected||!this.hostEl.isConnected)return;let s=createDiv({cls:"ai3d-pin-popover"}),a=s.createDiv({cls:"ai3d-pin-popover-title"});a.textContent=i.headingRef;let o=s.createDiv({cls:"ai3d-pin-popover-body"}),l=t.getBoundingClientRect();s.style.setProperty("--popover-left",`${l.left+l.width/2}px`),s.style.setProperty("--popover-top",`${l.bottom+4}px`),s.addEventListener("mouseenter",()=>this.cancelHoverClose()),s.addEventListener("mouseleave",()=>this.scheduleHoverClose()),activeDocument.body.appendChild(s),this.hoverPopover=s,await this.renderPreviewContent(o,r,i.notePath,"popover"),(e!==this.hoverRequestId||!t.isConnected||!this.hostEl.isConnected)&&(this.clearRenderedPreview(o),this.hoverPopover===s&&(this.hoverPopover=null),s.remove())}hideHoverPopover(){if(this.hoverTimeout&&(window.clearTimeout(this.hoverTimeout),this.hoverTimeout=null),this.hoverCloseTimeout&&(window.clearTimeout(this.hoverCloseTimeout),this.hoverCloseTimeout=null),this.hoverPopover){let e=this.hoverPopover.querySelector(".ai3d-pin-popover-body");e&&this.clearRenderedPreview(e),this.hoverPopover.remove(),this.hoverPopover=null}}cancelHoverClose(){this.hoverCloseTimeout&&(window.clearTimeout(this.hoverCloseTimeout),this.hoverCloseTimeout=null)}scheduleHoverClose(){this.hoverTimeout&&(window.clearTimeout(this.hoverTimeout),this.hoverTimeout=null,this.hoverRequestId++),this.cancelHoverClose(),this.hoverCloseTimeout=window.setTimeout(()=>{this.hoverCloseTimeout=null,this.hoverRequestId++,this.hideHoverPopover()},180)}clearRenderedPreview(e){let t=this.previewRenderChildren.get(e);t&&(this.previewRenderRoot.removeChild(t),this.previewRenderChildren.delete(e)),e.replaceChildren()}removePinElement(e){e.querySelectorAll(".ai3d-rendered-preview").forEach(t=>{this.clearRenderedPreview(t)}),e.remove()}async renderPreviewContent(e,t,i,r){let s=this.previewMode==="markdown"&&!!this.previewApp,a=r==="editor",o=r==="pin-snippet";if(!s){let c=a?300:o?180:1/0,f=t.length>c?t.slice(0,c)+"...":t;e.textContent=f,e.className=a?"ai3d-editor-content-preview":o?"ai3d-pin-snippet ai3d-rendered-preview":"ai3d-pin-popover-body ai3d-rendered-preview",a&&e.classList.remove("is-hidden");return}e.className=a?"ai3d-editor-content-preview ai3d-editor-content-preview--markdown markdown-rendered":o?"ai3d-pin-snippet ai3d-pin-snippet--markdown ai3d-rendered-preview markdown-rendered":"ai3d-pin-popover-body ai3d-pin-popover-body--markdown ai3d-rendered-preview markdown-rendered",a&&e.classList.remove("is-hidden");let l=this.previewRenderRoot.addChild(new Cp.Component);this.previewRenderChildren.set(e,l);try{await Cp.MarkdownRenderer.render(this.previewApp,t,e,i,l)}catch(c){this.previewRenderRoot.removeChild(l),this.previewRenderChildren.delete(e);let f=a?300:o?180:1/0;e.textContent=t.length>f?t.slice(0,f)+"...":t,e.className=a?"ai3d-editor-content-preview":o?"ai3d-pin-snippet ai3d-rendered-preview":"ai3d-pin-popover-body ai3d-rendered-preview",a&&e.classList.remove("is-hidden"),console.warn("[AI3D] Annotation markdown preview fallback:",c)}}pulsePin(e){let t=this.pinEls.get(e);t&&(this._pulseTimeout&&(window.clearTimeout(this._pulseTimeout),this._pulseTimeout=null),t.el.classList.remove("ai3d-pin-pulse"),t.el.offsetWidth,t.el.classList.add("ai3d-pin-pulse"),this._pulseTimeout=window.setTimeout(()=>{t.el.classList.remove("ai3d-pin-pulse"),this._pulseTimeout=null},1200))}destroy(){var e,t,i;this.hoverRequestId++,this.hideHoverPopover(),this._pulseTimeout&&(window.clearTimeout(this._pulseTimeout),this._pulseTimeout=null),this._headingDebounce&&(window.clearTimeout(this._headingDebounce),this._headingDebounce=null),this._headingDropdown=null,this._selectedHeading=null,(e=this.observer)==null||e.remove(),this.observer=null,(t=this.resizeObs)==null||t.disconnect(),this.resizeObs=null;for(let r of this.disposeCallbacks)r();this.disposeCallbacks=[],this.overlay.remove(),this.pinEls.clear(),(i=this.editorEl)==null||i.remove(),this.editorEl=null}createPinElement(e){let t=this.overlay.createDiv({cls:"ai3d-annotation-pin"});if(t.dataset.pinId=e.id,this.renderPinDisplay(t,e),this.mode==="edit"){let i=t.createEl("button",{cls:"ai3d-pin-delete"});i.textContent="\xD7",i.addEventListener("click",r=>{r.stopPropagation(),this.removePin(e.id)}),t.addEventListener("click",r=>{r.target.closest(".ai3d-pin-delete")||(r.stopPropagation(),this.editPin(e.id))})}t.addEventListener("pointerdown",i=>i.stopPropagation()),t.addEventListener("wheel",i=>{i.preventDefault(),i.stopPropagation(),this.provider.canvas.dispatchEvent(new WheelEvent("wheel",{bubbles:!0,cancelable:!0,clientX:i.clientX,clientY:i.clientY,ctrlKey:i.ctrlKey,deltaMode:i.deltaMode,deltaX:i.deltaX,deltaY:i.deltaY,deltaZ:i.deltaZ,metaKey:i.metaKey,shiftKey:i.shiftKey}))},{passive:!1}),e.notePath&&e.headingRef&&this.noteReader&&(t.addEventListener("mouseenter",()=>{this.cancelHoverClose(),this.hoverTimeout&&window.clearTimeout(this.hoverTimeout);let i=++this.hoverRequestId;this.hoverTimeout=window.setTimeout(()=>{this.hoverTimeout=null,i===this.hoverRequestId&&this.showHoverPopover(i,t,e)},300)}),t.addEventListener("mouseleave",()=>{this.scheduleHoverClose()})),this.pinEls.set(e.id,{el:t,worldPos:{x:e.position[0],y:e.position[1],z:e.position[2]}})}renderPinDisplay(e,t){let i=e.querySelector(".ai3d-pin-delete");if(e.querySelectorAll(".ai3d-rendered-preview").forEach(s=>{this.clearRenderedPreview(s)}),e.replaceChildren(),e.className=`ai3d-annotation-pin ai3d-annotation-pin--${this.displayMode}`,e.createDiv({cls:"ai3d-pin-dot"}).style.setProperty("--pin-color",t.color),e.title=t.label,e.setAttribute("aria-label",t.label),this.displayMode!=="dot"){let s=e.createDiv({cls:"ai3d-pin-content"}),a=s.createSpan({cls:"ai3d-pin-label"});if(a.textContent=t.label,this.displayMode==="snippet"&&t.notePath&&t.headingRef&&this.noteReader){let o=s.createDiv({cls:"ai3d-pin-snippet ai3d-rendered-preview"});this.loadPinSnippet(o,t.notePath,t.headingRef)}}i&&e.appendChild(i)}async loadPinSnippet(e,t,i){if(!this.noteReader)return;let r=await this.noteReader(t,i);!r||!e.isConnected||await this.renderPreviewContent(e,r,t,"pin-snippet")}startProjectionLoop(){this.observer=this.provider.observeRender(()=>this.updateProjections()),this.resizeObs=new ResizeObserver(()=>this.updateProjections()),this.resizeObs.observe(this.provider.canvas)}updateProjections(){if(this.pinEls.size===0)return;let{canvas:e}=this.provider;if(!this.hostEl.isConnected||!e.isConnected||e.clientWidth===0||e.clientHeight===0)return;let t=this.provider.getCameraStateKey();t===this.lastCamState?this.idleFrames++:(this.idleFrames=0,this.cameraIdle=!1),this.lastCamState=t,this.idleFrames>=kd.IDLE_THRESHOLD&&!this.cameraIdle&&(this.cameraIdle=!0),this.frameCount++;let i=this.cameraIdle?1:this.pinEls.size>=12?3:2;if(!this.cameraIdle&&this.frameCount%i!==0)return;let r=Array.from(this.pinEls.values()),s=this.cameraIdle?this.frameCount%eZ===0:this.frameCount%Jq===0,a=this.cameraIdle||r.length<=kb,o=a?0:this.movingOcclusionCursor%r.length,l=o+kb,c=kd._scratchProjection,f=[];for(let h=0;h1||c.depth<0)this.hidePin(d.el);else{d.el.style.setProperty("--pin-left",`${c.screenX}px`),d.el.style.setProperty("--pin-top",`${c.screenY}px`),this.updatePinPriority(d.el,c.depth),f.push({el:d.el,screenX:c.screenX,screenY:c.screenY,depth:c.depth});let u=a||h>=o&&hr.length&&h0&&(this.movingOcclusionCursor=(o+kb)%r.length),this.applyLabelAvoidance(f)}updatePinPriority(e,t){let i=Math.max(0,Math.min(1,1-t)),r=this.cameraIdle?0:160,s=e.classList.contains("ai3d-pin-occluded")?80:0;e.style.zIndex=String(100+r+Math.round(i*120)-s)}applyLabelAvoidance(e){if(e.length===0)return;if(e.length>tZ){for(let a of e)a.el.style.removeProperty("--pin-offset-y");return}let i=e.filter(a=>!a.el.classList.contains("ai3d-pin-hidden")&&!a.el.classList.contains("ai3d-pin-occluded")).sort((a,o)=>a.depth-o.depth).map(a=>({pin:a,rect:a.el.getBoundingClientRect()})),r=[],s=[];for(let{pin:a,rect:o}of i){let l=0,c=o;for(let f of r){if(!rZ(c,f,ow))continue;let h=a.screenY>=f.top+f.height/2?1:-1;l=Math.max(-lw,Math.min(lw,l+h*(f.height+ow)));let d=c.width,u=c.height;c=new DOMRect(c.x,c.y+l,d,u)}r.push(c),s.push({el:a.el,offset:l})}for(let{el:a,offset:o}of s)a.setCssProps({"--pin-offset-y":o===0?"0px":`${o}px`})}hidePin(e){e.classList.remove("ai3d-pin-occluded"),e.classList.add("ai3d-pin-hidden")}showPin(e){e.classList.remove("ai3d-pin-hidden")}};kd.IDLE_THRESHOLD=15,kd._scratchProjection={screenX:0,screenY:0,depth:0};Fc=kd});function sZ(n){return n!=null?n:dw}function Wd(n){var c;let e=n.ext.trim().toLowerCase(),t=(c=n.annotationMode)!=null?c:"none",i=!!n.allowEditModeOnThree,r=!!n.allowWorkbenchFeaturesOnThree,s=!!n.requireWorkbenchFeatures,a=sZ(n.rendererRollout);if(!(n.useThreeRenderer!==!1))return{backend:"babylon",ext:e,annotationMode:t,requireWorkbenchFeatures:s,rendererRollout:a,reason:"useThreeRenderer=false"};if(hw.has(e)&&(!s||r)){if(s&&!nZ.has(e))return{backend:"babylon",ext:e,annotationMode:t,requireWorkbenchFeatures:s,rendererRollout:a,reason:`workbench experimental Three supports GLB/GLTF only, ext=${e}`};if(t==="edit"&&a!=="three-direct-glb")return{backend:"babylon",ext:e,annotationMode:t,requireWorkbenchFeatures:s,rendererRollout:a,reason:`annotationMode=edit, rendererRollout=${a}`};if(a==="babylon-safe")return{backend:"babylon",ext:e,annotationMode:t,requireWorkbenchFeatures:s,rendererRollout:a,reason:`rendererRollout=${a}`};if(t==="edit"&&!i)return{backend:"babylon",ext:e,annotationMode:t,requireWorkbenchFeatures:s,rendererRollout:a,reason:"annotationMode=edit, allowEditModeOnThree=false"};let f=s?`${e} workbench preview`:t==="edit"?`${e} direct view edit preview`:t==="readonly"?`${e} preview with readonly annotations`:`simple ${e} preview`;return{backend:"three",ext:e,annotationMode:t,requireWorkbenchFeatures:s,rendererRollout:a,reason:f}}let l=[];return hw.has(e)||l.push(`ext=${e}`),t!=="none"&&l.push(`annotationMode=${t}`),t==="edit"&&!i&&l.push("allowEditModeOnThree=false"),s&&l.push("requireWorkbenchFeatures=true"),a!==dw&&l.push(`rendererRollout=${a}`),{backend:"babylon",ext:e,annotationMode:t,requireWorkbenchFeatures:s,rendererRollout:a,reason:l.join(", ")||"fallback route"}}function uw(){return{backend:"babylon",reason:"grid previews remain on the Babylon grid renderer"}}var dw,hw,nZ,Ev=C(()=>{"use strict";dw="three-direct-glb",hw=new Set(["glb","gltf","stl","ply","obj"]),nZ=new Set(["glb","gltf"])});function aZ(n){for(let e=n.length-1;e>=0;--e)if(n[e]>=65535)return!0;return!1}function oZ(n){return ArrayBuffer.isView(n)&&!(n instanceof DataView)}function fu(n){return document.createElementNS("http://www.w3.org/1999/xhtml",n)}function wF(){let n=fu("canvas");return n.style.display="block",n}function zp(...n){let e="THREE."+n.shift();hu?hu("log",e,...n):console.log(e,...n)}function FF(n){let e=n[0];if(typeof e=="string"&&e.startsWith("TSL:")){let t=n[1];t&&t.isStackTrace?n[0]+=" "+t.getLocation():n[1]='Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'}return n}function Mt(...n){n=FF(n);let e="THREE."+n.shift();if(hu)hu("warn",e,...n);else{let t=n[0];t&&t.isStackTrace?console.warn(t.getError(e)):console.warn(e,...n)}}function Ft(...n){n=FF(n);let e="THREE."+n.shift();if(hu)hu("error",e,...n);else{let t=n[0];t&&t.isStackTrace?console.error(t.getError(e)):console.error(e,...n)}}function oE(...n){let e=n.join(" ");e in mw||(mw[e]=!0,Mt(...n))}function BF(n,e,t){return new Promise(function(i,r){function s(){switch(n.clientWaitSync(e,n.SYNC_FLUSH_COMMANDS_BIT,0)){case n.WAIT_FAILED:r();break;case n.TIMEOUT_EXPIRED:setTimeout(s,t);break;default:i()}}setTimeout(s,t)})}function za(){let n=Math.random()*4294967295|0,e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,i=Math.random()*4294967295|0;return(bn[n&255]+bn[n>>8&255]+bn[n>>16&255]+bn[n>>24&255]+"-"+bn[e&255]+bn[e>>8&255]+"-"+bn[e>>16&15|64]+bn[e>>24&255]+"-"+bn[t&63|128]+bn[t>>8&255]+"-"+bn[t>>16&255]+bn[t>>24&255]+bn[i&255]+bn[i>>8&255]+bn[i>>16&255]+bn[i>>24&255]).toLowerCase()}function mi(n,e,t){return Math.max(e,Math.min(t,n))}function Y0(n,e){return(n%e+e)%e}function lZ(n,e,t,i,r){return i+(n-e)*(r-i)/(t-e)}function cZ(n,e,t){return n!==e?(t-n)/(e-n):0}function kp(n,e,t){return(1-t)*n+t*e}function fZ(n,e,t,i){return kp(n,e,1-Math.exp(-t*i))}function hZ(n,e=1){return e-Math.abs(Y0(n,e*2)-e)}function dZ(n,e,t){return n<=e?0:n>=t?1:(n=(n-e)/(t-e),n*n*(3-2*n))}function uZ(n,e,t){return n<=e?0:n>=t?1:(n=(n-e)/(t-e),n*n*n*(n*(n*6-15)+10))}function mZ(n,e){return n+Math.floor(Math.random()*(e-n+1))}function pZ(n,e){return n+Math.random()*(e-n)}function _Z(n){return n*(.5-Math.random())}function gZ(n){n!==void 0&&(pw=n);let e=pw+=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 vZ(n){return n*Gp}function EZ(n){return n*uh}function SZ(n){return(n&n-1)===0&&n!==0}function TZ(n){return Math.pow(2,Math.ceil(Math.log(n)/Math.LN2))}function AZ(n){return Math.pow(2,Math.floor(Math.log(n)/Math.LN2))}function xZ(n,e,t,i,r){let s=Math.cos,a=Math.sin,o=s(t/2),l=a(t/2),c=s((e+i)/2),f=a((e+i)/2),h=s((e-i)/2),d=a((e-i)/2),u=s((i-e)/2),m=a((i-e)/2);switch(r){case"XYX":n.set(o*f,l*h,l*d,o*c);break;case"YZY":n.set(l*d,o*f,l*h,o*c);break;case"ZXZ":n.set(l*h,l*d,o*f,o*c);break;case"XZX":n.set(o*f,l*m,l*u,o*c);break;case"YXY":n.set(l*u,o*f,l*m,o*c);break;case"ZYZ":n.set(l*m,l*u,o*f,o*c);break;default:Mt("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}}function Wa(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return n/4294967295;case Uint16Array:return n/65535;case Uint8Array:return n/255;case Int32Array:return Math.max(n/2147483647,-1);case Int16Array:return Math.max(n/32767,-1);case Int8Array:return Math.max(n/127,-1);default:throw new Error("Invalid component type.")}}function Yi(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return Math.round(n*4294967295);case Uint16Array:return Math.round(n*65535);case Uint8Array:return Math.round(n*255);case Int32Array:return Math.round(n*2147483647);case Int16Array:return Math.round(n*32767);case Int8Array:return Math.round(n*127);default:throw new Error("Invalid component type.")}}function RZ(){let n={enabled:!0,workingColorSpace:jn,spaces:{},convert:function(r,s,a){return this.enabled===!1||s===a||!s||!a||(this.spaces[s].transfer===Xi&&(r.r=Ml(r.r),r.g=Ml(r.g),r.b=Ml(r.b)),this.spaces[s].primaries!==this.spaces[a].primaries&&(r.applyMatrix3(this.spaces[s].toXYZ),r.applyMatrix3(this.spaces[a].fromXYZ)),this.spaces[a].transfer===Xi&&(r.r=ou(r.r),r.g=ou(r.g),r.b=ou(r.b))),r},workingToColorSpace:function(r,s){return this.convert(r,this.workingColorSpace,s)},colorSpaceToWorking:function(r,s){return this.convert(r,s,this.workingColorSpace)},getPrimaries:function(r){return this.spaces[r].primaries},getTransfer:function(r){return r===Ol?Hp:this.spaces[r].transfer},getToneMappingMode:function(r){return this.spaces[r].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(r,s=this.workingColorSpace){return r.fromArray(this.spaces[s].luminanceCoefficients)},define:function(r){Object.assign(this.spaces,r)},_getMatrix:function(r,s,a){return r.copy(this.spaces[s].toXYZ).multiply(this.spaces[a].fromXYZ)},_getDrawingBufferColorSpace:function(r){return this.spaces[r].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(r=this.workingColorSpace){return this.spaces[r].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(r,s){return oE("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),n.workingToColorSpace(r,s)},toWorkingColorSpace:function(r,s){return oE("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),n.colorSpaceToWorking(r,s)}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],i=[.3127,.329];return n.define({[jn]:{primaries:e,whitePoint:i,transfer:Hp,toXYZ:gw,fromXYZ:vw,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:Ni},outputColorSpaceConfig:{drawingBufferColorSpace:Ni}},[Ni]:{primaries:e,whitePoint:i,transfer:Xi,toXYZ:gw,fromXYZ:vw,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:Ni}}}),n}function Ml(n){return n<.04045?n*.0773993808:Math.pow(n*.9478672986+.0521327014,2.4)}function ou(n){return n<.0031308?n*12.92:1.055*Math.pow(n,.41666)-.055}function zb(n){return typeof HTMLImageElement!="undefined"&&n instanceof HTMLImageElement||typeof HTMLCanvasElement!="undefined"&&n instanceof HTMLCanvasElement||typeof ImageBitmap!="undefined"&&n instanceof ImageBitmap?lE.getDataURL(n):n.data?{data:Array.from(n.data),width:n.width,height:n.height,type:n.data.constructor.name}:(Mt("Texture: Unable to serialize Texture."),{})}function Kb(n,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?n+(e-n)*6*t:t<1/2?e:t<2/3?n+(e-n)*6*(2/3-t):n}function t0(n,e,t,i,r){for(let s=0,a=n.length-3;s<=a;s+=3){rh.fromArray(n,s);let o=r.x*Math.abs(rh.x)+r.y*Math.abs(rh.y)+r.z*Math.abs(rh.z),l=e.dot(rh),c=t.dot(rh),f=i.dot(rh);if(Math.max(-Math.max(l,c,f),Math.min(l,c,f))>o)return!1}return!0}function yv(n,e,t,i,r,s){iu.subVectors(n,t).addScalar(.5).multiply(i),r!==void 0?(Np.x=s*iu.x-r*iu.y,Np.y=r*iu.x+s*iu.y):Np.copy(iu),n.copy(e),n.x+=Np.x,n.y+=Np.y,n.applyMatrix4(GF)}function UZ(n,e,t,i,r,s,a,o){let l;if(e.side===pn?l=i.intersectTriangle(a,s,r,!0,o):l=i.intersectTriangle(r,s,a,e.side===Gs,o),l===null)return null;Bv.copy(o),Bv.applyMatrix4(n.matrixWorld);let c=t.ray.origin.distanceTo(Bv);return ct.far?null:{distance:c,point:Bv.clone(),object:n}}function Uv(n,e,t,i,r,s,a,o,l,c){n.getVertexPosition(o,Ov),n.getVertexPosition(l,Nv),n.getVertexPosition(c,wv);let f=UZ(n,e,t,i,Ov,Nv,wv,Dw);if(f){let h=new ne;Il.getBarycoord(Dw,Ov,Nv,wv,h),r&&(f.uv=Il.getInterpolatedAttribute(r,o,l,c,h,new bt)),s&&(f.uv1=Il.getInterpolatedAttribute(s,o,l,c,h,new bt)),a&&(f.normal=Il.getInterpolatedAttribute(a,o,l,c,h,new ne),f.normal.dot(i.direction)>0&&f.normal.multiplyScalar(-1));let d={a:o,b:l,c,normal:new ne,materialIndex:0};Il.getNormal(Ov,Nv,wv,d.normal),f.face=d,f.barycoord=h}return f}function Hv(n,e,t,i,r,s,a){let o=n.geometry.attributes.position;if(hE.fromBufferAttribute(o,r),dE.fromBufferAttribute(o,s),t.distanceSqToSegment(hE,dE,d0,Gw)>i)return;d0.applyMatrix4(n.matrixWorld);let c=e.ray.origin.distanceTo(d0);if(!(ce.far))return{distance:c,point:Gw.clone().applyMatrix4(n.matrixWorld),index:a,face:null,faceIndex:null,barycoord:null,object:n}}function zw(n,e,t,i,r,s,a){let o=v0.distanceSqToPoint(n);if(or.far)return;s.push({distance:c,distanceToRay:Math.sqrt(o),point:l,index:e,face:null,faceIndex:null,barycoord:null,object:a})}}function xh(n){let e={};for(let t in n){e[t]={};for(let i in n[t]){let r=n[t][i];if(Xw(r))r.isRenderTargetTexture?(Mt("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[t][i]=null):e[t][i]=r.clone();else if(Array.isArray(r))if(Xw(r[0])){let s=[];for(let a=0,o=r.length;a{qc={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},Zc={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},eF=0,I0=1,tF=2,h_=1,CE=2,Ru=3,Gs=0,pn=1,ma=2,ko=0,ch=1,M0=2,C0=3,y0=4,iF=5,Hc=100,rF=101,nF=102,sF=103,aF=104,oF=200,lF=201,cF=202,fF=203,Qv=204,$v=205,hF=206,dF=207,uF=208,mF=209,pF=210,_F=211,gF=212,vF=213,EF=214,Jv=0,eE=1,tE=2,fh=3,iE=4,rE=5,nE=6,sE=7,d_=0,SF=1,TF=2,Hs=0,P0=1,D0=2,L0=3,O0=4,N0=5,w0=6,F0=7,p0="attached",AF="detached",B0=300,Qc=301,Th=302,yE=303,PE=304,u_=306,Do=1e3,ha=1001,lu=1002,Dr=1003,DE=1004,Ah=1005,Lr=1006,bu=1007,qa=1008,_s=1009,U0=1010,V0=1011,Iu=1012,LE=1013,Za=1014,zs=1015,Wo=1016,OE=1017,NE=1018,Mu=1020,G0=35902,k0=35899,W0=1021,H0=1022,Xs=1023,Lo=1026,$c=1027,wE=1028,FE=1029,Jc=1030,BE=1031,UE=1033,m_=33776,p_=33777,__=33778,g_=33779,VE=35840,GE=35841,kE=35842,WE=35843,HE=36196,zE=37492,XE=37496,YE=37488,KE=37489,v_=37490,jE=37491,qE=37808,ZE=37809,QE=37810,$E=37811,JE=37812,eS=37813,tS=37814,iS=37815,rS=37816,nS=37817,sS=37818,aS=37819,oS=37820,lS=37821,cS=36492,fS=36494,hS=36495,dS=36283,uS=36284,E_=36285,mS=36286,xF=2200,RF=2201,bF=2202,hh=2300,dh=2301,Zv=2302,_0=2303,oh=2400,lh=2401,Wp=2402,pS=2500,IF=2501,z0=0,S_=1,Cu=2,MF=3200,yu=0,CF=1,Ol="",Ni="srgb",jn="srgb-linear",Hp="linear",Xi="srgb",ah=7680,g0=519,yF=512,PF=513,DF=514,_S=515,LF=516,OF=517,gS=518,NF=519,aE=35044,X0="300 es",Ha=2e3,cu=2001;mw={},hu=null;UF={[Jv]:eE,[tE]:nE,[iE]:sE,[fh]:rE,[eE]:Jv,[nE]:tE,[sE]:iE,[rE]:fh},da=class{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});let i=this._listeners;i[e]===void 0&&(i[e]=[]),i[e].indexOf(t)===-1&&i[e].push(t)}hasEventListener(e,t){let i=this._listeners;return i===void 0?!1:i[e]!==void 0&&i[e].indexOf(t)!==-1}removeEventListener(e,t){let i=this._listeners;if(i===void 0)return;let r=i[e];if(r!==void 0){let s=r.indexOf(t);s!==-1&&r.splice(s,1)}}dispatchEvent(e){let t=this._listeners;if(t===void 0)return;let i=t[e.type];if(i!==void 0){e.target=this;let r=i.slice(0);for(let s=0,a=r.length;s0){let u=.5/Math.sqrt(d+1);this._w=.25/u,this._x=(f-l)*u,this._y=(s-c)*u,this._z=(a-r)*u}else if(i>o&&i>h){let u=2*Math.sqrt(1+i-o-h);this._w=(f-l)/u,this._x=.25*u,this._y=(r+a)/u,this._z=(s+c)/u}else if(o>h){let u=2*Math.sqrt(1+o-i-h);this._w=(s-c)/u,this._x=(r+a)/u,this._y=.25*u,this._z=(l+f)/u}else{let u=2*Math.sqrt(1+h-i-o);this._w=(a-r)/u,this._x=(s+c)/u,this._y=(l+f)/u,this._z=.25*u}return this._onChangeCallback(),this}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()}angleTo(e){return 2*Math.acos(Math.abs(mi(this.dot(e),-1,1)))}rotateTowards(e,t){let i=this.angleTo(e);if(i===0)return this;let r=Math.min(1,t/i);return this.slerp(e,r),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}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}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){let i=e._x,r=e._y,s=e._z,a=e._w,o=t._x,l=t._y,c=t._z,f=t._w;return this._x=i*f+a*o+r*c-s*l,this._y=r*f+a*l+s*o-i*c,this._z=s*f+a*c+i*l-r*o,this._w=a*f-i*o-r*l-s*c,this._onChangeCallback(),this}slerp(e,t){let i=e._x,r=e._y,s=e._z,a=e._w,o=this.dot(e);o<0&&(i=-i,r=-r,s=-s,a=-a,o=-o);let l=1-t;if(o<.9995){let c=Math.acos(o),f=Math.sin(c);l=Math.sin(l*c)/f,t=Math.sin(t*c)/f,this._x=this._x*l+i*t,this._y=this._y*l+r*t,this._z=this._z*l+s*t,this._w=this._w*l+a*t,this._onChangeCallback()}else this._x=this._x*l+i*t,this._y=this._y*l+r*t,this._z=this._z*l+s*t,this._w=this._w*l+a*t,this.normalize();return this}slerpQuaternions(e,t,i){return this.copy(e).slerp(t,i)}random(){let e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),i=Math.random(),r=Math.sqrt(1-i),s=Math.sqrt(i);return this.set(r*Math.sin(e),r*Math.cos(e),s*Math.sin(t),s*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}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}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}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}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}},$0=class $0{constructor(e=0,t=0,i=0){this.x=e,this.y=t,this.z=i}set(e,t,i){return i===void 0&&(i=this.z),this.x=e,this.y=t,this.z=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}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}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)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(_w.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(_w.setFromAxisAngle(e,t))}applyMatrix3(e){let t=this.x,i=this.y,r=this.z,s=e.elements;return this.x=s[0]*t+s[3]*i+s[6]*r,this.y=s[1]*t+s[4]*i+s[7]*r,this.z=s[2]*t+s[5]*i+s[8]*r,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){let t=this.x,i=this.y,r=this.z,s=e.elements,a=1/(s[3]*t+s[7]*i+s[11]*r+s[15]);return this.x=(s[0]*t+s[4]*i+s[8]*r+s[12])*a,this.y=(s[1]*t+s[5]*i+s[9]*r+s[13])*a,this.z=(s[2]*t+s[6]*i+s[10]*r+s[14])*a,this}applyQuaternion(e){let t=this.x,i=this.y,r=this.z,s=e.x,a=e.y,o=e.z,l=e.w,c=2*(a*r-o*i),f=2*(o*t-s*r),h=2*(s*i-a*t);return this.x=t+l*c+a*h-o*f,this.y=i+l*f+o*c-s*h,this.z=r+l*h+s*f-a*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){let t=this.x,i=this.y,r=this.z,s=e.elements;return this.x=s[0]*t+s[4]*i+s[8]*r,this.y=s[1]*t+s[5]*i+s[9]*r,this.z=s[2]*t+s[6]*i+s[10]*r,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}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}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}clamp(e,t){return this.x=mi(this.x,e.x,t.x),this.y=mi(this.y,e.y,t.y),this.z=mi(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=mi(this.x,e,t),this.y=mi(this.y,e,t),this.z=mi(this.z,e,t),this}clampLength(e,t){let i=this.length();return this.divideScalar(i||1).multiplyScalar(mi(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}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}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}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){let i=e.x,r=e.y,s=e.z,a=t.x,o=t.y,l=t.z;return this.x=r*l-s*o,this.y=s*a-i*l,this.z=i*o-r*a,this}projectOnVector(e){let t=e.lengthSq();if(t===0)return this.set(0,0,0);let i=e.dot(this)/t;return this.copy(e).multiplyScalar(i)}projectOnPlane(e){return Wb.copy(this).projectOnVector(e),this.sub(Wb)}reflect(e){return this.sub(Wb.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let i=this.dot(e)/t;return Math.acos(mi(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,i=this.y-e.y,r=this.z-e.z;return t*t+i*i+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,i){let r=Math.sin(t)*e;return this.x=r*Math.sin(i),this.y=Math.cos(t)*e,this.z=r*Math.cos(i),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,i){return this.x=e*Math.sin(t),this.y=i,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){let t=this.setFromMatrixColumn(e,0).length(),i=this.setFromMatrixColumn(e,1).length(),r=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=i,this.z=r,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let 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}};$0.prototype.isVector3=!0;ne=$0,Wb=new ne,_w=new Zr,J0=class J0{constructor(e,t,i,r,s,a,o,l,c){this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,i,r,s,a,o,l,c)}set(e,t,i,r,s,a,o,l,c){let f=this.elements;return f[0]=e,f[1]=r,f[2]=o,f[3]=t,f[4]=s,f[5]=l,f[6]=i,f[7]=a,f[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){let 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}extractBasis(e,t,i){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(e){let 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}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let i=e.elements,r=t.elements,s=this.elements,a=i[0],o=i[3],l=i[6],c=i[1],f=i[4],h=i[7],d=i[2],u=i[5],m=i[8],p=r[0],_=r[3],g=r[6],v=r[1],x=r[4],A=r[7],S=r[2],E=r[5],R=r[8];return s[0]=a*p+o*v+l*S,s[3]=a*_+o*x+l*E,s[6]=a*g+o*A+l*R,s[1]=c*p+f*v+h*S,s[4]=c*_+f*x+h*E,s[7]=c*g+f*A+h*R,s[2]=d*p+u*v+m*S,s[5]=d*_+u*x+m*E,s[8]=d*g+u*A+m*R,this}multiplyScalar(e){let 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}determinant(){let e=this.elements,t=e[0],i=e[1],r=e[2],s=e[3],a=e[4],o=e[5],l=e[6],c=e[7],f=e[8];return t*a*f-t*o*c-i*s*f+i*o*l+r*s*c-r*a*l}invert(){let e=this.elements,t=e[0],i=e[1],r=e[2],s=e[3],a=e[4],o=e[5],l=e[6],c=e[7],f=e[8],h=f*a-o*c,d=o*l-f*s,u=c*s-a*l,m=t*h+i*d+r*u;if(m===0)return this.set(0,0,0,0,0,0,0,0,0);let p=1/m;return e[0]=h*p,e[1]=(r*c-f*i)*p,e[2]=(o*i-r*a)*p,e[3]=d*p,e[4]=(f*t-r*l)*p,e[5]=(r*s-o*t)*p,e[6]=u*p,e[7]=(i*l-c*t)*p,e[8]=(a*t-i*s)*p,this}transpose(){let e,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}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){let 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}setUvTransform(e,t,i,r,s,a,o){let l=Math.cos(s),c=Math.sin(s);return this.set(i*l,i*c,-i*(l*a+c*o)+a+e,-r*c,r*l,-r*(-c*a+l*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(Hb.makeScale(e,t)),this}rotate(e){return this.premultiply(Hb.makeRotation(-e)),this}translate(e,t){return this.premultiply(Hb.makeTranslation(e,t)),this}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}makeRotation(e){let t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,i,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){let t=this.elements,i=e.elements;for(let r=0;r<9;r++)if(t[r]!==i[r])return!1;return!0}fromArray(e,t=0){for(let i=0;i<9;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){let 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}clone(){return new this.constructor().fromArray(this.elements)}};J0.prototype.isMatrix3=!0;ti=J0,Hb=new ti,gw=new ti().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),vw=new ti().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);ai=RZ();lE=class{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement=="undefined")return e.src;let i;if(e instanceof HTMLCanvasElement)i=e;else{Hd===void 0&&(Hd=fu("canvas")),Hd.width=e.width,Hd.height=e.height;let r=Hd.getContext("2d");e instanceof ImageData?r.putImageData(e,0,0):r.drawImage(e,0,0,e.width,e.height),i=Hd}return i.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement!="undefined"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement!="undefined"&&e instanceof HTMLCanvasElement||typeof ImageBitmap!="undefined"&&e instanceof ImageBitmap){let t=fu("canvas");t.width=e.width,t.height=e.height;let i=t.getContext("2d");i.drawImage(e,0,0,e.width,e.height);let r=i.getImageData(0,0,e.width,e.height),s=r.data;for(let a=0;a1),this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(Xb).x}get height(){return this.source.getSize(Xb).y}get depth(){return this.source.getSize(Xb).z}get image(){return this.source.data}set image(e){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}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.normalized=e.normalized,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}setValues(e){for(let t in e){let i=e[t];if(i===void 0){Mt(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){Mt(`Texture.setValues(): property '${t}' does not exist.`);continue}r&&i&&r.isVector2&&i.isVector2||r&&i&&r.isVector3&&i.isVector3||r&&i&&r.isMatrix3&&i.isMatrix3?r.copy(i):this[t]=i}}toJSON(e){let t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];let 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,normalized:this.normalized,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}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==B0)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case Do:e.x=e.x-Math.floor(e.x);break;case ha:e.x=e.x<0?0:1;break;case lu: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 Do:e.y=e.y-Math.floor(e.y);break;case ha:e.y=e.y<0?0:1;break;case lu: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}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}};Ar.DEFAULT_IMAGE=null;Ar.DEFAULT_MAPPING=B0;Ar.DEFAULT_ANISOTROPY=1;eI=class eI{constructor(e=0,t=0,i=0,r=1){this.x=e,this.y=t,this.z=i,this.w=r}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,i,r){return this.x=e,this.y=t,this.z=i,this.w=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}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}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)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}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}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}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}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}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}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}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){let t=this.x,i=this.y,r=this.z,s=this.w,a=e.elements;return this.x=a[0]*t+a[4]*i+a[8]*r+a[12]*s,this.y=a[1]*t+a[5]*i+a[9]*r+a[13]*s,this.z=a[2]*t+a[6]*i+a[10]*r+a[14]*s,this.w=a[3]*t+a[7]*i+a[11]*r+a[15]*s,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);let 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}setAxisAngleFromRotationMatrix(e){let t,i,r,s,l=e.elements,c=l[0],f=l[4],h=l[8],d=l[1],u=l[5],m=l[9],p=l[2],_=l[6],g=l[10];if(Math.abs(f-d)<.01&&Math.abs(h-p)<.01&&Math.abs(m-_)<.01){if(Math.abs(f+d)<.1&&Math.abs(h+p)<.1&&Math.abs(m+_)<.1&&Math.abs(c+u+g-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;let x=(c+1)/2,A=(u+1)/2,S=(g+1)/2,E=(f+d)/4,R=(h+p)/4,I=(m+_)/4;return x>A&&x>S?x<.01?(i=0,r=.707106781,s=.707106781):(i=Math.sqrt(x),r=E/i,s=R/i):A>S?A<.01?(i=.707106781,r=0,s=.707106781):(r=Math.sqrt(A),i=E/r,s=I/r):S<.01?(i=.707106781,r=.707106781,s=0):(s=Math.sqrt(S),i=R/s,r=I/s),this.set(i,r,s,t),this}let v=Math.sqrt((_-m)*(_-m)+(h-p)*(h-p)+(d-f)*(d-f));return Math.abs(v)<.001&&(v=1),this.x=(_-m)/v,this.y=(h-p)/v,this.z=(d-f)/v,this.w=Math.acos((c+u+g-1)/2),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}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}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}clamp(e,t){return this.x=mi(this.x,e.x,t.x),this.y=mi(this.y,e.y,t.y),this.z=mi(this.z,e.z,t.z),this.w=mi(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=mi(this.x,e,t),this.y=mi(this.y,e,t),this.z=mi(this.z,e,t),this.w=mi(this.w,e,t),this}clampLength(e,t){let i=this.length();return this.divideScalar(i||1).multiplyScalar(mi(i,e,t))}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}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}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}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}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}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}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}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}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}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}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}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}};eI.prototype.isVector4=!0;Zi=eI,cE=class extends da{constructor(e=1,t=1,i={}){super(),i=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Lr,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 Zi(0,0,e,t),this.scissorTest=!1,this.viewport=new Zi(0,0,e,t),this.textures=[];let r={width:e,height:t,depth:i.depth},s=new Ar(r),a=i.count;for(let o=0;o1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}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>>0}enable(e){this.mask|=1<1){for(let t=0;t1){for(let i=0;i0&&(r.userData=this.userData),r.layers=this.layers.mask,r.matrix=this.matrix.toArray(),r.up=this.up.toArray(),this.pivot!==null&&(r.pivot=this.pivot.toArray()),this.matrixAutoUpdate===!1&&(r.matrixAutoUpdate=!1),this.morphTargetDictionary!==void 0&&(r.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),this.morphTargetInfluences!==void 0&&(r.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(r.type="InstancedMesh",r.count=this.count,r.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(r.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(r.type="BatchedMesh",r.perObjectFrustumCulled=this.perObjectFrustumCulled,r.sortObjects=this.sortObjects,r.drawRanges=this._drawRanges,r.reservedRanges=this._reservedRanges,r.geometryInfo=this._geometryInfo.map(o=>({...o,boundingBox:o.boundingBox?o.boundingBox.toJSON():void 0,boundingSphere:o.boundingSphere?o.boundingSphere.toJSON():void 0})),r.instanceInfo=this._instanceInfo.map(o=>({...o})),r.availableInstanceIds=this._availableInstanceIds.slice(),r.availableGeometryIds=this._availableGeometryIds.slice(),r.nextIndexStart=this._nextIndexStart,r.nextVertexStart=this._nextVertexStart,r.geometryCount=this._geometryCount,r.maxInstanceCount=this._maxInstanceCount,r.maxVertexCount=this._maxVertexCount,r.maxIndexCount=this._maxIndexCount,r.geometryInitialized=this._geometryInitialized,r.matricesTexture=this._matricesTexture.toJSON(e),r.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(r.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(r.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(r.boundingBox=this.boundingBox.toJSON()));function s(o,l){return o[l.uuid]===void 0&&(o[l.uuid]=l.toJSON(e)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?r.background=this.background.toJSON():this.background.isTexture&&(r.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(r.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){r.geometry=s(e.geometries,this.geometry);let o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){let l=o.shapes;if(Array.isArray(l))for(let c=0,f=l.length;c0){r.children=[];for(let o=0;o0){r.animations=[];for(let o=0;o0&&(i.geometries=o),l.length>0&&(i.materials=l),c.length>0&&(i.textures=c),f.length>0&&(i.images=f),h.length>0&&(i.shapes=h),d.length>0&&(i.skeletons=d),u.length>0&&(i.animations=u),m.length>0&&(i.nodes=m)}return i.object=r,i;function a(o){let l=[];for(let c in o){let f=o[c];delete f.metadata,l.push(f)}return l}}clone(e){return new this.constructor().copy(this,e)}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.pivot=e.pivot!==null?e.pivot.clone():null,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.static=e.static,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let i=0;iu+m?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!c.inputState.pinching&&d<=u-m&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else l!==null&&e.gripSpace&&(s=t.getPose(e.gripSpace,i),s!==null&&(l.matrix.fromArray(s.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,s.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(s.linearVelocity)):l.hasLinearVelocity=!1,s.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(s.angularVelocity)):l.hasAngularVelocity=!1,l.eventsEnabled&&l.dispatchEvent({type:"gripUpdated",data:e,target:this})));o!==null&&(r=t.getPose(e.targetRaySpace,i),r===null&&s!==null&&(r=s),r!==null&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(OZ)))}return o!==null&&(o.visible=r!==null),l!==null&&(l.visible=s!==null),c!==null&&(c.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){let i=new Vs;i.matrixAutoUpdate=!1,i.visible=!1,e.joints[t.jointName]=i,e.add(i)}return e.joints[t.jointName]}},VF={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},Uc={h:0,s:0,l:0},Av={h:0,s:0,l:0};ct=class{constructor(e,t,i){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,i)}set(e,t,i){if(t===void 0&&i===void 0){let r=e;r&&r.isColor?this.copy(r):typeof r=="number"?this.setHex(r):typeof r=="string"&&this.setStyle(r)}else this.setRGB(e,t,i);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Ni){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,ai.colorSpaceToWorking(this,t),this}setRGB(e,t,i,r=ai.workingColorSpace){return this.r=e,this.g=t,this.b=i,ai.colorSpaceToWorking(this,r),this}setHSL(e,t,i,r=ai.workingColorSpace){if(e=Y0(e,1),t=mi(t,0,1),i=mi(i,0,1),t===0)this.r=this.g=this.b=i;else{let s=i<=.5?i*(1+t):i+t-i*t,a=2*i-s;this.r=Kb(a,s,e+1/3),this.g=Kb(a,s,e),this.b=Kb(a,s,e-1/3)}return ai.colorSpaceToWorking(this,r),this}setStyle(e,t=Ni){function i(s){s!==void 0&&parseFloat(s)<1&&Mt("Color: Alpha component of "+e+" will be ignored.")}let r;if(r=/^(\w+)\(([^\)]*)\)/.exec(e)){let s,a=r[1],o=r[2];switch(a){case"rgb":case"rgba":if(s=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(s[4]),this.setRGB(Math.min(255,parseInt(s[1],10))/255,Math.min(255,parseInt(s[2],10))/255,Math.min(255,parseInt(s[3],10))/255,t);if(s=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(s[4]),this.setRGB(Math.min(100,parseInt(s[1],10))/100,Math.min(100,parseInt(s[2],10))/100,Math.min(100,parseInt(s[3],10))/100,t);break;case"hsl":case"hsla":if(s=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(s[4]),this.setHSL(parseFloat(s[1])/360,parseFloat(s[2])/100,parseFloat(s[3])/100,t);break;default:Mt("Color: Unknown color model "+e)}}else if(r=/^\#([A-Fa-f\d]+)$/.exec(e)){let s=r[1],a=s.length;if(a===3)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,t);if(a===6)return this.setHex(parseInt(s,16),t);Mt("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Ni){let i=VF[e.toLowerCase()];return i!==void 0?this.setHex(i,t):Mt("Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=Ml(e.r),this.g=Ml(e.g),this.b=Ml(e.b),this}copyLinearToSRGB(e){return this.r=ou(e.r),this.g=ou(e.g),this.b=ou(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Ni){return ai.workingToColorSpace(In.copy(this),e),Math.round(mi(In.r*255,0,255))*65536+Math.round(mi(In.g*255,0,255))*256+Math.round(mi(In.b*255,0,255))}getHexString(e=Ni){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=ai.workingColorSpace){ai.workingToColorSpace(In.copy(this),t);let i=In.r,r=In.g,s=In.b,a=Math.max(i,r,s),o=Math.min(i,r,s),l,c,f=(o+a)/2;if(o===a)l=0,c=0;else{let h=a-o;switch(c=f<=.5?h/(a+o):h/(2-a-o),a){case i:l=(r-s)/h+(r0&&(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}},Ga=new ne,Tl=new ne,jb=new ne,Al=new ne,Kd=new ne,jd=new ne,Iw=new ne,qb=new ne,Zb=new ne,Qb=new ne,$b=new Zi,Jb=new Zi,e0=new Zi,Il=class n{constructor(e=new ne,t=new ne,i=new ne){this.a=e,this.b=t,this.c=i}static getNormal(e,t,i,r){r.subVectors(i,t),Ga.subVectors(e,t),r.cross(Ga);let s=r.lengthSq();return s>0?r.multiplyScalar(1/Math.sqrt(s)):r.set(0,0,0)}static getBarycoord(e,t,i,r,s){Ga.subVectors(r,t),Tl.subVectors(i,t),jb.subVectors(e,t);let a=Ga.dot(Ga),o=Ga.dot(Tl),l=Ga.dot(jb),c=Tl.dot(Tl),f=Tl.dot(jb),h=a*c-o*o;if(h===0)return s.set(0,0,0),null;let d=1/h,u=(c*l-o*f)*d,m=(a*f-o*l)*d;return s.set(1-u-m,m,u)}static containsPoint(e,t,i,r){return this.getBarycoord(e,t,i,r,Al)===null?!1:Al.x>=0&&Al.y>=0&&Al.x+Al.y<=1}static getInterpolation(e,t,i,r,s,a,o,l){return this.getBarycoord(e,t,i,r,Al)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(s,Al.x),l.addScaledVector(a,Al.y),l.addScaledVector(o,Al.z),l)}static getInterpolatedAttribute(e,t,i,r,s,a){return $b.setScalar(0),Jb.setScalar(0),e0.setScalar(0),$b.fromBufferAttribute(e,t),Jb.fromBufferAttribute(e,i),e0.fromBufferAttribute(e,r),a.setScalar(0),a.addScaledVector($b,s.x),a.addScaledVector(Jb,s.y),a.addScaledVector(e0,s.z),a}static isFrontFacing(e,t,i,r){return Ga.subVectors(i,t),Tl.subVectors(e,t),Ga.cross(Tl).dot(r)<0}set(e,t,i){return this.a.copy(e),this.b.copy(t),this.c.copy(i),this}setFromPointsAndIndices(e,t,i,r){return this.a.copy(e[t]),this.b.copy(e[i]),this.c.copy(e[r]),this}setFromAttributeAndIndices(e,t,i,r){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,i),this.c.fromBufferAttribute(e,r),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Ga.subVectors(this.c,this.b),Tl.subVectors(this.a,this.b),Ga.cross(Tl).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return n.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return n.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,i,r,s){return n.getInterpolation(e,this.a,this.b,this.c,t,i,r,s)}containsPoint(e){return n.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return n.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){let i=this.a,r=this.b,s=this.c,a,o;Kd.subVectors(r,i),jd.subVectors(s,i),qb.subVectors(e,i);let l=Kd.dot(qb),c=jd.dot(qb);if(l<=0&&c<=0)return t.copy(i);Zb.subVectors(e,r);let f=Kd.dot(Zb),h=jd.dot(Zb);if(f>=0&&h<=f)return t.copy(r);let d=l*h-f*c;if(d<=0&&l>=0&&f<=0)return a=l/(l-f),t.copy(i).addScaledVector(Kd,a);Qb.subVectors(e,s);let u=Kd.dot(Qb),m=jd.dot(Qb);if(m>=0&&u<=m)return t.copy(s);let p=u*c-l*m;if(p<=0&&c>=0&&m<=0)return o=c/(c-m),t.copy(i).addScaledVector(jd,o);let _=f*m-u*h;if(_<=0&&h-f>=0&&u-m>=0)return Iw.subVectors(s,r),o=(h-f)/(h-f+(u-m)),t.copy(r).addScaledVector(Iw,o);let g=1/(_+p+d);return a=p*g,o=d*g,t.copy(i).addScaledVector(Kd,a).addScaledVector(jd,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}},Sr=class{constructor(e=new ne(1/0,1/0,1/0),t=new ne(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,i=e.length;t=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}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}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))}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}intersectsSphere(e){return this.clampPoint(e.center,ka),ka.distanceToSquared(e.center)<=e.radius*e.radius}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}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Pp),Rv.subVectors(this.max,Pp),qd.subVectors(e.a,Pp),Zd.subVectors(e.b,Pp),Qd.subVectors(e.c,Pp),Vc.subVectors(Zd,qd),Gc.subVectors(Qd,Zd),ih.subVectors(qd,Qd);let t=[0,-Vc.z,Vc.y,0,-Gc.z,Gc.y,0,-ih.z,ih.y,Vc.z,0,-Vc.x,Gc.z,0,-Gc.x,ih.z,0,-ih.x,-Vc.y,Vc.x,0,-Gc.y,Gc.x,0,-ih.y,ih.x,0];return!t0(t,qd,Zd,Qd,Rv)||(t=[1,0,0,0,1,0,0,0,1],!t0(t,qd,Zd,Qd,Rv))?!1:(bv.crossVectors(Vc,Gc),t=[bv.x,bv.y,bv.z],t0(t,qd,Zd,Qd,Rv))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,ka).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(ka).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(xl[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),xl[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),xl[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),xl[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),xl[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),xl[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),xl[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),xl[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(xl),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}},xl=[new ne,new ne,new ne,new ne,new ne,new ne,new ne,new ne],ka=new ne,xv=new Sr,qd=new ne,Zd=new ne,Qd=new ne,Vc=new ne,Gc=new ne,ih=new ne,Pp=new ne,Rv=new ne,bv=new ne,rh=new ne;Gr=new ne,Iv=new bt,NZ=0,or=class extends da{constructor(e,t,i=!1){if(super(),Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:NZ++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=i,this.usage=aE,this.updateRanges=[],this.gpuType=zs,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}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}copyAt(e,t,i){e*=this.itemSize,i*=t.itemSize;for(let r=0,s=this.itemSize;rthis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Dp.subVectors(e,this.center);let t=Dp.lengthSq();if(t>this.radius*this.radius){let i=Math.sqrt(t),r=(i-this.radius)*.5;this.center.addScaledVector(Dp,r/i),this.radius+=r}return this}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):(i0.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Dp.copy(e.center).add(i0)),this.expandByPoint(Dp.copy(e.center).sub(i0))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}},FZ=0,ca=new oi,r0=new er,$d=new ne,Us=new Sr,Lp=new Sr,ln=new ne,Ui=class n extends da{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:FZ++}),this.uuid=za(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(aZ(e)?Kp:Yp)(e,1):this.index=e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,i=0){this.groups.push({start:e,count:t,materialIndex:i})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){let t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);let i=this.attributes.normal;if(i!==void 0){let s=new ti().getNormalMatrix(e);i.applyNormalMatrix(s),i.needsUpdate=!0}let r=this.attributes.tangent;return r!==void 0&&(r.transformDirection(e),r.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return ca.makeRotationFromQuaternion(e),this.applyMatrix4(ca),this}rotateX(e){return ca.makeRotationX(e),this.applyMatrix4(ca),this}rotateY(e){return ca.makeRotationY(e),this.applyMatrix4(ca),this}rotateZ(e){return ca.makeRotationZ(e),this.applyMatrix4(ca),this}translate(e,t,i){return ca.makeTranslation(e,t,i),this.applyMatrix4(ca),this}scale(e,t,i){return ca.makeScale(e,t,i),this.applyMatrix4(ca),this}lookAt(e){return r0.lookAt(e),r0.updateMatrix(),this.applyMatrix4(r0.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter($d).negate(),this.translate($d.x,$d.y,$d.z),this}setFromPoints(e){let t=this.getAttribute("position");if(t===void 0){let i=[];for(let r=0,s=e.length;rt.count&&Mt("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Sr);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){Ft("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new ne(-1/0,-1/0,-1/0),new ne(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let i=0,r=t.length;i0&&(e.userData=this.userData),this.parameters!==void 0){let l=this.parameters;for(let c in l)l[c]!==void 0&&(e[c]=l[c]);return e}e.data={attributes:{}};let t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});let i=this.attributes;for(let l in i){let c=i[l];e.data.attributes[l]=c.toJSON(e.data)}let r={},s=!1;for(let l in this.morphAttributes){let c=this.morphAttributes[l],f=[];for(let h=0,d=c.length;h0&&(r[l]=f,s=!0)}s&&(e.data.morphAttributes=r,e.data.morphTargetsRelative=this.morphTargetsRelative);let a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));let o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;let t={};this.name=e.name;let i=e.index;i!==null&&this.setIndex(i.clone());let r=e.attributes;for(let c in r){let f=r[c];this.setAttribute(c,f.clone(t))}let s=e.morphAttributes;for(let c in s){let f=[],h=s[c];for(let d=0,u=h.length;d0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(let t in e){let i=e[t];if(i===void 0){Mt(`Material: parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){Mt(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}r&&r.isColor?r.set(i):r&&r.isVector3&&i&&i.isVector3?r.copy(i):this[t]=i}}toJSON(e){let t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});let 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!==ch&&(i.blending=this.blending),this.side!==Gs&&(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!==Qv&&(i.blendSrc=this.blendSrc),this.blendDst!==$v&&(i.blendDst=this.blendDst),this.blendEquation!==Hc&&(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!==fh&&(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!==g0&&(i.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(i.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(i.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==ah&&(i.stencilFail=this.stencilFail),this.stencilZFail!==ah&&(i.stencilZFail=this.stencilZFail),this.stencilZPass!==ah&&(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.allowOverride===!1&&(i.allowOverride=!1),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 r(s){let a=[];for(let o in s){let l=s[o];delete l.metadata,a.push(l)}return a}if(t){let s=r(e.textures),a=r(e.images);s.length>0&&(i.textures=s),a.length>0&&(i.images=a)}return i}clone(){return new this.constructor().copy(this)}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;let t=e.clippingPlanes,i=null;if(t!==null){let r=t.length;i=new Array(r);for(let s=0;s!==r;++s)i[s]=t[s].clone()}return this.clippingPlanes=i,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}},pu=class extends Or{constructor(e){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new ct(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.rotation=e.rotation,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}},Op=new ne,eu=new ne,tu=new ne,iu=new bt,Np=new bt,GF=new oi,Mv=new ne,wp=new ne,Cv=new ne,Mw=new bt,n0=new bt,Cw=new bt,jp=class extends er{constructor(e=new pu){if(super(),this.isSprite=!0,this.type="Sprite",Jd===void 0){Jd=new Ui;let t=new Float32Array([-.5,-.5,0,0,0,.5,-.5,0,1,0,.5,.5,0,1,1,-.5,.5,0,0,1]),i=new ph(t,5);Jd.setIndex([0,1,2,0,2,3]),Jd.setAttribute("position",new zc(i,3,0,!1)),Jd.setAttribute("uv",new zc(i,2,3,!1))}this.geometry=Jd,this.material=e,this.center=new bt(.5,.5),this.count=1}raycast(e,t){e.camera===null&&Ft('Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.'),eu.setFromMatrixScale(this.matrixWorld),GF.copy(e.camera.matrixWorld),this.modelViewMatrix.multiplyMatrices(e.camera.matrixWorldInverse,this.matrixWorld),tu.setFromMatrixPosition(this.modelViewMatrix),e.camera.isPerspectiveCamera&&this.material.sizeAttenuation===!1&&eu.multiplyScalar(-tu.z);let i=this.material.rotation,r,s;i!==0&&(s=Math.cos(i),r=Math.sin(i));let a=this.center;yv(Mv.set(-.5,-.5,0),tu,a,eu,r,s),yv(wp.set(.5,-.5,0),tu,a,eu,r,s),yv(Cv.set(.5,.5,0),tu,a,eu,r,s),Mw.set(0,0),n0.set(1,0),Cw.set(1,1);let o=e.ray.intersectTriangle(Mv,wp,Cv,!1,Op);if(o===null&&(yv(wp.set(-.5,.5,0),tu,a,eu,r,s),n0.set(0,1),o=e.ray.intersectTriangle(Mv,Cv,wp,!1,Op),o===null))return;let l=e.ray.origin.distanceTo(Op);le.far||t.push({distance:l,point:Op.clone(),uv:Il.getInterpolation(Op,Mv,wp,Cv,Mw,n0,Cw,new bt),face:null,object:this})}copy(e,t){return super.copy(e,t),e.center!==void 0&&this.center.copy(e.center),this.material=e.material,this}};Rl=new ne,s0=new ne,Pv=new ne,kc=new ne,a0=new ne,Dv=new ne,o0=new ne,Oo=class{constructor(e=new ne,t=new ne(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,Rl)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);let i=t.dot(this.direction);return i<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,i)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){let t=Rl.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Rl.copy(this.origin).addScaledVector(this.direction,t),Rl.distanceToSquared(e))}distanceSqToSegment(e,t,i,r){s0.copy(e).add(t).multiplyScalar(.5),Pv.copy(t).sub(e).normalize(),kc.copy(this.origin).sub(s0);let s=e.distanceTo(t)*.5,a=-this.direction.dot(Pv),o=kc.dot(this.direction),l=-kc.dot(Pv),c=kc.lengthSq(),f=Math.abs(1-a*a),h,d,u,m;if(f>0)if(h=a*l-o,d=a*o-l,m=s*f,h>=0)if(d>=-m)if(d<=m){let p=1/f;h*=p,d*=p,u=h*(h+a*d+2*o)+d*(a*h+d+2*l)+c}else d=s,h=Math.max(0,-(a*d+o)),u=-h*h+d*(d+2*l)+c;else d=-s,h=Math.max(0,-(a*d+o)),u=-h*h+d*(d+2*l)+c;else d<=-m?(h=Math.max(0,-(-a*s+o)),d=h>0?-s:Math.min(Math.max(-s,-l),s),u=-h*h+d*(d+2*l)+c):d<=m?(h=0,d=Math.min(Math.max(-s,-l),s),u=d*(d+2*l)+c):(h=Math.max(0,-(a*s+o)),d=h>0?s:Math.min(Math.max(-s,-l),s),u=-h*h+d*(d+2*l)+c);else d=a>0?-s:s,h=Math.max(0,-(a*d+o)),u=-h*h+d*(d+2*l)+c;return i&&i.copy(this.origin).addScaledVector(this.direction,h),r&&r.copy(s0).addScaledVector(Pv,d),u}intersectSphere(e,t){Rl.subVectors(e.center,this.origin);let i=Rl.dot(this.direction),r=Rl.dot(Rl)-i*i,s=e.radius*e.radius;if(r>s)return null;let a=Math.sqrt(s-r),o=i-a,l=i+a;return l<0?null:o<0?this.at(l,t):this.at(o,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){let t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;let i=-(this.origin.dot(e.normal)+e.constant)/t;return i>=0?i:null}intersectPlane(e,t){let i=this.distanceToPlane(e);return i===null?null:this.at(i,t)}intersectsPlane(e){let t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let i,r,s,a,o,l,c=1/this.direction.x,f=1/this.direction.y,h=1/this.direction.z,d=this.origin;return c>=0?(i=(e.min.x-d.x)*c,r=(e.max.x-d.x)*c):(i=(e.max.x-d.x)*c,r=(e.min.x-d.x)*c),f>=0?(s=(e.min.y-d.y)*f,a=(e.max.y-d.y)*f):(s=(e.max.y-d.y)*f,a=(e.min.y-d.y)*f),i>a||s>r||((s>i||isNaN(i))&&(i=s),(a=0?(o=(e.min.z-d.z)*h,l=(e.max.z-d.z)*h):(o=(e.max.z-d.z)*h,l=(e.min.z-d.z)*h),i>l||o>r)||((o>i||i!==i)&&(i=o),(l=0?i:r,t)}intersectsBox(e){return this.intersectBox(e,Rl)!==null}intersectTriangle(e,t,i,r,s){a0.subVectors(t,e),Dv.subVectors(i,e),o0.crossVectors(a0,Dv);let a=this.direction.dot(o0),o;if(a>0){if(r)return null;o=1}else if(a<0)o=-1,a=-a;else return null;kc.subVectors(this.origin,e);let l=o*this.direction.dot(Dv.crossVectors(kc,Dv));if(l<0)return null;let c=o*this.direction.dot(a0.cross(kc));if(c<0||l+c>a)return null;let f=-o*kc.dot(o0);return f<0?null:this.at(f/a,s)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}},qn=class extends Or{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new ct(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 Xa,this.combine=d_,this.reflectivity=1,this.refractionRatio=.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}},yw=new oi,nh=new Oo,Lv=new hs,Pw=new ne,Ov=new ne,Nv=new ne,wv=new ne,l0=new ne,Fv=new ne,Dw=new ne,Bv=new ne,ii=class extends er{constructor(e=new Ui,t=new qn){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}updateMorphTargets(){let t=this.geometry.morphAttributes,i=Object.keys(t);if(i.length>0){let r=t[i[0]];if(r!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,a=r.length;s(e.far-e.near)**2))&&(yw.copy(s).invert(),nh.copy(e.ray).applyMatrix4(yw),!(i.boundingBox!==null&&nh.intersectsBox(i.boundingBox)===!1)&&this._computeIntersections(e,t,nh)))}_computeIntersections(e,t,i){let r,s=this.geometry,a=this.material,o=s.index,l=s.attributes.position,c=s.attributes.uv,f=s.attributes.uv1,h=s.attributes.normal,d=s.groups,u=s.drawRange;if(o!==null)if(Array.isArray(a))for(let m=0,p=d.length;m1)?null:t.copy(e.start).addScaledVector(r,a)}intersectsLine(e){let t=this.distanceToPoint(e.start),i=this.distanceToPoint(e.end);return t<0&&i>0||i<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){let i=t||HZ.getNormalMatrix(e),r=this.coplanarPoint(h0).applyMatrix4(e),s=this.normal.applyMatrix3(i).normalize();return this.constant=-r.dot(s),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}},sh=new hs,zZ=new bt(.5,.5),kv=new ne,vu=class{constructor(e=new fa,t=new fa,i=new fa,r=new fa,s=new fa,a=new fa){this.planes=[e,t,i,r,s,a]}set(e,t,i,r,s,a){let o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(i),o[3].copy(r),o[4].copy(s),o[5].copy(a),this}copy(e){let t=this.planes;for(let i=0;i<6;i++)t[i].copy(e.planes[i]);return this}setFromProjectionMatrix(e,t=Ha,i=!1){let r=this.planes,s=e.elements,a=s[0],o=s[1],l=s[2],c=s[3],f=s[4],h=s[5],d=s[6],u=s[7],m=s[8],p=s[9],_=s[10],g=s[11],v=s[12],x=s[13],A=s[14],S=s[15];if(r[0].setComponents(c-a,u-f,g-m,S-v).normalize(),r[1].setComponents(c+a,u+f,g+m,S+v).normalize(),r[2].setComponents(c+o,u+h,g+p,S+x).normalize(),r[3].setComponents(c-o,u-h,g-p,S-x).normalize(),i)r[4].setComponents(l,d,_,A).normalize(),r[5].setComponents(c-l,u-d,g-_,S-A).normalize();else if(r[4].setComponents(c-l,u-d,g-_,S-A).normalize(),t===Ha)r[5].setComponents(c+l,u+d,g+_,S+A).normalize();else if(t===cu)r[5].setComponents(l,d,_,A).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),sh.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{let t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),sh.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(sh)}intersectsSprite(e){sh.center.set(0,0,0);let t=zZ.distanceTo(e.center);return sh.radius=.7071067811865476+t,sh.applyMatrix4(e.matrixWorld),this.intersectsSphere(sh)}intersectsSphere(e){let t=this.planes,i=e.center,r=-e.radius;for(let s=0;s<6;s++)if(t[s].distanceToPoint(i)0?e.max.x:e.min.x,kv.y=r.normal.y>0?e.max.y:e.min.y,kv.z=r.normal.z>0?e.max.z:e.min.z,r.distanceToPoint(kv)<0)return!1}return!0}containsPoint(e){let t=this.planes;for(let i=0;i<6;i++)if(t[i].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}},Mn=class extends Or{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new ct(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}},hE=new ne,dE=new ne,Vw=new oi,Vp=new Oo,Wv=new hs,d0=new ne,Gw=new ne,No=class extends er{constructor(e=new Ui,t=new Mn){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}computeLineDistances(){let e=this.geometry;if(e.index===null){let t=e.attributes.position,i=[0];for(let r=1,s=t.count;r0){let r=t[i[0]];if(r!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,a=r.length;s0){let r=t[i[0]];if(r!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,a=r.length;s0?1:-1,f.push(q.x,q.y,q.z),h.push(K/R),h.push(1-Q/I),k+=1}}for(let Q=0;Q0)&&u.push(x,A,E),(g!==i-1||l[Cd(l.sourcePath,l.sourceExt,l.targetExt),l]));function a(){let l=t();i(l),e==null||e(l)}return(n.length!==r.length||r.some((l,c)=>!Fq(l,n[c])))&&(e==null||e(r)),{get(l,c,f){return s.get(Cd(l,c,f))},set(l){s.set(Cd(l.sourcePath,l.sourceExt,l.targetExt),l),a()},delete(l,c,f){let h=s.delete(Cd(l,c,f));return h&&a(),h},clear(){s.size!==0&&(s.clear(),a())},entries(){return t()}}}var Nb=C(()=>{"use strict"});function Ba(n){return n.trim().toLowerCase().replace(/^\./,"")}function wb(n){return Bq.get(Ba(n))}function _l(n){let e=wb(n);return!!(e!=null&&e.enabled)}function Ap(n){return["splat","spz","sog"].includes(Ba(n))}function gl(){return GN.filter(n=>n.enabled).map(n=>n.ext)}var GN,Bq,Io=C(()=>{"use strict";GN=[{ext:"glb",family:"mesh",strategy:"direct",directLoader:"babylon",enabled:!0},{ext:"gltf",family:"mesh",strategy:"direct",directLoader:"babylon",enabled:!0},{ext:"stl",family:"mesh",strategy:"direct",directLoader:"custom-stl",enabled:!0},{ext:"obj",family:"mesh",strategy:"direct",directLoader:"babylon",converterId:"obj2gltf",outputFormat:"glb",enabled:!0},{ext:"ply",family:"mesh",strategy:"direct",directLoader:"custom-ply",enabled:!0},{ext:"fbx",family:"mesh",strategy:"convert",converterId:"fbx2gltf",outputFormat:"glb",enabled:!0},{ext:"step",family:"cad",strategy:"convert",converterId:"freecad",outputFormat:"glb",enabled:!0},{ext:"stp",family:"cad",strategy:"convert",converterId:"freecad",outputFormat:"glb",enabled:!0},{ext:"iges",family:"cad",strategy:"convert",converterId:"freecad",outputFormat:"glb",enabled:!0},{ext:"igs",family:"cad",strategy:"convert",converterId:"freecad",outputFormat:"glb",enabled:!0},{ext:"brep",family:"cad",strategy:"convert",converterId:"freecad",outputFormat:"glb",enabled:!0},{ext:"sldprt",family:"cad",strategy:"convert",converterId:"sldprt",outputFormat:"glb",enabled:!0},{ext:"3mf",family:"mesh",strategy:"convert",converterId:"assimp",outputFormat:"glb",enabled:!0},{ext:"dae",family:"mesh",strategy:"convert",converterId:"assimp",outputFormat:"glb",enabled:!0}],Bq=new Map(GN.map(n=>[n.ext,n]))});var Fb,zN=C(()=>{"use strict";Fb={"settings.title":"AI 3d model workbench","settings.folders":"Folders","settings.behavior":"Behavior","settings.converters":"Converters","settings.converterMenu":"Model converters","settings.converterMenu.desc":"Closed by default. Open this section only when you want to manually enable an optional local conversion route.","settings.environmentInspector":"Environment inspector","settings.environmentInspector.desc":"Closed by default. Open this section when you need to configure command paths or run environment checks.","settings.paths":"Converter paths","settings.diagnostics":"Converter command diagnostics","settings.performance":"Performance & display","settings.mobileSupport":"Mobile support","settings.knowledgeGeneration":"Knowledge generation","settings.sourceModelFolder":"Source model folder","settings.sourceModelFolder.desc":"Vault folder where source model files are stored.","settings.reportFolder":"Report folder","settings.reportFolder.desc":"Vault folder where generated knowledge notes are saved.","settings.partFolder":"Part notes folder","settings.partFolder.desc":"Vault folder where generated part note drafts are saved.","settings.snapshotFolder":"Snapshot folder","settings.snapshotFolder.desc":"Vault folder where exported snapshots are saved.","settings.autoGenerateKnowledgeNotes":"Auto-generate knowledge notes","settings.autoGenerateKnowledgeNotes.desc":"Reserved for a future automation flow. For now, generate notes manually from the command palette.","settings.annotationPreviewMode":"Annotation preview mode","settings.annotationPreviewMode.desc":"Choose how bound note previews render in annotation popovers and the editor.","settings.annotationPreviewMode.plainText":"Plain text","settings.annotationPreviewMode.markdown":"Markdown","settings.annotationDisplayMode":"Annotation display mode","settings.annotationDisplayMode.desc":"Choose how bookmark pins appear over the model.","settings.annotationDisplayMode.snippet":"Full snippet","settings.annotationDisplayMode.surface":"Single surface","settings.annotationDisplayMode.dot":"Single dot","settings.previewRendererRollout":"Preview compatibility mode","settings.previewRendererRollout.desc":"Controls how widely the Three.js preview path is used for single-model previews (GLB, GLTF, STL, PLY, OBJ). Switch back to Compatibility mode if pin projection, occlusion, edit pins, snapshots, or toolbar behavior regress. 3dgrid is not affected by this setting.","settings.previewRendererRollout.babylonSafe":"Compatibility mode","settings.previewRendererRollout.readonly":"Reading surfaces only","settings.previewRendererRollout.direct":"Reading + file view (Recommended)","settings.useThreeRenderer":"Use Three.js renderer","settings.useThreeRenderer.desc":"Toggle between Three.js (faster, lighter) and Babylon.js (full compatibility) for single-model previews. Three.js supports GLB/GLTF/STL/PLY/OBJ. 3dgrid always uses Babylon.js.","settings.experimentalThreeWorkbench":"Experimental Three workbench","settings.experimentalThreeWorkbench.desc":"Try the Three.js workbench path for direct GLB/GLTF files only. If loading fails, the file view falls back to Babylon.js automatically.","settings.autoRotateDefault":"Auto-rotate by default","settings.autoRotateDefault.desc":"Start model previews with auto-rotation enabled.","settings.snapshotNaming":"Snapshot naming","settings.snapshotNaming.desc":"How exported snapshot files are named.","settings.snapshotNaming.modelName":"Model name + timestamp","settings.snapshotNaming.timestamp":"Timestamp only","settings.logLevel":"Log level","settings.logLevel.desc":"Controls plugin runtime log verbosity in the developer console.","settings.language":"Language","settings.language.desc":"Display language for plugin settings. Takes effect immediately.","settings.analysisMode":"AI drafting mode","settings.analysisMode.desc":"Controls whether knowledge-note generation stays local or also requests a sanitized remote draft. Raw model upload is blocked by the current client.","settings.analysisMode.local":"Local evidence only","settings.analysisMode.hybrid":"Local evidence + remote draft","settings.analysisMode.remote":"Remote draft from evidence","settings.serviceBaseUrl":"Draft service URL","settings.serviceBaseUrl.desc":"Optional base URL for a service that accepts POST /draft-note. Leave empty to keep all drafting local.","settings.sendGeometrySummaryToRemote":"Send geometry summary","settings.sendGeometrySummaryToRemote.desc":"Allow sanitized mesh counts, bounds, part candidates, annotation coordinates, and nearest-part links to be included in remote draft input.","settings.sendPreviewImagesToRemote":"Send preview image references","settings.sendPreviewImagesToRemote.desc":"Allow generated preview image paths to be listed in the remote draft input. Image bytes are not uploaded by this client.","settings.sendRawModelToRemote":"Send raw model file","settings.sendRawModelToRemote.desc":"Reserved for future explicit upload support. If enabled manually, remote draft requests are blocked instead of uploading the model.","settings.enableCad":"Enable cad conversion for step, iges, and brep files","settings.enableCad.desc":"Enable cad conversion for step, iges, and brep formats. Requires cadquery and trimesh in your python environment.","settings.enableObj2gltf":"Enable obj2gltf converter (experimental)","settings.enableObj2gltf.desc":"Keep obj direct loading as the default. Enable this only if you want an optional local normalization route through obj2gltf.","settings.preferObj2gltf":"Prefer obj2gltf for obj","settings.preferObj2gltf.desc":"Recommended default is off. Turn this on only when you want normalized output files or direct obj loading is not good enough.","settings.enableFbx2gltf":"Enable FBX2glTF converter","settings.enableFbx2gltf.desc":"Enable conversion for fbx files via FBX2glTF. Requires the FBX2glTF binary installed locally.","settings.enableMesh":"Enable mesh conversion for 3mf and dae files","settings.enableMesh.desc":"Enable conversion for 3mf and dae formats via python trimesh. Requires trimesh, numpy, networkx, and pycollada in your python environment.","settings.enableSldprt":"Enable sldprt conversion for SolidWorks files","settings.enableSldprt.desc":"Enable conversion for SolidWorks sldprt files via FreeCAD. Requires FreeCAD installed locally.","settings.mobileSupport.desc":"On iOS, iPadOS, and Android, direct formats like GLB, GLTF, STL, OBJ, and PLY are supported. Local converter settings and diagnostics remain desktop-only.","settings.pythonCmd":"Path to the python command for cad conversion","settings.pythonCmd.desc":"Optional path to the python command used for cad conversion. Windows usually uses py. macOS and Linux usually use python3. Overrides auto-discovery when set.","settings.freecadCmd":"Path to the FreeCAD command for sldprt conversion","settings.freecadCmd.desc":"Optional path to the FreeCAD command used for SolidWorks file conversion. Windows usually uses FreeCADCmd.exe, macOS usually uses FreeCADCmd, and Linux usually uses freecadcmd. Overrides auto-discovery when set.","settings.obj2gltfCmd":"Path to the obj2gltf command","settings.obj2gltfCmd.desc":"Optional path to the obj2gltf command. Windows usually uses obj2gltf.cmd, and macOS and Linux usually use obj2gltf. Overrides auto-discovery when set.","settings.fbx2gltfCmd":"FBX2glTF command path","settings.fbx2gltfCmd.desc":"Optional path to the FBX2glTF command. Windows usually uses FBX2glTF.exe, and macOS and Linux usually use FBX2glTF. Overrides auto-discovery when set.","settings.assimpCmd":"Path to the python command for 3mf and dae conversion","settings.assimpCmd.desc":"Optional path to the python command used for 3mf and dae conversion. Windows usually uses py. macOS and Linux usually use python3. Overrides auto-discovery when set.","settings.diagnostics.desc":"Shows the exact executable path the plugin would use right now and runs lightweight self-checks for Python environments and converter CLIs.","settings.diagnostics.idle":"Diagnostics are off by default. Click Check now to run them manually.","settings.diagnostics.checkNow":"Check now","settings.diagnostics.checking":"Checking...","settings.diagnostics.refreshed":"Converter command diagnostics refreshed.","settings.diagnostics.checkingAvailability":"Checking converter command availability...","settings.diagnostics.available":"available","settings.diagnostics.notFound":"not found","settings.diagnostics.sourceLabel":"Source","settings.diagnostics.commandLabel":"Command","settings.diagnostics.resolvedPathLabel":"Resolved path","settings.diagnostics.selfCheckLabel":"Self-check","settings.diagnostics.selfCheckOk":"passed","settings.diagnostics.selfCheckFailed":"failed","settings.diagnostics.cadPythonCheck":"Python packages (cadquery, trimesh)","settings.diagnostics.meshPythonCheck":"Python packages (trimesh, numpy, networkx, collada)","settings.diagnostics.freecadCmdCheck":"FreeCADCmd launch probe","settings.diagnostics.obj2gltfCheck":"obj2gltf launch probe","settings.diagnostics.fbx2gltfCheck":"FBX2glTF launch probe","settings.canvasHeight":"Default canvas height","settings.canvasHeight.desc":"Default height (px) for inline model previews. Range: 200\u2013800.","settings.autoRotateSpeed":"Auto-rotate speed","settings.autoRotateSpeed.desc":"Rotation speed when auto-rotate is enabled. Range: 0.1\u20132.0.","settings.renderQuality":"Render quality","settings.renderQuality.desc":"Higher quality uses more GPU resources. Affects anti-aliasing and resolution.","settings.renderScale":"Resolution scale","settings.renderScale.desc":"Render resolution multiplier. 1.0 = native, 0.5 = half, 2.0 = double (supersampling). Range: 0.25\u20132.0.","modelLoad.warningTitle":"Model preview unavailable","modelLoad.warningMessage":"{ext} files need the {converterName} converter enabled in plugin settings before they can load.","modelLoad.warningHint":"Enable the matching converter in plugin settings, then reload this file.","modelLoad.mobileWarningMessage":"{ext} files need local conversion tools that are unavailable on iOS, iPadOS, and Android.","modelLoad.mobileWarningHint":"Open this file on desktop, or convert it to GLB, GLTF, OBJ, STL, or PLY first.","modelLoad.errorTitle":"Couldn't display this model","modelLoad.errorMessage":"Failed to load: {reason}","modelLoad.errorHint":"Check the file format or open the developer console for details.","headingPin.showSingle":"Show linked pin","headingPin.showMultiple":"Show linked pins","headingPin.linkedTo":"Pin linked to: {models}","helper.resetViewLabel":"Reset view","helper.resetViewDone":"Reset","helper.copyModelInfoLabel":"Copy model info as Markdown","helper.copySelectedPartInfoLabel":"Copy selected part info","helper.noSelectedPart":"Select a part first","helper.copied":"Copied!","helper.failed":"Failed","helper.toggleWireframeLabel":"Toggle wireframe","helper.wireframeOn":"Wireframe","helper.wireframeOff":"Solid","helper.toggleAxesLabel":"Toggle orientation axes","helper.axesOn":"Axes on","helper.axesOff":"Axes off","helper.toggleBoundingBoxLabel":"Toggle bounding box","helper.boundingBoxOn":"Bounding box on","helper.boundingBoxOff":"Bounding box off","helper.toggleFocusSelectionLabel":"Focus selected part","helper.focusSelectionOn":"Focus mode on","helper.focusSelectionOff":"Focus mode off","helper.toggleDisassemblyLabel":"Toggle disassembly mode","helper.disassemblyOn":"Disassembly on","helper.disassemblyOff":"Disassembly off","helper.resetPartsLabel":"Reset disassembled parts","helper.partsReset":"Parts reset","helper.changeResolutionLabel":"Change resolution","helper.resolutionValue":"Resolution: {value}","helper.toggleAnimationLabel":"Play or pause animation","helper.playing":"Playing","helper.paused":"Paused","helper.toggleMeasurementLabel":"Toggle distance measurement","helper.measurementOn":"Measurement on","helper.measurementOff":"Measurement off","helper.clearMeasurementsLabel":"Clear measurements","helper.measurementsCleared":"Cleared","helper.calibrateLabel":"Calibrate measurement scale","helper.calibrateTitle":"Measurement Calibration","helper.calibrateCurrent":"Current size:","helper.calibrateReal":"Real size:","helper.calibrateLock":"Lock ratio","helper.calibrateApply":"Apply","helper.calibrateReset":"Reset","helper.calibrated":"Scale applied","helper.calibrateResetDone":"Scale reset","helper.calibrateOpen":"Calibration panel opened","helper.calibrateClose":"Calibration panel closed","helper.removePreviewLabel":"Remove preview","helper.copySnapshotLabel":"Copy snapshot","helper.saveSnapshotLabel":"Save snapshot to vault","helper.saved":"Saved!","helper.downloadSnapshotLabel":"Download snapshot","helper.downloaded":"Downloaded!","helper.toggleAnnotationLabel":"Toggle annotation mode","helper.toggleAnnotationsVisibilityLabel":"Show or hide annotations","helper.annotateOn":"Annotation mode on","helper.annotateOff":"Annotation mode off","helper.annotationsVisible":"Annotations shown","helper.annotationsHidden":"Annotations hidden","helper.enableInteractionLabel":"Enable touch interaction","helper.disableInteractionLabel":"Return to scroll mode","helper.interactionOn":"Model interaction on","helper.interactionOff":"Scroll mode on","helper.showMoreActionsLabel":"Show more actions","helper.hideMoreActionsLabel":"Hide extra actions","helper.moreActionsShown":"More actions shown","helper.moreActionsHidden":"Extra actions hidden","helper.interactAction":"Interact","helper.scrollAction":"Scroll","workbench.emptyTitle":"No model","workbench.emptyText":'Use the "import 3D model" command to load a GLB, GLTF, STL, OBJ, or PLY file.',"workbench.modelTitle":"Model","workbench.studioTitle":"AI Model Workbench","workbench.studioTagline":"Inspect, annotate, and turn 3D assets into linked notes.","workbench.navLabel":"Workbench sections","workbench.navGallery":"Gallery","workbench.navLibrary":"Library","workbench.navNotebooks":"Notebooks","workbench.navSettings":"Settings","workbench.sourcesTitle":"Model sources","workbench.layersTitle":"Review layers","workbench.viewModeTitle":"View mode","workbench.modeMesh":"Mesh view","workbench.modeFocus":"Focus selection","workbench.modeMeshShort":"Mesh","workbench.modeFocusShort":"Focus","workbench.previewViewsTitle":"Preview views","workbench.connectionsTitle":"Knowledge connections","workbench.currentModelLabel":"Current model","workbench.noReportYet":"No report note yet","workbench.noIndexYet":"No knowledge index yet. Generate a knowledge note first.","workbench.noModelLoaded":"No model loaded","workbench.disassemblyTitle":"Disassembly","workbench.explodeLabel":"Explode","workbench.summaryTitle":"Summary","workbench.meshesLabel":"Meshes","workbench.splatsLabel":"Splats","workbench.trianglesLabel":"Triangles","workbench.verticesLabel":"Vertices","workbench.materialsLabel":"Materials","workbench.boundingSizeLabel":"Bounds","workbench.centerLabel":"Center","workbench.selectedPartTitle":"Selected Part","workbench.partMeshLabel":"Mesh","workbench.noSelectedPart":"Click a model part to inspect it here.","workbench.tagsTitle":"Tags","workbench.noTagsYet":"No tags yet","workbench.addTagPlaceholder":"Add tag...","workbench.addTagAction":"Add","workbench.annotationsTitle":"Annotations","workbench.exitAnnotate":"Exit annotate","workbench.annotate":"Annotate","workbench.annotateHintActive":"Click the model to add a label \xB7 press Esc to exit","workbench.annotateHintActiveMobile":"Tap the model to add a label. Switch back to Scroll when you want to move through the note again.","workbench.pinCount":"{count} pin(s)","workbench.editAction":"Edit","workbench.deleteAction":"Delete","workbench.resetViewAction":"Reset view","workbench.insertInfoAction":"Insert info","workbench.insertGalleryAction":"Insert Gallery","workbench.insertCompareAction":"Insert Compare","workbench.playAction":"Play","workbench.pauseAction":"Pause","workbench.saveProfileAction":"Save profile","workbench.generateNoteAction":"Generate note","workbench.openNoteAction":"Open note","workbench.openIndexAction":"Open index","workbench.recordTitle":"Specimen card","workbench.recordSubtitle":"Current asset profile","workbench.notesTitle":"Analysis notes","workbench.whereTitle":"Where it connects","workbench.noteReady":"Linked note ready","workbench.indexReady":"Knowledge index ready","workbench.notePending":"Linked note pending","workbench.analysisLabel":"Analysis","workbench.settingsUnavailable":"Open this plugin from Obsidian settings to change workbench options.","workbench.profileSaved":"Profile saved","workbench.viewReset":"View reset","workbench.infoInserted":"Model info inserted","workbench.infoCopied":"Model info copied","workbench.templateInserted":"Template inserted","workbench.templateCopied":"Template copied","workbench.mobileHint":"Mobile tip: tap Interact to move the model, then switch back to Scroll to keep reading the note.","workbench.mobileHintInteractive":"Interaction mode is on. Switch back to Scroll when you want to move through the note again.","directView.mobileHint":"Mobile tip: use the toolbar Interact button to switch between model interaction and note scrolling.","directWorkbench.modelLoadInterrupted":"Model load was interrupted by a newer request.","directWorkbench.backendLabel":"Backend","directWorkbench.routeLabel":"Route","directWorkbench.performanceLabel":"Performance","directWorkbench.partCandidatesLabel":"Part candidates","directWorkbench.knowledgeTitle":"Knowledge","directWorkbench.registeredTitle":"Registered part matches","directWorkbench.registeredLoading":"Checking...","directWorkbench.registeredCount":"{count} match(es)","directWorkbench.registeredEmpty":"No cross-model part match yet","directWorkbench.registeredUnavailable":"Part evidence unavailable","directWorkbench.registeredOpen":"Open","directWorkbench.registeredOpenNote":"Note","directWorkbench.registeredOpenModel":"Model","directWorkbench.registeredSourceModel":"From {model}","directWorkbench.registeredTargetPartNote":"Opens matched part note","directWorkbench.registeredTargetSourceModel":"Opens source model","directWorkbench.registeredTargetUnavailable":"No linked target","workbench.fileNotFound":"File not found: {path}","annotation.selectColor":"Select color {color}","annotation.sectionEmpty":"Section is empty.","modal.selectModel":"Select a 3D model...","main.commandImportModel":"Import a 3D model","main.commandGenerateNote":"Generate knowledge note","main.commandOpenKnowledgeIndex":"Open knowledge index","main.commandClearConversionCache":"Clear conversion cache","main.commandCheckConverters":"Check converters","main.commandCopyDiagnostics":"Copy diagnostics report","main.converterDiagnosticsMobileUnavailable":"Converter diagnostics are only available on desktop. On iOS, iPadOS, and Android, direct formats can still load.","main.diagnosticsCopied":"AI Model Workbench diagnostics copied to clipboard.","main.diagnosticsCopyFailed":"Couldn't copy diagnostics. A sanitized diagnostics note was created instead.","codeBlock.noModelPathOrConfig":"No model path or config specified.","codeBlock.jsonParseError":"JSON parse error: {error}","codeBlock.jsonParseLine":" (line {line})","codeBlock.noModelsInConfig":"No models specified in config.","codeBlock.unsupportedFormat":"Unsupported format: {ext}. Supported: {formats}","codeBlock.splatDisabled":"SPLAT preview is disabled in packaged builds. Local-only .splat support is planned first; .spz/.sog need locally bundled decoders before reevaluation.","codeBlock.noConfigSpecified":"No config specified.","codeBlock.noModelsSpecified":"No models specified.","codeBlock.mobileHint":"Mobile tip: use Interact to manipulate the model, then switch back to Scroll to keep moving through the note.","codeBlock.renderingGrid":"Rendering grid...","codeBlock.composeRequiresSections":'"compose" preset requires a "sections" array.',"codeBlock.composeNoValidSections":"Compose: no valid sections.","codeBlock.unknownPreset":'Unknown preset: "{preset}". Available: compare, showcase, explode, timeline, compose',"codeBlock.presetRequiresModels":'Preset "{preset}" requires {min}-{max} models, got {count}.',"codeBlock.gridFailed":"Grid failed: {reason}","livePreview.mobileHint":"Mobile tip: switch between Interact and Scroll depending on whether you want to move the model or keep reading.","loading.default":"Loading...","loading.preparingModel":"Preparing model...","loading.loadingModel":"Loading model..."}});var XN,YN=C(()=>{"use strict";XN={"settings.title":"AI 3D \u6A21\u578B\u5DE5\u4F5C\u53F0","settings.folders":"\u6587\u4EF6\u5939","settings.behavior":"\u884C\u4E3A","settings.converters":"\u8F6C\u6362\u5668","settings.converterMenu":"\u6A21\u578B\u8F6C\u6362\u5668","settings.converterMenu.desc":"\u9ED8\u8BA4\u6536\u8D77\u3002\u4EC5\u5728\u4F60\u9700\u8981\u624B\u52A8\u542F\u7528\u67D0\u6761\u672C\u5730\u8F6C\u6362\u8DEF\u7EBF\u65F6\u518D\u5C55\u5F00\u3002","settings.environmentInspector":"\u73AF\u5883\u68C0\u67E5\u5668","settings.environmentInspector.desc":"\u9ED8\u8BA4\u6536\u8D77\u3002\u4EC5\u5728\u9700\u8981\u914D\u7F6E\u547D\u4EE4\u8DEF\u5F84\u6216\u624B\u52A8\u6267\u884C\u73AF\u5883\u68C0\u67E5\u65F6\u518D\u5C55\u5F00\u3002","settings.paths":"\u8F6C\u6362\u5668\u8DEF\u5F84","settings.diagnostics":"\u8F6C\u6362\u5668\u547D\u4EE4\u8BCA\u65AD","settings.performance":"\u6027\u80FD\u4E0E\u663E\u793A","settings.mobileSupport":"\u79FB\u52A8\u7AEF\u652F\u6301","settings.knowledgeGeneration":"\u77E5\u8BC6\u751F\u6210","settings.sourceModelFolder":"\u6E90\u6A21\u578B\u6587\u4EF6\u5939","settings.sourceModelFolder.desc":"\u5B58\u653E\u6E90 3D \u6A21\u578B\u7684\u5E93\u6587\u4EF6\u5939\u3002","settings.reportFolder":"\u62A5\u544A\u6587\u4EF6\u5939","settings.reportFolder.desc":"\u4FDD\u5B58\u751F\u6210\u7684\u77E5\u8BC6\u7B14\u8BB0\u7684\u5E93\u6587\u4EF6\u5939\u3002","settings.partFolder":"\u90E8\u4EF6\u7B14\u8BB0\u6587\u4EF6\u5939","settings.partFolder.desc":"\u4FDD\u5B58\u751F\u6210\u7684\u90E8\u4EF6\u7B14\u8BB0\u8349\u7A3F\u7684\u5E93\u6587\u4EF6\u5939\u3002","settings.snapshotFolder":"\u5FEB\u7167\u6587\u4EF6\u5939","settings.snapshotFolder.desc":"\u4FDD\u5B58\u5BFC\u51FA\u5FEB\u7167\u7684\u5E93\u6587\u4EF6\u5939\u3002","settings.autoGenerateKnowledgeNotes":"\u81EA\u52A8\u751F\u6210\u77E5\u8BC6\u7B14\u8BB0","settings.autoGenerateKnowledgeNotes.desc":"\u9884\u7559\u7ED9\u540E\u7EED\u81EA\u52A8\u5316\u6D41\u7A0B\u3002\u5F53\u524D\u8BF7\u901A\u8FC7\u547D\u4EE4\u6216\u5DE5\u4F5C\u53F0\u6309\u94AE\u624B\u52A8\u751F\u6210\u77E5\u8BC6\u7B14\u8BB0\u3002","settings.annotationPreviewMode":"\u6807\u6CE8\u9884\u89C8\u6A21\u5F0F","settings.annotationPreviewMode.desc":"\u9009\u62E9\u6807\u6CE8\u7ED1\u5B9A\u7B14\u8BB0\u5728\u60AC\u6D6E\u9884\u89C8\u548C\u7F16\u8F91\u5668\u4E2D\u7684\u663E\u793A\u65B9\u5F0F\u3002","settings.annotationPreviewMode.plainText":"\u7EAF\u6587\u672C","settings.annotationPreviewMode.markdown":"Markdown","settings.annotationDisplayMode":"\u6807\u6CE8\u663E\u793A\u6A21\u5F0F","settings.annotationDisplayMode.desc":"\u9009\u62E9\u6A21\u578B\u4E0A\u4E66\u7B7E\u6807\u6CE8\u7684\u663E\u793A\u65B9\u5F0F\u3002","settings.annotationDisplayMode.snippet":"\u5B8C\u6574\u7247\u6BB5","settings.annotationDisplayMode.surface":"\u5355\u4E2A\u6807\u7B7E\u9762","settings.annotationDisplayMode.dot":"\u5355\u4E2A\u5706\u70B9","settings.previewRendererRollout":"\u9884\u89C8\u517C\u5BB9\u6A21\u5F0F","settings.previewRendererRollout.desc":"\u63A7\u5236\u5355\u6A21\u578B\u9884\u89C8\uFF08GLB\u3001GLTF\u3001STL\u3001PLY\u3001OBJ\uFF09\u4E2D Three.js \u6E32\u67D3\u8DEF\u5F84\u7684\u542F\u7528\u8303\u56F4\u3002\u53EA\u8981\u51FA\u73B0 pin \u6295\u5F71\u3001\u906E\u6321\u3001\u7F16\u8F91\u6001 pin\u3001\u5FEB\u7167\u6216\u5DE5\u5177\u680F\u884C\u4E3A\u56DE\u9000\uFF0C\u5C31\u5207\u56DE\u201C\u517C\u5BB9\u4F18\u5148\u201D\u3002workbench \u548C 3dgrid \u4E0D\u53D7\u8FD9\u4E2A\u8BBE\u7F6E\u5F71\u54CD\u3002","settings.previewRendererRollout.babylonSafe":"\u517C\u5BB9\u4F18\u5148","settings.previewRendererRollout.readonly":"\u4EC5\u9605\u8BFB\u573A\u666F","settings.previewRendererRollout.direct":"\u9605\u8BFB + \u6587\u4EF6\u89C6\u56FE\uFF08\u63A8\u8350\uFF09","settings.useThreeRenderer":"\u4F7F\u7528 Three.js \u6E32\u67D3\u5668","settings.useThreeRenderer.desc":"\u5728 Three.js\uFF08\u66F4\u5FEB\u3001\u66F4\u8F7B\u91CF\uFF09\u548C Babylon.js\uFF08\u5B8C\u5168\u517C\u5BB9\uFF09\u4E4B\u95F4\u5207\u6362\u5355\u6A21\u578B\u9884\u89C8\u6E32\u67D3\u5668\u3002Three.js \u652F\u6301 GLB/GLTF/STL/PLY/OBJ\u3002\u5DE5\u4F5C\u53F0\u548C 3dgrid \u59CB\u7EC8\u4F7F\u7528 Babylon.js\u3002","settings.experimentalThreeWorkbench":"\u5B9E\u9A8C\u6027 Three \u5DE5\u4F5C\u53F0","settings.experimentalThreeWorkbench.desc":"\u4EC5\u5BF9\u76F4\u8BFB GLB/GLTF \u6587\u4EF6\u5C1D\u8BD5\u4F7F\u7528 Three.js \u5DE5\u4F5C\u53F0\u8DEF\u5F84\u3002\u52A0\u8F7D\u5931\u8D25\u65F6\uFF0C\u6587\u4EF6\u89C6\u56FE\u4F1A\u81EA\u52A8\u56DE\u9000\u5230 Babylon.js\u3002","settings.autoRotateDefault":"\u9ED8\u8BA4\u81EA\u52A8\u65CB\u8F6C","settings.autoRotateDefault.desc":"\u542F\u52A8 3D \u9884\u89C8\u65F6\u9ED8\u8BA4\u5F00\u542F\u81EA\u52A8\u65CB\u8F6C\u3002","settings.snapshotNaming":"\u5FEB\u7167\u547D\u540D","settings.snapshotNaming.desc":"\u5BFC\u51FA\u5FEB\u7167\u6587\u4EF6\u7684\u547D\u540D\u65B9\u5F0F\u3002","settings.snapshotNaming.modelName":"\u6A21\u578B\u540D + \u65F6\u95F4\u6233","settings.snapshotNaming.timestamp":"\u4EC5\u65F6\u95F4\u6233","settings.logLevel":"\u65E5\u5FD7\u7EA7\u522B","settings.logLevel.desc":"\u63A7\u5236\u63D2\u4EF6\u5728\u5F00\u53D1\u8005\u63A7\u5236\u53F0\u4E2D\u7684\u65E5\u5FD7\u8BE6\u7EC6\u7A0B\u5EA6\u3002","settings.language":"\u8BED\u8A00","settings.language.desc":"\u63D2\u4EF6\u8BBE\u7F6E\u754C\u9762\u7684\u663E\u793A\u8BED\u8A00\u3002\u7ACB\u5373\u751F\u6548\u3002","settings.analysisMode":"AI \u8349\u7A3F\u6A21\u5F0F","settings.analysisMode.desc":"\u63A7\u5236\u77E5\u8BC6\u7B14\u8BB0\u751F\u6210\u4FDD\u6301\u672C\u5730\uFF0C\u8FD8\u662F\u989D\u5916\u8BF7\u6C42\u7ECF\u8FC7\u88C1\u526A\u7684\u8FDC\u7A0B\u8349\u7A3F\u3002\u5F53\u524D\u5BA2\u6237\u7AEF\u4F1A\u963B\u6B62\u539F\u59CB\u6A21\u578B\u4E0A\u4F20\u3002","settings.analysisMode.local":"\u4EC5\u672C\u5730\u8BC1\u636E","settings.analysisMode.hybrid":"\u672C\u5730\u8BC1\u636E + \u8FDC\u7A0B\u8349\u7A3F","settings.analysisMode.remote":"\u57FA\u4E8E\u8BC1\u636E\u7684\u8FDC\u7A0B\u8349\u7A3F","settings.serviceBaseUrl":"\u8349\u7A3F\u670D\u52A1 URL","settings.serviceBaseUrl.desc":"\u53EF\u9009\u7684\u8349\u7A3F\u670D\u52A1\u57FA\u7840\u5730\u5740\uFF0C\u670D\u52A1\u9700\u63A5\u6536 POST /draft-note\u3002\u7559\u7A7A\u65F6\u6240\u6709\u8349\u7A3F\u8F93\u5165\u90FD\u4FDD\u7559\u5728\u672C\u5730\u3002","settings.sendGeometrySummaryToRemote":"\u53D1\u9001\u51E0\u4F55\u6458\u8981","settings.sendGeometrySummaryToRemote.desc":"\u5141\u8BB8\u628A\u7ECF\u8FC7\u88C1\u526A\u7684\u7F51\u683C\u6570\u91CF\u3001\u5305\u56F4\u76D2\u3001\u90E8\u4EF6\u5019\u9009\u3001\u6807\u6CE8\u5750\u6807\u548C\u6700\u8FD1\u90E8\u4EF6\u5173\u8054\u52A0\u5165\u8FDC\u7A0B\u8349\u7A3F\u8F93\u5165\u3002","settings.sendPreviewImagesToRemote":"\u53D1\u9001\u9884\u89C8\u56FE\u5F15\u7528","settings.sendPreviewImagesToRemote.desc":"\u5141\u8BB8\u5728\u8FDC\u7A0B\u8349\u7A3F\u8F93\u5165\u4E2D\u5217\u51FA\u751F\u6210\u7684\u9884\u89C8\u56FE\u8DEF\u5F84\u3002\u5F53\u524D\u5BA2\u6237\u7AEF\u4E0D\u4F1A\u4E0A\u4F20\u56FE\u7247\u5B57\u8282\u3002","settings.sendRawModelToRemote":"\u53D1\u9001\u539F\u59CB\u6A21\u578B\u6587\u4EF6","settings.sendRawModelToRemote.desc":"\u9884\u7559\u7ED9\u672A\u6765\u663E\u5F0F\u4E0A\u4F20\u652F\u6301\u3002\u82E5\u624B\u52A8\u5F00\u542F\uFF0C\u8FDC\u7A0B\u8349\u7A3F\u8BF7\u6C42\u4F1A\u88AB\u963B\u6B62\uFF0C\u4E0D\u4F1A\u4E0A\u4F20\u6A21\u578B\u3002","settings.enableCad":"\u542F\u7528 CAD \u8F6C\u6362\u5668 (STEP/IGES/BREP)","settings.enableCad.desc":"\u542F\u7528 STEP/IGES/BREP \u683C\u5F0F\u7684 CAD \u8F6C\u6362\u8DEF\u7EBF\uFF0C\u901A\u8FC7 Python CadQuery (OpenCASCADE)\u3002\u9700\u8981\uFF1Apip install cadquery trimesh","settings.enableObj2gltf":"\u542F\u7528 obj2gltf \u8F6C\u6362\u5668\uFF08\u5B9E\u9A8C\u6027\uFF09","settings.enableObj2gltf.desc":"\u9ED8\u8BA4\u4F7F\u7528 OBJ \u76F4\u63A5\u52A0\u8F7D\u3002\u4EC5\u5728\u9700\u8981\u672C\u5730\u6807\u51C6\u5316 GLB \u8F93\u51FA\u65F6\u542F\u7528\u3002","settings.preferObj2gltf":"OBJ \u4F18\u5148\u4F7F\u7528 obj2gltf","settings.preferObj2gltf.desc":"\u9ED8\u8BA4\u5173\u95ED\u3002\u4EC5\u5728\u9700\u8981\u6807\u51C6\u5316 GLB \u8F93\u51FA\u6216\u76F4\u63A5 OBJ \u52A0\u8F7D\u6548\u679C\u4E0D\u4F73\u65F6\u5F00\u542F\u3002","settings.enableFbx2gltf":"\u542F\u7528 FBX2glTF \u8F6C\u6362\u5668","settings.enableFbx2gltf.desc":"\u542F\u7528 FBX \u6587\u4EF6\u901A\u8FC7 FBX2glTF \u8F6C\u6362\u3002\u9700\u8981\u672C\u5730\u5B89\u88C5 FBX2glTF \u4E8C\u8FDB\u5236\u6587\u4EF6\u3002","settings.enableMesh":"\u542F\u7528\u7F51\u683C\u8F6C\u6362\u5668 (3MF/DAE)","settings.enableMesh.desc":"\u542F\u7528 3MF \u548C DAE (Collada) \u683C\u5F0F\u7684\u8F6C\u6362\u8DEF\u7EBF\uFF0C\u901A\u8FC7 Python trimesh\u3002\u9700\u8981\u5B89\u88C5 Python \u548C trimesh (pip install trimesh numpy networkx pycollada)\u3002","settings.enableSldprt":"\u542F\u7528 SLDPRT \u8F6C\u6362\u5668 (SolidWorks)","settings.enableSldprt.desc":"\u542F\u7528 SolidWorks .sldprt \u6587\u4EF6\u901A\u8FC7 FreeCAD \u8F6C\u6362\u3002\u9700\u8981\u5B89\u88C5 FreeCAD (https://www.freecad.org/downloads.php)\u3002","settings.mobileSupport.desc":"\u5728 iOS\u3001iPadOS \u548C Android \u4E0A\uFF0CGLB\u3001GLTF\u3001STL\u3001OBJ\u3001PLY \u8FD9\u7C7B\u76F4\u8BFB\u683C\u5F0F\u53EF\u7528\u3002\u672C\u5730\u8F6C\u6362\u5668\u8BBE\u7F6E\u548C\u547D\u4EE4\u8BCA\u65AD\u4ECD\u4EC5\u652F\u6301\u684C\u9762\u7AEF\u3002","settings.pythonCmd":"Python \u547D\u4EE4\u8DEF\u5F84\uFF08CAD \u7528\uFF09","settings.pythonCmd.desc":"\u53EF\u9009\u7684 Python \u547D\u4EE4\u8DEF\u5F84\uFF0C\u7528\u4E8E CAD \u8F6C\u6362\u3002Windows \u901A\u5E38\u7528 py\uFF0CmacOS \u548C Linux \u901A\u5E38\u7528 python3\u3002\u8BBE\u7F6E\u540E\u8986\u76D6\u81EA\u52A8\u53D1\u73B0\u548C AI3D_FREECAD_CMD\u3002","settings.freecadCmd":"FreeCAD \u547D\u4EE4\u8DEF\u5F84\uFF08SLDPRT \u7528\uFF09","settings.freecadCmd.desc":"\u53EF\u9009\u7684 FreeCAD \u547D\u4EE4\u8DEF\u5F84\uFF0C\u7528\u4E8E SolidWorks \u6587\u4EF6\u8F6C\u6362\u3002Windows \u901A\u5E38\u7528 FreeCADCmd.exe\uFF0CmacOS \u901A\u5E38\u7528 FreeCADCmd\uFF0CLinux \u901A\u5E38\u7528 freecadcmd\u3002\u8BBE\u7F6E\u540E\u8986\u76D6\u81EA\u52A8\u53D1\u73B0\u548C AI3D_FREECADCMD\u3002","settings.obj2gltfCmd":"obj2gltf \u547D\u4EE4\u8DEF\u5F84","settings.obj2gltfCmd.desc":"\u53EF\u9009\u7684 obj2gltf \u547D\u4EE4\u8DEF\u5F84\u3002Windows \u901A\u5E38\u7528 obj2gltf.cmd\uFF0CmacOS \u548C Linux \u901A\u5E38\u7528 obj2gltf\u3002\u8BBE\u7F6E\u540E\u8986\u76D6\u81EA\u52A8\u53D1\u73B0\u548C AI3D_OBJ2GLTF_CMD\u3002","settings.fbx2gltfCmd":"FBX2glTF \u547D\u4EE4\u8DEF\u5F84","settings.fbx2gltfCmd.desc":"\u53EF\u9009\u7684 FBX2glTF \u547D\u4EE4\u8DEF\u5F84\u3002Windows \u901A\u5E38\u7528 FBX2glTF.exe\uFF0CmacOS \u548C Linux \u901A\u5E38\u7528 FBX2glTF\u3002\u8BBE\u7F6E\u540E\u8986\u76D6\u81EA\u52A8\u53D1\u73B0\u548C AI3D_FBX2GLTF_CMD\u3002","settings.assimpCmd":"Python \u547D\u4EE4\u8DEF\u5F84\uFF083MF/DAE \u7528\uFF09","settings.assimpCmd.desc":"\u53EF\u9009\u7684 Python \u547D\u4EE4\u8DEF\u5F84\uFF0C\u7528\u4E8E 3MF \u548C DAE \u8F6C\u6362\u3002Windows \u901A\u5E38\u7528 py\uFF0CmacOS \u548C Linux \u901A\u5E38\u7528 python3\u3002\u8BBE\u7F6E\u540E\u8986\u76D6\u81EA\u52A8\u53D1\u73B0\u548C AI3D_ASSIMP_CMD\u3002","settings.diagnostics.desc":"\u663E\u793A\u63D2\u4EF6\u5F53\u524D\u5B9E\u9645\u4F7F\u7528\u7684\u53EF\u6267\u884C\u6587\u4EF6\u8DEF\u5F84\uFF0C\u5E76\u4E3A Python \u73AF\u5883\u548C\u8F6C\u6362\u5668\u547D\u4EE4\u6267\u884C\u8F7B\u91CF\u81EA\u68C0\u3002","settings.diagnostics.idle":"\u73AF\u5883\u68C0\u67E5\u9ED8\u8BA4\u5173\u95ED\u3002\u70B9\u51FB\u201C\u7ACB\u5373\u68C0\u67E5\u201D\u540E\u624D\u4F1A\u6267\u884C\u3002","settings.diagnostics.checkNow":"\u7ACB\u5373\u68C0\u67E5","settings.diagnostics.checking":"\u68C0\u67E5\u4E2D...","settings.diagnostics.refreshed":"AI 3D \u8F6C\u6362\u5668\u547D\u4EE4\u8BCA\u65AD\u5DF2\u5237\u65B0\u3002","settings.diagnostics.checkingAvailability":"\u6B63\u5728\u68C0\u67E5\u8F6C\u6362\u5668\u547D\u4EE4\u53EF\u7528\u6027...","settings.diagnostics.available":"\u53EF\u7528","settings.diagnostics.notFound":"\u672A\u627E\u5230","settings.diagnostics.sourceLabel":"\u6765\u6E90","settings.diagnostics.commandLabel":"\u547D\u4EE4","settings.diagnostics.resolvedPathLabel":"\u89E3\u6790\u8DEF\u5F84","settings.diagnostics.selfCheckLabel":"\u81EA\u68C0","settings.diagnostics.selfCheckOk":"\u901A\u8FC7","settings.diagnostics.selfCheckFailed":"\u5931\u8D25","settings.diagnostics.cadPythonCheck":"Python \u5305\uFF08cadquery\u3001trimesh\uFF09","settings.diagnostics.meshPythonCheck":"Python \u5305\uFF08trimesh\u3001numpy\u3001networkx\u3001collada\uFF09","settings.diagnostics.freecadCmdCheck":"FreeCADCmd \u542F\u52A8\u63A2\u6D4B","settings.diagnostics.obj2gltfCheck":"obj2gltf \u542F\u52A8\u63A2\u6D4B","settings.diagnostics.fbx2gltfCheck":"FBX2glTF \u542F\u52A8\u63A2\u6D4B","settings.canvasHeight":"\u9ED8\u8BA4\u753B\u5E03\u9AD8\u5EA6","settings.canvasHeight.desc":"\u5185\u8054 3D \u9884\u89C8\u7684\u9ED8\u8BA4\u9AD8\u5EA6\uFF08\u50CF\u7D20\uFF09\u3002\u8303\u56F4\uFF1A200\u2013800\u3002","settings.autoRotateSpeed":"\u81EA\u52A8\u65CB\u8F6C\u901F\u5EA6","settings.autoRotateSpeed.desc":"\u542F\u7528\u81EA\u52A8\u65CB\u8F6C\u65F6\u7684\u65CB\u8F6C\u901F\u5EA6\u3002\u8303\u56F4\uFF1A0.1\u20132.0\u3002","settings.renderQuality":"\u6E32\u67D3\u8D28\u91CF","settings.renderQuality.desc":"\u66F4\u9AD8\u8D28\u91CF\u4F7F\u7528\u66F4\u591A GPU \u8D44\u6E90\u3002\u5F71\u54CD\u6297\u952F\u9F7F\u548C\u5206\u8FA8\u7387\u3002","settings.renderScale":"\u6E32\u67D3\u7F29\u653E","settings.renderScale.desc":"\u6E32\u67D3\u5206\u8FA8\u7387\u500D\u6570\u30021.0 = \u539F\u59CB\uFF0C0.5 = \u4E00\u534A\uFF0C2.0 = \u53CC\u500D\uFF08\u8D85\u91C7\u6837\uFF09\u3002\u8303\u56F4\uFF1A0.25\u20132.0\u3002","modelLoad.warningTitle":"\u6682\u65F6\u65E0\u6CD5\u9884\u89C8\u6A21\u578B","modelLoad.warningMessage":"{ext} \u6587\u4EF6\u9700\u8981\u5148\u5728\u63D2\u4EF6\u8BBE\u7F6E\u4E2D\u542F\u7528 {converterName} \u8F6C\u6362\u5668\uFF0C\u624D\u80FD\u52A0\u8F7D\u3002","modelLoad.warningHint":"\u8BF7\u5148\u5728\u63D2\u4EF6\u8BBE\u7F6E\u4E2D\u542F\u7528\u5BF9\u5E94\u8F6C\u6362\u5668\uFF0C\u7136\u540E\u91CD\u65B0\u52A0\u8F7D\u5F53\u524D\u6587\u4EF6\u3002","modelLoad.mobileWarningMessage":"{ext} \u6587\u4EF6\u9700\u8981\u672C\u5730\u8F6C\u6362\u5DE5\u5177\uFF0C\u4F46\u8FD9\u4E9B\u5DE5\u5177\u5728 iOS\u3001iPadOS \u548C Android \u4E0A\u4E0D\u53EF\u7528\u3002","modelLoad.mobileWarningHint":"\u8BF7\u5728\u684C\u9762\u7AEF\u6253\u5F00\u6B64\u6587\u4EF6\uFF0C\u6216\u5148\u5C06\u5B83\u8F6C\u6362\u4E3A GLB\u3001GLTF\u3001OBJ\u3001STL \u6216 PLY\u3002","modelLoad.errorTitle":"\u65E0\u6CD5\u663E\u793A\u8FD9\u4E2A\u6A21\u578B","modelLoad.errorMessage":"\u52A0\u8F7D\u5931\u8D25\uFF1A{reason}","modelLoad.errorHint":"\u8BF7\u68C0\u67E5\u6587\u4EF6\u683C\u5F0F\uFF0C\u6216\u6253\u5F00\u5F00\u53D1\u8005\u63A7\u5236\u53F0\u67E5\u770B\u8BE6\u7EC6\u4FE1\u606F\u3002","headingPin.showSingle":"\u663E\u793A\u5173\u8054\u6807\u6CE8","headingPin.showMultiple":"\u663E\u793A\u5173\u8054\u6807\u6CE8","headingPin.linkedTo":"\u5173\u8054\u5230\uFF1A{models}","helper.resetViewLabel":"\u91CD\u7F6E\u89C6\u56FE","helper.resetViewDone":"\u5DF2\u91CD\u7F6E","helper.copyModelInfoLabel":"\u590D\u5236\u6A21\u578B\u4FE1\u606F\u4E3A Markdown","helper.copySelectedPartInfoLabel":"\u590D\u5236\u9009\u4E2D\u90E8\u4EF6\u4FE1\u606F","helper.noSelectedPart":"\u8BF7\u5148\u70B9\u51FB\u4E00\u4E2A\u90E8\u4EF6","helper.copied":"\u5DF2\u590D\u5236","helper.failed":"\u5931\u8D25","helper.toggleWireframeLabel":"\u5207\u6362\u7EBF\u6846\u663E\u793A","helper.wireframeOn":"\u7EBF\u6846","helper.wireframeOff":"\u5B9E\u4F53","helper.toggleAxesLabel":"\u5207\u6362\u65B9\u5411\u5750\u6807\u8F74","helper.axesOn":"\u5750\u6807\u8F74\u5DF2\u5F00\u542F","helper.axesOff":"\u5750\u6807\u8F74\u5DF2\u5173\u95ED","helper.toggleBoundingBoxLabel":"\u5207\u6362\u5305\u56F4\u76D2","helper.boundingBoxOn":"\u5305\u56F4\u76D2\u5DF2\u5F00\u542F","helper.boundingBoxOff":"\u5305\u56F4\u76D2\u5DF2\u5173\u95ED","helper.toggleFocusSelectionLabel":"\u805A\u7126\u9009\u4E2D\u90E8\u4EF6","helper.focusSelectionOn":"\u805A\u7126\u6A21\u5F0F\u5DF2\u5F00\u542F","helper.focusSelectionOff":"\u805A\u7126\u6A21\u5F0F\u5DF2\u5173\u95ED","helper.toggleDisassemblyLabel":"\u5207\u6362\u5206\u89E3\u6A21\u5F0F","helper.disassemblyOn":"\u5206\u89E3\u6A21\u5F0F\u5DF2\u5F00\u542F","helper.disassemblyOff":"\u5206\u89E3\u6A21\u5F0F\u5DF2\u5173\u95ED","helper.resetPartsLabel":"\u91CD\u7F6E\u5206\u89E3\u90E8\u4EF6","helper.partsReset":"\u90E8\u4EF6\u5DF2\u91CD\u7F6E","helper.changeResolutionLabel":"\u5207\u6362\u5206\u8FA8\u7387","helper.resolutionValue":"\u5206\u8FA8\u7387\uFF1A{value}","helper.toggleAnimationLabel":"\u64AD\u653E\u6216\u6682\u505C\u52A8\u753B","helper.playing":"\u64AD\u653E\u4E2D","helper.paused":"\u5DF2\u6682\u505C","helper.toggleMeasurementLabel":"\u5207\u6362\u8DDD\u79BB\u6D4B\u91CF","helper.measurementOn":"\u6D4B\u91CF\u5DF2\u5F00\u542F","helper.measurementOff":"\u6D4B\u91CF\u5DF2\u5173\u95ED","helper.clearMeasurementsLabel":"\u6E05\u9664\u6D4B\u91CF","helper.measurementsCleared":"\u5DF2\u6E05\u9664","helper.calibrateLabel":"\u6821\u51C6\u6D4B\u91CF\u6BD4\u4F8B","helper.calibrateTitle":"\u6D4B\u91CF\u6821\u51C6","helper.calibrateCurrent":"\u5F53\u524D\u5C3A\u5BF8\uFF1A","helper.calibrateReal":"\u771F\u5B9E\u5C3A\u5BF8\uFF1A","helper.calibrateLock":"\u9501\u5B9A\u6BD4\u4F8B","helper.calibrateApply":"\u5E94\u7528","helper.calibrateReset":"\u91CD\u7F6E","helper.calibrated":"\u6BD4\u4F8B\u5DF2\u5E94\u7528","helper.calibrateResetDone":"\u6BD4\u4F8B\u5DF2\u91CD\u7F6E","helper.calibrateOpen":"\u6821\u51C6\u9762\u677F\u5DF2\u6253\u5F00","helper.calibrateClose":"\u6821\u51C6\u9762\u677F\u5DF2\u5173\u95ED","helper.removePreviewLabel":"\u79FB\u9664\u9884\u89C8","helper.copySnapshotLabel":"\u590D\u5236\u5FEB\u7167","helper.saveSnapshotLabel":"\u4FDD\u5B58\u5FEB\u7167\u5230\u4ED3\u5E93","helper.saved":"\u5DF2\u4FDD\u5B58","helper.downloadSnapshotLabel":"\u4E0B\u8F7D\u5FEB\u7167","helper.downloaded":"\u5DF2\u4E0B\u8F7D","helper.toggleAnnotationLabel":"\u5207\u6362\u6807\u6CE8\u6A21\u5F0F","helper.toggleAnnotationsVisibilityLabel":"\u663E\u793A\u6216\u9690\u85CF\u6807\u6CE8","helper.annotateOn":"\u6807\u6CE8\u6A21\u5F0F\u5DF2\u5F00\u542F","helper.annotateOff":"\u6807\u6CE8\u6A21\u5F0F\u5DF2\u5173\u95ED","helper.annotationsVisible":"\u6807\u6CE8\u5DF2\u663E\u793A","helper.annotationsHidden":"\u6807\u6CE8\u5DF2\u9690\u85CF","helper.enableInteractionLabel":"\u542F\u7528\u89E6\u63A7\u4EA4\u4E92","helper.disableInteractionLabel":"\u5207\u56DE\u6EDA\u52A8\u6A21\u5F0F","helper.interactionOn":"\u6A21\u578B\u4EA4\u4E92\u5DF2\u5F00\u542F","helper.interactionOff":"\u6EDA\u52A8\u6A21\u5F0F\u5DF2\u5F00\u542F","helper.showMoreActionsLabel":"\u663E\u793A\u66F4\u591A\u64CD\u4F5C","helper.hideMoreActionsLabel":"\u6536\u8D77\u989D\u5916\u64CD\u4F5C","helper.moreActionsShown":"\u5DF2\u5C55\u5F00\u66F4\u591A\u64CD\u4F5C","helper.moreActionsHidden":"\u5DF2\u6536\u8D77\u989D\u5916\u64CD\u4F5C","helper.interactAction":"\u4EA4\u4E92","helper.scrollAction":"\u6EDA\u52A8","workbench.emptyTitle":"\u6682\u65E0\u6A21\u578B","workbench.emptyText":"\u4F7F\u7528\u201C\u5BFC\u5165 3D \u6A21\u578B\u201D\u547D\u4EE4\u52A0\u8F7D GLB\u3001GLTF\u3001STL\u3001OBJ \u6216 PLY \u6587\u4EF6\u3002","workbench.modelTitle":"3D \u6A21\u578B","workbench.studioTitle":"AI \u6A21\u578B\u5DE5\u4F5C\u53F0","workbench.studioTagline":"\u68C0\u67E5\u3001\u6807\u6CE8\uFF0C\u5E76\u628A 3D \u8D44\u4EA7\u6574\u7406\u6210\u53CC\u94FE\u7B14\u8BB0\u3002","workbench.navLabel":"\u5DE5\u4F5C\u53F0\u5206\u533A","workbench.navGallery":"\u753B\u5ECA","workbench.navLibrary":"\u8D44\u6599\u5E93","workbench.navNotebooks":"\u7B14\u8BB0\u672C","workbench.navSettings":"\u8BBE\u7F6E","workbench.sourcesTitle":"\u6A21\u578B\u6765\u6E90","workbench.layersTitle":"\u5BA1\u9605\u5C42","workbench.viewModeTitle":"\u89C6\u56FE\u6A21\u5F0F","workbench.modeMesh":"\u7F51\u683C\u89C6\u56FE","workbench.modeFocus":"\u805A\u7126\u9009\u533A","workbench.modeMeshShort":"\u7F51\u683C","workbench.modeFocusShort":"\u805A\u7126","workbench.previewViewsTitle":"\u9884\u89C8\u89C6\u56FE","workbench.connectionsTitle":"\u77E5\u8BC6\u8FDE\u63A5","workbench.currentModelLabel":"\u5F53\u524D\u6A21\u578B","workbench.noReportYet":"\u8FD8\u6CA1\u6709\u62A5\u544A\u7B14\u8BB0","workbench.noIndexYet":"\u8FD8\u6CA1\u6709\u77E5\u8BC6\u7D22\u5F15\u3002\u8BF7\u5148\u751F\u6210\u77E5\u8BC6\u7B14\u8BB0\u3002","workbench.noModelLoaded":"\u5C1A\u672A\u52A0\u8F7D\u6A21\u578B","workbench.disassemblyTitle":"\u5206\u89E3","workbench.explodeLabel":"\u7206\u70B8","workbench.summaryTitle":"\u6458\u8981","workbench.meshesLabel":"\u7F51\u683C","workbench.splatsLabel":"\u70B9\u4E91","workbench.trianglesLabel":"\u4E09\u89D2\u5F62","workbench.verticesLabel":"\u9876\u70B9","workbench.materialsLabel":"\u6750\u8D28","workbench.boundingSizeLabel":"\u5305\u56F4\u76D2","workbench.centerLabel":"\u4E2D\u5FC3","workbench.selectedPartTitle":"\u5F53\u524D\u9009\u4E2D\u90E8\u4EF6","workbench.partMeshLabel":"\u7F51\u683C","workbench.noSelectedPart":"\u70B9\u51FB\u6A21\u578B\u4E2D\u7684\u90E8\u4EF6\u540E\u4F1A\u663E\u793A\u8BE6\u7EC6\u4FE1\u606F\u3002","workbench.tagsTitle":"\u6807\u7B7E","workbench.noTagsYet":"\u8FD8\u6CA1\u6709\u6807\u7B7E","workbench.addTagPlaceholder":"\u6DFB\u52A0\u6807\u7B7E...","workbench.addTagAction":"\u6DFB\u52A0","workbench.annotationsTitle":"\u6807\u6CE8","workbench.exitAnnotate":"\u9000\u51FA\u6807\u6CE8","workbench.annotate":"\u6807\u6CE8","workbench.annotateHintActive":"\u70B9\u51FB\u6A21\u578B\u6DFB\u52A0\u6807\u7B7E \xB7 \u6309 Esc \u9000\u51FA","workbench.annotateHintActiveMobile":"\u70B9\u6309\u6A21\u578B\u6DFB\u52A0\u6807\u7B7E\u3002\u9700\u8981\u7EE7\u7EED\u9605\u8BFB\u65F6\u5207\u56DE\u201C\u6EDA\u52A8\u201D\u3002","workbench.pinCount":"{count} \u4E2A\u6807\u6CE8","workbench.editAction":"\u7F16\u8F91","workbench.deleteAction":"\u5220\u9664","workbench.resetViewAction":"\u91CD\u7F6E\u89C6\u56FE","workbench.insertInfoAction":"\u63D2\u5165\u4FE1\u606F","workbench.insertGalleryAction":"\u63D2\u5165 Gallery","workbench.insertCompareAction":"\u63D2\u5165\u5BF9\u6BD4","workbench.playAction":"\u64AD\u653E","workbench.pauseAction":"\u6682\u505C","workbench.saveProfileAction":"\u4FDD\u5B58\u914D\u7F6E","workbench.generateNoteAction":"\u751F\u6210\u7B14\u8BB0","workbench.openNoteAction":"\u6253\u5F00\u7B14\u8BB0","workbench.openIndexAction":"\u6253\u5F00\u7D22\u5F15","workbench.recordTitle":"\u6807\u672C\u5361","workbench.recordSubtitle":"\u5F53\u524D\u8D44\u4EA7\u6863\u6848","workbench.notesTitle":"\u5206\u6790\u672D\u8BB0","workbench.whereTitle":"\u5173\u8054\u4F4D\u7F6E","workbench.noteReady":"\u5173\u8054\u7B14\u8BB0\u5DF2\u5C31\u7EEA","workbench.indexReady":"\u77E5\u8BC6\u7D22\u5F15\u5DF2\u5C31\u7EEA","workbench.notePending":"\u5173\u8054\u7B14\u8BB0\u5F85\u751F\u6210","workbench.analysisLabel":"\u5206\u6790","workbench.settingsUnavailable":"\u8BF7\u4ECE Obsidian \u8BBE\u7F6E\u4E2D\u6253\u5F00\u672C\u63D2\u4EF6\u6765\u8C03\u6574\u5DE5\u4F5C\u53F0\u9009\u9879\u3002","workbench.profileSaved":"\u914D\u7F6E\u5DF2\u4FDD\u5B58","workbench.viewReset":"\u89C6\u56FE\u5DF2\u91CD\u7F6E","workbench.infoInserted":"\u6A21\u578B\u4FE1\u606F\u5DF2\u63D2\u5165","workbench.infoCopied":"\u6A21\u578B\u4FE1\u606F\u5DF2\u590D\u5236","workbench.templateInserted":"\u6A21\u677F\u5DF2\u63D2\u5165","workbench.templateCopied":"\u6A21\u677F\u5DF2\u590D\u5236","workbench.mobileHint":"\u79FB\u52A8\u7AEF\u63D0\u793A\uFF1A\u9700\u8981\u64CD\u4F5C\u6A21\u578B\u65F6\u70B9\u201C\u4EA4\u4E92\u201D\uFF0C\u7EE7\u7EED\u9605\u8BFB\u7B14\u8BB0\u65F6\u5207\u56DE\u201C\u6EDA\u52A8\u201D\u3002","workbench.mobileHintInteractive":"\u5F53\u524D\u4E3A\u4EA4\u4E92\u6A21\u5F0F\u3002\u9700\u8981\u7EE7\u7EED\u6EDA\u52A8\u7B14\u8BB0\u65F6\uFF0C\u8BF7\u5207\u56DE\u201C\u6EDA\u52A8\u201D\u3002","directView.mobileHint":"\u79FB\u52A8\u7AEF\u63D0\u793A\uFF1A\u4F7F\u7528\u4E0B\u65B9\u5DE5\u5177\u680F\u91CC\u7684\u201C\u4EA4\u4E92\u201D\u6309\u94AE\uFF0C\u5728\u6A21\u578B\u64CD\u4F5C\u548C\u7B14\u8BB0\u6EDA\u52A8\u4E4B\u95F4\u5207\u6362\u3002","directWorkbench.modelLoadInterrupted":"\u6A21\u578B\u52A0\u8F7D\u88AB\u65B0\u8BF7\u6C42\u4E2D\u65AD\u3002","directWorkbench.backendLabel":"\u540E\u7AEF","directWorkbench.routeLabel":"\u8DEF\u7531","directWorkbench.performanceLabel":"\u6027\u80FD","directWorkbench.partCandidatesLabel":"\u5019\u9009\u96F6\u4EF6","directWorkbench.knowledgeTitle":"\u77E5\u8BC6","directWorkbench.registeredTitle":"\u5DF2\u6CE8\u518C\u96F6\u4EF6\u5339\u914D","directWorkbench.registeredLoading":"\u68C0\u67E5\u4E2D...","directWorkbench.registeredCount":"{count} \u4E2A\u5339\u914D","directWorkbench.registeredEmpty":"\u6682\u65E0\u8DE8\u6A21\u578B\u96F6\u4EF6\u5339\u914D","directWorkbench.registeredUnavailable":"\u6682\u65E0\u96F6\u4EF6\u8BC1\u636E","directWorkbench.registeredOpen":"\u6253\u5F00","directWorkbench.registeredOpenNote":"\u7B14\u8BB0","directWorkbench.registeredOpenModel":"\u6A21\u578B","directWorkbench.registeredSourceModel":"\u6765\u81EA {model}","directWorkbench.registeredTargetPartNote":"\u6253\u5F00\u5339\u914D\u96F6\u4EF6\u7B14\u8BB0","directWorkbench.registeredTargetSourceModel":"\u6253\u5F00\u6765\u6E90\u6A21\u578B","directWorkbench.registeredTargetUnavailable":"\u6682\u65E0\u53EF\u6253\u5F00\u76EE\u6807","workbench.fileNotFound":"\u672A\u627E\u5230\u6587\u4EF6\uFF1A{path}","annotation.selectColor":"\u9009\u62E9\u989C\u8272 {color}","annotation.sectionEmpty":"\u8BE5\u6BB5\u5185\u5BB9\u4E3A\u7A7A\u3002","modal.selectModel":"\u9009\u62E9\u4E00\u4E2A 3D \u6A21\u578B...","main.commandImportModel":"\u5BFC\u5165 3D \u6A21\u578B","main.commandGenerateNote":"\u751F\u6210\u77E5\u8BC6\u7B14\u8BB0","main.commandOpenKnowledgeIndex":"\u6253\u5F00\u77E5\u8BC6\u7D22\u5F15","main.commandClearConversionCache":"\u6E05\u9664\u8F6C\u6362\u7F13\u5B58","main.commandCheckConverters":"\u68C0\u67E5\u8F6C\u6362\u5668","main.commandCopyDiagnostics":"\u590D\u5236\u8BCA\u65AD\u62A5\u544A","main.converterDiagnosticsMobileUnavailable":"\u8F6C\u6362\u5668\u8BCA\u65AD\u4EC5\u652F\u6301\u684C\u9762\u7AEF\u3002\u5728 iOS\u3001iPadOS \u548C Android \u4E0A\uFF0C\u76F4\u8BFB\u683C\u5F0F\u4ECD\u53EF\u52A0\u8F7D\u3002","main.diagnosticsCopied":"AI Model Workbench \u8BCA\u65AD\u62A5\u544A\u5DF2\u590D\u5236\u5230\u526A\u8D34\u677F\u3002","main.diagnosticsCopyFailed":"\u65E0\u6CD5\u590D\u5236\u8BCA\u65AD\u62A5\u544A\uFF0C\u5DF2\u6539\u4E3A\u521B\u5EFA\u4E00\u4EFD\u8131\u654F\u8BCA\u65AD\u7B14\u8BB0\u3002","codeBlock.noModelPathOrConfig":"\u672A\u6307\u5B9A\u6A21\u578B\u8DEF\u5F84\u6216\u914D\u7F6E\u3002","codeBlock.jsonParseError":"JSON \u89E3\u6790\u9519\u8BEF\uFF1A{error}","codeBlock.jsonParseLine":"\uFF08\u7B2C {line} \u884C\uFF09","codeBlock.noModelsInConfig":"\u914D\u7F6E\u4E2D\u672A\u6307\u5B9A\u6A21\u578B\u3002","codeBlock.unsupportedFormat":"\u4E0D\u652F\u6301\u7684\u683C\u5F0F\uFF1A{ext}\u3002\u652F\u6301\uFF1A{formats}","codeBlock.splatDisabled":"\u5F53\u524D\u6253\u5305\u7248\u672C\u6682\u672A\u542F\u7528 SPLAT \u9884\u89C8\u3002\u540E\u7EED\u4F1A\u4F18\u5148\u6062\u590D\u672C\u5730-only .splat\uFF1B.spz/.sog \u9700\u8981\u672C\u5730\u6253\u5305\u89E3\u7801\u5668\u540E\u518D\u8BC4\u4F30\u3002","codeBlock.noConfigSpecified":"\u672A\u6307\u5B9A\u914D\u7F6E\u3002","codeBlock.noModelsSpecified":"\u672A\u6307\u5B9A\u6A21\u578B\u3002","codeBlock.mobileHint":"\u79FB\u52A8\u7AEF\u63D0\u793A\uFF1A\u9700\u8981\u64CD\u4F5C\u6A21\u578B\u65F6\u70B9\u201C\u4EA4\u4E92\u201D\uFF0C\u7EE7\u7EED\u9605\u8BFB\u7B14\u8BB0\u65F6\u5207\u56DE\u201C\u6EDA\u52A8\u201D\u3002","codeBlock.renderingGrid":"\u6B63\u5728\u6E32\u67D3\u7F51\u683C...","codeBlock.composeRequiresSections":"\u201Ccompose\u201D \u9884\u8BBE\u9700\u8981\u63D0\u4F9B \u201Csections\u201D \u6570\u7EC4\u3002","codeBlock.composeNoValidSections":"Compose\uFF1A\u6CA1\u6709\u6709\u6548\u7684\u5206\u6BB5\u3002","codeBlock.unknownPreset":"\u672A\u77E5\u9884\u8BBE\uFF1A\u201C{preset}\u201D\u3002\u53EF\u7528\uFF1Acompare\u3001showcase\u3001explode\u3001timeline\u3001compose","codeBlock.presetRequiresModels":"\u9884\u8BBE \u201C{preset}\u201D \u9700\u8981 {min}-{max} \u4E2A\u6A21\u578B\uFF0C\u5F53\u524D\u4E3A {count} \u4E2A\u3002","codeBlock.gridFailed":"\u7F51\u683C\u6E32\u67D3\u5931\u8D25\uFF1A{reason}","livePreview.mobileHint":"\u79FB\u52A8\u7AEF\u63D0\u793A\uFF1A\u9700\u8981\u62D6\u52A8\u6A21\u578B\u65F6\u5207\u5230\u201C\u4EA4\u4E92\u201D\uFF0C\u7EE7\u7EED\u9605\u8BFB\u65F6\u5207\u56DE\u201C\u6EDA\u52A8\u201D\u3002","loading.default":"\u52A0\u8F7D\u4E2D...","loading.preparingModel":"\u6B63\u5728\u51C6\u5907\u6A21\u578B...","loading.loadingModel":"\u6B63\u5728\u52A0\u8F7D\u6A21\u578B..."}});function Rp(n){KN=n;for(let e of Bb)e()}function J(n){var e,t,i;return(i=(t=(e=Wq[KN])==null?void 0:e[n])!=null?t:Fb[n])!=null?i:n}function jN(n){return Bb.add(n),()=>{Bb.delete(n)}}function Hq(n,e){return n.replace(/\{(\w+)\}/g,(t,i)=>{var r;return(r=e[i])!=null?r:""})}function ur(n,e){return Hq(J(n),e)}var Wq,KN,Bb,ia=C(()=>{"use strict";zN();YN();Wq={en:Fb,"zh-CN":XN},KN="en",Bb=new Set});function zq(){if("require"in activeWindow)return activeWindow.require}function uv(){if("process"in activeWindow)return activeWindow.process}function bp(n){let e=zq();if(!e)return null;try{return e(n)}catch(t){return null}}function os(n,e){if(n===null)throw new Error(`${e} is not available in this environment (mobile or web).`);return n}function ls(n,e){return os(Pd,"node:fs/promises").access(n,e)}function ra(n){return os(Pd,"node:fs/promises").readFile(n)}function Dd(n,e,t){return os(Pd,"node:fs/promises").writeFile(n,e,{encoding:t})}function Ld(n,e){return os(Pd,"node:fs/promises").mkdir(n,e)}function Od(n,e){return os(Pd,"node:fs/promises").rm(n,e)}function $N(n){return os(Pd,"node:fs/promises").stat(n)}function zi(...n){return os(vl,"node:path").join(...n)}function Mo(n){return os(vl,"node:path").dirname(n)}function Co(n,e){return os(vl,"node:path").basename(n,e)}function na(n){return os(vl,"node:path").extname(n)}function Ub(n){return os(vl,"node:path").normalize(n)}function Xn(n){return os(vl,"node:path").isAbsolute(n)}function sa(n,e,t,i){os(Xq,"node:child_process").execFile(n,e,t,i)}function Nd(){return os(Yq,"node:os").tmpdir()}var Pd,yd,vl,Xq,Yq,qN,cs,ZN,JN,QN,ew,or=C(()=>{"use strict";Pd=bp("node:fs/promises"),yd=bp("node:fs"),vl=bp("node:path"),Xq=bp("node:child_process"),Yq=bp("node:os");cs=(qN=yd==null?void 0:yd.constants.F_OK)!=null?qN:0,JN=(ZN=yd==null?void 0:yd.constants.X_OK)!=null?ZN:0;ew=(QN=vl==null?void 0:vl.delimiter)!=null?QN:":"});function Vb(n){return n.replace(/\\/g,"/")}function mv(n){let e=Vb(n),t=[];for(let i of e.split("/"))if(!(!i||i===".")){if(i===".."){t.pop();continue}t.push(i)}return t.join("/")}function tw(n){try{return decodeURIComponent(n)}catch(e){return n}}function Ns(n,e){var r;let t=tw((r=e.split(/[?#]/,1)[0])!=null?r:e),i=mv(t);return n?mv(`${n}/${i}`):i}function Ip(n){let e=Vb(n).replace(/\/+$/,""),t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function aa(n){let e=Vb(n).replace(/\/+$/,""),t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}function jr(n){return aa(n).replace(/\.[^.]+$/,"")}async function Kq(n,e){let t=mv(e);if(!t)return null;let i=t.split("/"),r="",s=n.vault.getRoot().children;for(let a of i){let o=s.find(c=>c.name===a),l=o!=null?o:s.find(c=>c.name.toLowerCase()===a.toLowerCase());if(!l)return null;if(r=r?`${r}/${l.name}`:l.name,l instanceof wd.TFile)return r;if(!(l instanceof wd.TFolder))return null;s=l.children}return null}function jq(n){return Uint8Array.from(n).buffer}function qq(n){let e=n.vault.adapter;return typeof e.getBasePath=="function"?e.getBasePath():typeof e.basePath=="string"&&e.basePath.length>0?e.basePath:null}function Fd(n,e){var r,s;let t=n.vault.getAbstractFileByPath(e);if(t)return t.path;let i=(s=(r=n.metadataCache)==null?void 0:r.getFirstLinkpathDest)==null?void 0:s.call(r,e,"");return i?i.path:null}function eh(n,e){if(Xn(e))return Ub(e);let t=qq(n);return t?Ub(zi(t,e)):null}async function Ua(n,e){if(Xn(e)){let r=await ra(e);return jq(r)}let t=mv(tw(e)),i=n.vault.getAbstractFileByPath(t);if(!(i instanceof wd.TFile)){let r=await Kq(n,t);if(r){let s=n.vault.getAbstractFileByPath(r);if(s instanceof wd.TFile)return n.vault.readBinary(s)}throw new Error(`File not found: ${t}`)}return n.vault.readBinary(i)}var wd,oa=C(()=>{"use strict";wd=require("obsidian");or();or()});function Ht(n){return{x:n.x,y:n.y,z:n.z}}function qr(n){return{x:n.x,y:n.y,z:n.z}}function Bd(n,e){return{x:n.x-e.x,y:n.y-e.y,z:n.z-e.z}}function Mp(n,e){return{x:n.x*e,y:n.y*e,z:n.z*e}}function nw(n,e){let t=Bd(n,e);return Math.hypot(t.x,t.y,t.z)}function Gb(n){let e=Math.hypot(n.x,n.y,n.z);return e<=Number.EPSILON?null:Mp(n,1/e)}function th(n,e){return{x:n.x+e.x,y:n.y+e.y,z:n.z+e.z}}function iw(n,e){return n.x*e.x+n.y*e.y+n.z*e.z}function sw(n,e,t){return{x:e==="x"?n.x+t:n.x,y:e==="y"?n.y+t:n.y,z:e==="z"?n.z+t:n.z}}function aw(n){return Math.max(n*.01,.01)}function Oc(n,e,t=aw(e)){return n{"use strict"});function iZ(){return`pin-${Date.now()}-${$q++}`}function fw(n){return qr(n)}function rZ(n,e,t){return n.lefte.left-t&&n.tope.top-t}var Cp,Vd,$q,kb,Jq,eZ,ow,lw,tZ,cw,Gd,wc,Ev=C(()=>{"use strict";Cp=require("obsidian");ia();oa();ws();Vd=["#4a9eff","#ff6b6b","#51cf66","#ffd43b","#845ef7","#ff922b","#22b8cf","#f06595","#94d82d","#ffa8a8"],$q=1,kb=4,Jq=2,eZ=6,ow=6,lw=72,tZ=80,cw=200;Gd=class Gd{constructor(e,t,i,r,s,a,o,l={}){this.provider=e;this.hostEl=t;this.mode=i;this.onChange=s;this.noteReader=a;this.headingSearch=o;this.pinEls=new Map;this.observer=null;this.resizeObs=null;this.annotations=[];this.editorEl=null;this.disposeCallbacks=[];this.frameCount=0;this.lastCamState="";this.idleFrames=0;this.cameraIdle=!1;this.movingOcclusionCursor=0;this.hoverPopover=null;this.hoverTimeout=null;this.hoverCloseTimeout=null;this.hoverRequestId=0;this._highlightHandler=null;this._pulseTimeout=null;this._headingDropdown=null;this._headingDebounce=null;this._selectedHeading=null;this.previewRenderRoot=new Cp.Component;this.previewRenderChildren=new WeakMap;var c,f;this.previewApp=l.app,this.previewMode=(c=l.previewMode)!=null?c:"plain-text",this.displayMode=(f=l.displayMode)!=null?f:"surface",this.previewRenderRoot.load(),this.overlay=this.hostEl.createDiv({cls:"ai3d-annotation-overlay"}),this.setAnnotations(r),this._highlightHandler=h=>{let d=h.detail,u=d==null?void 0:d.pinId;u&&this.pulsePin(u)},activeDocument.addEventListener("ai3d-pin-highlight",this._highlightHandler),this.disposeCallbacks.push(()=>activeDocument.removeEventListener("ai3d-pin-highlight",this._highlightHandler)),this.disposeCallbacks.push(()=>this.previewRenderRoot.unload()),this.startProjectionLoop()}setAnnotations(e){for(let[,t]of this.pinEls)this.removePinElement(t.el);this.pinEls.clear(),this.annotations=[...e];for(let t of e)this.createPinElement(t);this.updateProjections()}addPin(e,t,i){var s;if(this.annotations.length>=cw)return console.warn(`[AI3D] Pin limit (${cw}) reached; ignoring new pin.`),this.annotations[this.annotations.length-1];let r={id:iZ(),position:[e.x,e.y,e.z],label:t,color:i!=null?i:Vd[this.annotations.length%Vd.length],createdAt:new Date().toISOString()};return this.annotations.push(r),this.createPinElement(r),this.updateProjections(),(s=this.onChange)==null||s.call(this,this.annotations),r}removePin(e){var i;let t=this.pinEls.get(e);t&&(this.removePinElement(t.el),this.pinEls.delete(e)),this.annotations=this.annotations.filter(r=>r.id!==e),(i=this.onChange)==null||i.call(this,this.annotations)}updatePin(e,t){var s;let i=this.annotations.find(a=>a.id===e);if(!i)return;Object.assign(i,t);let r=this.pinEls.get(e);if(r){t.position&&(r.worldPos={x:t.position[0],y:t.position[1],z:t.position[2]});let a=r.el.querySelector(".ai3d-pin-label");a&&t.label!==void 0&&(a.textContent=t.label);let o=r.el.querySelector(".ai3d-pin-dot");o&&t.color!==void 0&&o.style.setProperty("--pin-color",t.color),(t.notePath!==void 0||t.headingRef!==void 0||t.label!==void 0)&&this.renderPinDisplay(r.el,i)}this.updateProjections(),(s=this.onChange)==null||s.call(this,this.annotations)}showEditor(e,t,i){this.showEditorInternal(e,t,i)}editPin(e){let t=this.annotations.find(o=>o.id===e);if(!t)return;let i=this.pinEls.get(e);if(!i)return;let r=i.el.getBoundingClientRect(),s=r.left+r.width/2,a=r.top;this.showEditorInternal(s,a,fw(i.worldPos),t)}getPinPosition(e){let t=this.pinEls.get(e);return t?fw(t.worldPos):null}getAnnotations(){return this.annotations}showEditorInternal(e,t,i,r){var O,V;this.hideEditor(),this._selectedHeading=null;let s=this.overlay.createDiv({cls:"ai3d-annotation-editor"}),a=s.createDiv({cls:"ai3d-editor-input-wrap"}),o=a.createEl("input",{cls:"ai3d-annotation-editor-input"});o.type="text",o.placeholder=this.headingSearch?"Label or search heading...":"Label...",r&&(o.value=r.label);let l=a.createSpan({cls:"ai3d-editor-binding-tag is-hidden"}),c=l.createEl("button",{cls:"ai3d-editor-binding-clear"});c.textContent="\xD7",c.addEventListener("click",N=>{N.stopPropagation(),this._selectedHeading=null,l.classList.add("is-hidden"),f.classList.add("is-hidden"),f.textContent="",o.value="",o.focus()});let f=s.createDiv({cls:"ai3d-editor-content-preview is-hidden"}),h=s.createDiv({cls:"ai3d-heading-dropdown is-hidden"});this._headingDropdown=h;let d=-1,u=[],m=N=>{let F=h.querySelectorAll(".ai3d-heading-dropdown-item");F.forEach(U=>U.classList.remove("active")),d=N,N>=0&&N{var G;this._selectedHeading=N,o.value=N.heading;let F=jr(N.notePath);(G=l.querySelector(".ai3d-editor-binding-text"))==null||G.remove();let U=l.createSpan({cls:"ai3d-editor-binding-text"});U.textContent=`\u{1F4C4} ${F}`,l.classList.remove("is-hidden"),_(),o.focus(),this.loadContentPreview(f,N.notePath,N.heading)},_=()=>{h.classList.add("is-hidden"),h.replaceChildren(),d=-1},g=N=>{if(h.replaceChildren(),d=-1,u=N,N.length===0){h.classList.add("is-hidden");return}for(let F=0;F{Z.preventDefault(),Z.stopPropagation(),p(U)}),G.addEventListener("mouseenter",()=>m(F))}h.classList.remove("is-hidden")};o.addEventListener("input",()=>{if(!this.headingSearch)return;this._headingDebounce&&window.clearTimeout(this._headingDebounce);let N=o.value.trim();if(N.length<1){_();return}this._headingDebounce=window.setTimeout(()=>{let F=this.headingSearch(N);g(F)},150)}),o.addEventListener("keydown",N=>{if(h.classList.contains("is-hidden")){N.key==="Enter"?(N.preventDefault(),R.click()):N.key==="Escape"&&(N.preventDefault(),this.hideEditor());return}let F=h.querySelectorAll(".ai3d-heading-dropdown-item");N.key==="ArrowDown"?(N.preventDefault(),m(Math.min(d+1,F.length-1))):N.key==="ArrowUp"?(N.preventDefault(),m(Math.max(d-1,0))):N.key==="Enter"?(N.preventDefault(),d>=0&&d{window.setTimeout(_,150)});let v=s.createDiv({cls:"ai3d-annotation-editor-colors"}),x=(O=r==null?void 0:r.color)==null?void 0:O.trim(),A=x||Vd[0],S=x&&!Vd.includes(x)?[x,...Vd]:Vd;for(let N of S){let F=v.createEl("button",{cls:"ai3d-pin-color-swatch"});F.type="button",F.title=N,F.setAttribute("aria-label",ur("annotation.selectColor",{color:N})),F.style.setProperty("--swatch-color",N),F.style.backgroundColor=N,N===A&&F.classList.add("is-selected"),F.addEventListener("click",U=>{U.stopPropagation(),A=N,v.querySelectorAll(".ai3d-pin-color-swatch").forEach(G=>G.classList.remove("is-selected")),F.classList.add("is-selected")})}let E=s.createDiv({cls:"ai3d-annotation-editor-actions"});if(r){let N=E.createEl("button",{cls:"ai3d-annotation-editor-btn ai3d-annotation-editor-delete"});N.textContent="Delete",N.addEventListener("click",F=>{F.stopPropagation(),this.removePin(r.id),this.hideEditor()})}let R=E.createEl("button",{cls:"ai3d-annotation-editor-btn ai3d-annotation-editor-confirm"});R.textContent=r?"Save":"OK",R.addEventListener("click",N=>{N.stopPropagation();let F=o.value.trim()||"Pin",U=this._selectedHeading;if(r){let G={label:F,color:A};U&&(G.notePath=U.notePath,G.headingRef=U.heading,G.headingLevel=U.level),this.updatePin(r.id,G)}else{let G=this.addPin(i,F,A);U&&this.updatePin(G.id,{notePath:U.notePath,headingRef:U.heading,headingLevel:U.level})}this.hideEditor()});let I=E.createEl("button",{cls:"ai3d-annotation-editor-btn ai3d-annotation-editor-cancel"});I.textContent="Cancel",I.addEventListener("click",N=>{N.stopPropagation(),this.hideEditor()});let y=this.overlay.getBoundingClientRect(),M=e-y.left,D=t-y.top;if(s.style.setProperty("--editor-left",`${Math.max(0,Math.min(M,y.width-220))}px`),s.style.setProperty("--editor-top",`${Math.max(0,Math.min(D-10,y.height-160))}px`),this.editorEl=s,r!=null&&r.notePath&&(r!=null&&r.headingRef)){let N=jr(r.notePath),F=l.createSpan({cls:"ai3d-editor-binding-text"});F.textContent=`\u{1F4C4} ${N}`,l.classList.remove("is-hidden"),this._selectedHeading={notePath:r.notePath,heading:r.headingRef,level:(V=r.headingLevel)!=null?V:2},this.loadContentPreview(f,r.notePath,r.headingRef)}window.requestAnimationFrame(()=>o.focus()),s.addEventListener("pointerdown",N=>N.stopPropagation()),s.addEventListener("mousedown",N=>N.stopPropagation())}hideEditor(){if(this._headingDebounce&&(window.clearTimeout(this._headingDebounce),this._headingDebounce=null),this._headingDropdown=null,this._selectedHeading=null,this.editorEl){let e=this.editorEl.querySelector(".ai3d-editor-content-preview");e&&this.clearRenderedPreview(e),this.editorEl.remove(),this.editorEl=null}}async loadContentPreview(e,t,i){if(!this.noteReader)return;this.clearRenderedPreview(e),e.classList.add("is-hidden");let r=await this.noteReader(t,i);if(!r){e.textContent=J("annotation.sectionEmpty"),e.className="ai3d-editor-content-preview ai3d-editor-content-preview--empty",e.classList.remove("is-hidden");return}await this.renderPreviewContent(e,r,t,"editor")}async showHoverPopover(e,t,i){if(!this.noteReader||!i.notePath||!i.headingRef)return;this.hideHoverPopover();let r=await this.noteReader(i.notePath,i.headingRef);if(!r||e!==this.hoverRequestId||!t.isConnected||!this.hostEl.isConnected)return;let s=createDiv({cls:"ai3d-pin-popover"}),a=s.createDiv({cls:"ai3d-pin-popover-title"});a.textContent=i.headingRef;let o=s.createDiv({cls:"ai3d-pin-popover-body"}),l=t.getBoundingClientRect();s.style.setProperty("--popover-left",`${l.left+l.width/2}px`),s.style.setProperty("--popover-top",`${l.bottom+4}px`),s.addEventListener("mouseenter",()=>this.cancelHoverClose()),s.addEventListener("mouseleave",()=>this.scheduleHoverClose()),activeDocument.body.appendChild(s),this.hoverPopover=s,await this.renderPreviewContent(o,r,i.notePath,"popover"),(e!==this.hoverRequestId||!t.isConnected||!this.hostEl.isConnected)&&(this.clearRenderedPreview(o),this.hoverPopover===s&&(this.hoverPopover=null),s.remove())}hideHoverPopover(){if(this.hoverTimeout&&(window.clearTimeout(this.hoverTimeout),this.hoverTimeout=null),this.hoverCloseTimeout&&(window.clearTimeout(this.hoverCloseTimeout),this.hoverCloseTimeout=null),this.hoverPopover){let e=this.hoverPopover.querySelector(".ai3d-pin-popover-body");e&&this.clearRenderedPreview(e),this.hoverPopover.remove(),this.hoverPopover=null}}cancelHoverClose(){this.hoverCloseTimeout&&(window.clearTimeout(this.hoverCloseTimeout),this.hoverCloseTimeout=null)}scheduleHoverClose(){this.hoverTimeout&&(window.clearTimeout(this.hoverTimeout),this.hoverTimeout=null,this.hoverRequestId++),this.cancelHoverClose(),this.hoverCloseTimeout=window.setTimeout(()=>{this.hoverCloseTimeout=null,this.hoverRequestId++,this.hideHoverPopover()},180)}clearRenderedPreview(e){let t=this.previewRenderChildren.get(e);t&&(this.previewRenderRoot.removeChild(t),this.previewRenderChildren.delete(e)),e.replaceChildren()}removePinElement(e){e.querySelectorAll(".ai3d-rendered-preview").forEach(t=>{this.clearRenderedPreview(t)}),e.remove()}async renderPreviewContent(e,t,i,r){let s=this.previewMode==="markdown"&&!!this.previewApp,a=r==="editor",o=r==="pin-snippet";if(!s){let c=a?300:o?180:1/0,f=t.length>c?t.slice(0,c)+"...":t;e.textContent=f,e.className=a?"ai3d-editor-content-preview":o?"ai3d-pin-snippet ai3d-rendered-preview":"ai3d-pin-popover-body ai3d-rendered-preview",a&&e.classList.remove("is-hidden");return}e.className=a?"ai3d-editor-content-preview ai3d-editor-content-preview--markdown markdown-rendered":o?"ai3d-pin-snippet ai3d-pin-snippet--markdown ai3d-rendered-preview markdown-rendered":"ai3d-pin-popover-body ai3d-pin-popover-body--markdown ai3d-rendered-preview markdown-rendered",a&&e.classList.remove("is-hidden");let l=this.previewRenderRoot.addChild(new Cp.Component);this.previewRenderChildren.set(e,l);try{await Cp.MarkdownRenderer.render(this.previewApp,t,e,i,l)}catch(c){this.previewRenderRoot.removeChild(l),this.previewRenderChildren.delete(e);let f=a?300:o?180:1/0;e.textContent=t.length>f?t.slice(0,f)+"...":t,e.className=a?"ai3d-editor-content-preview":o?"ai3d-pin-snippet ai3d-rendered-preview":"ai3d-pin-popover-body ai3d-rendered-preview",a&&e.classList.remove("is-hidden"),console.warn("[AI3D] Annotation markdown preview fallback:",c)}}pulsePin(e){let t=this.pinEls.get(e);t&&(this._pulseTimeout&&(window.clearTimeout(this._pulseTimeout),this._pulseTimeout=null),t.el.classList.remove("ai3d-pin-pulse"),t.el.offsetWidth,t.el.classList.add("ai3d-pin-pulse"),this._pulseTimeout=window.setTimeout(()=>{t.el.classList.remove("ai3d-pin-pulse"),this._pulseTimeout=null},1200))}destroy(){var e,t,i;this.hoverRequestId++,this.hideHoverPopover(),this._pulseTimeout&&(window.clearTimeout(this._pulseTimeout),this._pulseTimeout=null),this._headingDebounce&&(window.clearTimeout(this._headingDebounce),this._headingDebounce=null),this._headingDropdown=null,this._selectedHeading=null,(e=this.observer)==null||e.remove(),this.observer=null,(t=this.resizeObs)==null||t.disconnect(),this.resizeObs=null;for(let r of this.disposeCallbacks)r();this.disposeCallbacks=[],this.overlay.remove(),this.pinEls.clear(),(i=this.editorEl)==null||i.remove(),this.editorEl=null}createPinElement(e){let t=this.overlay.createDiv({cls:"ai3d-annotation-pin"});if(t.dataset.pinId=e.id,this.renderPinDisplay(t,e),this.mode==="edit"){let i=t.createEl("button",{cls:"ai3d-pin-delete"});i.textContent="\xD7",i.addEventListener("click",r=>{r.stopPropagation(),this.removePin(e.id)}),t.addEventListener("click",r=>{r.target.closest(".ai3d-pin-delete")||(r.stopPropagation(),this.editPin(e.id))})}t.addEventListener("pointerdown",i=>i.stopPropagation()),t.addEventListener("wheel",i=>{i.preventDefault(),i.stopPropagation(),this.provider.canvas.dispatchEvent(new WheelEvent("wheel",{bubbles:!0,cancelable:!0,clientX:i.clientX,clientY:i.clientY,ctrlKey:i.ctrlKey,deltaMode:i.deltaMode,deltaX:i.deltaX,deltaY:i.deltaY,deltaZ:i.deltaZ,metaKey:i.metaKey,shiftKey:i.shiftKey}))},{passive:!1}),e.notePath&&e.headingRef&&this.noteReader&&(t.addEventListener("mouseenter",()=>{this.cancelHoverClose(),this.hoverTimeout&&window.clearTimeout(this.hoverTimeout);let i=++this.hoverRequestId;this.hoverTimeout=window.setTimeout(()=>{this.hoverTimeout=null,i===this.hoverRequestId&&this.showHoverPopover(i,t,e)},300)}),t.addEventListener("mouseleave",()=>{this.scheduleHoverClose()})),this.pinEls.set(e.id,{el:t,worldPos:{x:e.position[0],y:e.position[1],z:e.position[2]}})}renderPinDisplay(e,t){let i=e.querySelector(".ai3d-pin-delete");if(e.querySelectorAll(".ai3d-rendered-preview").forEach(s=>{this.clearRenderedPreview(s)}),e.replaceChildren(),e.className=`ai3d-annotation-pin ai3d-annotation-pin--${this.displayMode}`,e.createDiv({cls:"ai3d-pin-dot"}).style.setProperty("--pin-color",t.color),e.title=t.label,e.setAttribute("aria-label",t.label),this.displayMode!=="dot"){let s=e.createDiv({cls:"ai3d-pin-content"}),a=s.createSpan({cls:"ai3d-pin-label"});if(a.textContent=t.label,this.displayMode==="snippet"&&t.notePath&&t.headingRef&&this.noteReader){let o=s.createDiv({cls:"ai3d-pin-snippet ai3d-rendered-preview"});this.loadPinSnippet(o,t.notePath,t.headingRef)}}i&&e.appendChild(i)}async loadPinSnippet(e,t,i){if(!this.noteReader)return;let r=await this.noteReader(t,i);!r||!e.isConnected||await this.renderPreviewContent(e,r,t,"pin-snippet")}startProjectionLoop(){this.observer=this.provider.observeRender(()=>this.updateProjections()),this.resizeObs=new ResizeObserver(()=>this.updateProjections()),this.resizeObs.observe(this.provider.canvas)}updateProjections(){if(this.pinEls.size===0)return;let{canvas:e}=this.provider;if(!this.hostEl.isConnected||!e.isConnected||e.clientWidth===0||e.clientHeight===0)return;let t=this.provider.getCameraStateKey();t===this.lastCamState?this.idleFrames++:(this.idleFrames=0,this.cameraIdle=!1),this.lastCamState=t,this.idleFrames>=Gd.IDLE_THRESHOLD&&!this.cameraIdle&&(this.cameraIdle=!0),this.frameCount++;let i=this.cameraIdle?1:this.pinEls.size>=12?3:2;if(!this.cameraIdle&&this.frameCount%i!==0)return;let r=Array.from(this.pinEls.values()),s=this.cameraIdle?this.frameCount%eZ===0:this.frameCount%Jq===0,a=this.cameraIdle||r.length<=kb,o=a?0:this.movingOcclusionCursor%r.length,l=o+kb,c=Gd._scratchProjection,f=[];for(let h=0;h1||c.depth<0)this.hidePin(d.el);else{d.el.style.setProperty("--pin-left",`${c.screenX}px`),d.el.style.setProperty("--pin-top",`${c.screenY}px`),this.updatePinPriority(d.el,c.depth),f.push({el:d.el,screenX:c.screenX,screenY:c.screenY,depth:c.depth});let u=a||h>=o&&hr.length&&h0&&(this.movingOcclusionCursor=(o+kb)%r.length),this.applyLabelAvoidance(f)}updatePinPriority(e,t){let i=Math.max(0,Math.min(1,1-t)),r=this.cameraIdle?0:160,s=e.classList.contains("ai3d-pin-occluded")?80:0;e.style.zIndex=String(100+r+Math.round(i*120)-s)}applyLabelAvoidance(e){if(e.length===0)return;if(e.length>tZ){for(let a of e)a.el.style.removeProperty("--pin-offset-y");return}let i=e.filter(a=>!a.el.classList.contains("ai3d-pin-hidden")&&!a.el.classList.contains("ai3d-pin-occluded")).sort((a,o)=>a.depth-o.depth).map(a=>({pin:a,rect:a.el.getBoundingClientRect()})),r=[],s=[];for(let{pin:a,rect:o}of i){let l=0,c=o;for(let f of r){if(!rZ(c,f,ow))continue;let h=a.screenY>=f.top+f.height/2?1:-1;l=Math.max(-lw,Math.min(lw,l+h*(f.height+ow)));let d=c.width,u=c.height;c=new DOMRect(c.x,c.y+l,d,u)}r.push(c),s.push({el:a.el,offset:l})}for(let{el:a,offset:o}of s)a.setCssProps({"--pin-offset-y":o===0?"0px":`${o}px`})}hidePin(e){e.classList.remove("ai3d-pin-occluded"),e.classList.add("ai3d-pin-hidden")}showPin(e){e.classList.remove("ai3d-pin-hidden")}};Gd.IDLE_THRESHOLD=15,Gd._scratchProjection={screenX:0,screenY:0,depth:0};wc=Gd});function sZ(n){return n!=null?n:dw}function kd(n){var c;let e=n.ext.trim().toLowerCase(),t=(c=n.annotationMode)!=null?c:"none",i=!!n.allowEditModeOnThree,r=!!n.allowWorkbenchFeaturesOnThree,s=!!n.requireWorkbenchFeatures,a=sZ(n.rendererRollout);if(!(n.useThreeRenderer!==!1))return{backend:"babylon",ext:e,annotationMode:t,requireWorkbenchFeatures:s,rendererRollout:a,reason:"useThreeRenderer=false"};if(hw.has(e)&&(!s||r)){if(s&&!nZ.has(e))return{backend:"babylon",ext:e,annotationMode:t,requireWorkbenchFeatures:s,rendererRollout:a,reason:`workbench experimental Three supports GLB/GLTF only, ext=${e}`};if(t==="edit"&&a!=="three-direct-glb")return{backend:"babylon",ext:e,annotationMode:t,requireWorkbenchFeatures:s,rendererRollout:a,reason:`annotationMode=edit, rendererRollout=${a}`};if(a==="babylon-safe")return{backend:"babylon",ext:e,annotationMode:t,requireWorkbenchFeatures:s,rendererRollout:a,reason:`rendererRollout=${a}`};if(t==="edit"&&!i)return{backend:"babylon",ext:e,annotationMode:t,requireWorkbenchFeatures:s,rendererRollout:a,reason:"annotationMode=edit, allowEditModeOnThree=false"};let f=s?`${e} workbench preview`:t==="edit"?`${e} direct view edit preview`:t==="readonly"?`${e} preview with readonly annotations`:`simple ${e} preview`;return{backend:"three",ext:e,annotationMode:t,requireWorkbenchFeatures:s,rendererRollout:a,reason:f}}let l=[];return hw.has(e)||l.push(`ext=${e}`),t!=="none"&&l.push(`annotationMode=${t}`),t==="edit"&&!i&&l.push("allowEditModeOnThree=false"),s&&l.push("requireWorkbenchFeatures=true"),a!==dw&&l.push(`rendererRollout=${a}`),{backend:"babylon",ext:e,annotationMode:t,requireWorkbenchFeatures:s,rendererRollout:a,reason:l.join(", ")||"fallback route"}}function uw(){return{backend:"babylon",reason:"grid previews remain on the Babylon grid renderer"}}var dw,hw,nZ,Sv=C(()=>{"use strict";dw="three-direct-glb",hw=new Set(["glb","gltf","stl","ply","obj"]),nZ=new Set(["glb","gltf"])});function aZ(n){for(let e=n.length-1;e>=0;--e)if(n[e]>=65535)return!0;return!1}function oZ(n){return ArrayBuffer.isView(n)&&!(n instanceof DataView)}function cu(n){return document.createElementNS("http://www.w3.org/1999/xhtml",n)}function wF(){let n=cu("canvas");return n.style.display="block",n}function zp(...n){let e="THREE."+n.shift();fu?fu("log",e,...n):console.log(e,...n)}function FF(n){let e=n[0];if(typeof e=="string"&&e.startsWith("TSL:")){let t=n[1];t&&t.isStackTrace?n[0]+=" "+t.getLocation():n[1]='Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'}return n}function Ct(...n){n=FF(n);let e="THREE."+n.shift();if(fu)fu("warn",e,...n);else{let t=n[0];t&&t.isStackTrace?console.warn(t.getError(e)):console.warn(e,...n)}}function Bt(...n){n=FF(n);let e="THREE."+n.shift();if(fu)fu("error",e,...n);else{let t=n[0];t&&t.isStackTrace?console.error(t.getError(e)):console.error(e,...n)}}function lE(...n){let e=n.join(" ");e in mw||(mw[e]=!0,Ct(...n))}function BF(n,e,t){return new Promise(function(i,r){function s(){switch(n.clientWaitSync(e,n.SYNC_FLUSH_COMMANDS_BIT,0)){case n.WAIT_FAILED:r();break;case n.TIMEOUT_EXPIRED:setTimeout(s,t);break;default:i()}}setTimeout(s,t)})}function za(){let n=Math.random()*4294967295|0,e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,i=Math.random()*4294967295|0;return(bn[n&255]+bn[n>>8&255]+bn[n>>16&255]+bn[n>>24&255]+"-"+bn[e&255]+bn[e>>8&255]+"-"+bn[e>>16&15|64]+bn[e>>24&255]+"-"+bn[t&63|128]+bn[t>>8&255]+"-"+bn[t>>16&255]+bn[t>>24&255]+bn[i&255]+bn[i>>8&255]+bn[i>>16&255]+bn[i>>24&255]).toLowerCase()}function mi(n,e,t){return Math.max(e,Math.min(t,n))}function Y0(n,e){return(n%e+e)%e}function lZ(n,e,t,i,r){return i+(n-e)*(r-i)/(t-e)}function cZ(n,e,t){return n!==e?(t-n)/(e-n):0}function kp(n,e,t){return(1-t)*n+t*e}function fZ(n,e,t,i){return kp(n,e,1-Math.exp(-t*i))}function hZ(n,e=1){return e-Math.abs(Y0(n,e*2)-e)}function dZ(n,e,t){return n<=e?0:n>=t?1:(n=(n-e)/(t-e),n*n*(3-2*n))}function uZ(n,e,t){return n<=e?0:n>=t?1:(n=(n-e)/(t-e),n*n*n*(n*(n*6-15)+10))}function mZ(n,e){return n+Math.floor(Math.random()*(e-n+1))}function pZ(n,e){return n+Math.random()*(e-n)}function _Z(n){return n*(.5-Math.random())}function gZ(n){n!==void 0&&(pw=n);let e=pw+=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 vZ(n){return n*Gp}function EZ(n){return n*uh}function SZ(n){return(n&n-1)===0&&n!==0}function TZ(n){return Math.pow(2,Math.ceil(Math.log(n)/Math.LN2))}function AZ(n){return Math.pow(2,Math.floor(Math.log(n)/Math.LN2))}function xZ(n,e,t,i,r){let s=Math.cos,a=Math.sin,o=s(t/2),l=a(t/2),c=s((e+i)/2),f=a((e+i)/2),h=s((e-i)/2),d=a((e-i)/2),u=s((i-e)/2),m=a((i-e)/2);switch(r){case"XYX":n.set(o*f,l*h,l*d,o*c);break;case"YZY":n.set(l*d,o*f,l*h,o*c);break;case"ZXZ":n.set(l*h,l*d,o*f,o*c);break;case"XZX":n.set(o*f,l*m,l*u,o*c);break;case"YXY":n.set(l*u,o*f,l*m,o*c);break;case"ZYZ":n.set(l*m,l*u,o*f,o*c);break;default:Ct("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}}function Wa(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return n/4294967295;case Uint16Array:return n/65535;case Uint8Array:return n/255;case Int32Array:return Math.max(n/2147483647,-1);case Int16Array:return Math.max(n/32767,-1);case Int8Array:return Math.max(n/127,-1);default:throw new Error("Invalid component type.")}}function Yi(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return Math.round(n*4294967295);case Uint16Array:return Math.round(n*65535);case Uint8Array:return Math.round(n*255);case Int32Array:return Math.round(n*2147483647);case Int16Array:return Math.round(n*32767);case Int8Array:return Math.round(n*127);default:throw new Error("Invalid component type.")}}function RZ(){let n={enabled:!0,workingColorSpace:Kn,spaces:{},convert:function(r,s,a){return this.enabled===!1||s===a||!s||!a||(this.spaces[s].transfer===Xi&&(r.r=Il(r.r),r.g=Il(r.g),r.b=Il(r.b)),this.spaces[s].primaries!==this.spaces[a].primaries&&(r.applyMatrix3(this.spaces[s].toXYZ),r.applyMatrix3(this.spaces[a].fromXYZ)),this.spaces[a].transfer===Xi&&(r.r=au(r.r),r.g=au(r.g),r.b=au(r.b))),r},workingToColorSpace:function(r,s){return this.convert(r,this.workingColorSpace,s)},colorSpaceToWorking:function(r,s){return this.convert(r,s,this.workingColorSpace)},getPrimaries:function(r){return this.spaces[r].primaries},getTransfer:function(r){return r===Ll?Hp:this.spaces[r].transfer},getToneMappingMode:function(r){return this.spaces[r].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(r,s=this.workingColorSpace){return r.fromArray(this.spaces[s].luminanceCoefficients)},define:function(r){Object.assign(this.spaces,r)},_getMatrix:function(r,s,a){return r.copy(this.spaces[s].toXYZ).multiply(this.spaces[a].fromXYZ)},_getDrawingBufferColorSpace:function(r){return this.spaces[r].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(r=this.workingColorSpace){return this.spaces[r].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(r,s){return lE("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),n.workingToColorSpace(r,s)},toWorkingColorSpace:function(r,s){return lE("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),n.colorSpaceToWorking(r,s)}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],i=[.3127,.329];return n.define({[Kn]:{primaries:e,whitePoint:i,transfer:Hp,toXYZ:gw,fromXYZ:vw,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:Fi},outputColorSpaceConfig:{drawingBufferColorSpace:Fi}},[Fi]:{primaries:e,whitePoint:i,transfer:Xi,toXYZ:gw,fromXYZ:vw,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:Fi}}}),n}function Il(n){return n<.04045?n*.0773993808:Math.pow(n*.9478672986+.0521327014,2.4)}function au(n){return n<.0031308?n*12.92:1.055*Math.pow(n,.41666)-.055}function zb(n){return typeof HTMLImageElement!="undefined"&&n instanceof HTMLImageElement||typeof HTMLCanvasElement!="undefined"&&n instanceof HTMLCanvasElement||typeof ImageBitmap!="undefined"&&n instanceof ImageBitmap?cE.getDataURL(n):n.data?{data:Array.from(n.data),width:n.width,height:n.height,type:n.data.constructor.name}:(Ct("Texture: Unable to serialize Texture."),{})}function Kb(n,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?n+(e-n)*6*t:t<1/2?e:t<2/3?n+(e-n)*6*(2/3-t):n}function t0(n,e,t,i,r){for(let s=0,a=n.length-3;s<=a;s+=3){rh.fromArray(n,s);let o=r.x*Math.abs(rh.x)+r.y*Math.abs(rh.y)+r.z*Math.abs(rh.z),l=e.dot(rh),c=t.dot(rh),f=i.dot(rh);if(Math.max(-Math.max(l,c,f),Math.min(l,c,f))>o)return!1}return!0}function Pv(n,e,t,i,r,s){tu.subVectors(n,t).addScalar(.5).multiply(i),r!==void 0?(Np.x=s*tu.x-r*tu.y,Np.y=r*tu.x+s*tu.y):Np.copy(tu),n.copy(e),n.x+=Np.x,n.y+=Np.y,n.applyMatrix4(GF)}function UZ(n,e,t,i,r,s,a,o){let l;if(e.side===pn?l=i.intersectTriangle(a,s,r,!0,o):l=i.intersectTriangle(r,s,a,e.side===Vs,o),l===null)return null;Uv.copy(o),Uv.applyMatrix4(n.matrixWorld);let c=t.ray.origin.distanceTo(Uv);return ct.far?null:{distance:c,point:Uv.clone(),object:n}}function Vv(n,e,t,i,r,s,a,o,l,c){n.getVertexPosition(o,Nv),n.getVertexPosition(l,wv),n.getVertexPosition(c,Fv);let f=UZ(n,e,t,i,Nv,wv,Fv,Dw);if(f){let h=new ne;bl.getBarycoord(Dw,Nv,wv,Fv,h),r&&(f.uv=bl.getInterpolatedAttribute(r,o,l,c,h,new It)),s&&(f.uv1=bl.getInterpolatedAttribute(s,o,l,c,h,new It)),a&&(f.normal=bl.getInterpolatedAttribute(a,o,l,c,h,new ne),f.normal.dot(i.direction)>0&&f.normal.multiplyScalar(-1));let d={a:o,b:l,c,normal:new ne,materialIndex:0};bl.getNormal(Nv,wv,Fv,d.normal),f.face=d,f.barycoord=h}return f}function zv(n,e,t,i,r,s,a){let o=n.geometry.attributes.position;if(dE.fromBufferAttribute(o,r),uE.fromBufferAttribute(o,s),t.distanceSqToSegment(dE,uE,d0,Gw)>i)return;d0.applyMatrix4(n.matrixWorld);let c=e.ray.origin.distanceTo(d0);if(!(ce.far))return{distance:c,point:Gw.clone().applyMatrix4(n.matrixWorld),index:a,face:null,faceIndex:null,barycoord:null,object:n}}function zw(n,e,t,i,r,s,a){let o=v0.distanceSqToPoint(n);if(or.far)return;s.push({distance:c,distanceToRay:Math.sqrt(o),point:l,index:e,face:null,faceIndex:null,barycoord:null,object:a})}}function xh(n){let e={};for(let t in n){e[t]={};for(let i in n[t]){let r=n[t][i];if(Xw(r))r.isRenderTargetTexture?(Ct("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[t][i]=null):e[t][i]=r.clone();else if(Array.isArray(r))if(Xw(r[0])){let s=[];for(let a=0,o=r.length;a{jc={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},qc={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},eF=0,I0=1,tF=2,h_=1,yE=2,xu=3,Vs=0,pn=1,ua=2,ko=0,ch=1,M0=2,C0=3,y0=4,iF=5,Wc=100,rF=101,nF=102,sF=103,aF=104,oF=200,lF=201,cF=202,fF=203,$v=204,Jv=205,hF=206,dF=207,uF=208,mF=209,pF=210,_F=211,gF=212,vF=213,EF=214,eE=0,tE=1,iE=2,fh=3,rE=4,nE=5,sE=6,aE=7,d_=0,SF=1,TF=2,Ws=0,P0=1,D0=2,L0=3,O0=4,N0=5,w0=6,F0=7,p0="attached",AF="detached",B0=300,Zc=301,Th=302,PE=303,DE=304,u_=306,Do=1e3,fa=1001,ou=1002,Dr=1003,LE=1004,Ah=1005,Lr=1006,Ru=1007,qa=1008,ps=1009,U0=1010,V0=1011,bu=1012,OE=1013,Za=1014,Hs=1015,Wo=1016,NE=1017,wE=1018,Iu=1020,G0=35902,k0=35899,W0=1021,H0=1022,zs=1023,Lo=1026,Qc=1027,FE=1028,BE=1029,$c=1030,UE=1031,VE=1033,m_=33776,p_=33777,__=33778,g_=33779,GE=35840,kE=35841,WE=35842,HE=35843,zE=36196,XE=37492,YE=37496,KE=37488,jE=37489,v_=37490,qE=37491,ZE=37808,QE=37809,$E=37810,JE=37811,eS=37812,tS=37813,iS=37814,rS=37815,nS=37816,sS=37817,aS=37818,oS=37819,lS=37820,cS=37821,fS=36492,hS=36494,dS=36495,uS=36283,mS=36284,E_=36285,pS=36286,xF=2200,RF=2201,bF=2202,hh=2300,dh=2301,Qv=2302,_0=2303,oh=2400,lh=2401,Wp=2402,_S=2500,IF=2501,z0=0,S_=1,Mu=2,MF=3200,Cu=0,CF=1,Ll="",Fi="srgb",Kn="srgb-linear",Hp="linear",Xi="srgb",ah=7680,g0=519,yF=512,PF=513,DF=514,gS=515,LF=516,OF=517,vS=518,NF=519,oE=35044,X0="300 es",Ha=2e3,lu=2001;mw={},fu=null;UF={[eE]:tE,[iE]:sE,[rE]:aE,[fh]:nE,[tE]:eE,[sE]:iE,[aE]:rE,[nE]:fh},ha=class{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});let i=this._listeners;i[e]===void 0&&(i[e]=[]),i[e].indexOf(t)===-1&&i[e].push(t)}hasEventListener(e,t){let i=this._listeners;return i===void 0?!1:i[e]!==void 0&&i[e].indexOf(t)!==-1}removeEventListener(e,t){let i=this._listeners;if(i===void 0)return;let r=i[e];if(r!==void 0){let s=r.indexOf(t);s!==-1&&r.splice(s,1)}}dispatchEvent(e){let t=this._listeners;if(t===void 0)return;let i=t[e.type];if(i!==void 0){e.target=this;let r=i.slice(0);for(let s=0,a=r.length;s0){let u=.5/Math.sqrt(d+1);this._w=.25/u,this._x=(f-l)*u,this._y=(s-c)*u,this._z=(a-r)*u}else if(i>o&&i>h){let u=2*Math.sqrt(1+i-o-h);this._w=(f-l)/u,this._x=.25*u,this._y=(r+a)/u,this._z=(s+c)/u}else if(o>h){let u=2*Math.sqrt(1+o-i-h);this._w=(s-c)/u,this._x=(r+a)/u,this._y=.25*u,this._z=(l+f)/u}else{let u=2*Math.sqrt(1+h-i-o);this._w=(a-r)/u,this._x=(s+c)/u,this._y=(l+f)/u,this._z=.25*u}return this._onChangeCallback(),this}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()}angleTo(e){return 2*Math.acos(Math.abs(mi(this.dot(e),-1,1)))}rotateTowards(e,t){let i=this.angleTo(e);if(i===0)return this;let r=Math.min(1,t/i);return this.slerp(e,r),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}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}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){let i=e._x,r=e._y,s=e._z,a=e._w,o=t._x,l=t._y,c=t._z,f=t._w;return this._x=i*f+a*o+r*c-s*l,this._y=r*f+a*l+s*o-i*c,this._z=s*f+a*c+i*l-r*o,this._w=a*f-i*o-r*l-s*c,this._onChangeCallback(),this}slerp(e,t){let i=e._x,r=e._y,s=e._z,a=e._w,o=this.dot(e);o<0&&(i=-i,r=-r,s=-s,a=-a,o=-o);let l=1-t;if(o<.9995){let c=Math.acos(o),f=Math.sin(c);l=Math.sin(l*c)/f,t=Math.sin(t*c)/f,this._x=this._x*l+i*t,this._y=this._y*l+r*t,this._z=this._z*l+s*t,this._w=this._w*l+a*t,this._onChangeCallback()}else this._x=this._x*l+i*t,this._y=this._y*l+r*t,this._z=this._z*l+s*t,this._w=this._w*l+a*t,this.normalize();return this}slerpQuaternions(e,t,i){return this.copy(e).slerp(t,i)}random(){let e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),i=Math.random(),r=Math.sqrt(1-i),s=Math.sqrt(i);return this.set(r*Math.sin(e),r*Math.cos(e),s*Math.sin(t),s*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}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}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}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}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}},$0=class $0{constructor(e=0,t=0,i=0){this.x=e,this.y=t,this.z=i}set(e,t,i){return i===void 0&&(i=this.z),this.x=e,this.y=t,this.z=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}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}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)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(_w.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(_w.setFromAxisAngle(e,t))}applyMatrix3(e){let t=this.x,i=this.y,r=this.z,s=e.elements;return this.x=s[0]*t+s[3]*i+s[6]*r,this.y=s[1]*t+s[4]*i+s[7]*r,this.z=s[2]*t+s[5]*i+s[8]*r,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){let t=this.x,i=this.y,r=this.z,s=e.elements,a=1/(s[3]*t+s[7]*i+s[11]*r+s[15]);return this.x=(s[0]*t+s[4]*i+s[8]*r+s[12])*a,this.y=(s[1]*t+s[5]*i+s[9]*r+s[13])*a,this.z=(s[2]*t+s[6]*i+s[10]*r+s[14])*a,this}applyQuaternion(e){let t=this.x,i=this.y,r=this.z,s=e.x,a=e.y,o=e.z,l=e.w,c=2*(a*r-o*i),f=2*(o*t-s*r),h=2*(s*i-a*t);return this.x=t+l*c+a*h-o*f,this.y=i+l*f+o*c-s*h,this.z=r+l*h+s*f-a*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){let t=this.x,i=this.y,r=this.z,s=e.elements;return this.x=s[0]*t+s[4]*i+s[8]*r,this.y=s[1]*t+s[5]*i+s[9]*r,this.z=s[2]*t+s[6]*i+s[10]*r,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}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}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}clamp(e,t){return this.x=mi(this.x,e.x,t.x),this.y=mi(this.y,e.y,t.y),this.z=mi(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=mi(this.x,e,t),this.y=mi(this.y,e,t),this.z=mi(this.z,e,t),this}clampLength(e,t){let i=this.length();return this.divideScalar(i||1).multiplyScalar(mi(i,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}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}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}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){let i=e.x,r=e.y,s=e.z,a=t.x,o=t.y,l=t.z;return this.x=r*l-s*o,this.y=s*a-i*l,this.z=i*o-r*a,this}projectOnVector(e){let t=e.lengthSq();if(t===0)return this.set(0,0,0);let i=e.dot(this)/t;return this.copy(e).multiplyScalar(i)}projectOnPlane(e){return Wb.copy(this).projectOnVector(e),this.sub(Wb)}reflect(e){return this.sub(Wb.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let i=this.dot(e)/t;return Math.acos(mi(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,i=this.y-e.y,r=this.z-e.z;return t*t+i*i+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,i){let r=Math.sin(t)*e;return this.x=r*Math.sin(i),this.y=Math.cos(t)*e,this.z=r*Math.cos(i),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,i){return this.x=e*Math.sin(t),this.y=i,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){let t=this.setFromMatrixColumn(e,0).length(),i=this.setFromMatrixColumn(e,1).length(),r=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=i,this.z=r,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let 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}};$0.prototype.isVector3=!0;ne=$0,Wb=new ne,_w=new Zr,J0=class J0{constructor(e,t,i,r,s,a,o,l,c){this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,i,r,s,a,o,l,c)}set(e,t,i,r,s,a,o,l,c){let f=this.elements;return f[0]=e,f[1]=r,f[2]=o,f[3]=t,f[4]=s,f[5]=l,f[6]=i,f[7]=a,f[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){let 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}extractBasis(e,t,i){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(e){let 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}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let i=e.elements,r=t.elements,s=this.elements,a=i[0],o=i[3],l=i[6],c=i[1],f=i[4],h=i[7],d=i[2],u=i[5],m=i[8],p=r[0],_=r[3],g=r[6],v=r[1],x=r[4],A=r[7],S=r[2],E=r[5],R=r[8];return s[0]=a*p+o*v+l*S,s[3]=a*_+o*x+l*E,s[6]=a*g+o*A+l*R,s[1]=c*p+f*v+h*S,s[4]=c*_+f*x+h*E,s[7]=c*g+f*A+h*R,s[2]=d*p+u*v+m*S,s[5]=d*_+u*x+m*E,s[8]=d*g+u*A+m*R,this}multiplyScalar(e){let 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}determinant(){let e=this.elements,t=e[0],i=e[1],r=e[2],s=e[3],a=e[4],o=e[5],l=e[6],c=e[7],f=e[8];return t*a*f-t*o*c-i*s*f+i*o*l+r*s*c-r*a*l}invert(){let e=this.elements,t=e[0],i=e[1],r=e[2],s=e[3],a=e[4],o=e[5],l=e[6],c=e[7],f=e[8],h=f*a-o*c,d=o*l-f*s,u=c*s-a*l,m=t*h+i*d+r*u;if(m===0)return this.set(0,0,0,0,0,0,0,0,0);let p=1/m;return e[0]=h*p,e[1]=(r*c-f*i)*p,e[2]=(o*i-r*a)*p,e[3]=d*p,e[4]=(f*t-r*l)*p,e[5]=(r*s-o*t)*p,e[6]=u*p,e[7]=(i*l-c*t)*p,e[8]=(a*t-i*s)*p,this}transpose(){let e,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}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){let 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}setUvTransform(e,t,i,r,s,a,o){let l=Math.cos(s),c=Math.sin(s);return this.set(i*l,i*c,-i*(l*a+c*o)+a+e,-r*c,r*l,-r*(-c*a+l*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(Hb.makeScale(e,t)),this}rotate(e){return this.premultiply(Hb.makeRotation(-e)),this}translate(e,t){return this.premultiply(Hb.makeTranslation(e,t)),this}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}makeRotation(e){let t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,i,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){let t=this.elements,i=e.elements;for(let r=0;r<9;r++)if(t[r]!==i[r])return!1;return!0}fromArray(e,t=0){for(let i=0;i<9;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){let 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}clone(){return new this.constructor().fromArray(this.elements)}};J0.prototype.isMatrix3=!0;ii=J0,Hb=new ii,gw=new ii().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),vw=new ii().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);oi=RZ();cE=class{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement=="undefined")return e.src;let i;if(e instanceof HTMLCanvasElement)i=e;else{Wd===void 0&&(Wd=cu("canvas")),Wd.width=e.width,Wd.height=e.height;let r=Wd.getContext("2d");e instanceof ImageData?r.putImageData(e,0,0):r.drawImage(e,0,0,e.width,e.height),i=Wd}return i.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement!="undefined"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement!="undefined"&&e instanceof HTMLCanvasElement||typeof ImageBitmap!="undefined"&&e instanceof ImageBitmap){let t=cu("canvas");t.width=e.width,t.height=e.height;let i=t.getContext("2d");i.drawImage(e,0,0,e.width,e.height);let r=i.getImageData(0,0,e.width,e.height),s=r.data;for(let a=0;a1),this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(Xb).x}get height(){return this.source.getSize(Xb).y}get depth(){return this.source.getSize(Xb).z}get image(){return this.source.data}set image(e){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}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.normalized=e.normalized,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}setValues(e){for(let t in e){let i=e[t];if(i===void 0){Ct(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){Ct(`Texture.setValues(): property '${t}' does not exist.`);continue}r&&i&&r.isVector2&&i.isVector2||r&&i&&r.isVector3&&i.isVector3||r&&i&&r.isMatrix3&&i.isMatrix3?r.copy(i):this[t]=i}}toJSON(e){let t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];let 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,normalized:this.normalized,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}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==B0)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case Do:e.x=e.x-Math.floor(e.x);break;case fa:e.x=e.x<0?0:1;break;case ou: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 Do:e.y=e.y-Math.floor(e.y);break;case fa:e.y=e.y<0?0:1;break;case ou: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}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}};Ar.DEFAULT_IMAGE=null;Ar.DEFAULT_MAPPING=B0;Ar.DEFAULT_ANISOTROPY=1;eI=class eI{constructor(e=0,t=0,i=0,r=1){this.x=e,this.y=t,this.z=i,this.w=r}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,i,r){return this.x=e,this.y=t,this.z=i,this.w=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}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}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)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}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}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}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}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}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}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}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){let t=this.x,i=this.y,r=this.z,s=this.w,a=e.elements;return this.x=a[0]*t+a[4]*i+a[8]*r+a[12]*s,this.y=a[1]*t+a[5]*i+a[9]*r+a[13]*s,this.z=a[2]*t+a[6]*i+a[10]*r+a[14]*s,this.w=a[3]*t+a[7]*i+a[11]*r+a[15]*s,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);let 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}setAxisAngleFromRotationMatrix(e){let t,i,r,s,l=e.elements,c=l[0],f=l[4],h=l[8],d=l[1],u=l[5],m=l[9],p=l[2],_=l[6],g=l[10];if(Math.abs(f-d)<.01&&Math.abs(h-p)<.01&&Math.abs(m-_)<.01){if(Math.abs(f+d)<.1&&Math.abs(h+p)<.1&&Math.abs(m+_)<.1&&Math.abs(c+u+g-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;let x=(c+1)/2,A=(u+1)/2,S=(g+1)/2,E=(f+d)/4,R=(h+p)/4,I=(m+_)/4;return x>A&&x>S?x<.01?(i=0,r=.707106781,s=.707106781):(i=Math.sqrt(x),r=E/i,s=R/i):A>S?A<.01?(i=.707106781,r=0,s=.707106781):(r=Math.sqrt(A),i=E/r,s=I/r):S<.01?(i=.707106781,r=.707106781,s=0):(s=Math.sqrt(S),i=R/s,r=I/s),this.set(i,r,s,t),this}let v=Math.sqrt((_-m)*(_-m)+(h-p)*(h-p)+(d-f)*(d-f));return Math.abs(v)<.001&&(v=1),this.x=(_-m)/v,this.y=(h-p)/v,this.z=(d-f)/v,this.w=Math.acos((c+u+g-1)/2),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}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}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}clamp(e,t){return this.x=mi(this.x,e.x,t.x),this.y=mi(this.y,e.y,t.y),this.z=mi(this.z,e.z,t.z),this.w=mi(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=mi(this.x,e,t),this.y=mi(this.y,e,t),this.z=mi(this.z,e,t),this.w=mi(this.w,e,t),this}clampLength(e,t){let i=this.length();return this.divideScalar(i||1).multiplyScalar(mi(i,e,t))}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}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}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}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}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}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}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}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}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}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}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}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}};eI.prototype.isVector4=!0;Qi=eI,fE=class extends ha{constructor(e=1,t=1,i={}){super(),i=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Lr,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 Qi(0,0,e,t),this.scissorTest=!1,this.viewport=new Qi(0,0,e,t),this.textures=[];let r={width:e,height:t,depth:i.depth},s=new Ar(r),a=i.count;for(let o=0;o1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}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>>0}enable(e){this.mask|=1<1){for(let t=0;t1){for(let i=0;i0&&(r.userData=this.userData),r.layers=this.layers.mask,r.matrix=this.matrix.toArray(),r.up=this.up.toArray(),this.pivot!==null&&(r.pivot=this.pivot.toArray()),this.matrixAutoUpdate===!1&&(r.matrixAutoUpdate=!1),this.morphTargetDictionary!==void 0&&(r.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),this.morphTargetInfluences!==void 0&&(r.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(r.type="InstancedMesh",r.count=this.count,r.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(r.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(r.type="BatchedMesh",r.perObjectFrustumCulled=this.perObjectFrustumCulled,r.sortObjects=this.sortObjects,r.drawRanges=this._drawRanges,r.reservedRanges=this._reservedRanges,r.geometryInfo=this._geometryInfo.map(o=>({...o,boundingBox:o.boundingBox?o.boundingBox.toJSON():void 0,boundingSphere:o.boundingSphere?o.boundingSphere.toJSON():void 0})),r.instanceInfo=this._instanceInfo.map(o=>({...o})),r.availableInstanceIds=this._availableInstanceIds.slice(),r.availableGeometryIds=this._availableGeometryIds.slice(),r.nextIndexStart=this._nextIndexStart,r.nextVertexStart=this._nextVertexStart,r.geometryCount=this._geometryCount,r.maxInstanceCount=this._maxInstanceCount,r.maxVertexCount=this._maxVertexCount,r.maxIndexCount=this._maxIndexCount,r.geometryInitialized=this._geometryInitialized,r.matricesTexture=this._matricesTexture.toJSON(e),r.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(r.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(r.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(r.boundingBox=this.boundingBox.toJSON()));function s(o,l){return o[l.uuid]===void 0&&(o[l.uuid]=l.toJSON(e)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?r.background=this.background.toJSON():this.background.isTexture&&(r.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(r.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){r.geometry=s(e.geometries,this.geometry);let o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){let l=o.shapes;if(Array.isArray(l))for(let c=0,f=l.length;c0){r.children=[];for(let o=0;o0){r.animations=[];for(let o=0;o0&&(i.geometries=o),l.length>0&&(i.materials=l),c.length>0&&(i.textures=c),f.length>0&&(i.images=f),h.length>0&&(i.shapes=h),d.length>0&&(i.skeletons=d),u.length>0&&(i.animations=u),m.length>0&&(i.nodes=m)}return i.object=r,i;function a(o){let l=[];for(let c in o){let f=o[c];delete f.metadata,l.push(f)}return l}}clone(e){return new this.constructor().copy(this,e)}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.pivot=e.pivot!==null?e.pivot.clone():null,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.static=e.static,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let i=0;iu+m?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!c.inputState.pinching&&d<=u-m&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else l!==null&&e.gripSpace&&(s=t.getPose(e.gripSpace,i),s!==null&&(l.matrix.fromArray(s.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,s.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(s.linearVelocity)):l.hasLinearVelocity=!1,s.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(s.angularVelocity)):l.hasAngularVelocity=!1,l.eventsEnabled&&l.dispatchEvent({type:"gripUpdated",data:e,target:this})));o!==null&&(r=t.getPose(e.targetRaySpace,i),r===null&&s!==null&&(r=s),r!==null&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(OZ)))}return o!==null&&(o.visible=r!==null),l!==null&&(l.visible=s!==null),c!==null&&(c.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){let i=new Us;i.matrixAutoUpdate=!1,i.visible=!1,e.joints[t.jointName]=i,e.add(i)}return e.joints[t.jointName]}},VF={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},Bc={h:0,s:0,l:0},xv={h:0,s:0,l:0};ft=class{constructor(e,t,i){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,i)}set(e,t,i){if(t===void 0&&i===void 0){let r=e;r&&r.isColor?this.copy(r):typeof r=="number"?this.setHex(r):typeof r=="string"&&this.setStyle(r)}else this.setRGB(e,t,i);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Fi){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,oi.colorSpaceToWorking(this,t),this}setRGB(e,t,i,r=oi.workingColorSpace){return this.r=e,this.g=t,this.b=i,oi.colorSpaceToWorking(this,r),this}setHSL(e,t,i,r=oi.workingColorSpace){if(e=Y0(e,1),t=mi(t,0,1),i=mi(i,0,1),t===0)this.r=this.g=this.b=i;else{let s=i<=.5?i*(1+t):i+t-i*t,a=2*i-s;this.r=Kb(a,s,e+1/3),this.g=Kb(a,s,e),this.b=Kb(a,s,e-1/3)}return oi.colorSpaceToWorking(this,r),this}setStyle(e,t=Fi){function i(s){s!==void 0&&parseFloat(s)<1&&Ct("Color: Alpha component of "+e+" will be ignored.")}let r;if(r=/^(\w+)\(([^\)]*)\)/.exec(e)){let s,a=r[1],o=r[2];switch(a){case"rgb":case"rgba":if(s=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(s[4]),this.setRGB(Math.min(255,parseInt(s[1],10))/255,Math.min(255,parseInt(s[2],10))/255,Math.min(255,parseInt(s[3],10))/255,t);if(s=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(s[4]),this.setRGB(Math.min(100,parseInt(s[1],10))/100,Math.min(100,parseInt(s[2],10))/100,Math.min(100,parseInt(s[3],10))/100,t);break;case"hsl":case"hsla":if(s=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return i(s[4]),this.setHSL(parseFloat(s[1])/360,parseFloat(s[2])/100,parseFloat(s[3])/100,t);break;default:Ct("Color: Unknown color model "+e)}}else if(r=/^\#([A-Fa-f\d]+)$/.exec(e)){let s=r[1],a=s.length;if(a===3)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,t);if(a===6)return this.setHex(parseInt(s,16),t);Ct("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Fi){let i=VF[e.toLowerCase()];return i!==void 0?this.setHex(i,t):Ct("Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=Il(e.r),this.g=Il(e.g),this.b=Il(e.b),this}copyLinearToSRGB(e){return this.r=au(e.r),this.g=au(e.g),this.b=au(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Fi){return oi.workingToColorSpace(In.copy(this),e),Math.round(mi(In.r*255,0,255))*65536+Math.round(mi(In.g*255,0,255))*256+Math.round(mi(In.b*255,0,255))}getHexString(e=Fi){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=oi.workingColorSpace){oi.workingToColorSpace(In.copy(this),t);let i=In.r,r=In.g,s=In.b,a=Math.max(i,r,s),o=Math.min(i,r,s),l,c,f=(o+a)/2;if(o===a)l=0,c=0;else{let h=a-o;switch(c=f<=.5?h/(a+o):h/(2-a-o),a){case i:l=(r-s)/h+(r0&&(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}},Ga=new ne,Sl=new ne,jb=new ne,Tl=new ne,Yd=new ne,Kd=new ne,Iw=new ne,qb=new ne,Zb=new ne,Qb=new ne,$b=new Qi,Jb=new Qi,e0=new Qi,bl=class n{constructor(e=new ne,t=new ne,i=new ne){this.a=e,this.b=t,this.c=i}static getNormal(e,t,i,r){r.subVectors(i,t),Ga.subVectors(e,t),r.cross(Ga);let s=r.lengthSq();return s>0?r.multiplyScalar(1/Math.sqrt(s)):r.set(0,0,0)}static getBarycoord(e,t,i,r,s){Ga.subVectors(r,t),Sl.subVectors(i,t),jb.subVectors(e,t);let a=Ga.dot(Ga),o=Ga.dot(Sl),l=Ga.dot(jb),c=Sl.dot(Sl),f=Sl.dot(jb),h=a*c-o*o;if(h===0)return s.set(0,0,0),null;let d=1/h,u=(c*l-o*f)*d,m=(a*f-o*l)*d;return s.set(1-u-m,m,u)}static containsPoint(e,t,i,r){return this.getBarycoord(e,t,i,r,Tl)===null?!1:Tl.x>=0&&Tl.y>=0&&Tl.x+Tl.y<=1}static getInterpolation(e,t,i,r,s,a,o,l){return this.getBarycoord(e,t,i,r,Tl)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(s,Tl.x),l.addScaledVector(a,Tl.y),l.addScaledVector(o,Tl.z),l)}static getInterpolatedAttribute(e,t,i,r,s,a){return $b.setScalar(0),Jb.setScalar(0),e0.setScalar(0),$b.fromBufferAttribute(e,t),Jb.fromBufferAttribute(e,i),e0.fromBufferAttribute(e,r),a.setScalar(0),a.addScaledVector($b,s.x),a.addScaledVector(Jb,s.y),a.addScaledVector(e0,s.z),a}static isFrontFacing(e,t,i,r){return Ga.subVectors(i,t),Sl.subVectors(e,t),Ga.cross(Sl).dot(r)<0}set(e,t,i){return this.a.copy(e),this.b.copy(t),this.c.copy(i),this}setFromPointsAndIndices(e,t,i,r){return this.a.copy(e[t]),this.b.copy(e[i]),this.c.copy(e[r]),this}setFromAttributeAndIndices(e,t,i,r){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,i),this.c.fromBufferAttribute(e,r),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Ga.subVectors(this.c,this.b),Sl.subVectors(this.a,this.b),Ga.cross(Sl).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return n.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return n.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,i,r,s){return n.getInterpolation(e,this.a,this.b,this.c,t,i,r,s)}containsPoint(e){return n.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return n.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){let i=this.a,r=this.b,s=this.c,a,o;Yd.subVectors(r,i),Kd.subVectors(s,i),qb.subVectors(e,i);let l=Yd.dot(qb),c=Kd.dot(qb);if(l<=0&&c<=0)return t.copy(i);Zb.subVectors(e,r);let f=Yd.dot(Zb),h=Kd.dot(Zb);if(f>=0&&h<=f)return t.copy(r);let d=l*h-f*c;if(d<=0&&l>=0&&f<=0)return a=l/(l-f),t.copy(i).addScaledVector(Yd,a);Qb.subVectors(e,s);let u=Yd.dot(Qb),m=Kd.dot(Qb);if(m>=0&&u<=m)return t.copy(s);let p=u*c-l*m;if(p<=0&&c>=0&&m<=0)return o=c/(c-m),t.copy(i).addScaledVector(Kd,o);let _=f*m-u*h;if(_<=0&&h-f>=0&&u-m>=0)return Iw.subVectors(s,r),o=(h-f)/(h-f+(u-m)),t.copy(r).addScaledVector(Iw,o);let g=1/(_+p+d);return a=p*g,o=d*g,t.copy(i).addScaledVector(Yd,a).addScaledVector(Kd,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}},Sr=class{constructor(e=new ne(1/0,1/0,1/0),t=new ne(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,i=e.length;t=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}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}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))}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}intersectsSphere(e){return this.clampPoint(e.center,ka),ka.distanceToSquared(e.center)<=e.radius*e.radius}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}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Pp),bv.subVectors(this.max,Pp),jd.subVectors(e.a,Pp),qd.subVectors(e.b,Pp),Zd.subVectors(e.c,Pp),Uc.subVectors(qd,jd),Vc.subVectors(Zd,qd),ih.subVectors(jd,Zd);let t=[0,-Uc.z,Uc.y,0,-Vc.z,Vc.y,0,-ih.z,ih.y,Uc.z,0,-Uc.x,Vc.z,0,-Vc.x,ih.z,0,-ih.x,-Uc.y,Uc.x,0,-Vc.y,Vc.x,0,-ih.y,ih.x,0];return!t0(t,jd,qd,Zd,bv)||(t=[1,0,0,0,1,0,0,0,1],!t0(t,jd,qd,Zd,bv))?!1:(Iv.crossVectors(Uc,Vc),t=[Iv.x,Iv.y,Iv.z],t0(t,jd,qd,Zd,bv))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,ka).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(ka).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(Al[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Al[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Al[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Al[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Al[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Al[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Al[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Al[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Al),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}},Al=[new ne,new ne,new ne,new ne,new ne,new ne,new ne,new ne],ka=new ne,Rv=new Sr,jd=new ne,qd=new ne,Zd=new ne,Uc=new ne,Vc=new ne,ih=new ne,Pp=new ne,bv=new ne,Iv=new ne,rh=new ne;Gr=new ne,Mv=new It,NZ=0,lr=class extends ha{constructor(e,t,i=!1){if(super(),Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:NZ++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=i,this.usage=oE,this.updateRanges=[],this.gpuType=Hs,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}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}copyAt(e,t,i){e*=this.itemSize,i*=t.itemSize;for(let r=0,s=this.itemSize;rthis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Dp.subVectors(e,this.center);let t=Dp.lengthSq();if(t>this.radius*this.radius){let i=Math.sqrt(t),r=(i-this.radius)*.5;this.center.addScaledVector(Dp,r/i),this.radius+=r}return this}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):(i0.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Dp.copy(e.center).add(i0)),this.expandByPoint(Dp.copy(e.center).sub(i0))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}},FZ=0,la=new li,r0=new ir,Qd=new ne,Bs=new Sr,Lp=new Sr,ln=new ne,Vi=class n extends ha{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:FZ++}),this.uuid=za(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(aZ(e)?Kp:Yp)(e,1):this.index=e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,i=0){this.groups.push({start:e,count:t,materialIndex:i})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){let t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);let i=this.attributes.normal;if(i!==void 0){let s=new ii().getNormalMatrix(e);i.applyNormalMatrix(s),i.needsUpdate=!0}let r=this.attributes.tangent;return r!==void 0&&(r.transformDirection(e),r.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return la.makeRotationFromQuaternion(e),this.applyMatrix4(la),this}rotateX(e){return la.makeRotationX(e),this.applyMatrix4(la),this}rotateY(e){return la.makeRotationY(e),this.applyMatrix4(la),this}rotateZ(e){return la.makeRotationZ(e),this.applyMatrix4(la),this}translate(e,t,i){return la.makeTranslation(e,t,i),this.applyMatrix4(la),this}scale(e,t,i){return la.makeScale(e,t,i),this.applyMatrix4(la),this}lookAt(e){return r0.lookAt(e),r0.updateMatrix(),this.applyMatrix4(r0.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Qd).negate(),this.translate(Qd.x,Qd.y,Qd.z),this}setFromPoints(e){let t=this.getAttribute("position");if(t===void 0){let i=[];for(let r=0,s=e.length;rt.count&&Ct("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Sr);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){Bt("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new ne(-1/0,-1/0,-1/0),new ne(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let i=0,r=t.length;i0&&(e.userData=this.userData),this.parameters!==void 0){let l=this.parameters;for(let c in l)l[c]!==void 0&&(e[c]=l[c]);return e}e.data={attributes:{}};let t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});let i=this.attributes;for(let l in i){let c=i[l];e.data.attributes[l]=c.toJSON(e.data)}let r={},s=!1;for(let l in this.morphAttributes){let c=this.morphAttributes[l],f=[];for(let h=0,d=c.length;h0&&(r[l]=f,s=!0)}s&&(e.data.morphAttributes=r,e.data.morphTargetsRelative=this.morphTargetsRelative);let a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));let o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;let t={};this.name=e.name;let i=e.index;i!==null&&this.setIndex(i.clone());let r=e.attributes;for(let c in r){let f=r[c];this.setAttribute(c,f.clone(t))}let s=e.morphAttributes;for(let c in s){let f=[],h=s[c];for(let d=0,u=h.length;d0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(let t in e){let i=e[t];if(i===void 0){Ct(`Material: parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){Ct(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}r&&r.isColor?r.set(i):r&&r.isVector3&&i&&i.isVector3?r.copy(i):this[t]=i}}toJSON(e){let t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});let 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!==ch&&(i.blending=this.blending),this.side!==Vs&&(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!==$v&&(i.blendSrc=this.blendSrc),this.blendDst!==Jv&&(i.blendDst=this.blendDst),this.blendEquation!==Wc&&(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!==fh&&(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!==g0&&(i.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(i.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(i.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==ah&&(i.stencilFail=this.stencilFail),this.stencilZFail!==ah&&(i.stencilZFail=this.stencilZFail),this.stencilZPass!==ah&&(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.allowOverride===!1&&(i.allowOverride=!1),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 r(s){let a=[];for(let o in s){let l=s[o];delete l.metadata,a.push(l)}return a}if(t){let s=r(e.textures),a=r(e.images);s.length>0&&(i.textures=s),a.length>0&&(i.images=a)}return i}clone(){return new this.constructor().copy(this)}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;let t=e.clippingPlanes,i=null;if(t!==null){let r=t.length;i=new Array(r);for(let s=0;s!==r;++s)i[s]=t[s].clone()}return this.clippingPlanes=i,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}},mu=class extends Or{constructor(e){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new ft(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.rotation=e.rotation,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}},Op=new ne,Jd=new ne,eu=new ne,tu=new It,Np=new It,GF=new li,Cv=new ne,wp=new ne,yv=new ne,Mw=new It,n0=new It,Cw=new It,jp=class extends ir{constructor(e=new mu){if(super(),this.isSprite=!0,this.type="Sprite",$d===void 0){$d=new Vi;let t=new Float32Array([-.5,-.5,0,0,0,.5,-.5,0,1,0,.5,.5,0,1,1,-.5,.5,0,0,1]),i=new ph(t,5);$d.setIndex([0,1,2,0,2,3]),$d.setAttribute("position",new Hc(i,3,0,!1)),$d.setAttribute("uv",new Hc(i,2,3,!1))}this.geometry=$d,this.material=e,this.center=new It(.5,.5),this.count=1}raycast(e,t){e.camera===null&&Bt('Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.'),Jd.setFromMatrixScale(this.matrixWorld),GF.copy(e.camera.matrixWorld),this.modelViewMatrix.multiplyMatrices(e.camera.matrixWorldInverse,this.matrixWorld),eu.setFromMatrixPosition(this.modelViewMatrix),e.camera.isPerspectiveCamera&&this.material.sizeAttenuation===!1&&Jd.multiplyScalar(-eu.z);let i=this.material.rotation,r,s;i!==0&&(s=Math.cos(i),r=Math.sin(i));let a=this.center;Pv(Cv.set(-.5,-.5,0),eu,a,Jd,r,s),Pv(wp.set(.5,-.5,0),eu,a,Jd,r,s),Pv(yv.set(.5,.5,0),eu,a,Jd,r,s),Mw.set(0,0),n0.set(1,0),Cw.set(1,1);let o=e.ray.intersectTriangle(Cv,wp,yv,!1,Op);if(o===null&&(Pv(wp.set(-.5,.5,0),eu,a,Jd,r,s),n0.set(0,1),o=e.ray.intersectTriangle(Cv,yv,wp,!1,Op),o===null))return;let l=e.ray.origin.distanceTo(Op);le.far||t.push({distance:l,point:Op.clone(),uv:bl.getInterpolation(Op,Cv,wp,yv,Mw,n0,Cw,new It),face:null,object:this})}copy(e,t){return super.copy(e,t),e.center!==void 0&&this.center.copy(e.center),this.material=e.material,this}};xl=new ne,s0=new ne,Dv=new ne,Gc=new ne,a0=new ne,Lv=new ne,o0=new ne,Oo=class{constructor(e=new ne,t=new ne(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,xl)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);let i=t.dot(this.direction);return i<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,i)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){let t=xl.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(xl.copy(this.origin).addScaledVector(this.direction,t),xl.distanceToSquared(e))}distanceSqToSegment(e,t,i,r){s0.copy(e).add(t).multiplyScalar(.5),Dv.copy(t).sub(e).normalize(),Gc.copy(this.origin).sub(s0);let s=e.distanceTo(t)*.5,a=-this.direction.dot(Dv),o=Gc.dot(this.direction),l=-Gc.dot(Dv),c=Gc.lengthSq(),f=Math.abs(1-a*a),h,d,u,m;if(f>0)if(h=a*l-o,d=a*o-l,m=s*f,h>=0)if(d>=-m)if(d<=m){let p=1/f;h*=p,d*=p,u=h*(h+a*d+2*o)+d*(a*h+d+2*l)+c}else d=s,h=Math.max(0,-(a*d+o)),u=-h*h+d*(d+2*l)+c;else d=-s,h=Math.max(0,-(a*d+o)),u=-h*h+d*(d+2*l)+c;else d<=-m?(h=Math.max(0,-(-a*s+o)),d=h>0?-s:Math.min(Math.max(-s,-l),s),u=-h*h+d*(d+2*l)+c):d<=m?(h=0,d=Math.min(Math.max(-s,-l),s),u=d*(d+2*l)+c):(h=Math.max(0,-(a*s+o)),d=h>0?s:Math.min(Math.max(-s,-l),s),u=-h*h+d*(d+2*l)+c);else d=a>0?-s:s,h=Math.max(0,-(a*d+o)),u=-h*h+d*(d+2*l)+c;return i&&i.copy(this.origin).addScaledVector(this.direction,h),r&&r.copy(s0).addScaledVector(Dv,d),u}intersectSphere(e,t){xl.subVectors(e.center,this.origin);let i=xl.dot(this.direction),r=xl.dot(xl)-i*i,s=e.radius*e.radius;if(r>s)return null;let a=Math.sqrt(s-r),o=i-a,l=i+a;return l<0?null:o<0?this.at(l,t):this.at(o,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){let t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;let i=-(this.origin.dot(e.normal)+e.constant)/t;return i>=0?i:null}intersectPlane(e,t){let i=this.distanceToPlane(e);return i===null?null:this.at(i,t)}intersectsPlane(e){let t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let i,r,s,a,o,l,c=1/this.direction.x,f=1/this.direction.y,h=1/this.direction.z,d=this.origin;return c>=0?(i=(e.min.x-d.x)*c,r=(e.max.x-d.x)*c):(i=(e.max.x-d.x)*c,r=(e.min.x-d.x)*c),f>=0?(s=(e.min.y-d.y)*f,a=(e.max.y-d.y)*f):(s=(e.max.y-d.y)*f,a=(e.min.y-d.y)*f),i>a||s>r||((s>i||isNaN(i))&&(i=s),(a=0?(o=(e.min.z-d.z)*h,l=(e.max.z-d.z)*h):(o=(e.max.z-d.z)*h,l=(e.min.z-d.z)*h),i>l||o>r)||((o>i||i!==i)&&(i=o),(l=0?i:r,t)}intersectsBox(e){return this.intersectBox(e,xl)!==null}intersectTriangle(e,t,i,r,s){a0.subVectors(t,e),Lv.subVectors(i,e),o0.crossVectors(a0,Lv);let a=this.direction.dot(o0),o;if(a>0){if(r)return null;o=1}else if(a<0)o=-1,a=-a;else return null;Gc.subVectors(this.origin,e);let l=o*this.direction.dot(Lv.crossVectors(Gc,Lv));if(l<0)return null;let c=o*this.direction.dot(a0.cross(Gc));if(c<0||l+c>a)return null;let f=-o*Gc.dot(o0);return f<0?null:this.at(f/a,s)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}},jn=class extends Or{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new ft(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 Xa,this.combine=d_,this.reflectivity=1,this.refractionRatio=.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}},yw=new li,nh=new Oo,Ov=new fs,Pw=new ne,Nv=new ne,wv=new ne,Fv=new ne,l0=new ne,Bv=new ne,Dw=new ne,Uv=new ne,ri=class extends ir{constructor(e=new Vi,t=new jn){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}updateMorphTargets(){let t=this.geometry.morphAttributes,i=Object.keys(t);if(i.length>0){let r=t[i[0]];if(r!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,a=r.length;s(e.far-e.near)**2))&&(yw.copy(s).invert(),nh.copy(e.ray).applyMatrix4(yw),!(i.boundingBox!==null&&nh.intersectsBox(i.boundingBox)===!1)&&this._computeIntersections(e,t,nh)))}_computeIntersections(e,t,i){let r,s=this.geometry,a=this.material,o=s.index,l=s.attributes.position,c=s.attributes.uv,f=s.attributes.uv1,h=s.attributes.normal,d=s.groups,u=s.drawRange;if(o!==null)if(Array.isArray(a))for(let m=0,p=d.length;m1)?null:t.copy(e.start).addScaledVector(r,a)}intersectsLine(e){let t=this.distanceToPoint(e.start),i=this.distanceToPoint(e.end);return t<0&&i>0||i<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){let i=t||HZ.getNormalMatrix(e),r=this.coplanarPoint(h0).applyMatrix4(e),s=this.normal.applyMatrix3(i).normalize();return this.constant=-r.dot(s),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}},sh=new fs,zZ=new It(.5,.5),Wv=new ne,gu=class{constructor(e=new ca,t=new ca,i=new ca,r=new ca,s=new ca,a=new ca){this.planes=[e,t,i,r,s,a]}set(e,t,i,r,s,a){let o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(i),o[3].copy(r),o[4].copy(s),o[5].copy(a),this}copy(e){let t=this.planes;for(let i=0;i<6;i++)t[i].copy(e.planes[i]);return this}setFromProjectionMatrix(e,t=Ha,i=!1){let r=this.planes,s=e.elements,a=s[0],o=s[1],l=s[2],c=s[3],f=s[4],h=s[5],d=s[6],u=s[7],m=s[8],p=s[9],_=s[10],g=s[11],v=s[12],x=s[13],A=s[14],S=s[15];if(r[0].setComponents(c-a,u-f,g-m,S-v).normalize(),r[1].setComponents(c+a,u+f,g+m,S+v).normalize(),r[2].setComponents(c+o,u+h,g+p,S+x).normalize(),r[3].setComponents(c-o,u-h,g-p,S-x).normalize(),i)r[4].setComponents(l,d,_,A).normalize(),r[5].setComponents(c-l,u-d,g-_,S-A).normalize();else if(r[4].setComponents(c-l,u-d,g-_,S-A).normalize(),t===Ha)r[5].setComponents(c+l,u+d,g+_,S+A).normalize();else if(t===lu)r[5].setComponents(l,d,_,A).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),sh.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{let t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),sh.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(sh)}intersectsSprite(e){sh.center.set(0,0,0);let t=zZ.distanceTo(e.center);return sh.radius=.7071067811865476+t,sh.applyMatrix4(e.matrixWorld),this.intersectsSphere(sh)}intersectsSphere(e){let t=this.planes,i=e.center,r=-e.radius;for(let s=0;s<6;s++)if(t[s].distanceToPoint(i)0?e.max.x:e.min.x,Wv.y=r.normal.y>0?e.max.y:e.min.y,Wv.z=r.normal.z>0?e.max.z:e.min.z,r.distanceToPoint(Wv)<0)return!1}return!0}containsPoint(e){let t=this.planes;for(let i=0;i<6;i++)if(t[i].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}},Mn=class extends Or{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new ft(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}},dE=new ne,uE=new ne,Vw=new li,Vp=new Oo,Hv=new fs,d0=new ne,Gw=new ne,No=class extends ir{constructor(e=new Vi,t=new Mn){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}computeLineDistances(){let e=this.geometry;if(e.index===null){let t=e.attributes.position,i=[0];for(let r=1,s=t.count;r0){let r=t[i[0]];if(r!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,a=r.length;s0){let r=t[i[0]];if(r!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,a=r.length;s0?1:-1,f.push(j.x,j.y,j.z),h.push(Y/R),h.push(1-Z/I),G+=1}}for(let Z=0;Z0)&&u.push(x,A,E),(g!==i-1||l0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;let i={};for(let r in this.extensions)this.extensions[r]===!0&&(i[r]=!0);return Object.keys(i).length>0&&(t.extensions=i),t}},mE=class extends Ws{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}},Cn=class extends Or{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new ct(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 ct(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=yu,this.normalScale=new bt(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 Xa,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}},us=class extends Cn{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 bt(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return mi(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(t){this.ior=(1+.4*t)/(1-.4*t)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new ct(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 ct(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new ct(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)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}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}},vh=class extends Or{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new ct(16777215),this.specular=new ct(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ct(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=yu,this.normalScale=new bt(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Xa,this.combine=d_,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.envMapIntensity=e.envMapIntensity,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}},i_=class extends Or{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new ct(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ct(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=yu,this.normalScale=new bt(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Xa,this.combine=d_,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=.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.envMapIntensity=e.envMapIntensity,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}},pE=class extends Or{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=MF,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}},_E=class extends Or{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}};wo=class{constructor(e,t,i,r){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=r!==void 0?r:new t.constructor(i),this.sampleValues=t,this.valueSize=i,this.settings=null,this.DefaultSettings_={}}evaluate(e){let t=this.parameterPositions,i=this._cachedIndex,r=t[i],s=t[i-1];e:{t:{let a;i:{r:if(!(e=s)){let o=t[1];e=s)break t}a=i,i=0;break i}break e}for(;i>>1;et;)--a;if(++a,s!==0||a!==r){s>=a&&(a=Math.max(a,1),s=a-1);let o=this.getValueSize();this.times=i.slice(s,a),this.values=this.values.slice(s*o,a*o)}return this}validate(){let e=!0,t=this.getValueSize();t-Math.floor(t)!==0&&(Ft("KeyframeTrack: Invalid value size in track.",this),e=!1);let i=this.times,r=this.values,s=i.length;s===0&&(Ft("KeyframeTrack: Track is empty.",this),e=!1);let a=null;for(let o=0;o!==s;o++){let l=i[o];if(typeof l=="number"&&isNaN(l)){Ft("KeyframeTrack: Time is not a valid number.",this,o,l),e=!1;break}if(a!==null&&a>l){Ft("KeyframeTrack: Out of order keys.",this,o,l,a),e=!1;break}a=l}if(r!==void 0&&oZ(r))for(let o=0,l=r.length;o!==l;++o){let c=r[o];if(isNaN(c)){Ft("KeyframeTrack: Value is not a valid number.",this,o,c),e=!1;break}}return e}optimize(){let e=this.times.slice(),t=this.values.slice(),i=this.getValueSize(),r=this.getInterpolation()===Zv,s=e.length-1,a=1;for(let o=1;o0){e[a]=e[s];for(let o=s*i,l=a*i,c=0;c!==i;++c)t[l+c]=t[o+c];++a}return a!==e.length?(this.times=e.slice(0,a),this.values=t.slice(0,a*i)):(this.times=e,this.values=t),this}clone(){let e=this.times.slice(),t=this.values.slice(),i=this.constructor,r=new i(this.name,e,t);return r.createInterpolant=this.createInterpolant,r}};ms.prototype.ValueTypeName="";ms.prototype.TimeBufferType=Float32Array;ms.prototype.ValueBufferType=Float32Array;ms.prototype.DefaultInterpolation=dh;yl=class extends ms{constructor(e,t,i){super(e,t,i)}};yl.prototype.ValueTypeName="bool";yl.prototype.ValueBufferType=Array;yl.prototype.DefaultInterpolation=hh;yl.prototype.InterpolantFactoryMethodLinear=void 0;yl.prototype.InterpolantFactoryMethodSmooth=void 0;n_=class extends ms{constructor(e,t,i,r){super(e,t,i,r)}};n_.prototype.ValueTypeName="color";Fo=class extends ms{constructor(e,t,i,r){super(e,t,i,r)}};Fo.prototype.ValueTypeName="number";SE=class extends wo{constructor(e,t,i,r){super(e,t,i,r)}interpolate_(e,t,i,r){let s=this.resultBuffer,a=this.sampleValues,o=this.valueSize,l=(i-t)/(r-t),c=e*o;for(let f=c+o;c!==f;c+=4)Zr.slerpFlat(s,0,a,c-o,a,c,l);return s}},Bo=class extends ms{constructor(e,t,i,r){super(e,t,i,r)}InterpolantFactoryMethodLinear(e){return new SE(this.times,this.values,this.getValueSize(),e)}};Bo.prototype.ValueTypeName="quaternion";Bo.prototype.InterpolantFactoryMethodSmooth=void 0;Pl=class extends ms{constructor(e,t,i){super(e,t,i)}};Pl.prototype.ValueTypeName="string";Pl.prototype.ValueBufferType=Array;Pl.prototype.DefaultInterpolation=hh;Pl.prototype.InterpolantFactoryMethodLinear=void 0;Pl.prototype.InterpolantFactoryMethodSmooth=void 0;Uo=class extends ms{constructor(e,t,i,r){super(e,t,i,r)}};Uo.prototype.ValueTypeName="vector";Eh=class{constructor(e="",t=-1,i=[],r=pS){this.name=e,this.tracks=i,this.duration=t,this.blendMode=r,this.uuid=za(),this.userData={},this.duration<0&&this.resetDuration()}static parse(e){let t=[],i=e.tracks,r=1/(e.fps||1);for(let a=0,o=i.length;a!==o;++a)t.push(ZZ(i[a]).scale(r));let s=new this(e.name,e.duration,t,e.blendMode);return s.uuid=e.uuid,s.userData=JSON.parse(e.userData||"{}"),s}static toJSON(e){let t=[],i=e.tracks,r={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode,userData:JSON.stringify(e.userData)};for(let s=0,a=i.length;s!==a;++s)t.push(ms.toJSON(i[s]));return r}static CreateFromMorphTargetSequence(e,t,i,r){let s=t.length,a=[];for(let o=0;o1){let h=f[1],d=r[h];d||(r[h]=d=[]),d.push(c)}}let a=[];for(let o in r)a.push(this.CreateFromMorphTargetSequence(o,r[o],t,i));return a}static parseAnimation(e,t){if(Mt("AnimationClip: parseAnimation() is deprecated and will be removed with r185"),!e)return Ft("AnimationClip: No animation in JSONLoader data."),null;let i=function(h,d,u,m,p){if(u.length!==0){let _=[],g=[];WF(u,_,g,m),_.length!==0&&p.push(new h(d,_,g))}},r=[],s=e.name||"default",a=e.fps||30,o=e.blendMode,l=e.length||-1,c=e.hierarchy||[];for(let h=0;h{t&&t(s),this.manager.itemEnd(e)},0);return}if(bl[e]!==void 0){bl[e].push({onLoad:t,onProgress:i,onError:r});return}bl[e]=[],bl[e].push({onLoad:t,onProgress:i,onError:r});let 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&&Mt("FileLoader: HTTP Status 0 received."),typeof ReadableStream=="undefined"||c.body===void 0||c.body.getReader===void 0)return c;let f=bl[e],h=c.body.getReader(),d=c.headers.get("X-File-Size")||c.headers.get("Content-Length"),u=d?parseInt(d):0,m=u!==0,p=0,_=new ReadableStream({start(g){v();function v(){h.read().then(({done:x,value:A})=>{if(x)g.close();else{p+=A.byteLength;let S=new ProgressEvent("progress",{lengthComputable:m,loaded:p,total:u});for(let E=0,R=f.length;E{g.error(x)})}}});return new Response(_)}else throw new E0(`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(f=>new DOMParser().parseFromString(f,o));case"json":return c.json();default:if(o==="")return c.text();{let h=/charset="?([^;"\s]*)"?/i.exec(o),d=h&&h[1]?h[1].toLowerCase():void 0,u=new TextDecoder(d);return c.arrayBuffer().then(m=>u.decode(m))}}}).then(c=>{Po.add(`file:${e}`,c);let f=bl[e];delete bl[e];for(let h=0,d=f.length;h{let f=bl[e];if(f===void 0)throw this.manager.itemError(e),c;delete bl[e];for(let h=0,d=f.length;h{this.manager.itemEnd(e)}),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}},nu=new WeakMap,AE=class extends cn{constructor(e){super(e)}load(e,t,i,r){this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let s=this,a=Po.get(`image:${e}`);if(a!==void 0){if(a.complete===!0)s.manager.itemStart(e),setTimeout(function(){t&&t(a),s.manager.itemEnd(e)},0);else{let h=nu.get(a);h===void 0&&(h=[],nu.set(a,h)),h.push({onLoad:t,onError:r})}return a}let o=fu("img");function l(){f(),t&&t(this);let h=nu.get(this)||[];for(let d=0;d{m0.has(a)===!0?(r&&r(m0.get(a)),s.manager.itemError(e),s.manager.itemEnd(e)):(t&&t(c),s.manager.itemEnd(e))});return}setTimeout(function(){t&&t(a),s.manager.itemEnd(e)},0);return}let 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;let l=fetch(e,o).then(function(c){return c.blob()}).then(function(c){return createImageBitmap(c,Object.assign(s.options,{colorSpaceConversion:"none"}))}).then(function(c){Po.add(`image-bitmap:${e}`,c),t&&t(c),s.manager.itemEnd(e)}).catch(function(c){r&&r(c),m0.set(l,c),Po.remove(`image-bitmap:${e}`),s.manager.itemError(e),s.manager.itemEnd(e)});Po.add(`image-bitmap:${e}`,l),s.manager.itemStart(e)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}},su=-90,au=1,xE=class extends er{constructor(e,t,i){super(),this.type="CubeCamera",this.renderTarget=i,this.coordinateSystem=null,this.activeMipmapLevel=0;let r=new kr(su,au,e,t);r.layers=this.layers,this.add(r);let s=new kr(su,au,e,t);s.layers=this.layers,this.add(s);let a=new kr(su,au,e,t);a.layers=this.layers,this.add(a);let o=new kr(su,au,e,t);o.layers=this.layers,this.add(o);let l=new kr(su,au,e,t);l.layers=this.layers,this.add(l);let c=new kr(su,au,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){let e=this.coordinateSystem,t=this.children.concat(),[i,r,s,a,o,l]=t;for(let c of t)this.remove(c);if(e===Ha)i.up.set(0,1,0),i.lookAt(1,0,0),r.up.set(0,1,0),r.lookAt(-1,0,0),s.up.set(0,0,-1),s.lookAt(0,1,0),a.up.set(0,0,1),a.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),l.up.set(0,1,0),l.lookAt(0,0,-1);else if(e===cu)i.up.set(0,-1,0),i.lookAt(-1,0,0),r.up.set(0,-1,0),r.lookAt(1,0,0),s.up.set(0,0,1),s.lookAt(0,1,0),a.up.set(0,0,-1),a.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),l.up.set(0,-1,0),l.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(let c of t)this.add(c),c.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();let{renderTarget:i,activeMipmapLevel:r}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());let[s,a,o,l,c,f]=this.children,h=e.getRenderTarget(),d=e.getActiveCubeFace(),u=e.getActiveMipmapLevel(),m=e.xr.enabled;e.xr.enabled=!1;let p=i.texture.generateMipmaps;i.texture.generateMipmaps=!1;let _=!1;e.isWebGLRenderer===!0?_=e.state.buffers.depth.getReversed():_=e.reversedDepthBuffer,e.setRenderTarget(i,0,r),_&&e.autoClear===!1&&e.clearDepth(),e.render(t,s),e.setRenderTarget(i,1,r),_&&e.autoClear===!1&&e.clearDepth(),e.render(t,a),e.setRenderTarget(i,2,r),_&&e.autoClear===!1&&e.clearDepth(),e.render(t,o),e.setRenderTarget(i,3,r),_&&e.autoClear===!1&&e.clearDepth(),e.render(t,l),e.setRenderTarget(i,4,r),_&&e.autoClear===!1&&e.clearDepth(),e.render(t,c),i.texture.generateMipmaps=p,e.setRenderTarget(i,5,r),_&&e.autoClear===!1&&e.clearDepth(),e.render(t,f),e.setRenderTarget(h,d,u),e.xr.enabled=m,i.texture.needsPMREMUpdate=!0}},RE=class extends kr{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}},bE=class{constructor(e,t,i){this.binding=e,this.valueSize=i;let r,s,a;switch(t){case"quaternion":r=this._slerp,s=this._slerpAdditive,a=this._setAdditiveIdentityQuaternion,this.buffer=new Float64Array(i*6),this._workIndex=5;break;case"string":case"bool":r=this._select,s=this._select,a=this._setAdditiveIdentityOther,this.buffer=new Array(i*5);break;default:r=this._lerp,s=this._lerpAdditive,a=this._setAdditiveIdentityNumeric,this.buffer=new Float64Array(i*5)}this._mixBufferRegion=r,this._mixBufferRegionAdditive=s,this._setIdentity=a,this._origIndex=3,this._addIndex=4,this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,this.useCount=0,this.referenceCount=0}accumulate(e,t){let i=this.buffer,r=this.valueSize,s=e*r+r,a=this.cumulativeWeight;if(a===0){for(let o=0;o!==r;++o)i[s+o]=i[o];a=t}else{a+=t;let o=t/a;this._mixBufferRegion(i,s,0,o,r)}this.cumulativeWeight=a}accumulateAdditive(e){let t=this.buffer,i=this.valueSize,r=i*this._addIndex;this.cumulativeWeightAdditive===0&&this._setIdentity(),this._mixBufferRegionAdditive(t,r,0,e,i),this.cumulativeWeightAdditive+=e}apply(e){let t=this.valueSize,i=this.buffer,r=e*t+t,s=this.cumulativeWeight,a=this.cumulativeWeightAdditive,o=this.binding;if(this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,s<1){let l=t*this._origIndex;this._mixBufferRegion(i,r,l,1-s,t)}a>0&&this._mixBufferRegionAdditive(i,r,this._addIndex*t,1,t);for(let l=t,c=t+t;l!==c;++l)if(i[l]!==i[l+t]){o.setValue(i,r);break}}saveOriginalState(){let e=this.binding,t=this.buffer,i=this.valueSize,r=i*this._origIndex;e.getValue(t,r);for(let s=i,a=r;s!==a;++s)t[s]=t[r+s%i];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){let e=this.valueSize*3;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){let e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let i=e;i=.5)for(let a=0;a!==s;++a)e[t+a]=e[i+a]}_slerp(e,t,i,r){Zr.slerpFlat(e,t,e,t,e,i,r)}_slerpAdditive(e,t,i,r,s){let a=this._workIndex*s;Zr.multiplyQuaternionsFlat(e,a,e,t,e,i),Zr.slerpFlat(e,t,e,t,e,a,r)}_lerp(e,t,i,r,s){let a=1-r;for(let o=0;o!==s;++o){let l=t+o;e[l]=e[l]*a+e[i+o]*r}}_lerpAdditive(e,t,i,r,s){for(let a=0;a!==s;++a){let o=t+a;e[o]=e[o]+e[i+a]*r}}},j0="\\[\\]\\.:\\/",QZ=new RegExp("["+j0+"]","g"),q0="[^"+j0+"]",$Z="[^"+j0.replace("\\.","")+"]",JZ=/((?:WC+[\/:])*)/.source.replace("WC",q0),eQ=/(WCOD+)?/.source.replace("WCOD",$Z),tQ=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",q0),iQ=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",q0),rQ=new RegExp("^"+JZ+eQ+tQ+iQ+"$"),nQ=["material","materials","bones","map"],x0=class{constructor(e,t,i){let r=i||qi.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,r)}getValue(e,t){this.bind();let i=this._targetGroup.nCachedObjects_,r=this._bindings[i];r!==void 0&&r.getValue(e,t)}setValue(e,t){let i=this._bindings;for(let r=this._targetGroup.nCachedObjects_,s=i.length;r!==s;++r)i[r].setValue(e,t)}bind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,i=e.length;t!==i;++t)e[t].bind()}unbind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,i=e.length;t!==i;++t)e[t].unbind()}},qi=class n{constructor(e,t,i){this.path=t,this.parsedPath=i||n.parseTrackName(t),this.node=n.findNode(e,this.parsedPath.nodeName),this.rootNode=e,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(e,t,i){return e&&e.isAnimationObjectGroup?new n.Composite(e,t,i):new n(e,t,i)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(QZ,"")}static parseTrackName(e){let t=rQ.exec(e);if(t===null)throw new Error("PropertyBinding: Cannot parse trackName: "+e);let i={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},r=i.nodeName&&i.nodeName.lastIndexOf(".");if(r!==void 0&&r!==-1){let s=i.nodeName.substring(r+1);nQ.indexOf(s)!==-1&&(i.nodeName=i.nodeName.substring(0,r),i.objectName=s)}if(i.propertyName===null||i.propertyName.length===0)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+e);return i}static findNode(e,t){if(t===void 0||t===""||t==="."||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){let i=e.skeleton.getBoneByName(t);if(i!==void 0)return i}if(e.children){let i=function(s){for(let a=0;a0){let l=this._interpolants,c=this._propertyBindings;switch(this.blendMode){case IF:for(let f=0,h=l.length;f!==h;++f)l[f].evaluate(a),c[f].accumulateAdditive(o);break;case pS:default:for(let f=0,h=l.length;f!==h;++f)l[f].evaluate(a),c[f].accumulate(r,o)}}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;let i=this._weightInterpolant;if(i!==null){let r=i.evaluate(e)[0];t*=r,e>i.parameterPositions[1]&&(this.stopFading(),r===0&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;let i=this._timeScaleInterpolant;if(i!==null){let r=i.evaluate(e)[0];t*=r,e>i.parameterPositions[1]&&(this.stopWarping(),t===0?this.paused=!0:this.timeScale=t)}}return this._effectiveTimeScale=t,t}_updateTime(e){let t=this._clip.duration,i=this.loop,r=this.time+e,s=this._loopCount,a=i===bF;if(e===0)return s===-1?r:a&&(s&1)===1?t-r:r;if(i===xF){s===-1&&(this._loopCount=0,this._setEndings(!0,!0,!1));e:{if(r>=t)r=t;else if(r<0)r=0;else{this.time=r;break e}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=r,this._mixer.dispatchEvent({type:"finished",action:this,direction:e<0?-1:1})}}else{if(s===-1&&(e>=0?(s=0,this._setEndings(!0,this.repetitions===0,a)):this._setEndings(this.repetitions===0,!0,a)),r>=t||r<0){let o=Math.floor(r/t);r-=t*o,s+=Math.abs(o);let l=this.repetitions-s;if(l<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,r=e>0?t:0,this.time=r,this._mixer.dispatchEvent({type:"finished",action:this,direction:e>0?1:-1});else{if(l===1){let c=e<0;this._setEndings(c,!c,a)}else this._setEndings(!1,!1,a);this._loopCount=s,this.time=r,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:o})}}else this._loopCount=s,this.time=r;if(a&&(s&1)===1)return t-r}return r}_setEndings(e,t,i){let r=this._interpolantSettings;i?(r.endingStart=lh,r.endingEnd=lh):(e?r.endingStart=this.zeroSlopeAtStart?lh:oh:r.endingStart=Wp,t?r.endingEnd=this.zeroSlopeAtEnd?lh:oh:r.endingEnd=Wp)}_scheduleFading(e,t,i){let r=this._mixer,s=r.time,a=this._weightInterpolant;a===null&&(a=r._lendControlInterpolant(),this._weightInterpolant=a);let o=a.parameterPositions,l=a.sampleValues;return o[0]=s,l[0]=t,o[1]=s+e,l[1]=i,this}},sQ=new Float32Array(1),l_=class extends da{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1,typeof __THREE_DEVTOOLS__!="undefined"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}_bindAction(e,t){let i=e._localRoot||this._root,r=e._clip.tracks,s=r.length,a=e._propertyBindings,o=e._interpolants,l=i.uuid,c=this._bindingsByRootAndName,f=c[l];f===void 0&&(f={},c[l]=f);for(let h=0;h!==s;++h){let d=r[h],u=d.name,m=f[u];if(m!==void 0)++m.referenceCount,a[h]=m;else{if(m=a[h],m!==void 0){m._cacheIndex===null&&(++m.referenceCount,this._addInactiveBinding(m,l,u));continue}let p=t&&t._propertyBindings[h].binding.parsedPath;m=new bE(qi.create(i,u,p),d.ValueTypeName,d.getValueSize()),++m.referenceCount,this._addInactiveBinding(m,l,u),a[h]=m}o[h].resultBuffer=m.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(e._cacheIndex===null){let i=(e._localRoot||this._root).uuid,r=e._clip.uuid,s=this._actionsByClip[r];this._bindAction(e,s&&s.knownActions[0]),this._addInactiveAction(e,r,i)}let t=e._propertyBindings;for(let i=0,r=t.length;i!==r;++i){let s=t[i];s.useCount++===0&&(this._lendBinding(s),s.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){let t=e._propertyBindings;for(let i=0,r=t.length;i!==r;++i){let s=t[i];--s.useCount===0&&(s.restoreOriginalState(),this._takeBackBinding(s))}this._takeBackAction(e)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;let e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}}}_isActiveAction(e){let t=e._cacheIndex;return t!==null&&t=0;--i)e[i].stop();return this}update(e){e*=this.timeScale;let t=this._actions,i=this._nActiveActions,r=this.time+=e,s=Math.sign(e),a=this._accuIndex^=1;for(let c=0;c!==i;++c)t[c]._update(r,e,s,a);let o=this._bindings,l=this._nActiveBindings;for(let c=0;c!==l;++c)o[c].apply(a);return this}setTime(e){this.time=0;for(let t=0;tu.start-m.start);let d=0;for(let u=1;u0;x=e.get(x,A)}return x}function m(v){let x=!1,A=u(v);A===null?_(a,o):A&&A.isColor&&(_(A,1),x=!0);let S=n.xr.getEnvironmentBlendMode();S==="additive"?t.buffers.color.setClear(0,0,0,1,s):S==="alpha-blend"&&t.buffers.color.setClear(0,0,0,0,s),(n.autoClear||x)&&(t.buffers.depth.setTest(!0),t.buffers.depth.setMask(!0),t.buffers.color.setMask(!0),n.clear(n.autoClearColor,n.autoClearDepth,n.autoClearStencil))}function p(v,x){let A=u(x);A&&(A.isCubeTexture||A.mapping===u_)?(c===void 0&&(c=new ii(new Yc(1,1,1),new Ws({name:"BackgroundCubeMaterial",uniforms:xh(zo.backgroundCube.uniforms),vertexShader:zo.backgroundCube.vertexShader,fragmentShader:zo.backgroundCube.fragmentShader,side:pn,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute("normal"),c.geometry.deleteAttribute("uv"),c.onBeforeRender=function(S,E,R){this.matrixWorld.copyPosition(R.matrixWorld)},Object.defineProperty(c.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),i.update(c)),c.material.uniforms.envMap.value=A,c.material.uniforms.backgroundBlurriness.value=x.backgroundBlurriness,c.material.uniforms.backgroundIntensity.value=x.backgroundIntensity,c.material.uniforms.backgroundRotation.value.setFromMatrix4(HJ.makeRotationFromEuler(x.backgroundRotation)).transpose(),A.isCubeTexture&&A.isRenderTargetTexture===!1&&c.material.uniforms.backgroundRotation.value.premultiply(d1),c.material.toneMapped=ai.getTransfer(A.colorSpace)!==Xi,(f!==A||h!==A.version||d!==n.toneMapping)&&(c.material.needsUpdate=!0,f=A,h=A.version,d=n.toneMapping),c.layers.enableAll(),v.unshift(c,c.geometry,c.material,0,0,null)):A&&A.isTexture&&(l===void 0&&(l=new ii(new gh(2,2),new Ws({name:"BackgroundMaterial",uniforms:xh(zo.background.uniforms),vertexShader:zo.background.vertexShader,fragmentShader:zo.background.fragmentShader,side:Gs,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),i.update(l)),l.material.uniforms.t2D.value=A,l.material.uniforms.backgroundIntensity.value=x.backgroundIntensity,l.material.toneMapped=ai.getTransfer(A.colorSpace)!==Xi,A.matrixAutoUpdate===!0&&A.updateMatrix(),l.material.uniforms.uvTransform.value.copy(A.matrix),(f!==A||h!==A.version||d!==n.toneMapping)&&(l.material.needsUpdate=!0,f=A,h=A.version,d=n.toneMapping),l.layers.enableAll(),v.unshift(l,l.geometry,l.material,0,0,null))}function _(v,x){v.getRGB(ES,K0(n)),t.buffers.color.setClear(ES.r,ES.g,ES.b,x,s)}function g(){c!==void 0&&(c.geometry.dispose(),c.material.dispose(),c=void 0),l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0)}return{getClearColor:function(){return a},setClearColor:function(v,x=1){a.set(v),o=x,_(a,o)},getClearAlpha:function(){return o},setClearAlpha:function(v){o=v,_(a,o)},render:m,addToRenderList:p,dispose:g}}function XJ(n,e){let t=n.getParameter(n.MAX_VERTEX_ATTRIBS),i={},r=d(null),s=r,a=!1;function o(D,O,V,N,F){let U=!1,k=h(D,N,V,O);s!==k&&(s=k,c(s.object)),U=u(D,N,V,F),U&&m(D,N,V,F),F!==null&&e.update(F,n.ELEMENT_ARRAY_BUFFER),(U||a)&&(a=!1,A(D,O,V,N),F!==null&&n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,e.get(F).buffer))}function l(){return n.createVertexArray()}function c(D){return n.bindVertexArray(D)}function f(D){return n.deleteVertexArray(D)}function h(D,O,V,N){let F=N.wireframe===!0,U=i[O.id];U===void 0&&(U={},i[O.id]=U);let k=D.isInstancedMesh===!0?D.id:0,ee=U[k];ee===void 0&&(ee={},U[k]=ee);let q=ee[V.id];q===void 0&&(q={},ee[V.id]=q);let Q=q[F];return Q===void 0&&(Q=d(l()),q[F]=Q),Q}function d(D){let O=[],V=[],N=[];for(let F=0;F=0){let Y=F[q],K=U[q];if(K===void 0&&(q==="instanceMatrix"&&D.instanceMatrix&&(K=D.instanceMatrix),q==="instanceColor"&&D.instanceColor&&(K=D.instanceColor)),Y===void 0||Y.attribute!==K||K&&Y.data!==K.data)return!0;k++}return s.attributesNum!==k||s.index!==N}function m(D,O,V,N){let F={},U=O.attributes,k=0,ee=V.getAttributes();for(let q in ee)if(ee[q].location>=0){let Y=U[q];Y===void 0&&(q==="instanceMatrix"&&D.instanceMatrix&&(Y=D.instanceMatrix),q==="instanceColor"&&D.instanceColor&&(Y=D.instanceColor));let K={};K.attribute=Y,Y&&Y.data&&(K.data=Y.data),F[q]=K,k++}s.attributes=F,s.attributesNum=k,s.index=N}function p(){let D=s.newAttributes;for(let O=0,V=D.length;O=0){let Q=F[ee];if(Q===void 0&&(ee==="instanceMatrix"&&D.instanceMatrix&&(Q=D.instanceMatrix),ee==="instanceColor"&&D.instanceColor&&(Q=D.instanceColor)),Q!==void 0){let Y=Q.normalized,K=Q.itemSize,de=e.get(Q);if(de===void 0)continue;let Re=de.buffer,Fe=de.type,se=de.bytesPerElement,ue=Fe===n.INT||Fe===n.UNSIGNED_INT||Q.gpuType===LE;if(Q.isInterleavedBufferAttribute){let re=Q.data,he=re.stride,De=Q.offset;if(re.isInstancedInterleavedBuffer){for(let fe=0;fe0&&n.getShaderPrecisionFormat(n.FRAGMENT_SHADER,n.HIGH_FLOAT).precision>0)return"highp";R="mediump"}return R==="mediump"&&n.getShaderPrecisionFormat(n.VERTEX_SHADER,n.MEDIUM_FLOAT).precision>0&&n.getShaderPrecisionFormat(n.FRAGMENT_SHADER,n.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let c=t.precision!==void 0?t.precision:"highp",f=l(c);f!==c&&(Mt("WebGLRenderer:",c,"not supported, using",f,"instead."),c=f);let h=t.logarithmicDepthBuffer===!0,d=t.reversedDepthBuffer===!0&&e.has("EXT_clip_control");t.reversedDepthBuffer===!0&&d===!1&&Mt("WebGLRenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer.");let u=n.getParameter(n.MAX_TEXTURE_IMAGE_UNITS),m=n.getParameter(n.MAX_VERTEX_TEXTURE_IMAGE_UNITS),p=n.getParameter(n.MAX_TEXTURE_SIZE),_=n.getParameter(n.MAX_CUBE_MAP_TEXTURE_SIZE),g=n.getParameter(n.MAX_VERTEX_ATTRIBS),v=n.getParameter(n.MAX_VERTEX_UNIFORM_VECTORS),x=n.getParameter(n.MAX_VARYING_VECTORS),A=n.getParameter(n.MAX_FRAGMENT_UNIFORM_VECTORS),S=n.getParameter(n.MAX_SAMPLES),E=n.getParameter(n.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:s,getMaxPrecision:l,textureFormatReadable:a,textureTypeReadable:o,precision:c,logarithmicDepthBuffer:h,reversedDepthBuffer:d,maxTextures:u,maxVertexTextures:m,maxTextureSize:p,maxCubemapSize:_,maxAttributes:g,maxVertexUniforms:v,maxVaryings:x,maxFragmentUniforms:A,maxSamples:S,samples:E}}function jJ(n){let e=this,t=null,i=0,r=!1,s=!1,a=new fa,o=new ti,l={value:null,needsUpdate:!1};this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(h,d){let u=h.length!==0||d||i!==0||r;return r=d,i=h.length,u},this.beginShadows=function(){s=!0,f(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(h,d){t=f(h,d,0)},this.setState=function(h,d,u){let m=h.clippingPlanes,p=h.clipIntersection,_=h.clipShadows,g=n.get(h);if(!r||m===null||m.length===0||s&&!_)s?f(null):c();else{let v=s?0:i,x=v*4,A=g.clippingState||null;l.value=A,A=f(m,d,x,u);for(let S=0;S!==x;++S)A[S]=t[S];g.clippingState=A,this.numIntersection=p?this.numPlanes:0,this.numPlanes+=v}};function c(){l.value!==t&&(l.value=t,l.needsUpdate=i>0),e.numPlanes=i,e.numIntersection=0}function f(h,d,u,m){let p=h!==null?h.length:0,_=null;if(p!==0){if(_=l.value,m!==!0||_===null){let g=u+p*4,v=d.matrixWorldInverse;o.getNormalMatrix(v),(_===null||_.lengthn-ef?l=HF[a-n+ef-1]:a===0&&(l=0),t.push(l);let c=1/(o-2),f=-c,h=1+c,d=[f,f,h,f,h,h,f,f,h,h,f,h],u=6,m=6,p=3,_=2,g=1,v=new Float32Array(p*m*u),x=new Float32Array(_*m*u),A=new Float32Array(g*m*u);for(let E=0;E2?0:-1,y=[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];v.set(y,p*m*E),x.set(d,_*m*E);let M=[E,E,E,E,E,E];A.set(M,g*m*E)}let S=new Ui;S.setAttribute("position",new or(v,p)),S.setAttribute("uv",new or(x,_)),S.setAttribute("faceIndex",new or(A,g)),i.push(new ii(S,null)),r>ef&&r--}return{lodMeshes:i,sizeLods:e,sigmas:t}}function XF(n,e,t){let i=new ks(n,e,t);return i.texture.mapping=u_,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function Pu(n,e,t,i,r){n.viewport.set(e,t,i,r),n.scissor.set(e,t,i,r)}function $J(n,e,t){return new Ws({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:qJ,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${n}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:xS(),fragmentShader:` +}`,ks=class extends Or{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=YZ,this.fragmentShader=KZ,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,multiDraw:!1},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=xh(e.uniforms),this.uniformsGroups=XZ(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.defaultAttributeValues=Object.assign({},e.defaultAttributeValues),this.index0AttributeName=e.index0AttributeName,this.uniformsNeedUpdate=e.uniformsNeedUpdate,this}toJSON(e){let t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(let r in this.uniforms){let a=this.uniforms[r].value;a&&a.isTexture?t.uniforms[r]={type:"t",value:a.toJSON(e).uuid}:a&&a.isColor?t.uniforms[r]={type:"c",value:a.getHex()}:a&&a.isVector2?t.uniforms[r]={type:"v2",value:a.toArray()}:a&&a.isVector3?t.uniforms[r]={type:"v3",value:a.toArray()}:a&&a.isVector4?t.uniforms[r]={type:"v4",value:a.toArray()}:a&&a.isMatrix3?t.uniforms[r]={type:"m3",value:a.toArray()}:a&&a.isMatrix4?t.uniforms[r]={type:"m4",value:a.toArray()}:t.uniforms[r]={value:a}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;let i={};for(let r in this.extensions)this.extensions[r]===!0&&(i[r]=!0);return Object.keys(i).length>0&&(t.extensions=i),t}},pE=class extends ks{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}},Cn=class extends Or{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new ft(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 ft(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Cu,this.normalScale=new It(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 Xa,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}},ds=class extends Cn{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 It(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return mi(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(t){this.ior=(1+.4*t)/(1-.4*t)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new ft(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 ft(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new ft(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)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}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}},vh=class extends Or{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new ft(16777215),this.specular=new ft(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ft(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Cu,this.normalScale=new It(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Xa,this.combine=d_,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.envMapIntensity=e.envMapIntensity,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}},i_=class extends Or{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new ft(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ft(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Cu,this.normalScale=new It(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Xa,this.combine=d_,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=.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.envMapIntensity=e.envMapIntensity,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}},_E=class extends Or{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=MF,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}},gE=class extends Or{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}};wo=class{constructor(e,t,i,r){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=r!==void 0?r:new t.constructor(i),this.sampleValues=t,this.valueSize=i,this.settings=null,this.DefaultSettings_={}}evaluate(e){let t=this.parameterPositions,i=this._cachedIndex,r=t[i],s=t[i-1];e:{t:{let a;i:{r:if(!(e=s)){let o=t[1];e=s)break t}a=i,i=0;break i}break e}for(;i>>1;et;)--a;if(++a,s!==0||a!==r){s>=a&&(a=Math.max(a,1),s=a-1);let o=this.getValueSize();this.times=i.slice(s,a),this.values=this.values.slice(s*o,a*o)}return this}validate(){let e=!0,t=this.getValueSize();t-Math.floor(t)!==0&&(Bt("KeyframeTrack: Invalid value size in track.",this),e=!1);let i=this.times,r=this.values,s=i.length;s===0&&(Bt("KeyframeTrack: Track is empty.",this),e=!1);let a=null;for(let o=0;o!==s;o++){let l=i[o];if(typeof l=="number"&&isNaN(l)){Bt("KeyframeTrack: Time is not a valid number.",this,o,l),e=!1;break}if(a!==null&&a>l){Bt("KeyframeTrack: Out of order keys.",this,o,l,a),e=!1;break}a=l}if(r!==void 0&&oZ(r))for(let o=0,l=r.length;o!==l;++o){let c=r[o];if(isNaN(c)){Bt("KeyframeTrack: Value is not a valid number.",this,o,c),e=!1;break}}return e}optimize(){let e=this.times.slice(),t=this.values.slice(),i=this.getValueSize(),r=this.getInterpolation()===Qv,s=e.length-1,a=1;for(let o=1;o0){e[a]=e[s];for(let o=s*i,l=a*i,c=0;c!==i;++c)t[l+c]=t[o+c];++a}return a!==e.length?(this.times=e.slice(0,a),this.values=t.slice(0,a*i)):(this.times=e,this.values=t),this}clone(){let e=this.times.slice(),t=this.values.slice(),i=this.constructor,r=new i(this.name,e,t);return r.createInterpolant=this.createInterpolant,r}};us.prototype.ValueTypeName="";us.prototype.TimeBufferType=Float32Array;us.prototype.ValueBufferType=Float32Array;us.prototype.DefaultInterpolation=dh;Cl=class extends us{constructor(e,t,i){super(e,t,i)}};Cl.prototype.ValueTypeName="bool";Cl.prototype.ValueBufferType=Array;Cl.prototype.DefaultInterpolation=hh;Cl.prototype.InterpolantFactoryMethodLinear=void 0;Cl.prototype.InterpolantFactoryMethodSmooth=void 0;n_=class extends us{constructor(e,t,i,r){super(e,t,i,r)}};n_.prototype.ValueTypeName="color";Fo=class extends us{constructor(e,t,i,r){super(e,t,i,r)}};Fo.prototype.ValueTypeName="number";TE=class extends wo{constructor(e,t,i,r){super(e,t,i,r)}interpolate_(e,t,i,r){let s=this.resultBuffer,a=this.sampleValues,o=this.valueSize,l=(i-t)/(r-t),c=e*o;for(let f=c+o;c!==f;c+=4)Zr.slerpFlat(s,0,a,c-o,a,c,l);return s}},Bo=class extends us{constructor(e,t,i,r){super(e,t,i,r)}InterpolantFactoryMethodLinear(e){return new TE(this.times,this.values,this.getValueSize(),e)}};Bo.prototype.ValueTypeName="quaternion";Bo.prototype.InterpolantFactoryMethodSmooth=void 0;yl=class extends us{constructor(e,t,i){super(e,t,i)}};yl.prototype.ValueTypeName="string";yl.prototype.ValueBufferType=Array;yl.prototype.DefaultInterpolation=hh;yl.prototype.InterpolantFactoryMethodLinear=void 0;yl.prototype.InterpolantFactoryMethodSmooth=void 0;Uo=class extends us{constructor(e,t,i,r){super(e,t,i,r)}};Uo.prototype.ValueTypeName="vector";Eh=class{constructor(e="",t=-1,i=[],r=_S){this.name=e,this.tracks=i,this.duration=t,this.blendMode=r,this.uuid=za(),this.userData={},this.duration<0&&this.resetDuration()}static parse(e){let t=[],i=e.tracks,r=1/(e.fps||1);for(let a=0,o=i.length;a!==o;++a)t.push(ZZ(i[a]).scale(r));let s=new this(e.name,e.duration,t,e.blendMode);return s.uuid=e.uuid,s.userData=JSON.parse(e.userData||"{}"),s}static toJSON(e){let t=[],i=e.tracks,r={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode,userData:JSON.stringify(e.userData)};for(let s=0,a=i.length;s!==a;++s)t.push(us.toJSON(i[s]));return r}static CreateFromMorphTargetSequence(e,t,i,r){let s=t.length,a=[];for(let o=0;o1){let h=f[1],d=r[h];d||(r[h]=d=[]),d.push(c)}}let a=[];for(let o in r)a.push(this.CreateFromMorphTargetSequence(o,r[o],t,i));return a}static parseAnimation(e,t){if(Ct("AnimationClip: parseAnimation() is deprecated and will be removed with r185"),!e)return Bt("AnimationClip: No animation in JSONLoader data."),null;let i=function(h,d,u,m,p){if(u.length!==0){let _=[],g=[];WF(u,_,g,m),_.length!==0&&p.push(new h(d,_,g))}},r=[],s=e.name||"default",a=e.fps||30,o=e.blendMode,l=e.length||-1,c=e.hierarchy||[];for(let h=0;h{t&&t(s),this.manager.itemEnd(e)},0);return}if(Rl[e]!==void 0){Rl[e].push({onLoad:t,onProgress:i,onError:r});return}Rl[e]=[],Rl[e].push({onLoad:t,onProgress:i,onError:r});let 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&&Ct("FileLoader: HTTP Status 0 received."),typeof ReadableStream=="undefined"||c.body===void 0||c.body.getReader===void 0)return c;let f=Rl[e],h=c.body.getReader(),d=c.headers.get("X-File-Size")||c.headers.get("Content-Length"),u=d?parseInt(d):0,m=u!==0,p=0,_=new ReadableStream({start(g){v();function v(){h.read().then(({done:x,value:A})=>{if(x)g.close();else{p+=A.byteLength;let S=new ProgressEvent("progress",{lengthComputable:m,loaded:p,total:u});for(let E=0,R=f.length;E{g.error(x)})}}});return new Response(_)}else throw new E0(`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(f=>new DOMParser().parseFromString(f,o));case"json":return c.json();default:if(o==="")return c.text();{let h=/charset="?([^;"\s]*)"?/i.exec(o),d=h&&h[1]?h[1].toLowerCase():void 0,u=new TextDecoder(d);return c.arrayBuffer().then(m=>u.decode(m))}}}).then(c=>{Po.add(`file:${e}`,c);let f=Rl[e];delete Rl[e];for(let h=0,d=f.length;h{let f=Rl[e];if(f===void 0)throw this.manager.itemError(e),c;delete Rl[e];for(let h=0,d=f.length;h{this.manager.itemEnd(e)}),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}},ru=new WeakMap,xE=class extends cn{constructor(e){super(e)}load(e,t,i,r){this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let s=this,a=Po.get(`image:${e}`);if(a!==void 0){if(a.complete===!0)s.manager.itemStart(e),setTimeout(function(){t&&t(a),s.manager.itemEnd(e)},0);else{let h=ru.get(a);h===void 0&&(h=[],ru.set(a,h)),h.push({onLoad:t,onError:r})}return a}let o=cu("img");function l(){f(),t&&t(this);let h=ru.get(this)||[];for(let d=0;d{m0.has(a)===!0?(r&&r(m0.get(a)),s.manager.itemError(e),s.manager.itemEnd(e)):(t&&t(c),s.manager.itemEnd(e))});return}setTimeout(function(){t&&t(a),s.manager.itemEnd(e)},0);return}let 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;let l=fetch(e,o).then(function(c){return c.blob()}).then(function(c){return createImageBitmap(c,Object.assign(s.options,{colorSpaceConversion:"none"}))}).then(function(c){Po.add(`image-bitmap:${e}`,c),t&&t(c),s.manager.itemEnd(e)}).catch(function(c){r&&r(c),m0.set(l,c),Po.remove(`image-bitmap:${e}`),s.manager.itemError(e),s.manager.itemEnd(e)});Po.add(`image-bitmap:${e}`,l),s.manager.itemStart(e)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}},nu=-90,su=1,RE=class extends ir{constructor(e,t,i){super(),this.type="CubeCamera",this.renderTarget=i,this.coordinateSystem=null,this.activeMipmapLevel=0;let r=new kr(nu,su,e,t);r.layers=this.layers,this.add(r);let s=new kr(nu,su,e,t);s.layers=this.layers,this.add(s);let a=new kr(nu,su,e,t);a.layers=this.layers,this.add(a);let o=new kr(nu,su,e,t);o.layers=this.layers,this.add(o);let l=new kr(nu,su,e,t);l.layers=this.layers,this.add(l);let c=new kr(nu,su,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){let e=this.coordinateSystem,t=this.children.concat(),[i,r,s,a,o,l]=t;for(let c of t)this.remove(c);if(e===Ha)i.up.set(0,1,0),i.lookAt(1,0,0),r.up.set(0,1,0),r.lookAt(-1,0,0),s.up.set(0,0,-1),s.lookAt(0,1,0),a.up.set(0,0,1),a.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),l.up.set(0,1,0),l.lookAt(0,0,-1);else if(e===lu)i.up.set(0,-1,0),i.lookAt(-1,0,0),r.up.set(0,-1,0),r.lookAt(1,0,0),s.up.set(0,0,1),s.lookAt(0,1,0),a.up.set(0,0,-1),a.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),l.up.set(0,-1,0),l.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(let c of t)this.add(c),c.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();let{renderTarget:i,activeMipmapLevel:r}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());let[s,a,o,l,c,f]=this.children,h=e.getRenderTarget(),d=e.getActiveCubeFace(),u=e.getActiveMipmapLevel(),m=e.xr.enabled;e.xr.enabled=!1;let p=i.texture.generateMipmaps;i.texture.generateMipmaps=!1;let _=!1;e.isWebGLRenderer===!0?_=e.state.buffers.depth.getReversed():_=e.reversedDepthBuffer,e.setRenderTarget(i,0,r),_&&e.autoClear===!1&&e.clearDepth(),e.render(t,s),e.setRenderTarget(i,1,r),_&&e.autoClear===!1&&e.clearDepth(),e.render(t,a),e.setRenderTarget(i,2,r),_&&e.autoClear===!1&&e.clearDepth(),e.render(t,o),e.setRenderTarget(i,3,r),_&&e.autoClear===!1&&e.clearDepth(),e.render(t,l),e.setRenderTarget(i,4,r),_&&e.autoClear===!1&&e.clearDepth(),e.render(t,c),i.texture.generateMipmaps=p,e.setRenderTarget(i,5,r),_&&e.autoClear===!1&&e.clearDepth(),e.render(t,f),e.setRenderTarget(h,d,u),e.xr.enabled=m,i.texture.needsPMREMUpdate=!0}},bE=class extends kr{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}},IE=class{constructor(e,t,i){this.binding=e,this.valueSize=i;let r,s,a;switch(t){case"quaternion":r=this._slerp,s=this._slerpAdditive,a=this._setAdditiveIdentityQuaternion,this.buffer=new Float64Array(i*6),this._workIndex=5;break;case"string":case"bool":r=this._select,s=this._select,a=this._setAdditiveIdentityOther,this.buffer=new Array(i*5);break;default:r=this._lerp,s=this._lerpAdditive,a=this._setAdditiveIdentityNumeric,this.buffer=new Float64Array(i*5)}this._mixBufferRegion=r,this._mixBufferRegionAdditive=s,this._setIdentity=a,this._origIndex=3,this._addIndex=4,this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,this.useCount=0,this.referenceCount=0}accumulate(e,t){let i=this.buffer,r=this.valueSize,s=e*r+r,a=this.cumulativeWeight;if(a===0){for(let o=0;o!==r;++o)i[s+o]=i[o];a=t}else{a+=t;let o=t/a;this._mixBufferRegion(i,s,0,o,r)}this.cumulativeWeight=a}accumulateAdditive(e){let t=this.buffer,i=this.valueSize,r=i*this._addIndex;this.cumulativeWeightAdditive===0&&this._setIdentity(),this._mixBufferRegionAdditive(t,r,0,e,i),this.cumulativeWeightAdditive+=e}apply(e){let t=this.valueSize,i=this.buffer,r=e*t+t,s=this.cumulativeWeight,a=this.cumulativeWeightAdditive,o=this.binding;if(this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,s<1){let l=t*this._origIndex;this._mixBufferRegion(i,r,l,1-s,t)}a>0&&this._mixBufferRegionAdditive(i,r,this._addIndex*t,1,t);for(let l=t,c=t+t;l!==c;++l)if(i[l]!==i[l+t]){o.setValue(i,r);break}}saveOriginalState(){let e=this.binding,t=this.buffer,i=this.valueSize,r=i*this._origIndex;e.getValue(t,r);for(let s=i,a=r;s!==a;++s)t[s]=t[r+s%i];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){let e=this.valueSize*3;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){let e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let i=e;i=.5)for(let a=0;a!==s;++a)e[t+a]=e[i+a]}_slerp(e,t,i,r){Zr.slerpFlat(e,t,e,t,e,i,r)}_slerpAdditive(e,t,i,r,s){let a=this._workIndex*s;Zr.multiplyQuaternionsFlat(e,a,e,t,e,i),Zr.slerpFlat(e,t,e,t,e,a,r)}_lerp(e,t,i,r,s){let a=1-r;for(let o=0;o!==s;++o){let l=t+o;e[l]=e[l]*a+e[i+o]*r}}_lerpAdditive(e,t,i,r,s){for(let a=0;a!==s;++a){let o=t+a;e[o]=e[o]+e[i+a]*r}}},j0="\\[\\]\\.:\\/",QZ=new RegExp("["+j0+"]","g"),q0="[^"+j0+"]",$Z="[^"+j0.replace("\\.","")+"]",JZ=/((?:WC+[\/:])*)/.source.replace("WC",q0),eQ=/(WCOD+)?/.source.replace("WCOD",$Z),tQ=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",q0),iQ=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",q0),rQ=new RegExp("^"+JZ+eQ+tQ+iQ+"$"),nQ=["material","materials","bones","map"],x0=class{constructor(e,t,i){let r=i||Zi.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,r)}getValue(e,t){this.bind();let i=this._targetGroup.nCachedObjects_,r=this._bindings[i];r!==void 0&&r.getValue(e,t)}setValue(e,t){let i=this._bindings;for(let r=this._targetGroup.nCachedObjects_,s=i.length;r!==s;++r)i[r].setValue(e,t)}bind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,i=e.length;t!==i;++t)e[t].bind()}unbind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,i=e.length;t!==i;++t)e[t].unbind()}},Zi=class n{constructor(e,t,i){this.path=t,this.parsedPath=i||n.parseTrackName(t),this.node=n.findNode(e,this.parsedPath.nodeName),this.rootNode=e,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(e,t,i){return e&&e.isAnimationObjectGroup?new n.Composite(e,t,i):new n(e,t,i)}static sanitizeNodeName(e){return e.replace(/\s/g,"_").replace(QZ,"")}static parseTrackName(e){let t=rQ.exec(e);if(t===null)throw new Error("PropertyBinding: Cannot parse trackName: "+e);let i={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},r=i.nodeName&&i.nodeName.lastIndexOf(".");if(r!==void 0&&r!==-1){let s=i.nodeName.substring(r+1);nQ.indexOf(s)!==-1&&(i.nodeName=i.nodeName.substring(0,r),i.objectName=s)}if(i.propertyName===null||i.propertyName.length===0)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+e);return i}static findNode(e,t){if(t===void 0||t===""||t==="."||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){let i=e.skeleton.getBoneByName(t);if(i!==void 0)return i}if(e.children){let i=function(s){for(let a=0;a0){let l=this._interpolants,c=this._propertyBindings;switch(this.blendMode){case IF:for(let f=0,h=l.length;f!==h;++f)l[f].evaluate(a),c[f].accumulateAdditive(o);break;case _S:default:for(let f=0,h=l.length;f!==h;++f)l[f].evaluate(a),c[f].accumulate(r,o)}}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;let i=this._weightInterpolant;if(i!==null){let r=i.evaluate(e)[0];t*=r,e>i.parameterPositions[1]&&(this.stopFading(),r===0&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;let i=this._timeScaleInterpolant;if(i!==null){let r=i.evaluate(e)[0];t*=r,e>i.parameterPositions[1]&&(this.stopWarping(),t===0?this.paused=!0:this.timeScale=t)}}return this._effectiveTimeScale=t,t}_updateTime(e){let t=this._clip.duration,i=this.loop,r=this.time+e,s=this._loopCount,a=i===bF;if(e===0)return s===-1?r:a&&(s&1)===1?t-r:r;if(i===xF){s===-1&&(this._loopCount=0,this._setEndings(!0,!0,!1));e:{if(r>=t)r=t;else if(r<0)r=0;else{this.time=r;break e}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=r,this._mixer.dispatchEvent({type:"finished",action:this,direction:e<0?-1:1})}}else{if(s===-1&&(e>=0?(s=0,this._setEndings(!0,this.repetitions===0,a)):this._setEndings(this.repetitions===0,!0,a)),r>=t||r<0){let o=Math.floor(r/t);r-=t*o,s+=Math.abs(o);let l=this.repetitions-s;if(l<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,r=e>0?t:0,this.time=r,this._mixer.dispatchEvent({type:"finished",action:this,direction:e>0?1:-1});else{if(l===1){let c=e<0;this._setEndings(c,!c,a)}else this._setEndings(!1,!1,a);this._loopCount=s,this.time=r,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:o})}}else this._loopCount=s,this.time=r;if(a&&(s&1)===1)return t-r}return r}_setEndings(e,t,i){let r=this._interpolantSettings;i?(r.endingStart=lh,r.endingEnd=lh):(e?r.endingStart=this.zeroSlopeAtStart?lh:oh:r.endingStart=Wp,t?r.endingEnd=this.zeroSlopeAtEnd?lh:oh:r.endingEnd=Wp)}_scheduleFading(e,t,i){let r=this._mixer,s=r.time,a=this._weightInterpolant;a===null&&(a=r._lendControlInterpolant(),this._weightInterpolant=a);let o=a.parameterPositions,l=a.sampleValues;return o[0]=s,l[0]=t,o[1]=s+e,l[1]=i,this}},sQ=new Float32Array(1),l_=class extends ha{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1,typeof __THREE_DEVTOOLS__!="undefined"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}_bindAction(e,t){let i=e._localRoot||this._root,r=e._clip.tracks,s=r.length,a=e._propertyBindings,o=e._interpolants,l=i.uuid,c=this._bindingsByRootAndName,f=c[l];f===void 0&&(f={},c[l]=f);for(let h=0;h!==s;++h){let d=r[h],u=d.name,m=f[u];if(m!==void 0)++m.referenceCount,a[h]=m;else{if(m=a[h],m!==void 0){m._cacheIndex===null&&(++m.referenceCount,this._addInactiveBinding(m,l,u));continue}let p=t&&t._propertyBindings[h].binding.parsedPath;m=new IE(Zi.create(i,u,p),d.ValueTypeName,d.getValueSize()),++m.referenceCount,this._addInactiveBinding(m,l,u),a[h]=m}o[h].resultBuffer=m.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(e._cacheIndex===null){let i=(e._localRoot||this._root).uuid,r=e._clip.uuid,s=this._actionsByClip[r];this._bindAction(e,s&&s.knownActions[0]),this._addInactiveAction(e,r,i)}let t=e._propertyBindings;for(let i=0,r=t.length;i!==r;++i){let s=t[i];s.useCount++===0&&(this._lendBinding(s),s.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){let t=e._propertyBindings;for(let i=0,r=t.length;i!==r;++i){let s=t[i];--s.useCount===0&&(s.restoreOriginalState(),this._takeBackBinding(s))}this._takeBackAction(e)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;let e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}}}_isActiveAction(e){let t=e._cacheIndex;return t!==null&&t=0;--i)e[i].stop();return this}update(e){e*=this.timeScale;let t=this._actions,i=this._nActiveActions,r=this.time+=e,s=Math.sign(e),a=this._accuIndex^=1;for(let c=0;c!==i;++c)t[c]._update(r,e,s,a);let o=this._bindings,l=this._nActiveBindings;for(let c=0;c!==l;++c)o[c].apply(a);return this}setTime(e){this.time=0;for(let t=0;tu.start-m.start);let d=0;for(let u=1;u0;x=e.get(x,A)}return x}function m(v){let x=!1,A=u(v);A===null?_(a,o):A&&A.isColor&&(_(A,1),x=!0);let S=n.xr.getEnvironmentBlendMode();S==="additive"?t.buffers.color.setClear(0,0,0,1,s):S==="alpha-blend"&&t.buffers.color.setClear(0,0,0,0,s),(n.autoClear||x)&&(t.buffers.depth.setTest(!0),t.buffers.depth.setMask(!0),t.buffers.color.setMask(!0),n.clear(n.autoClearColor,n.autoClearDepth,n.autoClearStencil))}function p(v,x){let A=u(x);A&&(A.isCubeTexture||A.mapping===u_)?(c===void 0&&(c=new ri(new Xc(1,1,1),new ks({name:"BackgroundCubeMaterial",uniforms:xh(zo.backgroundCube.uniforms),vertexShader:zo.backgroundCube.vertexShader,fragmentShader:zo.backgroundCube.fragmentShader,side:pn,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute("normal"),c.geometry.deleteAttribute("uv"),c.onBeforeRender=function(S,E,R){this.matrixWorld.copyPosition(R.matrixWorld)},Object.defineProperty(c.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),i.update(c)),c.material.uniforms.envMap.value=A,c.material.uniforms.backgroundBlurriness.value=x.backgroundBlurriness,c.material.uniforms.backgroundIntensity.value=x.backgroundIntensity,c.material.uniforms.backgroundRotation.value.setFromMatrix4(HJ.makeRotationFromEuler(x.backgroundRotation)).transpose(),A.isCubeTexture&&A.isRenderTargetTexture===!1&&c.material.uniforms.backgroundRotation.value.premultiply(d1),c.material.toneMapped=oi.getTransfer(A.colorSpace)!==Xi,(f!==A||h!==A.version||d!==n.toneMapping)&&(c.material.needsUpdate=!0,f=A,h=A.version,d=n.toneMapping),c.layers.enableAll(),v.unshift(c,c.geometry,c.material,0,0,null)):A&&A.isTexture&&(l===void 0&&(l=new ri(new gh(2,2),new ks({name:"BackgroundMaterial",uniforms:xh(zo.background.uniforms),vertexShader:zo.background.vertexShader,fragmentShader:zo.background.fragmentShader,side:Vs,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),i.update(l)),l.material.uniforms.t2D.value=A,l.material.uniforms.backgroundIntensity.value=x.backgroundIntensity,l.material.toneMapped=oi.getTransfer(A.colorSpace)!==Xi,A.matrixAutoUpdate===!0&&A.updateMatrix(),l.material.uniforms.uvTransform.value.copy(A.matrix),(f!==A||h!==A.version||d!==n.toneMapping)&&(l.material.needsUpdate=!0,f=A,h=A.version,d=n.toneMapping),l.layers.enableAll(),v.unshift(l,l.geometry,l.material,0,0,null))}function _(v,x){v.getRGB(SS,K0(n)),t.buffers.color.setClear(SS.r,SS.g,SS.b,x,s)}function g(){c!==void 0&&(c.geometry.dispose(),c.material.dispose(),c=void 0),l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0)}return{getClearColor:function(){return a},setClearColor:function(v,x=1){a.set(v),o=x,_(a,o)},getClearAlpha:function(){return o},setClearAlpha:function(v){o=v,_(a,o)},render:m,addToRenderList:p,dispose:g}}function XJ(n,e){let t=n.getParameter(n.MAX_VERTEX_ATTRIBS),i={},r=d(null),s=r,a=!1;function o(D,O,V,N,F){let U=!1,G=h(D,N,V,O);s!==G&&(s=G,c(s.object)),U=u(D,N,V,F),U&&m(D,N,V,F),F!==null&&e.update(F,n.ELEMENT_ARRAY_BUFFER),(U||a)&&(a=!1,A(D,O,V,N),F!==null&&n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,e.get(F).buffer))}function l(){return n.createVertexArray()}function c(D){return n.bindVertexArray(D)}function f(D){return n.deleteVertexArray(D)}function h(D,O,V,N){let F=N.wireframe===!0,U=i[O.id];U===void 0&&(U={},i[O.id]=U);let G=D.isInstancedMesh===!0?D.id:0,ee=U[G];ee===void 0&&(ee={},U[G]=ee);let j=ee[V.id];j===void 0&&(j={},ee[V.id]=j);let Z=j[F];return Z===void 0&&(Z=d(l()),j[F]=Z),Z}function d(D){let O=[],V=[],N=[];for(let F=0;F=0){let X=F[j],Y=U[j];if(Y===void 0&&(j==="instanceMatrix"&&D.instanceMatrix&&(Y=D.instanceMatrix),j==="instanceColor"&&D.instanceColor&&(Y=D.instanceColor)),X===void 0||X.attribute!==Y||Y&&X.data!==Y.data)return!0;G++}return s.attributesNum!==G||s.index!==N}function m(D,O,V,N){let F={},U=O.attributes,G=0,ee=V.getAttributes();for(let j in ee)if(ee[j].location>=0){let X=U[j];X===void 0&&(j==="instanceMatrix"&&D.instanceMatrix&&(X=D.instanceMatrix),j==="instanceColor"&&D.instanceColor&&(X=D.instanceColor));let Y={};Y.attribute=X,X&&X.data&&(Y.data=X.data),F[j]=Y,G++}s.attributes=F,s.attributesNum=G,s.index=N}function p(){let D=s.newAttributes;for(let O=0,V=D.length;O=0){let Z=F[ee];if(Z===void 0&&(ee==="instanceMatrix"&&D.instanceMatrix&&(Z=D.instanceMatrix),ee==="instanceColor"&&D.instanceColor&&(Z=D.instanceColor)),Z!==void 0){let X=Z.normalized,Y=Z.itemSize,ue=e.get(Z);if(ue===void 0)continue;let Re=ue.buffer,Be=ue.type,ae=ue.bytesPerElement,me=Be===n.INT||Be===n.UNSIGNED_INT||Z.gpuType===OE;if(Z.isInterleavedBufferAttribute){let re=Z.data,de=re.stride,De=Z.offset;if(re.isInstancedInterleavedBuffer){for(let he=0;he0&&n.getShaderPrecisionFormat(n.FRAGMENT_SHADER,n.HIGH_FLOAT).precision>0)return"highp";R="mediump"}return R==="mediump"&&n.getShaderPrecisionFormat(n.VERTEX_SHADER,n.MEDIUM_FLOAT).precision>0&&n.getShaderPrecisionFormat(n.FRAGMENT_SHADER,n.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let c=t.precision!==void 0?t.precision:"highp",f=l(c);f!==c&&(Ct("WebGLRenderer:",c,"not supported, using",f,"instead."),c=f);let h=t.logarithmicDepthBuffer===!0,d=t.reversedDepthBuffer===!0&&e.has("EXT_clip_control");t.reversedDepthBuffer===!0&&d===!1&&Ct("WebGLRenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer.");let u=n.getParameter(n.MAX_TEXTURE_IMAGE_UNITS),m=n.getParameter(n.MAX_VERTEX_TEXTURE_IMAGE_UNITS),p=n.getParameter(n.MAX_TEXTURE_SIZE),_=n.getParameter(n.MAX_CUBE_MAP_TEXTURE_SIZE),g=n.getParameter(n.MAX_VERTEX_ATTRIBS),v=n.getParameter(n.MAX_VERTEX_UNIFORM_VECTORS),x=n.getParameter(n.MAX_VARYING_VECTORS),A=n.getParameter(n.MAX_FRAGMENT_UNIFORM_VECTORS),S=n.getParameter(n.MAX_SAMPLES),E=n.getParameter(n.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:s,getMaxPrecision:l,textureFormatReadable:a,textureTypeReadable:o,precision:c,logarithmicDepthBuffer:h,reversedDepthBuffer:d,maxTextures:u,maxVertexTextures:m,maxTextureSize:p,maxCubemapSize:_,maxAttributes:g,maxVertexUniforms:v,maxVaryings:x,maxFragmentUniforms:A,maxSamples:S,samples:E}}function jJ(n){let e=this,t=null,i=0,r=!1,s=!1,a=new ca,o=new ii,l={value:null,needsUpdate:!1};this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(h,d){let u=h.length!==0||d||i!==0||r;return r=d,i=h.length,u},this.beginShadows=function(){s=!0,f(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(h,d){t=f(h,d,0)},this.setState=function(h,d,u){let m=h.clippingPlanes,p=h.clipIntersection,_=h.clipShadows,g=n.get(h);if(!r||m===null||m.length===0||s&&!_)s?f(null):c();else{let v=s?0:i,x=v*4,A=g.clippingState||null;l.value=A,A=f(m,d,x,u);for(let S=0;S!==x;++S)A[S]=t[S];g.clippingState=A,this.numIntersection=p?this.numPlanes:0,this.numPlanes+=v}};function c(){l.value!==t&&(l.value=t,l.needsUpdate=i>0),e.numPlanes=i,e.numIntersection=0}function f(h,d,u,m){let p=h!==null?h.length:0,_=null;if(p!==0){if(_=l.value,m!==!0||_===null){let g=u+p*4,v=d.matrixWorldInverse;o.getNormalMatrix(v),(_===null||_.lengthn-Jc?l=HF[a-n+Jc-1]:a===0&&(l=0),t.push(l);let c=1/(o-2),f=-c,h=1+c,d=[f,f,h,f,h,h,f,f,h,h,f,h],u=6,m=6,p=3,_=2,g=1,v=new Float32Array(p*m*u),x=new Float32Array(_*m*u),A=new Float32Array(g*m*u);for(let E=0;E2?0:-1,y=[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];v.set(y,p*m*E),x.set(d,_*m*E);let M=[E,E,E,E,E,E];A.set(M,g*m*E)}let S=new Vi;S.setAttribute("position",new lr(v,p)),S.setAttribute("uv",new lr(x,_)),S.setAttribute("faceIndex",new lr(A,g)),i.push(new ri(S,null)),r>Jc&&r--}return{lodMeshes:i,sizeLods:e,sigmas:t}}function XF(n,e,t){let i=new Gs(n,e,t);return i.texture.mapping=u_,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function yu(n,e,t,i,r){n.viewport.set(e,t,i,r),n.scissor.set(e,t,i,r)}function $J(n,e,t){return new ks({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:qJ,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${n}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:RS(),fragmentShader:` precision highp float; precision highp int; @@ -108,7 +108,7 @@ gl_FragColor = vec4(prefilteredColor, 1.0); } - `,blending:ko,depthTest:!1,depthWrite:!1})}function JJ(n,e,t){let i=new Float32Array(Rh),r=new ne(0,1,0);return new Ws({name:"SphericalGaussianBlur",defines:{n:Rh,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${n}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:i},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:r}},vertexShader:xS(),fragmentShader:` + `,blending:ko,depthTest:!1,depthWrite:!1})}function JJ(n,e,t){let i=new Float32Array(Rh),r=new ne(0,1,0);return new ks({name:"SphericalGaussianBlur",defines:{n:Rh,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${n}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:i},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:r}},vertexShader:RS(),fragmentShader:` precision mediump float; precision mediump int; @@ -168,7 +168,7 @@ } } - `,blending:ko,depthTest:!1,depthWrite:!1})}function YF(){return new Ws({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:xS(),fragmentShader:` + `,blending:ko,depthTest:!1,depthWrite:!1})}function YF(){return new ks({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:RS(),fragmentShader:` precision mediump float; precision mediump int; @@ -187,7 +187,7 @@ gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); } - `,blending:ko,depthTest:!1,depthWrite:!1})}function KF(){return new Ws({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:xS(),fragmentShader:` + `,blending:ko,depthTest:!1,depthWrite:!1})}function KF(){return new ks({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:RS(),fragmentShader:` precision mediump float; precision mediump int; @@ -203,7 +203,7 @@ gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); } - `,blending:ko,depthTest:!1,depthWrite:!1})}function xS(){return` + `,blending:ko,depthTest:!1,depthWrite:!1})}function RS(){return` precision mediump float; precision mediump int; @@ -258,7 +258,7 @@ gl_Position = vec4( position, 1.0 ); } - `}function eee(n){let e=new WeakMap,t=new WeakMap,i=null;function r(d,u=!1){return d==null?null:u?a(d):s(d)}function s(d){if(d&&d.isTexture){let u=d.mapping;if(u===yE||u===PE)if(e.has(d)){let m=e.get(d).texture;return o(m,d.mapping)}else{let m=d.image;if(m&&m.height>0){let p=new TS(m.height);return p.fromEquirectangularTexture(n,d),e.set(d,p),d.addEventListener("dispose",c),o(p.texture,d.mapping)}else return null}}return d}function a(d){if(d&&d.isTexture){let u=d.mapping,m=u===yE||u===PE,p=u===Qc||u===Th;if(m||p){let _=t.get(d),g=_!==void 0?_.texture.pmremVersion:0;if(d.isRenderTargetTexture&&d.pmremVersion!==g)return i===null&&(i=new Lu(n)),_=m?i.fromEquirectangular(d,_):i.fromCubemap(d,_),_.texture.pmremVersion=d.pmremVersion,t.set(d,_),_.texture;if(_!==void 0)return _.texture;{let v=d.image;return m&&v&&v.height>0||p&&v&&l(v)?(i===null&&(i=new Lu(n)),_=m?i.fromEquirectangular(d):i.fromCubemap(d),_.texture.pmremVersion=d.pmremVersion,t.set(d,_),d.addEventListener("dispose",f),_.texture):null}}}return d}function o(d,u){return u===yE?d.mapping=Qc:u===PE&&(d.mapping=Th),d}function l(d){let u=0,m=6;for(let p=0;p=65535?Kp:Yp)(d,1);_.version=p;let g=s.get(h);g&&e.remove(g),s.set(h,_)}function f(h){let d=s.get(h);if(d){let u=h.index;u!==null&&d.versione.maxTextureSize&&(S=Math.ceil(A/e.maxTextureSize),A=e.maxTextureSize);let E=new Float32Array(A*S*4*h),R=new Xp(E,A,S,h);R.type=zs,R.needsUpdate=!0;let I=x*4;for(let M=0;M0){let p=new AS(m.height);return p.fromEquirectangularTexture(n,d),e.set(d,p),d.addEventListener("dispose",c),o(p.texture,d.mapping)}else return null}}return d}function a(d){if(d&&d.isTexture){let u=d.mapping,m=u===PE||u===DE,p=u===Zc||u===Th;if(m||p){let _=t.get(d),g=_!==void 0?_.texture.pmremVersion:0;if(d.isRenderTargetTexture&&d.pmremVersion!==g)return i===null&&(i=new Du(n)),_=m?i.fromEquirectangular(d,_):i.fromCubemap(d,_),_.texture.pmremVersion=d.pmremVersion,t.set(d,_),_.texture;if(_!==void 0)return _.texture;{let v=d.image;return m&&v&&v.height>0||p&&v&&l(v)?(i===null&&(i=new Du(n)),_=m?i.fromEquirectangular(d):i.fromCubemap(d),_.texture.pmremVersion=d.pmremVersion,t.set(d,_),d.addEventListener("dispose",f),_.texture):null}}}return d}function o(d,u){return u===PE?d.mapping=Zc:u===DE&&(d.mapping=Th),d}function l(d){let u=0,m=6;for(let p=0;p=65535?Kp:Yp)(d,1);_.version=p;let g=s.get(h);g&&e.remove(g),s.set(h,_)}function f(h){let d=s.get(h);if(d){let u=h.index;u!==null&&d.versione.maxTextureSize&&(S=Math.ceil(A/e.maxTextureSize),A=e.maxTextureSize);let E=new Float32Array(A*S*4*h),R=new Xp(E,A,S,h);R.type=Hs,R.needsUpdate=!0;let I=x*4;for(let M=0;M0&&_[0].isRenderPass===!0;let x=s.width,A=s.height;for(let S=0;S<_.length;S++){let E=_[S];E.setSize&&E.setSize(x,A)}},this.begin=function(v,x){if(u||v.toneMapping===Hs&&_.length===0)return!1;if(p=x,x!==null){let A=x.width,S=x.height;(s.width!==A||s.height!==S)&&this.setSize(A,S)}return g===!1&&v.setRenderTarget(s),m=v.toneMapping,v.toneMapping=Hs,!0},this.hasRenderPass=function(){return g},this.end=function(v,x){v.toneMapping=m,u=!0;let A=s,S=a;for(let E=0;E<_.length;E++){let R=_[E];if(R.enabled!==!1&&(R.render(v,S,A,x),R.needsSwap!==!1)){let I=A;A=S,S=I}}if(h!==v.outputColorSpace||d!==v.toneMapping){h=v.outputColorSpace,d=v.toneMapping,l.defines={},ai.getTransfer(h)===Xi&&(l.defines.SRGB_TRANSFER="");let E=oee[d];E&&(l.defines[E]=""),l.needsUpdate=!0}l.uniforms.tDiffuse.value=A.texture,v.setRenderTarget(p),v.render(c,f),p=null,u=!1},this.isCompositing=function(){return u},this.dispose=function(){s.depthTexture&&s.depthTexture.dispose(),s.dispose(),a.dispose(),o.dispose(),l.dispose()}}function Ou(n,e,t){let i=n[0];if(i<=0||i>0)return n;let r=e*t,s=jF[r];if(s===void 0&&(s=new Float32Array(r),jF[r]=s),e!==0){i.toArray(s,0);for(let a=1,o=0;a!==e;++a)o+=t,n[a].toArray(s,o)}return s}function Qr(n,e){if(n.length!==e.length)return!1;for(let t=0,i=n.length;t0&&_[0].isRenderPass===!0;let x=s.width,A=s.height;for(let S=0;S<_.length;S++){let E=_[S];E.setSize&&E.setSize(x,A)}},this.begin=function(v,x){if(u||v.toneMapping===Ws&&_.length===0)return!1;if(p=x,x!==null){let A=x.width,S=x.height;(s.width!==A||s.height!==S)&&this.setSize(A,S)}return g===!1&&v.setRenderTarget(s),m=v.toneMapping,v.toneMapping=Ws,!0},this.hasRenderPass=function(){return g},this.end=function(v,x){v.toneMapping=m,u=!0;let A=s,S=a;for(let E=0;E<_.length;E++){let R=_[E];if(R.enabled!==!1&&(R.render(v,S,A,x),R.needsSwap!==!1)){let I=A;A=S,S=I}}if(h!==v.outputColorSpace||d!==v.toneMapping){h=v.outputColorSpace,d=v.toneMapping,l.defines={},oi.getTransfer(h)===Xi&&(l.defines.SRGB_TRANSFER="");let E=oee[d];E&&(l.defines[E]=""),l.needsUpdate=!0}l.uniforms.tDiffuse.value=A.texture,v.setRenderTarget(p),v.render(c,f),p=null,u=!1},this.isCompositing=function(){return u},this.dispose=function(){s.depthTexture&&s.depthTexture.dispose(),s.dispose(),a.dispose(),o.dispose(),l.dispose()}}function Lu(n,e,t){let i=n[0];if(i<=0||i>0)return n;let r=e*t,s=jF[r];if(s===void 0&&(s=new Float32Array(r),jF[r]=s),e!==0){i.toArray(s,0);for(let a=1,o=0;a!==e;++a)o+=t,n[a].toArray(s,o)}return s}function Qr(n,e){if(n.length!==e.length)return!1;for(let t=0,i=n.length;t":" "} ${o}: ${t[a]}`)}return i.join(` -`)}function Jee(n){ai._getMatrix(t1,ai.workingColorSpace,n);let e=`mat3( ${t1.elements.map(t=>t.toFixed(4))} )`;switch(ai.getTransfer(n)){case Hp:return[e,"LinearTransferOETF"];case Xi:return[e,"sRGBTransferOETF"];default:return Mt("WebGLProgram: Unsupported color space: ",n),[e,"LinearTransferOETF"]}}function i1(n,e,t){let i=n.getShaderParameter(e,n.COMPILE_STATUS),s=(n.getShaderInfoLog(e)||"").trim();if(i&&s==="")return"";let a=/ERROR: 0:(\d+)/.exec(s);if(a){let o=parseInt(a[1]);return t.toUpperCase()+` +`)}function Jee(n){oi._getMatrix(t1,oi.workingColorSpace,n);let e=`mat3( ${t1.elements.map(t=>t.toFixed(4))} )`;switch(oi.getTransfer(n)){case Hp:return[e,"LinearTransferOETF"];case Xi:return[e,"sRGBTransferOETF"];default:return Ct("WebGLProgram: Unsupported color space: ",n),[e,"LinearTransferOETF"]}}function i1(n,e,t){let i=n.getShaderParameter(e,n.COMPILE_STATUS),s=(n.getShaderInfoLog(e)||"").trim();if(i&&s==="")return"";let a=/ERROR: 0:(\d+)/.exec(s);if(a){let o=parseInt(a[1]);return t.toUpperCase()+` `+s+` `+$ee(n.getShaderSource(e),o)}else return s}function ete(n,e){let t=Jee(e);return[`vec4 ${n}( vec4 value ) {`,` return ${t[1]}( vec4( value.rgb * ${t[0]}, value.a ) );`,"}"].join(` -`)}function ite(n,e){let t=tte[e];return t===void 0?(Mt("WebGLProgram: Unsupported toneMapping:",e),"vec3 "+n+"( vec3 color ) { return LinearToneMapping( color ); }"):"vec3 "+n+"( vec3 color ) { return "+t+"ToneMapping( color ); }"}function rte(){ai.getLuminanceCoefficients(SS);let n=SS.x.toFixed(4),e=SS.y.toFixed(4),t=SS.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${n}, ${e}, ${t} );`," return dot( weights, rgb );","}"].join(` +`)}function ite(n,e){let t=tte[e];return t===void 0?(Ct("WebGLProgram: Unsupported toneMapping:",e),"vec3 "+n+"( vec3 color ) { return LinearToneMapping( color ); }"):"vec3 "+n+"( vec3 color ) { return "+t+"ToneMapping( color ); }"}function rte(){oi.getLuminanceCoefficients(TS);let n=TS.x.toFixed(4),e=TS.y.toFixed(4),t=TS.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${n}, ${e}, ${t} );`," return dot( weights, rgb );","}"].join(` `)}function nte(n){return[n.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",n.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(R_).join(` `)}function ste(n){let e=[];for(let t in n){let i=n[t];i!==!1&&e.push("#define "+t+" "+i)}return e.join(` -`)}function ate(n,e){let t={},i=n.getProgramParameter(e,n.ACTIVE_ATTRIBUTES);for(let r=0;r")}return uI(t)}function s1(n){return n.replace(fte,hte)}function hte(n,e,t,i){let r="";for(let s=parseInt(e);s")}return uI(t)}function s1(n){return n.replace(fte,hte)}function hte(n,e,t,i){let r="";for(let s=parseInt(e);s0&&(g+=` `)):(_=[a1(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,m,t.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",t.batching?"#define USE_BATCHING":"",t.batchingColor?"#define USE_BATCHING_COLOR":"",t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.instancingMorph?"#define USE_INSTANCING_MORPH":"",t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+f:"",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.vertexNormals?"#define HAS_NORMAL":"",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(R_).join(` -`),g=[a1(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,m,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+c:"",t.envMap?"#define "+f:"",t.envMap?"#define "+h:"",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.packedNormalMap?"#define USE_PACKED_NORMALMAP":"",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?"#define USE_COLOR":"",t.vertexAlphas||t.batchingColor?"#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.numLightProbeGrids>0?"#define USE_LIGHT_PROBES_GRID":"",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!==Hs?"#define TONE_MAPPING":"",t.toneMapping!==Hs?fi.tonemapping_pars_fragment:"",t.toneMapping!==Hs?ite("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",fi.colorspace_pars_fragment,ete("linearToOutputTexel",t.outputColorSpace),rte(),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",` +`),g=[a1(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,m,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+c:"",t.envMap?"#define "+f:"",t.envMap?"#define "+h:"",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.packedNormalMap?"#define USE_PACKED_NORMALMAP":"",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?"#define USE_COLOR":"",t.vertexAlphas||t.batchingColor?"#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.numLightProbeGrids>0?"#define USE_LIGHT_PROBES_GRID":"",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!==Ws?"#define TONE_MAPPING":"",t.toneMapping!==Ws?hi.tonemapping_pars_fragment:"",t.toneMapping!==Ws?ite("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",hi.colorspace_pars_fragment,ete("linearToOutputTexel",t.outputColorSpace),rte(),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",` `].filter(R_).join(` `)),a=uI(a),a=r1(a,t),a=n1(a,t),o=uI(o),o=r1(o,t),o=n1(o,t),a=s1(a),o=s1(o),t.isRawShaderMaterial!==!0&&(v=`#version 300 es `,_=[u,"#define attribute in","#define varying out","#define texture2D texture"].join(` `)+` `+_,g=["#define varying in",t.glslVersion===X0?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===X0?"":"#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(` `)+` -`+g);let x=v+_+a,A=v+g+o,S=e1(r,r.VERTEX_SHADER,x),E=e1(r,r.FRAGMENT_SHADER,A);r.attachShader(p,S),r.attachShader(p,E),t.index0AttributeName!==void 0?r.bindAttribLocation(p,0,t.index0AttributeName):t.morphTargets===!0&&r.bindAttribLocation(p,0,"position"),r.linkProgram(p);function R(D){if(n.debug.checkShaderErrors){let O=r.getProgramInfoLog(p)||"",V=r.getShaderInfoLog(S)||"",N=r.getShaderInfoLog(E)||"",F=O.trim(),U=V.trim(),k=N.trim(),ee=!0,q=!0;if(r.getProgramParameter(p,r.LINK_STATUS)===!1)if(ee=!1,typeof n.debug.onShaderError=="function")n.debug.onShaderError(r,p,S,E);else{let Q=i1(r,S,"vertex"),Y=i1(r,E,"fragment");Ft("THREE.WebGLProgram: Shader Error "+r.getError()+" - VALIDATE_STATUS "+r.getProgramParameter(p,r.VALIDATE_STATUS)+` +`+g);let x=v+_+a,A=v+g+o,S=e1(r,r.VERTEX_SHADER,x),E=e1(r,r.FRAGMENT_SHADER,A);r.attachShader(p,S),r.attachShader(p,E),t.index0AttributeName!==void 0?r.bindAttribLocation(p,0,t.index0AttributeName):t.morphTargets===!0&&r.bindAttribLocation(p,0,"position"),r.linkProgram(p);function R(D){if(n.debug.checkShaderErrors){let O=r.getProgramInfoLog(p)||"",V=r.getShaderInfoLog(S)||"",N=r.getShaderInfoLog(E)||"",F=O.trim(),U=V.trim(),G=N.trim(),ee=!0,j=!0;if(r.getProgramParameter(p,r.LINK_STATUS)===!1)if(ee=!1,typeof n.debug.onShaderError=="function")n.debug.onShaderError(r,p,S,E);else{let Z=i1(r,S,"vertex"),X=i1(r,E,"fragment");Bt("THREE.WebGLProgram: Shader Error "+r.getError()+" - VALIDATE_STATUS "+r.getProgramParameter(p,r.VALIDATE_STATUS)+` Material Name: `+D.name+` Material Type: `+D.type+` Program Info Log: `+F+` -`+Q+` -`+Y)}else F!==""?Mt("WebGLProgram: Program Info Log:",F):(U===""||k==="")&&(q=!1);q&&(D.diagnostics={runnable:ee,programLog:F,vertexShader:{log:U,prefix:_},fragmentShader:{log:k,prefix:g}})}r.deleteShader(S),r.deleteShader(E),I=new Du(r,p),y=ate(r,p)}let I;this.getUniforms=function(){return I===void 0&&R(this),I};let y;this.getAttributes=function(){return y===void 0&&R(this),y};let M=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return M===!1&&(M=r.getProgramParameter(p,Zee)),M},this.destroy=function(){i.releaseStatesOfProgram(this),r.deleteProgram(p),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=Qee++,this.cacheKey=e,this.usedTimes=1,this.program=p,this.vertexShader=S,this.fragmentShader=E,this}function xte(n){return n===Jc||n===v_||n===E_}function Rte(n,e,t,i,r,s){let a=new uu,o=new mI,l=new Set,c=[],f=new Map,h=i.logarithmicDepthBuffer,d=i.precision,u={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distance",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 m(I){return l.add(I),I===0?"uv":`uv${I}`}function p(I,y,M,D,O,V){let N=D.fog,F=O.geometry,U=I.isMeshStandardMaterial||I.isMeshLambertMaterial||I.isMeshPhongMaterial?D.environment:null,k=I.isMeshStandardMaterial||I.isMeshLambertMaterial&&!I.envMap||I.isMeshPhongMaterial&&!I.envMap,ee=e.get(I.envMap||U,k),q=ee&&ee.mapping===u_?ee.image.height:null,Q=u[I.type];I.precision!==null&&(d=i.getMaxPrecision(I.precision),d!==I.precision&&Mt("WebGLProgram.getParameters:",I.precision,"not supported, using",d,"instead."));let Y=F.morphAttributes.position||F.morphAttributes.normal||F.morphAttributes.color,K=Y!==void 0?Y.length:0,de=0;F.morphAttributes.position!==void 0&&(de=1),F.morphAttributes.normal!==void 0&&(de=2),F.morphAttributes.color!==void 0&&(de=3);let Re,Fe,se,ue;if(Q){let Wt=zo[Q];Re=Wt.vertexShader,Fe=Wt.fragmentShader}else Re=I.vertexShader,Fe=I.fragmentShader,o.update(I),se=o.getVertexShaderID(I),ue=o.getFragmentShaderID(I);let re=n.getRenderTarget(),he=n.state.buffers.depth.getReversed(),De=O.isInstancedMesh===!0,fe=O.isBatchedMesh===!0,be=!!I.map,Xe=!!I.matcap,Et=!!ee,Ke=!!I.aoMap,qe=!!I.lightMap,Qt=!!I.bumpMap,Dt=!!I.normalMap,Fi=!!I.displacementMap,ae=!!I.emissiveMap,Bi=!!I.metalnessMap,ei=!!I.roughnessMap,Wi=I.anisotropy>0,ot=I.clearcoat>0,Ci=I.dispersion>0,X=I.iridescence>0,B=I.sheen>0,me=I.transmission>0,ye=Wi&&!!I.anisotropyMap,Be=ot&&!!I.clearcoatMap,Je=ot&&!!I.clearcoatNormalMap,rt=ot&&!!I.clearcoatRoughnessMap,Ce=X&&!!I.iridescenceMap,Pe=X&&!!I.iridescenceThicknessMap,je=B&&!!I.sheenColorMap,St=B&&!!I.sheenRoughnessMap,nt=!!I.specularMap,et=!!I.specularColorMap,Vt=!!I.specularIntensityMap,jt=me&&!!I.transmissionMap,vi=me&&!!I.thicknessMap,G=!!I.gradientMap,ve=!!I.alphaMap,Ae=I.alphaTest>0,He=!!I.alphaHash,ke=!!I.extensions,Oe=Hs;I.toneMapped&&(re===null||re.isXRRenderTarget===!0)&&(Oe=n.toneMapping);let Tt={shaderID:Q,shaderType:I.type,shaderName:I.name,vertexShader:Re,fragmentShader:Fe,defines:I.defines,customVertexShaderID:se,customFragmentShaderID:ue,isRawShaderMaterial:I.isRawShaderMaterial===!0,glslVersion:I.glslVersion,precision:d,batching:fe,batchingColor:fe&&O._colorsTexture!==null,instancing:De,instancingColor:De&&O.instanceColor!==null,instancingMorph:De&&O.morphTexture!==null,outputColorSpace:re===null?n.outputColorSpace:re.isXRRenderTarget===!0?re.texture.colorSpace:ai.workingColorSpace,alphaToCoverage:!!I.alphaToCoverage,map:be,matcap:Xe,envMap:Et,envMapMode:Et&&ee.mapping,envMapCubeUVHeight:q,aoMap:Ke,lightMap:qe,bumpMap:Qt,normalMap:Dt,displacementMap:Fi,emissiveMap:ae,normalMapObjectSpace:Dt&&I.normalMapType===CF,normalMapTangentSpace:Dt&&I.normalMapType===yu,packedNormalMap:Dt&&I.normalMapType===yu&&xte(I.normalMap.format),metalnessMap:Bi,roughnessMap:ei,anisotropy:Wi,anisotropyMap:ye,clearcoat:ot,clearcoatMap:Be,clearcoatNormalMap:Je,clearcoatRoughnessMap:rt,dispersion:Ci,iridescence:X,iridescenceMap:Ce,iridescenceThicknessMap:Pe,sheen:B,sheenColorMap:je,sheenRoughnessMap:St,specularMap:nt,specularColorMap:et,specularIntensityMap:Vt,transmission:me,transmissionMap:jt,thicknessMap:vi,gradientMap:G,opaque:I.transparent===!1&&I.blending===ch&&I.alphaToCoverage===!1,alphaMap:ve,alphaTest:Ae,alphaHash:He,combine:I.combine,mapUv:be&&m(I.map.channel),aoMapUv:Ke&&m(I.aoMap.channel),lightMapUv:qe&&m(I.lightMap.channel),bumpMapUv:Qt&&m(I.bumpMap.channel),normalMapUv:Dt&&m(I.normalMap.channel),displacementMapUv:Fi&&m(I.displacementMap.channel),emissiveMapUv:ae&&m(I.emissiveMap.channel),metalnessMapUv:Bi&&m(I.metalnessMap.channel),roughnessMapUv:ei&&m(I.roughnessMap.channel),anisotropyMapUv:ye&&m(I.anisotropyMap.channel),clearcoatMapUv:Be&&m(I.clearcoatMap.channel),clearcoatNormalMapUv:Je&&m(I.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:rt&&m(I.clearcoatRoughnessMap.channel),iridescenceMapUv:Ce&&m(I.iridescenceMap.channel),iridescenceThicknessMapUv:Pe&&m(I.iridescenceThicknessMap.channel),sheenColorMapUv:je&&m(I.sheenColorMap.channel),sheenRoughnessMapUv:St&&m(I.sheenRoughnessMap.channel),specularMapUv:nt&&m(I.specularMap.channel),specularColorMapUv:et&&m(I.specularColorMap.channel),specularIntensityMapUv:Vt&&m(I.specularIntensityMap.channel),transmissionMapUv:jt&&m(I.transmissionMap.channel),thicknessMapUv:vi&&m(I.thicknessMap.channel),alphaMapUv:ve&&m(I.alphaMap.channel),vertexTangents:!!F.attributes.tangent&&(Dt||Wi),vertexNormals:!!F.attributes.normal,vertexColors:I.vertexColors,vertexAlphas:I.vertexColors===!0&&!!F.attributes.color&&F.attributes.color.itemSize===4,pointsUvs:O.isPoints===!0&&!!F.attributes.uv&&(be||ve),fog:!!N,useFog:I.fog===!0,fogExp2:!!N&&N.isFogExp2,flatShading:I.wireframe===!1&&(I.flatShading===!0||F.attributes.normal===void 0&&Dt===!1&&(I.isMeshLambertMaterial||I.isMeshPhongMaterial||I.isMeshStandardMaterial||I.isMeshPhysicalMaterial)),sizeAttenuation:I.sizeAttenuation===!0,logarithmicDepthBuffer:h,reversedDepthBuffer:he,skinning:O.isSkinnedMesh===!0,morphTargets:F.morphAttributes.position!==void 0,morphNormals:F.morphAttributes.normal!==void 0,morphColors:F.morphAttributes.color!==void 0,morphTargetsCount:K,morphTextureStride:de,numDirLights:y.directional.length,numPointLights:y.point.length,numSpotLights:y.spot.length,numSpotLightMaps:y.spotLightMap.length,numRectAreaLights:y.rectArea.length,numHemiLights:y.hemi.length,numDirLightShadows:y.directionalShadowMap.length,numPointLightShadows:y.pointShadowMap.length,numSpotLightShadows:y.spotShadowMap.length,numSpotLightShadowsWithMaps:y.numSpotLightShadowsWithMaps,numLightProbes:y.numLightProbes,numLightProbeGrids:V.length,numClippingPlanes:s.numPlanes,numClipIntersection:s.numIntersection,dithering:I.dithering,shadowMapEnabled:n.shadowMap.enabled&&M.length>0,shadowMapType:n.shadowMap.type,toneMapping:Oe,decodeVideoTexture:be&&I.map.isVideoTexture===!0&&ai.getTransfer(I.map.colorSpace)===Xi,decodeVideoTextureEmissive:ae&&I.emissiveMap.isVideoTexture===!0&&ai.getTransfer(I.emissiveMap.colorSpace)===Xi,premultipliedAlpha:I.premultipliedAlpha,doubleSided:I.side===ma,flipSided:I.side===pn,useDepthPacking:I.depthPacking>=0,depthPacking:I.depthPacking||0,index0AttributeName:I.index0AttributeName,extensionClipCullDistance:ke&&I.extensions.clipCullDistance===!0&&t.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(ke&&I.extensions.multiDraw===!0||fe)&&t.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:t.has("KHR_parallel_shader_compile"),customProgramCacheKey:I.customProgramCacheKey()};return Tt.vertexUv1s=l.has(1),Tt.vertexUv2s=l.has(2),Tt.vertexUv3s=l.has(3),l.clear(),Tt}function _(I){let y=[];if(I.shaderID?y.push(I.shaderID):(y.push(I.customVertexShaderID),y.push(I.customFragmentShaderID)),I.defines!==void 0)for(let M in I.defines)y.push(M),y.push(I.defines[M]);return I.isRawShaderMaterial===!1&&(g(y,I),v(y,I),y.push(n.outputColorSpace)),y.push(I.customProgramCacheKey),y.join()}function g(I,y){I.push(y.precision),I.push(y.outputColorSpace),I.push(y.envMapMode),I.push(y.envMapCubeUVHeight),I.push(y.mapUv),I.push(y.alphaMapUv),I.push(y.lightMapUv),I.push(y.aoMapUv),I.push(y.bumpMapUv),I.push(y.normalMapUv),I.push(y.displacementMapUv),I.push(y.emissiveMapUv),I.push(y.metalnessMapUv),I.push(y.roughnessMapUv),I.push(y.anisotropyMapUv),I.push(y.clearcoatMapUv),I.push(y.clearcoatNormalMapUv),I.push(y.clearcoatRoughnessMapUv),I.push(y.iridescenceMapUv),I.push(y.iridescenceThicknessMapUv),I.push(y.sheenColorMapUv),I.push(y.sheenRoughnessMapUv),I.push(y.specularMapUv),I.push(y.specularColorMapUv),I.push(y.specularIntensityMapUv),I.push(y.transmissionMapUv),I.push(y.thicknessMapUv),I.push(y.combine),I.push(y.fogExp2),I.push(y.sizeAttenuation),I.push(y.morphTargetsCount),I.push(y.morphAttributeCount),I.push(y.numDirLights),I.push(y.numPointLights),I.push(y.numSpotLights),I.push(y.numSpotLightMaps),I.push(y.numHemiLights),I.push(y.numRectAreaLights),I.push(y.numDirLightShadows),I.push(y.numPointLightShadows),I.push(y.numSpotLightShadows),I.push(y.numSpotLightShadowsWithMaps),I.push(y.numLightProbes),I.push(y.shadowMapType),I.push(y.toneMapping),I.push(y.numClippingPlanes),I.push(y.numClipIntersection),I.push(y.depthPacking)}function v(I,y){a.disableAll(),y.instancing&&a.enable(0),y.instancingColor&&a.enable(1),y.instancingMorph&&a.enable(2),y.matcap&&a.enable(3),y.envMap&&a.enable(4),y.normalMapObjectSpace&&a.enable(5),y.normalMapTangentSpace&&a.enable(6),y.clearcoat&&a.enable(7),y.iridescence&&a.enable(8),y.alphaTest&&a.enable(9),y.vertexColors&&a.enable(10),y.vertexAlphas&&a.enable(11),y.vertexUv1s&&a.enable(12),y.vertexUv2s&&a.enable(13),y.vertexUv3s&&a.enable(14),y.vertexTangents&&a.enable(15),y.anisotropy&&a.enable(16),y.alphaHash&&a.enable(17),y.batching&&a.enable(18),y.dispersion&&a.enable(19),y.batchingColor&&a.enable(20),y.gradientMap&&a.enable(21),y.packedNormalMap&&a.enable(22),y.vertexNormals&&a.enable(23),I.push(a.mask),a.disableAll(),y.fog&&a.enable(0),y.useFog&&a.enable(1),y.flatShading&&a.enable(2),y.logarithmicDepthBuffer&&a.enable(3),y.reversedDepthBuffer&&a.enable(4),y.skinning&&a.enable(5),y.morphTargets&&a.enable(6),y.morphNormals&&a.enable(7),y.morphColors&&a.enable(8),y.premultipliedAlpha&&a.enable(9),y.shadowMapEnabled&&a.enable(10),y.doubleSided&&a.enable(11),y.flipSided&&a.enable(12),y.useDepthPacking&&a.enable(13),y.dithering&&a.enable(14),y.transmission&&a.enable(15),y.sheen&&a.enable(16),y.opaque&&a.enable(17),y.pointsUvs&&a.enable(18),y.decodeVideoTexture&&a.enable(19),y.decodeVideoTextureEmissive&&a.enable(20),y.alphaToCoverage&&a.enable(21),y.numLightProbeGrids>0&&a.enable(22),I.push(a.mask)}function x(I){let y=u[I.type],M;if(y){let D=zo[y];M=kF.clone(D.uniforms)}else M=I.uniforms;return M}function A(I,y){let M=f.get(y);return M!==void 0?++M.usedTimes:(M=new Tte(n,y,I,r),c.push(M),f.set(y,M)),M}function S(I){if(--I.usedTimes===0){let y=c.indexOf(I);c[y]=c[c.length-1],c.pop(),f.delete(I.cacheKey),I.destroy()}}function E(I){o.remove(I)}function R(){o.dispose()}return{getParameters:p,getProgramCacheKey:_,getUniforms:x,acquireProgram:A,releaseProgram:S,releaseShaderCache:E,programs:c,dispose:R}}function bte(){let n=new WeakMap;function e(a){return n.has(a)}function t(a){let o=n.get(a);return o===void 0&&(o={},n.set(a,o)),o}function i(a){n.delete(a)}function r(a,o,l){n.get(a)[o]=l}function s(){n=new WeakMap}return{has:e,get:t,remove:i,update:r,dispose:s}}function Ite(n,e){return n.groupOrder!==e.groupOrder?n.groupOrder-e.groupOrder:n.renderOrder!==e.renderOrder?n.renderOrder-e.renderOrder:n.material.id!==e.material.id?n.material.id-e.material.id:n.materialVariant!==e.materialVariant?n.materialVariant-e.materialVariant:n.z!==e.z?n.z-e.z:n.id-e.id}function o1(n,e){return n.groupOrder!==e.groupOrder?n.groupOrder-e.groupOrder:n.renderOrder!==e.renderOrder?n.renderOrder-e.renderOrder:n.z!==e.z?e.z-n.z:n.id-e.id}function l1(){let n=[],e=0,t=[],i=[],r=[];function s(){e=0,t.length=0,i.length=0,r.length=0}function a(d){let u=0;return d.isInstancedMesh&&(u+=2),d.isSkinnedMesh&&(u+=1),u}function o(d,u,m,p,_,g){let v=n[e];return v===void 0?(v={id:d.id,object:d,geometry:u,material:m,materialVariant:a(d),groupOrder:p,renderOrder:d.renderOrder,z:_,group:g},n[e]=v):(v.id=d.id,v.object=d,v.geometry=u,v.material=m,v.materialVariant=a(d),v.groupOrder=p,v.renderOrder=d.renderOrder,v.z=_,v.group=g),e++,v}function l(d,u,m,p,_,g){let v=o(d,u,m,p,_,g);m.transmission>0?i.push(v):m.transparent===!0?r.push(v):t.push(v)}function c(d,u,m,p,_,g){let v=o(d,u,m,p,_,g);m.transmission>0?i.unshift(v):m.transparent===!0?r.unshift(v):t.unshift(v)}function f(d,u){t.length>1&&t.sort(d||Ite),i.length>1&&i.sort(u||o1),r.length>1&&r.sort(u||o1)}function h(){for(let d=e,u=n.length;d=s.length?(a=new l1,s.push(a)):a=s[r],a}function t(){n=new WeakMap}return{get:e,dispose:t}}function Cte(){let n={};return{get:function(e){if(n[e.id]!==void 0)return n[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new ne,color:new ct};break;case"SpotLight":t={position:new ne,direction:new ne,color:new ct,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new ne,color:new ct,distance:0,decay:0};break;case"HemisphereLight":t={direction:new ne,skyColor:new ct,groundColor:new ct};break;case"RectAreaLight":t={color:new ct,position:new ne,halfWidth:new ne,halfHeight:new ne};break}return n[e.id]=t,t}}}function yte(){let n={};return{get:function(e){if(n[e.id]!==void 0)return n[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new bt};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new bt};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new bt,shadowCameraNear:1,shadowCameraFar:1e3};break}return n[e.id]=t,t}}}function Dte(n,e){return(e.castShadow?2:0)-(n.castShadow?2:0)+(e.map?1:0)-(n.map?1:0)}function Lte(n){let e=new Cte,t=yte(),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 ne);let r=new ne,s=new oi,a=new oi;function o(c){let f=0,h=0,d=0;for(let y=0;y<9;y++)i.probe[y].set(0,0,0);let u=0,m=0,p=0,_=0,g=0,v=0,x=0,A=0,S=0,E=0,R=0;c.sort(Dte);for(let y=0,M=c.length;y0&&(n.has("OES_texture_float_linear")===!0?(i.rectAreaLTC1=mt.LTC_FLOAT_1,i.rectAreaLTC2=mt.LTC_FLOAT_2):(i.rectAreaLTC1=mt.LTC_HALF_1,i.rectAreaLTC2=mt.LTC_HALF_2)),i.ambient[0]=f,i.ambient[1]=h,i.ambient[2]=d;let I=i.hash;(I.directionalLength!==u||I.pointLength!==m||I.spotLength!==p||I.rectAreaLength!==_||I.hemiLength!==g||I.numDirectionalShadows!==v||I.numPointShadows!==x||I.numSpotShadows!==A||I.numSpotMaps!==S||I.numLightProbes!==R)&&(i.directional.length=u,i.spot.length=p,i.rectArea.length=_,i.point.length=m,i.hemi.length=g,i.directionalShadow.length=v,i.directionalShadowMap.length=v,i.pointShadow.length=x,i.pointShadowMap.length=x,i.spotShadow.length=A,i.spotShadowMap.length=A,i.directionalShadowMatrix.length=v,i.pointShadowMatrix.length=x,i.spotLightMatrix.length=A+S-E,i.spotLightMap.length=S,i.numSpotLightShadowsWithMaps=E,i.numLightProbes=R,I.directionalLength=u,I.pointLength=m,I.spotLength=p,I.rectAreaLength=_,I.hemiLength=g,I.numDirectionalShadows=v,I.numPointShadows=x,I.numSpotShadows=A,I.numSpotMaps=S,I.numLightProbes=R,i.version=Pte++)}function l(c,f){let h=0,d=0,u=0,m=0,p=0,_=f.matrixWorldInverse;for(let g=0,v=c.length;g=a.length?(o=new c1(n),a.push(o)):o=a[s],o}function i(){e=new WeakMap}return{get:t,dispose:i}}function Ute(n,e,t){let i=new vu,r=new bt,s=new bt,a=new Zi,o=new pE,l=new _E,c={},f=t.maxTextureSize,h={[Gs]:pn,[pn]:Gs,[ma]:ma},d=new Ws({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new bt},radius:{value:4}},vertexShader:Nte,fragmentShader:wte}),u=d.clone();u.defines.HORIZONTAL_PASS=1;let m=new Ui;m.setAttribute("position",new or(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let p=new ii(m,d),_=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=h_;let g=this.type;this.render=function(E,R,I){if(_.enabled===!1||_.autoUpdate===!1&&_.needsUpdate===!1||E.length===0)return;this.type===CE&&(Mt("WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead."),this.type=h_);let y=n.getRenderTarget(),M=n.getActiveCubeFace(),D=n.getActiveMipmapLevel(),O=n.state;O.setBlending(ko),O.buffers.depth.getReversed()===!0?O.buffers.color.setClear(0,0,0,0):O.buffers.color.setClear(1,1,1,1),O.buffers.depth.setTest(!0),O.setScissorTest(!1);let V=g!==this.type;V&&R.traverse(function(N){N.material&&(Array.isArray(N.material)?N.material.forEach(F=>F.needsUpdate=!0):N.material.needsUpdate=!0)});for(let N=0,F=E.length;Nf||r.y>f)&&(r.x>f&&(s.x=Math.floor(f/ee.x),r.x=s.x*ee.x,k.mapSize.x=s.x),r.y>f&&(s.y=Math.floor(f/ee.y),r.y=s.y*ee.y,k.mapSize.y=s.y));let q=n.state.buffers.depth.getReversed();if(k.camera._reversedDepth=q,k.map===null||V===!0){if(k.map!==null&&(k.map.depthTexture!==null&&(k.map.depthTexture.dispose(),k.map.depthTexture=null),k.map.dispose()),this.type===Ru){if(U.isPointLight){Mt("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}k.map=new ks(r.x,r.y,{format:Jc,type:Wo,minFilter:Lr,magFilter:Lr,generateMipmaps:!1}),k.map.texture.name=U.name+".shadowMap",k.map.depthTexture=new Cl(r.x,r.y,zs),k.map.depthTexture.name=U.name+".shadowMapDepth",k.map.depthTexture.format=Lo,k.map.depthTexture.compareFunction=null,k.map.depthTexture.minFilter=Dr,k.map.depthTexture.magFilter=Dr}else U.isPointLight?(k.map=new TS(r.x),k.map.depthTexture=new uE(r.x,Za)):(k.map=new ks(r.x,r.y),k.map.depthTexture=new Cl(r.x,r.y,Za)),k.map.depthTexture.name=U.name+".shadowMap",k.map.depthTexture.format=Lo,this.type===h_?(k.map.depthTexture.compareFunction=q?gS:_S,k.map.depthTexture.minFilter=Lr,k.map.depthTexture.magFilter=Lr):(k.map.depthTexture.compareFunction=null,k.map.depthTexture.minFilter=Dr,k.map.depthTexture.magFilter=Dr);k.camera.updateProjectionMatrix()}let Q=k.map.isWebGLCubeRenderTarget?6:1;for(let Y=0;Y0||R.map&&R.alphaTest>0||R.alphaToCoverage===!0){let O=M.uuid,V=R.uuid,N=c[O];N===void 0&&(N={},c[O]=N);let F=N[V];F===void 0&&(F=M.clone(),N[V]=F,R.addEventListener("dispose",S)),M=F}if(M.visible=R.visible,M.wireframe=R.wireframe,y===Ru?M.side=R.shadowSide!==null?R.shadowSide:R.side:M.side=R.shadowSide!==null?R.shadowSide:h[R.side],M.alphaMap=R.alphaMap,M.alphaTest=R.alphaToCoverage===!0?.5:R.alphaTest,M.map=R.map,M.clipShadows=R.clipShadows,M.clippingPlanes=R.clippingPlanes,M.clipIntersection=R.clipIntersection,M.displacementMap=R.displacementMap,M.displacementScale=R.displacementScale,M.displacementBias=R.displacementBias,M.wireframeLinewidth=R.wireframeLinewidth,M.linewidth=R.linewidth,I.isPointLight===!0&&M.isMeshDistanceMaterial===!0){let O=n.properties.get(M);O.light=I}return M}function A(E,R,I,y,M){if(E.visible===!1)return;if(E.layers.test(R.layers)&&(E.isMesh||E.isLine||E.isPoints)&&(E.castShadow||E.receiveShadow&&M===Ru)&&(!E.frustumCulled||i.intersectsObject(E))){E.modelViewMatrix.multiplyMatrices(I.matrixWorldInverse,E.matrixWorld);let V=e.update(E),N=E.material;if(Array.isArray(N)){let F=V.groups;for(let U=0,k=F.length;U=1):q.indexOf("OpenGL ES")!==-1&&(ee=parseFloat(/^OpenGL ES (\d)/.exec(q)[1]),k=ee>=2);let Q=null,Y={},K=n.getParameter(n.SCISSOR_BOX),de=n.getParameter(n.VIEWPORT),Re=new Zi().fromArray(K),Fe=new Zi().fromArray(de);function se(G,ve,Ae,He){let ke=new Uint8Array(4),Oe=n.createTexture();n.bindTexture(G,Oe),n.texParameteri(G,n.TEXTURE_MIN_FILTER,n.NEAREST),n.texParameteri(G,n.TEXTURE_MAG_FILTER,n.NEAREST);for(let Tt=0;Ttme||Be.height>me)&&(ye=me/Math.max(Be.width,Be.height)),ye<1)if(typeof HTMLImageElement!="undefined"&&X instanceof HTMLImageElement||typeof HTMLCanvasElement!="undefined"&&X instanceof HTMLCanvasElement||typeof ImageBitmap!="undefined"&&X instanceof ImageBitmap||typeof VideoFrame!="undefined"&&X instanceof VideoFrame){let Je=Math.floor(ye*Be.width),rt=Math.floor(ye*Be.height);d===void 0&&(d=p(Je,rt));let Ce=B?p(Je,rt):d;return Ce.width=Je,Ce.height=rt,Ce.getContext("2d").drawImage(X,0,0,Je,rt),Mt("WebGLRenderer: Texture has been resized from ("+Be.width+"x"+Be.height+") to ("+Je+"x"+rt+")."),Ce}else return"data"in X&&Mt("WebGLRenderer: Image in DataTexture is too big ("+Be.width+"x"+Be.height+")."),X;return X}function g(X){return X.generateMipmaps}function v(X){n.generateMipmap(X)}function x(X){return X.isWebGLCubeRenderTarget?n.TEXTURE_CUBE_MAP:X.isWebGL3DRenderTarget?n.TEXTURE_3D:X.isWebGLArrayRenderTarget||X.isCompressedArrayTexture?n.TEXTURE_2D_ARRAY:n.TEXTURE_2D}function A(X,B,me,ye,Be,Je=!1){if(X!==null){if(n[X]!==void 0)return n[X];Mt("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+X+"'")}let rt;ye&&(rt=e.get("EXT_texture_norm16"),rt||Mt("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let Ce=B;if(B===n.RED&&(me===n.FLOAT&&(Ce=n.R32F),me===n.HALF_FLOAT&&(Ce=n.R16F),me===n.UNSIGNED_BYTE&&(Ce=n.R8),me===n.UNSIGNED_SHORT&&rt&&(Ce=rt.R16_EXT),me===n.SHORT&&rt&&(Ce=rt.R16_SNORM_EXT)),B===n.RED_INTEGER&&(me===n.UNSIGNED_BYTE&&(Ce=n.R8UI),me===n.UNSIGNED_SHORT&&(Ce=n.R16UI),me===n.UNSIGNED_INT&&(Ce=n.R32UI),me===n.BYTE&&(Ce=n.R8I),me===n.SHORT&&(Ce=n.R16I),me===n.INT&&(Ce=n.R32I)),B===n.RG&&(me===n.FLOAT&&(Ce=n.RG32F),me===n.HALF_FLOAT&&(Ce=n.RG16F),me===n.UNSIGNED_BYTE&&(Ce=n.RG8),me===n.UNSIGNED_SHORT&&rt&&(Ce=rt.RG16_EXT),me===n.SHORT&&rt&&(Ce=rt.RG16_SNORM_EXT)),B===n.RG_INTEGER&&(me===n.UNSIGNED_BYTE&&(Ce=n.RG8UI),me===n.UNSIGNED_SHORT&&(Ce=n.RG16UI),me===n.UNSIGNED_INT&&(Ce=n.RG32UI),me===n.BYTE&&(Ce=n.RG8I),me===n.SHORT&&(Ce=n.RG16I),me===n.INT&&(Ce=n.RG32I)),B===n.RGB_INTEGER&&(me===n.UNSIGNED_BYTE&&(Ce=n.RGB8UI),me===n.UNSIGNED_SHORT&&(Ce=n.RGB16UI),me===n.UNSIGNED_INT&&(Ce=n.RGB32UI),me===n.BYTE&&(Ce=n.RGB8I),me===n.SHORT&&(Ce=n.RGB16I),me===n.INT&&(Ce=n.RGB32I)),B===n.RGBA_INTEGER&&(me===n.UNSIGNED_BYTE&&(Ce=n.RGBA8UI),me===n.UNSIGNED_SHORT&&(Ce=n.RGBA16UI),me===n.UNSIGNED_INT&&(Ce=n.RGBA32UI),me===n.BYTE&&(Ce=n.RGBA8I),me===n.SHORT&&(Ce=n.RGBA16I),me===n.INT&&(Ce=n.RGBA32I)),B===n.RGB&&(me===n.UNSIGNED_SHORT&&rt&&(Ce=rt.RGB16_EXT),me===n.SHORT&&rt&&(Ce=rt.RGB16_SNORM_EXT),me===n.UNSIGNED_INT_5_9_9_9_REV&&(Ce=n.RGB9_E5),me===n.UNSIGNED_INT_10F_11F_11F_REV&&(Ce=n.R11F_G11F_B10F)),B===n.RGBA){let Pe=Je?Hp:ai.getTransfer(Be);me===n.FLOAT&&(Ce=n.RGBA32F),me===n.HALF_FLOAT&&(Ce=n.RGBA16F),me===n.UNSIGNED_BYTE&&(Ce=Pe===Xi?n.SRGB8_ALPHA8:n.RGBA8),me===n.UNSIGNED_SHORT&&rt&&(Ce=rt.RGBA16_EXT),me===n.SHORT&&rt&&(Ce=rt.RGBA16_SNORM_EXT),me===n.UNSIGNED_SHORT_4_4_4_4&&(Ce=n.RGBA4),me===n.UNSIGNED_SHORT_5_5_5_1&&(Ce=n.RGB5_A1)}return(Ce===n.R16F||Ce===n.R32F||Ce===n.RG16F||Ce===n.RG32F||Ce===n.RGBA16F||Ce===n.RGBA32F)&&e.get("EXT_color_buffer_float"),Ce}function S(X,B){let me;return X?B===null||B===Za||B===Mu?me=n.DEPTH24_STENCIL8:B===zs?me=n.DEPTH32F_STENCIL8:B===Iu&&(me=n.DEPTH24_STENCIL8,Mt("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):B===null||B===Za||B===Mu?me=n.DEPTH_COMPONENT24:B===zs?me=n.DEPTH_COMPONENT32F:B===Iu&&(me=n.DEPTH_COMPONENT16),me}function E(X,B){return g(X)===!0||X.isFramebufferTexture&&X.minFilter!==Dr&&X.minFilter!==Lr?Math.log2(Math.max(B.width,B.height))+1:X.mipmaps!==void 0&&X.mipmaps.length>0?X.mipmaps.length:X.isCompressedTexture&&Array.isArray(X.image)?B.mipmaps.length:1}function R(X){let B=X.target;B.removeEventListener("dispose",R),y(B),B.isVideoTexture&&f.delete(B),B.isHTMLTexture&&h.delete(B)}function I(X){let B=X.target;B.removeEventListener("dispose",I),D(B)}function y(X){let B=i.get(X);if(B.__webglInit===void 0)return;let me=X.source,ye=u.get(me);if(ye){let Be=ye[B.__cacheKey];Be.usedTimes--,Be.usedTimes===0&&M(X),Object.keys(ye).length===0&&u.delete(me)}i.remove(X)}function M(X){let B=i.get(X);n.deleteTexture(B.__webglTexture);let me=X.source,ye=u.get(me);delete ye[B.__cacheKey],a.memory.textures--}function D(X){let B=i.get(X);if(X.depthTexture&&(X.depthTexture.dispose(),i.remove(X.depthTexture)),X.isWebGLCubeRenderTarget)for(let ye=0;ye<6;ye++){if(Array.isArray(B.__webglFramebuffer[ye]))for(let Be=0;Be=r.maxTextures&&Mt("WebGLTextures: Trying to use "+X+" texture units while this GPU supports only "+r.maxTextures),O+=1,X}function k(X){let B=[];return B.push(X.wrapS),B.push(X.wrapT),B.push(X.wrapR||0),B.push(X.magFilter),B.push(X.minFilter),B.push(X.anisotropy),B.push(X.internalFormat),B.push(X.format),B.push(X.type),B.push(X.generateMipmaps),B.push(X.premultiplyAlpha),B.push(X.flipY),B.push(X.unpackAlignment),B.push(X.colorSpace),B.join()}function ee(X,B){let me=i.get(X);if(X.isVideoTexture&&Wi(X),X.isRenderTargetTexture===!1&&X.isExternalTexture!==!0&&X.version>0&&me.__version!==X.version){let ye=X.image;if(ye===null)Mt("WebGLRenderer: Texture marked for update but no image data found.");else if(ye.complete===!1)Mt("WebGLRenderer: Texture marked for update but image is incomplete");else{he(me,X,B);return}}else X.isExternalTexture&&(me.__webglTexture=X.sourceTexture?X.sourceTexture:null);t.bindTexture(n.TEXTURE_2D,me.__webglTexture,n.TEXTURE0+B)}function q(X,B){let me=i.get(X);if(X.isRenderTargetTexture===!1&&X.version>0&&me.__version!==X.version){he(me,X,B);return}else X.isExternalTexture&&(me.__webglTexture=X.sourceTexture?X.sourceTexture:null);t.bindTexture(n.TEXTURE_2D_ARRAY,me.__webglTexture,n.TEXTURE0+B)}function Q(X,B){let me=i.get(X);if(X.isRenderTargetTexture===!1&&X.version>0&&me.__version!==X.version){he(me,X,B);return}t.bindTexture(n.TEXTURE_3D,me.__webglTexture,n.TEXTURE0+B)}function Y(X,B){let me=i.get(X);if(X.isCubeDepthTexture!==!0&&X.version>0&&me.__version!==X.version){De(me,X,B);return}t.bindTexture(n.TEXTURE_CUBE_MAP,me.__webglTexture,n.TEXTURE0+B)}let K={[Do]:n.REPEAT,[ha]:n.CLAMP_TO_EDGE,[lu]:n.MIRRORED_REPEAT},de={[Dr]:n.NEAREST,[DE]:n.NEAREST_MIPMAP_NEAREST,[Ah]:n.NEAREST_MIPMAP_LINEAR,[Lr]:n.LINEAR,[bu]:n.LINEAR_MIPMAP_NEAREST,[qa]:n.LINEAR_MIPMAP_LINEAR},Re={[yF]:n.NEVER,[NF]:n.ALWAYS,[PF]:n.LESS,[_S]:n.LEQUAL,[DF]:n.EQUAL,[gS]:n.GEQUAL,[LF]:n.GREATER,[OF]:n.NOTEQUAL};function Fe(X,B){if(B.type===zs&&e.has("OES_texture_float_linear")===!1&&(B.magFilter===Lr||B.magFilter===bu||B.magFilter===Ah||B.magFilter===qa||B.minFilter===Lr||B.minFilter===bu||B.minFilter===Ah||B.minFilter===qa)&&Mt("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),n.texParameteri(X,n.TEXTURE_WRAP_S,K[B.wrapS]),n.texParameteri(X,n.TEXTURE_WRAP_T,K[B.wrapT]),(X===n.TEXTURE_3D||X===n.TEXTURE_2D_ARRAY)&&n.texParameteri(X,n.TEXTURE_WRAP_R,K[B.wrapR]),n.texParameteri(X,n.TEXTURE_MAG_FILTER,de[B.magFilter]),n.texParameteri(X,n.TEXTURE_MIN_FILTER,de[B.minFilter]),B.compareFunction&&(n.texParameteri(X,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE),n.texParameteri(X,n.TEXTURE_COMPARE_FUNC,Re[B.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(B.magFilter===Dr||B.minFilter!==Ah&&B.minFilter!==qa||B.type===zs&&e.has("OES_texture_float_linear")===!1)return;if(B.anisotropy>1||i.get(B).__currentAnisotropy){let me=e.get("EXT_texture_filter_anisotropic");n.texParameterf(X,me.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(B.anisotropy,r.getMaxAnisotropy())),i.get(B).__currentAnisotropy=B.anisotropy}}}function se(X,B){let me=!1;X.__webglInit===void 0&&(X.__webglInit=!0,B.addEventListener("dispose",R));let ye=B.source,Be=u.get(ye);Be===void 0&&(Be={},u.set(ye,Be));let Je=k(B);if(Je!==X.__cacheKey){Be[Je]===void 0&&(Be[Je]={texture:n.createTexture(),usedTimes:0},a.memory.textures++,me=!0),Be[Je].usedTimes++;let rt=Be[X.__cacheKey];rt!==void 0&&(Be[X.__cacheKey].usedTimes--,rt.usedTimes===0&&M(B)),X.__cacheKey=Je,X.__webglTexture=Be[Je].texture}return me}function ue(X,B,me){return Math.floor(Math.floor(X/me)/B)}function re(X,B,me,ye){let Je=X.updateRanges;if(Je.length===0)t.texSubImage2D(n.TEXTURE_2D,0,0,0,B.width,B.height,me,ye,B.data);else{Je.sort((St,nt)=>St.start-nt.start);let rt=0;for(let St=1;St0){jt&&vi&&t.texStorage2D(n.TEXTURE_2D,ve,nt,Vt[0].width,Vt[0].height);for(let Ae=0,He=Vt.length;Ae0){let ke=Z0(et.width,et.height,B.format,B.type);for(let Oe of B.layerUpdates){let Tt=et.data.subarray(Oe*ke/et.data.BYTES_PER_ELEMENT,(Oe+1)*ke/et.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,Ae,0,0,Oe,et.width,et.height,1,je,Tt)}B.clearLayerUpdates()}else t.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,Ae,0,0,0,et.width,et.height,Pe.depth,je,et.data)}else t.compressedTexImage3D(n.TEXTURE_2D_ARRAY,Ae,nt,et.width,et.height,Pe.depth,0,et.data,0,0);else Mt("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else jt?G&&t.texSubImage3D(n.TEXTURE_2D_ARRAY,Ae,0,0,0,et.width,et.height,Pe.depth,je,St,et.data):t.texImage3D(n.TEXTURE_2D_ARRAY,Ae,nt,et.width,et.height,Pe.depth,0,je,St,et.data)}else{jt&&vi&&t.texStorage2D(n.TEXTURE_2D,ve,nt,Vt[0].width,Vt[0].height);for(let Ae=0,He=Vt.length;Ae0){let Ae=Z0(Pe.width,Pe.height,B.format,B.type);for(let He of B.layerUpdates){let ke=Pe.data.subarray(He*Ae/Pe.data.BYTES_PER_ELEMENT,(He+1)*Ae/Pe.data.BYTES_PER_ELEMENT);t.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,He,Pe.width,Pe.height,1,je,St,ke)}B.clearLayerUpdates()}else t.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,0,Pe.width,Pe.height,Pe.depth,je,St,Pe.data)}else t.texImage3D(n.TEXTURE_2D_ARRAY,0,nt,Pe.width,Pe.height,Pe.depth,0,je,St,Pe.data);else if(B.isData3DTexture)jt?(vi&&t.texStorage3D(n.TEXTURE_3D,ve,nt,Pe.width,Pe.height,Pe.depth),G&&t.texSubImage3D(n.TEXTURE_3D,0,0,0,0,Pe.width,Pe.height,Pe.depth,je,St,Pe.data)):t.texImage3D(n.TEXTURE_3D,0,nt,Pe.width,Pe.height,Pe.depth,0,je,St,Pe.data);else if(B.isFramebufferTexture){if(vi)if(jt)t.texStorage2D(n.TEXTURE_2D,ve,nt,Pe.width,Pe.height);else{let Ae=Pe.width,He=Pe.height;for(let ke=0;ke>=1,He>>=1}}else if(B.isHTMLTexture){if("texElementImage2D"in n){let Ae=n.canvas;if(Ae.hasAttribute("layoutsubtree")||Ae.setAttribute("layoutsubtree","true"),Pe.parentNode!==Ae){Ae.appendChild(Pe),h.add(B),Ae.onpaint=Wt=>{let nr=Wt.changedElements;for(let di of h)nr.includes(di.image)&&(di.needsUpdate=!0)},Ae.requestPaint();return}let He=0,ke=n.RGBA,Oe=n.RGBA,Tt=n.UNSIGNED_BYTE;n.texElementImage2D(n.TEXTURE_2D,He,ke,Oe,Tt,Pe),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE)}}else if(Vt.length>0){if(jt&&vi){let Ae=Ci(Vt[0]);t.texStorage2D(n.TEXTURE_2D,ve,nt,Ae.width,Ae.height)}for(let Ae=0,He=Vt.length;Ae0&&He++;let Oe=Ci(nt[0]);t.texStorage2D(n.TEXTURE_CUBE_MAP,He,vi,Oe.width,Oe.height)}for(let Oe=0;Oe<6;Oe++)if(St){G?Ae&&t.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+Oe,0,0,0,nt[Oe].width,nt[Oe].height,Vt,jt,nt[Oe].data):t.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+Oe,0,vi,nt[Oe].width,nt[Oe].height,0,Vt,jt,nt[Oe].data);for(let Tt=0;Tt>Je),et=Math.max(1,B.height>>Je);Be===n.TEXTURE_3D||Be===n.TEXTURE_2D_ARRAY?t.texImage3D(Be,Je,Pe,nt,et,B.depth,0,rt,Ce,null):t.texImage2D(Be,Je,Pe,nt,et,0,rt,Ce,null)}t.bindFramebuffer(n.FRAMEBUFFER,X),ei(B)?o.framebufferTexture2DMultisampleEXT(n.FRAMEBUFFER,ye,Be,St.__webglTexture,0,Bi(B)):(Be===n.TEXTURE_2D||Be>=n.TEXTURE_CUBE_MAP_POSITIVE_X&&Be<=n.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&n.framebufferTexture2D(n.FRAMEBUFFER,ye,Be,St.__webglTexture,Je),t.bindFramebuffer(n.FRAMEBUFFER,null)}function be(X,B,me){if(n.bindRenderbuffer(n.RENDERBUFFER,X),B.depthBuffer){let ye=B.depthTexture,Be=ye&&ye.isDepthTexture?ye.type:null,Je=S(B.stencilBuffer,Be),rt=B.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT;ei(B)?o.renderbufferStorageMultisampleEXT(n.RENDERBUFFER,Bi(B),Je,B.width,B.height):me?n.renderbufferStorageMultisample(n.RENDERBUFFER,Bi(B),Je,B.width,B.height):n.renderbufferStorage(n.RENDERBUFFER,Je,B.width,B.height),n.framebufferRenderbuffer(n.FRAMEBUFFER,rt,n.RENDERBUFFER,X)}else{let ye=B.textures;for(let Be=0;Be{delete B.__boundDepthTexture,delete B.__depthDisposeCallback,ye.removeEventListener("dispose",Be)};ye.addEventListener("dispose",Be),B.__depthDisposeCallback=Be}B.__boundDepthTexture=ye}if(X.depthTexture&&!B.__autoAllocateDepthBuffer)if(me)for(let ye=0;ye<6;ye++)Xe(B.__webglFramebuffer[ye],X,ye);else{let ye=X.texture.mipmaps;ye&&ye.length>0?Xe(B.__webglFramebuffer[0],X,0):Xe(B.__webglFramebuffer,X,0)}else if(me){B.__webglDepthbuffer=[];for(let ye=0;ye<6;ye++)if(t.bindFramebuffer(n.FRAMEBUFFER,B.__webglFramebuffer[ye]),B.__webglDepthbuffer[ye]===void 0)B.__webglDepthbuffer[ye]=n.createRenderbuffer(),be(B.__webglDepthbuffer[ye],X,!1);else{let Be=X.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,Je=B.__webglDepthbuffer[ye];n.bindRenderbuffer(n.RENDERBUFFER,Je),n.framebufferRenderbuffer(n.FRAMEBUFFER,Be,n.RENDERBUFFER,Je)}}else{let ye=X.texture.mipmaps;if(ye&&ye.length>0?t.bindFramebuffer(n.FRAMEBUFFER,B.__webglFramebuffer[0]):t.bindFramebuffer(n.FRAMEBUFFER,B.__webglFramebuffer),B.__webglDepthbuffer===void 0)B.__webglDepthbuffer=n.createRenderbuffer(),be(B.__webglDepthbuffer,X,!1);else{let Be=X.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,Je=B.__webglDepthbuffer;n.bindRenderbuffer(n.RENDERBUFFER,Je),n.framebufferRenderbuffer(n.FRAMEBUFFER,Be,n.RENDERBUFFER,Je)}}t.bindFramebuffer(n.FRAMEBUFFER,null)}function Ke(X,B,me){let ye=i.get(X);B!==void 0&&fe(ye.__webglFramebuffer,X,X.texture,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,0),me!==void 0&&Et(X)}function qe(X){let B=X.texture,me=i.get(X),ye=i.get(B);X.addEventListener("dispose",I);let Be=X.textures,Je=X.isWebGLCubeRenderTarget===!0,rt=Be.length>1;if(rt||(ye.__webglTexture===void 0&&(ye.__webglTexture=n.createTexture()),ye.__version=B.version,a.memory.textures++),Je){me.__webglFramebuffer=[];for(let Ce=0;Ce<6;Ce++)if(B.mipmaps&&B.mipmaps.length>0){me.__webglFramebuffer[Ce]=[];for(let Pe=0;Pe0){me.__webglFramebuffer=[];for(let Ce=0;Ce0&&ei(X)===!1){me.__webglMultisampledFramebuffer=n.createFramebuffer(),me.__webglColorRenderbuffer=[],t.bindFramebuffer(n.FRAMEBUFFER,me.__webglMultisampledFramebuffer);for(let Ce=0;Ce0)for(let Pe=0;Pe0)for(let Pe=0;Pe0){if(ei(X)===!1){let B=X.textures,me=X.width,ye=X.height,Be=n.COLOR_BUFFER_BIT,Je=X.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,rt=i.get(X),Ce=B.length>1;if(Ce)for(let je=0;je0?t.bindFramebuffer(n.DRAW_FRAMEBUFFER,rt.__webglFramebuffer[0]):t.bindFramebuffer(n.DRAW_FRAMEBUFFER,rt.__webglFramebuffer);for(let je=0;je0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&B.__useRenderToTexture!==!1}function Wi(X){let B=a.render.frame;f.get(X)!==B&&(f.set(X,B),X.update())}function ot(X,B){let me=X.colorSpace,ye=X.format,Be=X.type;return X.isCompressedTexture===!0||X.isVideoTexture===!0||me!==jn&&me!==Ol&&(ai.getTransfer(me)===Xi?(ye!==Xs||Be!==_s)&&Mt("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):Ft("WebGLTextures: Unsupported texture color space:",me)),B}function Ci(X){return typeof HTMLImageElement!="undefined"&&X instanceof HTMLImageElement?(c.width=X.naturalWidth||X.width,c.height=X.naturalHeight||X.height):typeof VideoFrame!="undefined"&&X instanceof VideoFrame?(c.width=X.displayWidth,c.height=X.displayHeight):(c.width=X.width,c.height=X.height),c}this.allocateTextureUnit=U,this.resetTextureUnits=V,this.getTextureUnits=N,this.setTextureUnits=F,this.setTexture2D=ee,this.setTexture2DArray=q,this.setTexture3D=Q,this.setTextureCube=Y,this.rebindTextures=Ke,this.setupRenderTarget=qe,this.updateRenderTargetMipmap=Qt,this.updateMultisampleRenderTarget=ae,this.setupDepthRenderbuffer=Et,this.setupFrameBufferTexture=fe,this.useMultisampledRTT=ei,this.isReversedDepthBuffer=function(){return t.buffers.depth.getReversed()}}function kte(n,e){function t(i,r=Ol){let s,a=ai.getTransfer(r);if(i===_s)return n.UNSIGNED_BYTE;if(i===OE)return n.UNSIGNED_SHORT_4_4_4_4;if(i===NE)return n.UNSIGNED_SHORT_5_5_5_1;if(i===G0)return n.UNSIGNED_INT_5_9_9_9_REV;if(i===k0)return n.UNSIGNED_INT_10F_11F_11F_REV;if(i===U0)return n.BYTE;if(i===V0)return n.SHORT;if(i===Iu)return n.UNSIGNED_SHORT;if(i===LE)return n.INT;if(i===Za)return n.UNSIGNED_INT;if(i===zs)return n.FLOAT;if(i===Wo)return n.HALF_FLOAT;if(i===W0)return n.ALPHA;if(i===H0)return n.RGB;if(i===Xs)return n.RGBA;if(i===Lo)return n.DEPTH_COMPONENT;if(i===$c)return n.DEPTH_STENCIL;if(i===wE)return n.RED;if(i===FE)return n.RED_INTEGER;if(i===Jc)return n.RG;if(i===BE)return n.RG_INTEGER;if(i===UE)return n.RGBA_INTEGER;if(i===m_||i===p_||i===__||i===g_)if(a===Xi)if(s=e.get("WEBGL_compressed_texture_s3tc_srgb"),s!==null){if(i===m_)return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===p_)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===__)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===g_)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(s=e.get("WEBGL_compressed_texture_s3tc"),s!==null){if(i===m_)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===p_)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===__)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===g_)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(i===VE||i===GE||i===kE||i===WE)if(s=e.get("WEBGL_compressed_texture_pvrtc"),s!==null){if(i===VE)return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(i===GE)return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===kE)return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(i===WE)return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(i===HE||i===zE||i===XE||i===YE||i===KE||i===v_||i===jE)if(s=e.get("WEBGL_compressed_texture_etc"),s!==null){if(i===HE||i===zE)return a===Xi?s.COMPRESSED_SRGB8_ETC2:s.COMPRESSED_RGB8_ETC2;if(i===XE)return a===Xi?s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:s.COMPRESSED_RGBA8_ETC2_EAC;if(i===YE)return s.COMPRESSED_R11_EAC;if(i===KE)return s.COMPRESSED_SIGNED_R11_EAC;if(i===v_)return s.COMPRESSED_RG11_EAC;if(i===jE)return s.COMPRESSED_SIGNED_RG11_EAC}else return null;if(i===qE||i===ZE||i===QE||i===$E||i===JE||i===eS||i===tS||i===iS||i===rS||i===nS||i===sS||i===aS||i===oS||i===lS)if(s=e.get("WEBGL_compressed_texture_astc"),s!==null){if(i===qE)return a===Xi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:s.COMPRESSED_RGBA_ASTC_4x4_KHR;if(i===ZE)return a===Xi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:s.COMPRESSED_RGBA_ASTC_5x4_KHR;if(i===QE)return a===Xi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:s.COMPRESSED_RGBA_ASTC_5x5_KHR;if(i===$E)return a===Xi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:s.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===JE)return a===Xi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:s.COMPRESSED_RGBA_ASTC_6x6_KHR;if(i===eS)return a===Xi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:s.COMPRESSED_RGBA_ASTC_8x5_KHR;if(i===tS)return a===Xi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:s.COMPRESSED_RGBA_ASTC_8x6_KHR;if(i===iS)return a===Xi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:s.COMPRESSED_RGBA_ASTC_8x8_KHR;if(i===rS)return a===Xi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:s.COMPRESSED_RGBA_ASTC_10x5_KHR;if(i===nS)return a===Xi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:s.COMPRESSED_RGBA_ASTC_10x6_KHR;if(i===sS)return a===Xi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:s.COMPRESSED_RGBA_ASTC_10x8_KHR;if(i===aS)return a===Xi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:s.COMPRESSED_RGBA_ASTC_10x10_KHR;if(i===oS)return a===Xi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:s.COMPRESSED_RGBA_ASTC_12x10_KHR;if(i===lS)return a===Xi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:s.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(i===cS||i===fS||i===hS)if(s=e.get("EXT_texture_compression_bptc"),s!==null){if(i===cS)return a===Xi?s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:s.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(i===fS)return s.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(i===hS)return s.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(i===dS||i===uS||i===E_||i===mS)if(s=e.get("EXT_texture_compression_rgtc"),s!==null){if(i===dS)return s.COMPRESSED_RED_RGTC1_EXT;if(i===uS)return s.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(i===E_)return s.COMPRESSED_RED_GREEN_RGTC2_EXT;if(i===mS)return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return i===Mu?n.UNSIGNED_INT_24_8:n[i]!==void 0?n[i]:null}return{convert:t}}function Xte(n,e){function t(_,g){_.matrixAutoUpdate===!0&&_.updateMatrix(),g.value.copy(_.matrix)}function i(_,g){g.color.getRGB(_.fogColor.value,K0(n)),g.isFog?(_.fogNear.value=g.near,_.fogFar.value=g.far):g.isFogExp2&&(_.fogDensity.value=g.density)}function r(_,g,v,x,A){g.isNodeMaterial?g.uniformsNeedUpdate=!1:g.isMeshBasicMaterial?s(_,g):g.isMeshLambertMaterial?(s(_,g),g.envMap&&(_.envMapIntensity.value=g.envMapIntensity)):g.isMeshToonMaterial?(s(_,g),h(_,g)):g.isMeshPhongMaterial?(s(_,g),f(_,g),g.envMap&&(_.envMapIntensity.value=g.envMapIntensity)):g.isMeshStandardMaterial?(s(_,g),d(_,g),g.isMeshPhysicalMaterial&&u(_,g,A)):g.isMeshMatcapMaterial?(s(_,g),m(_,g)):g.isMeshDepthMaterial?s(_,g):g.isMeshDistanceMaterial?(s(_,g),p(_,g)):g.isMeshNormalMaterial?s(_,g):g.isLineBasicMaterial?(a(_,g),g.isLineDashedMaterial&&o(_,g)):g.isPointsMaterial?l(_,g,v,x):g.isSpriteMaterial?c(_,g):g.isShadowMaterial?(_.color.value.copy(g.color),_.opacity.value=g.opacity):g.isShaderMaterial&&(g.uniformsNeedUpdate=!1)}function s(_,g){_.opacity.value=g.opacity,g.color&&_.diffuse.value.copy(g.color),g.emissive&&_.emissive.value.copy(g.emissive).multiplyScalar(g.emissiveIntensity),g.map&&(_.map.value=g.map,t(g.map,_.mapTransform)),g.alphaMap&&(_.alphaMap.value=g.alphaMap,t(g.alphaMap,_.alphaMapTransform)),g.bumpMap&&(_.bumpMap.value=g.bumpMap,t(g.bumpMap,_.bumpMapTransform),_.bumpScale.value=g.bumpScale,g.side===pn&&(_.bumpScale.value*=-1)),g.normalMap&&(_.normalMap.value=g.normalMap,t(g.normalMap,_.normalMapTransform),_.normalScale.value.copy(g.normalScale),g.side===pn&&_.normalScale.value.negate()),g.displacementMap&&(_.displacementMap.value=g.displacementMap,t(g.displacementMap,_.displacementMapTransform),_.displacementScale.value=g.displacementScale,_.displacementBias.value=g.displacementBias),g.emissiveMap&&(_.emissiveMap.value=g.emissiveMap,t(g.emissiveMap,_.emissiveMapTransform)),g.specularMap&&(_.specularMap.value=g.specularMap,t(g.specularMap,_.specularMapTransform)),g.alphaTest>0&&(_.alphaTest.value=g.alphaTest);let v=e.get(g),x=v.envMap,A=v.envMapRotation;x&&(_.envMap.value=x,_.envMapRotation.value.setFromMatrix4(zte.makeRotationFromEuler(A)).transpose(),x.isCubeTexture&&x.isRenderTargetTexture===!1&&_.envMapRotation.value.premultiply(g1),_.reflectivity.value=g.reflectivity,_.ior.value=g.ior,_.refractionRatio.value=g.refractionRatio),g.lightMap&&(_.lightMap.value=g.lightMap,_.lightMapIntensity.value=g.lightMapIntensity,t(g.lightMap,_.lightMapTransform)),g.aoMap&&(_.aoMap.value=g.aoMap,_.aoMapIntensity.value=g.aoMapIntensity,t(g.aoMap,_.aoMapTransform))}function a(_,g){_.diffuse.value.copy(g.color),_.opacity.value=g.opacity,g.map&&(_.map.value=g.map,t(g.map,_.mapTransform))}function o(_,g){_.dashSize.value=g.dashSize,_.totalSize.value=g.dashSize+g.gapSize,_.scale.value=g.scale}function l(_,g,v,x){_.diffuse.value.copy(g.color),_.opacity.value=g.opacity,_.size.value=g.size*v,_.scale.value=x*.5,g.map&&(_.map.value=g.map,t(g.map,_.uvTransform)),g.alphaMap&&(_.alphaMap.value=g.alphaMap,t(g.alphaMap,_.alphaMapTransform)),g.alphaTest>0&&(_.alphaTest.value=g.alphaTest)}function c(_,g){_.diffuse.value.copy(g.color),_.opacity.value=g.opacity,_.rotation.value=g.rotation,g.map&&(_.map.value=g.map,t(g.map,_.mapTransform)),g.alphaMap&&(_.alphaMap.value=g.alphaMap,t(g.alphaMap,_.alphaMapTransform)),g.alphaTest>0&&(_.alphaTest.value=g.alphaTest)}function f(_,g){_.specular.value.copy(g.specular),_.shininess.value=Math.max(g.shininess,1e-4)}function h(_,g){g.gradientMap&&(_.gradientMap.value=g.gradientMap)}function d(_,g){_.metalness.value=g.metalness,g.metalnessMap&&(_.metalnessMap.value=g.metalnessMap,t(g.metalnessMap,_.metalnessMapTransform)),_.roughness.value=g.roughness,g.roughnessMap&&(_.roughnessMap.value=g.roughnessMap,t(g.roughnessMap,_.roughnessMapTransform)),g.envMap&&(_.envMapIntensity.value=g.envMapIntensity)}function u(_,g,v){_.ior.value=g.ior,g.sheen>0&&(_.sheenColor.value.copy(g.sheenColor).multiplyScalar(g.sheen),_.sheenRoughness.value=g.sheenRoughness,g.sheenColorMap&&(_.sheenColorMap.value=g.sheenColorMap,t(g.sheenColorMap,_.sheenColorMapTransform)),g.sheenRoughnessMap&&(_.sheenRoughnessMap.value=g.sheenRoughnessMap,t(g.sheenRoughnessMap,_.sheenRoughnessMapTransform))),g.clearcoat>0&&(_.clearcoat.value=g.clearcoat,_.clearcoatRoughness.value=g.clearcoatRoughness,g.clearcoatMap&&(_.clearcoatMap.value=g.clearcoatMap,t(g.clearcoatMap,_.clearcoatMapTransform)),g.clearcoatRoughnessMap&&(_.clearcoatRoughnessMap.value=g.clearcoatRoughnessMap,t(g.clearcoatRoughnessMap,_.clearcoatRoughnessMapTransform)),g.clearcoatNormalMap&&(_.clearcoatNormalMap.value=g.clearcoatNormalMap,t(g.clearcoatNormalMap,_.clearcoatNormalMapTransform),_.clearcoatNormalScale.value.copy(g.clearcoatNormalScale),g.side===pn&&_.clearcoatNormalScale.value.negate())),g.dispersion>0&&(_.dispersion.value=g.dispersion),g.iridescence>0&&(_.iridescence.value=g.iridescence,_.iridescenceIOR.value=g.iridescenceIOR,_.iridescenceThicknessMinimum.value=g.iridescenceThicknessRange[0],_.iridescenceThicknessMaximum.value=g.iridescenceThicknessRange[1],g.iridescenceMap&&(_.iridescenceMap.value=g.iridescenceMap,t(g.iridescenceMap,_.iridescenceMapTransform)),g.iridescenceThicknessMap&&(_.iridescenceThicknessMap.value=g.iridescenceThicknessMap,t(g.iridescenceThicknessMap,_.iridescenceThicknessMapTransform))),g.transmission>0&&(_.transmission.value=g.transmission,_.transmissionSamplerMap.value=v.texture,_.transmissionSamplerSize.value.set(v.width,v.height),g.transmissionMap&&(_.transmissionMap.value=g.transmissionMap,t(g.transmissionMap,_.transmissionMapTransform)),_.thickness.value=g.thickness,g.thicknessMap&&(_.thicknessMap.value=g.thicknessMap,t(g.thicknessMap,_.thicknessMapTransform)),_.attenuationDistance.value=g.attenuationDistance,_.attenuationColor.value.copy(g.attenuationColor)),g.anisotropy>0&&(_.anisotropyVector.value.set(g.anisotropy*Math.cos(g.anisotropyRotation),g.anisotropy*Math.sin(g.anisotropyRotation)),g.anisotropyMap&&(_.anisotropyMap.value=g.anisotropyMap,t(g.anisotropyMap,_.anisotropyMapTransform))),_.specularIntensity.value=g.specularIntensity,_.specularColor.value.copy(g.specularColor),g.specularColorMap&&(_.specularColorMap.value=g.specularColorMap,t(g.specularColorMap,_.specularColorMapTransform)),g.specularIntensityMap&&(_.specularIntensityMap.value=g.specularIntensityMap,t(g.specularIntensityMap,_.specularIntensityMapTransform))}function m(_,g){g.matcap&&(_.matcap.value=g.matcap)}function p(_,g){let v=e.get(g).light;_.referencePosition.value.setFromMatrixPosition(v.matrixWorld),_.nearDistance.value=v.shadow.camera.near,_.farDistance.value=v.shadow.camera.far}return{refreshFogUniforms:i,refreshMaterialUniforms:r}}function Yte(n,e,t,i){let r={},s={},a=[],o=n.getParameter(n.MAX_UNIFORM_BUFFER_BINDINGS);function l(v,x){let A=x.program;i.uniformBlockBinding(v,A)}function c(v,x){let A=r[v.id];A===void 0&&(m(v),A=f(v),r[v.id]=A,v.addEventListener("dispose",_));let S=x.program;i.updateUBOMapping(v,S);let E=e.render.frame;s[v.id]!==E&&(d(v),s[v.id]=E)}function f(v){let x=h();v.__bindingPointIndex=x;let A=n.createBuffer(),S=v.__size,E=v.usage;return n.bindBuffer(n.UNIFORM_BUFFER,A),n.bufferData(n.UNIFORM_BUFFER,S,E),n.bindBuffer(n.UNIFORM_BUFFER,null),n.bindBufferBase(n.UNIFORM_BUFFER,x,A),A}function h(){for(let v=0;v0&&(A+=S-E),v.__size=A,v.__cache={},this}function p(v){let x={boundary:0,storage:0};return typeof v=="number"||typeof v=="boolean"?(x.boundary=4,x.storage=4):v.isVector2?(x.boundary=8,x.storage=8):v.isVector3||v.isColor?(x.boundary=16,x.storage=12):v.isVector4?(x.boundary=16,x.storage=16):v.isMatrix3?(x.boundary=48,x.storage=48):v.isMatrix4?(x.boundary=64,x.storage=64):v.isTexture?Mt("WebGLRenderer: Texture samplers can not be part of an uniforms group."):ArrayBuffer.isView(v)?(x.boundary=16,x.storage=v.byteLength):Mt("WebGLRenderer: Unsupported uniform value type.",v),x}function _(v){let x=v.target;x.removeEventListener("dispose",_);let A=a.indexOf(x.__bindingPointIndex);a.splice(A,1),n.deleteBuffer(r[x.id]),delete r[x.id],delete s[x.id]}function g(){for(let v in r)n.deleteBuffer(r[v]);a=[],r={},s={}}return{bind:l,update:c,dispose:g}}function jte(){return Ho===null&&(Ho=new gu(Kte,16,16,Jc,Wo),Ho.name="DFG_LUT",Ho.minFilter=Lr,Ho.magFilter=Lr,Ho.wrapS=ha,Ho.wrapT=ha,Ho.generateMipmaps=!1,Ho.needsUpdate=!0),Ho}var cQ,fQ,hQ,dQ,uQ,mQ,pQ,_Q,gQ,vQ,EQ,SQ,TQ,AQ,xQ,RQ,bQ,IQ,MQ,CQ,yQ,PQ,DQ,LQ,OQ,NQ,wQ,FQ,BQ,UQ,VQ,GQ,kQ,WQ,HQ,zQ,XQ,YQ,KQ,jQ,qQ,ZQ,QQ,$Q,JQ,e$,t$,i$,r$,n$,s$,a$,o$,l$,c$,f$,h$,d$,u$,m$,p$,_$,g$,v$,E$,S$,T$,A$,x$,R$,b$,I$,M$,C$,y$,P$,D$,L$,O$,N$,w$,F$,B$,U$,V$,G$,k$,W$,H$,z$,X$,Y$,K$,j$,q$,Z$,Q$,$$,J$,eJ,tJ,iJ,rJ,nJ,sJ,aJ,oJ,lJ,cJ,fJ,hJ,dJ,uJ,mJ,pJ,_J,gJ,vJ,EJ,SJ,TJ,AJ,xJ,RJ,bJ,IJ,MJ,CJ,yJ,PJ,DJ,LJ,OJ,NJ,wJ,FJ,BJ,UJ,VJ,GJ,kJ,WJ,fi,mt,zo,ES,HJ,d1,ef,HF,Rh,qJ,A_,zF,rI,nI,sI,aI,ZJ,Lu,TS,oee,u1,cI,m1,p1,_1,jF,qF,ZF,QF,$F,fI,hI,dI,oI,Du,Zee,Qee,t1,tte,SS,ote,lte,fte,dte,mte,_te,vte,Ate,mI,pI,Pte,Nte,wte,Fte,Bte,f1,x_,lI,Wte,Hte,_I,gI,zte,g1,Kte,Ho,AS,Ys=C(()=>{iI();iI();cQ=`#ifdef USE_ALPHAHASH +`+Z+` +`+X)}else F!==""?Ct("WebGLProgram: Program Info Log:",F):(U===""||G==="")&&(j=!1);j&&(D.diagnostics={runnable:ee,programLog:F,vertexShader:{log:U,prefix:_},fragmentShader:{log:G,prefix:g}})}r.deleteShader(S),r.deleteShader(E),I=new Pu(r,p),y=ate(r,p)}let I;this.getUniforms=function(){return I===void 0&&R(this),I};let y;this.getAttributes=function(){return y===void 0&&R(this),y};let M=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return M===!1&&(M=r.getProgramParameter(p,Zee)),M},this.destroy=function(){i.releaseStatesOfProgram(this),r.deleteProgram(p),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=Qee++,this.cacheKey=e,this.usedTimes=1,this.program=p,this.vertexShader=S,this.fragmentShader=E,this}function xte(n){return n===$c||n===v_||n===E_}function Rte(n,e,t,i,r,s){let a=new du,o=new mI,l=new Set,c=[],f=new Map,h=i.logarithmicDepthBuffer,d=i.precision,u={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distance",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 m(I){return l.add(I),I===0?"uv":`uv${I}`}function p(I,y,M,D,O,V){let N=D.fog,F=O.geometry,U=I.isMeshStandardMaterial||I.isMeshLambertMaterial||I.isMeshPhongMaterial?D.environment:null,G=I.isMeshStandardMaterial||I.isMeshLambertMaterial&&!I.envMap||I.isMeshPhongMaterial&&!I.envMap,ee=e.get(I.envMap||U,G),j=ee&&ee.mapping===u_?ee.image.height:null,Z=u[I.type];I.precision!==null&&(d=i.getMaxPrecision(I.precision),d!==I.precision&&Ct("WebGLProgram.getParameters:",I.precision,"not supported, using",d,"instead."));let X=F.morphAttributes.position||F.morphAttributes.normal||F.morphAttributes.color,Y=X!==void 0?X.length:0,ue=0;F.morphAttributes.position!==void 0&&(ue=1),F.morphAttributes.normal!==void 0&&(ue=2),F.morphAttributes.color!==void 0&&(ue=3);let Re,Be,ae,me;if(Z){let qt=zo[Z];Re=qt.vertexShader,Be=qt.fragmentShader}else Re=I.vertexShader,Be=I.fragmentShader,o.update(I),ae=o.getVertexShaderID(I),me=o.getFragmentShaderID(I);let re=n.getRenderTarget(),de=n.state.buffers.depth.getReversed(),De=O.isInstancedMesh===!0,he=O.isBatchedMesh===!0,Ie=!!I.map,ze=!!I.matcap,St=!!ee,Ye=!!I.aoMap,je=!!I.lightMap,$t=!!I.bumpMap,Lt=!!I.normalMap,xi=!!I.displacementMap,oe=!!I.emissiveMap,Ui=!!I.metalnessMap,ti=!!I.roughnessMap,Ni=I.anisotropy>0,ot=I.clearcoat>0,yi=I.dispersion>0,z=I.iridescence>0,B=I.sheen>0,pe=I.transmission>0,Pe=Ni&&!!I.anisotropyMap,Ve=ot&&!!I.clearcoatMap,$e=ot&&!!I.clearcoatNormalMap,rt=ot&&!!I.clearcoatRoughnessMap,ye=z&&!!I.iridescenceMap,be=z&&!!I.iridescenceThicknessMap,ct=B&&!!I.sheenColorMap,Tt=B&&!!I.sheenRoughnessMap,nt=!!I.specularMap,Ze=!!I.specularColorMap,Wt=!!I.specularIntensityMap,jt=pe&&!!I.transmissionMap,se=pe&&!!I.thicknessMap,Q=!!I.gradientMap,Le=!!I.alphaMap,Ae=I.alphaTest>0,Je=!!I.alphaHash,Ke=!!I.extensions,Fe=Ws;I.toneMapped&&(re===null||re.isXRRenderTarget===!0)&&(Fe=n.toneMapping);let At={shaderID:Z,shaderType:I.type,shaderName:I.name,vertexShader:Re,fragmentShader:Be,defines:I.defines,customVertexShaderID:ae,customFragmentShaderID:me,isRawShaderMaterial:I.isRawShaderMaterial===!0,glslVersion:I.glslVersion,precision:d,batching:he,batchingColor:he&&O._colorsTexture!==null,instancing:De,instancingColor:De&&O.instanceColor!==null,instancingMorph:De&&O.morphTexture!==null,outputColorSpace:re===null?n.outputColorSpace:re.isXRRenderTarget===!0?re.texture.colorSpace:oi.workingColorSpace,alphaToCoverage:!!I.alphaToCoverage,map:Ie,matcap:ze,envMap:St,envMapMode:St&&ee.mapping,envMapCubeUVHeight:j,aoMap:Ye,lightMap:je,bumpMap:$t,normalMap:Lt,displacementMap:xi,emissiveMap:oe,normalMapObjectSpace:Lt&&I.normalMapType===CF,normalMapTangentSpace:Lt&&I.normalMapType===Cu,packedNormalMap:Lt&&I.normalMapType===Cu&&xte(I.normalMap.format),metalnessMap:Ui,roughnessMap:ti,anisotropy:Ni,anisotropyMap:Pe,clearcoat:ot,clearcoatMap:Ve,clearcoatNormalMap:$e,clearcoatRoughnessMap:rt,dispersion:yi,iridescence:z,iridescenceMap:ye,iridescenceThicknessMap:be,sheen:B,sheenColorMap:ct,sheenRoughnessMap:Tt,specularMap:nt,specularColorMap:Ze,specularIntensityMap:Wt,transmission:pe,transmissionMap:jt,thicknessMap:se,gradientMap:Q,opaque:I.transparent===!1&&I.blending===ch&&I.alphaToCoverage===!1,alphaMap:Le,alphaTest:Ae,alphaHash:Je,combine:I.combine,mapUv:Ie&&m(I.map.channel),aoMapUv:Ye&&m(I.aoMap.channel),lightMapUv:je&&m(I.lightMap.channel),bumpMapUv:$t&&m(I.bumpMap.channel),normalMapUv:Lt&&m(I.normalMap.channel),displacementMapUv:xi&&m(I.displacementMap.channel),emissiveMapUv:oe&&m(I.emissiveMap.channel),metalnessMapUv:Ui&&m(I.metalnessMap.channel),roughnessMapUv:ti&&m(I.roughnessMap.channel),anisotropyMapUv:Pe&&m(I.anisotropyMap.channel),clearcoatMapUv:Ve&&m(I.clearcoatMap.channel),clearcoatNormalMapUv:$e&&m(I.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:rt&&m(I.clearcoatRoughnessMap.channel),iridescenceMapUv:ye&&m(I.iridescenceMap.channel),iridescenceThicknessMapUv:be&&m(I.iridescenceThicknessMap.channel),sheenColorMapUv:ct&&m(I.sheenColorMap.channel),sheenRoughnessMapUv:Tt&&m(I.sheenRoughnessMap.channel),specularMapUv:nt&&m(I.specularMap.channel),specularColorMapUv:Ze&&m(I.specularColorMap.channel),specularIntensityMapUv:Wt&&m(I.specularIntensityMap.channel),transmissionMapUv:jt&&m(I.transmissionMap.channel),thicknessMapUv:se&&m(I.thicknessMap.channel),alphaMapUv:Le&&m(I.alphaMap.channel),vertexTangents:!!F.attributes.tangent&&(Lt||Ni),vertexNormals:!!F.attributes.normal,vertexColors:I.vertexColors,vertexAlphas:I.vertexColors===!0&&!!F.attributes.color&&F.attributes.color.itemSize===4,pointsUvs:O.isPoints===!0&&!!F.attributes.uv&&(Ie||Le),fog:!!N,useFog:I.fog===!0,fogExp2:!!N&&N.isFogExp2,flatShading:I.wireframe===!1&&(I.flatShading===!0||F.attributes.normal===void 0&&Lt===!1&&(I.isMeshLambertMaterial||I.isMeshPhongMaterial||I.isMeshStandardMaterial||I.isMeshPhysicalMaterial)),sizeAttenuation:I.sizeAttenuation===!0,logarithmicDepthBuffer:h,reversedDepthBuffer:de,skinning:O.isSkinnedMesh===!0,morphTargets:F.morphAttributes.position!==void 0,morphNormals:F.morphAttributes.normal!==void 0,morphColors:F.morphAttributes.color!==void 0,morphTargetsCount:Y,morphTextureStride:ue,numDirLights:y.directional.length,numPointLights:y.point.length,numSpotLights:y.spot.length,numSpotLightMaps:y.spotLightMap.length,numRectAreaLights:y.rectArea.length,numHemiLights:y.hemi.length,numDirLightShadows:y.directionalShadowMap.length,numPointLightShadows:y.pointShadowMap.length,numSpotLightShadows:y.spotShadowMap.length,numSpotLightShadowsWithMaps:y.numSpotLightShadowsWithMaps,numLightProbes:y.numLightProbes,numLightProbeGrids:V.length,numClippingPlanes:s.numPlanes,numClipIntersection:s.numIntersection,dithering:I.dithering,shadowMapEnabled:n.shadowMap.enabled&&M.length>0,shadowMapType:n.shadowMap.type,toneMapping:Fe,decodeVideoTexture:Ie&&I.map.isVideoTexture===!0&&oi.getTransfer(I.map.colorSpace)===Xi,decodeVideoTextureEmissive:oe&&I.emissiveMap.isVideoTexture===!0&&oi.getTransfer(I.emissiveMap.colorSpace)===Xi,premultipliedAlpha:I.premultipliedAlpha,doubleSided:I.side===ua,flipSided:I.side===pn,useDepthPacking:I.depthPacking>=0,depthPacking:I.depthPacking||0,index0AttributeName:I.index0AttributeName,extensionClipCullDistance:Ke&&I.extensions.clipCullDistance===!0&&t.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(Ke&&I.extensions.multiDraw===!0||he)&&t.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:t.has("KHR_parallel_shader_compile"),customProgramCacheKey:I.customProgramCacheKey()};return At.vertexUv1s=l.has(1),At.vertexUv2s=l.has(2),At.vertexUv3s=l.has(3),l.clear(),At}function _(I){let y=[];if(I.shaderID?y.push(I.shaderID):(y.push(I.customVertexShaderID),y.push(I.customFragmentShaderID)),I.defines!==void 0)for(let M in I.defines)y.push(M),y.push(I.defines[M]);return I.isRawShaderMaterial===!1&&(g(y,I),v(y,I),y.push(n.outputColorSpace)),y.push(I.customProgramCacheKey),y.join()}function g(I,y){I.push(y.precision),I.push(y.outputColorSpace),I.push(y.envMapMode),I.push(y.envMapCubeUVHeight),I.push(y.mapUv),I.push(y.alphaMapUv),I.push(y.lightMapUv),I.push(y.aoMapUv),I.push(y.bumpMapUv),I.push(y.normalMapUv),I.push(y.displacementMapUv),I.push(y.emissiveMapUv),I.push(y.metalnessMapUv),I.push(y.roughnessMapUv),I.push(y.anisotropyMapUv),I.push(y.clearcoatMapUv),I.push(y.clearcoatNormalMapUv),I.push(y.clearcoatRoughnessMapUv),I.push(y.iridescenceMapUv),I.push(y.iridescenceThicknessMapUv),I.push(y.sheenColorMapUv),I.push(y.sheenRoughnessMapUv),I.push(y.specularMapUv),I.push(y.specularColorMapUv),I.push(y.specularIntensityMapUv),I.push(y.transmissionMapUv),I.push(y.thicknessMapUv),I.push(y.combine),I.push(y.fogExp2),I.push(y.sizeAttenuation),I.push(y.morphTargetsCount),I.push(y.morphAttributeCount),I.push(y.numDirLights),I.push(y.numPointLights),I.push(y.numSpotLights),I.push(y.numSpotLightMaps),I.push(y.numHemiLights),I.push(y.numRectAreaLights),I.push(y.numDirLightShadows),I.push(y.numPointLightShadows),I.push(y.numSpotLightShadows),I.push(y.numSpotLightShadowsWithMaps),I.push(y.numLightProbes),I.push(y.shadowMapType),I.push(y.toneMapping),I.push(y.numClippingPlanes),I.push(y.numClipIntersection),I.push(y.depthPacking)}function v(I,y){a.disableAll(),y.instancing&&a.enable(0),y.instancingColor&&a.enable(1),y.instancingMorph&&a.enable(2),y.matcap&&a.enable(3),y.envMap&&a.enable(4),y.normalMapObjectSpace&&a.enable(5),y.normalMapTangentSpace&&a.enable(6),y.clearcoat&&a.enable(7),y.iridescence&&a.enable(8),y.alphaTest&&a.enable(9),y.vertexColors&&a.enable(10),y.vertexAlphas&&a.enable(11),y.vertexUv1s&&a.enable(12),y.vertexUv2s&&a.enable(13),y.vertexUv3s&&a.enable(14),y.vertexTangents&&a.enable(15),y.anisotropy&&a.enable(16),y.alphaHash&&a.enable(17),y.batching&&a.enable(18),y.dispersion&&a.enable(19),y.batchingColor&&a.enable(20),y.gradientMap&&a.enable(21),y.packedNormalMap&&a.enable(22),y.vertexNormals&&a.enable(23),I.push(a.mask),a.disableAll(),y.fog&&a.enable(0),y.useFog&&a.enable(1),y.flatShading&&a.enable(2),y.logarithmicDepthBuffer&&a.enable(3),y.reversedDepthBuffer&&a.enable(4),y.skinning&&a.enable(5),y.morphTargets&&a.enable(6),y.morphNormals&&a.enable(7),y.morphColors&&a.enable(8),y.premultipliedAlpha&&a.enable(9),y.shadowMapEnabled&&a.enable(10),y.doubleSided&&a.enable(11),y.flipSided&&a.enable(12),y.useDepthPacking&&a.enable(13),y.dithering&&a.enable(14),y.transmission&&a.enable(15),y.sheen&&a.enable(16),y.opaque&&a.enable(17),y.pointsUvs&&a.enable(18),y.decodeVideoTexture&&a.enable(19),y.decodeVideoTextureEmissive&&a.enable(20),y.alphaToCoverage&&a.enable(21),y.numLightProbeGrids>0&&a.enable(22),I.push(a.mask)}function x(I){let y=u[I.type],M;if(y){let D=zo[y];M=kF.clone(D.uniforms)}else M=I.uniforms;return M}function A(I,y){let M=f.get(y);return M!==void 0?++M.usedTimes:(M=new Tte(n,y,I,r),c.push(M),f.set(y,M)),M}function S(I){if(--I.usedTimes===0){let y=c.indexOf(I);c[y]=c[c.length-1],c.pop(),f.delete(I.cacheKey),I.destroy()}}function E(I){o.remove(I)}function R(){o.dispose()}return{getParameters:p,getProgramCacheKey:_,getUniforms:x,acquireProgram:A,releaseProgram:S,releaseShaderCache:E,programs:c,dispose:R}}function bte(){let n=new WeakMap;function e(a){return n.has(a)}function t(a){let o=n.get(a);return o===void 0&&(o={},n.set(a,o)),o}function i(a){n.delete(a)}function r(a,o,l){n.get(a)[o]=l}function s(){n=new WeakMap}return{has:e,get:t,remove:i,update:r,dispose:s}}function Ite(n,e){return n.groupOrder!==e.groupOrder?n.groupOrder-e.groupOrder:n.renderOrder!==e.renderOrder?n.renderOrder-e.renderOrder:n.material.id!==e.material.id?n.material.id-e.material.id:n.materialVariant!==e.materialVariant?n.materialVariant-e.materialVariant:n.z!==e.z?n.z-e.z:n.id-e.id}function o1(n,e){return n.groupOrder!==e.groupOrder?n.groupOrder-e.groupOrder:n.renderOrder!==e.renderOrder?n.renderOrder-e.renderOrder:n.z!==e.z?e.z-n.z:n.id-e.id}function l1(){let n=[],e=0,t=[],i=[],r=[];function s(){e=0,t.length=0,i.length=0,r.length=0}function a(d){let u=0;return d.isInstancedMesh&&(u+=2),d.isSkinnedMesh&&(u+=1),u}function o(d,u,m,p,_,g){let v=n[e];return v===void 0?(v={id:d.id,object:d,geometry:u,material:m,materialVariant:a(d),groupOrder:p,renderOrder:d.renderOrder,z:_,group:g},n[e]=v):(v.id=d.id,v.object=d,v.geometry=u,v.material=m,v.materialVariant=a(d),v.groupOrder=p,v.renderOrder=d.renderOrder,v.z=_,v.group=g),e++,v}function l(d,u,m,p,_,g){let v=o(d,u,m,p,_,g);m.transmission>0?i.push(v):m.transparent===!0?r.push(v):t.push(v)}function c(d,u,m,p,_,g){let v=o(d,u,m,p,_,g);m.transmission>0?i.unshift(v):m.transparent===!0?r.unshift(v):t.unshift(v)}function f(d,u){t.length>1&&t.sort(d||Ite),i.length>1&&i.sort(u||o1),r.length>1&&r.sort(u||o1)}function h(){for(let d=e,u=n.length;d=s.length?(a=new l1,s.push(a)):a=s[r],a}function t(){n=new WeakMap}return{get:e,dispose:t}}function Cte(){let n={};return{get:function(e){if(n[e.id]!==void 0)return n[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new ne,color:new ft};break;case"SpotLight":t={position:new ne,direction:new ne,color:new ft,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new ne,color:new ft,distance:0,decay:0};break;case"HemisphereLight":t={direction:new ne,skyColor:new ft,groundColor:new ft};break;case"RectAreaLight":t={color:new ft,position:new ne,halfWidth:new ne,halfHeight:new ne};break}return n[e.id]=t,t}}}function yte(){let n={};return{get:function(e){if(n[e.id]!==void 0)return n[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new It};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new It};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new It,shadowCameraNear:1,shadowCameraFar:1e3};break}return n[e.id]=t,t}}}function Dte(n,e){return(e.castShadow?2:0)-(n.castShadow?2:0)+(e.map?1:0)-(n.map?1:0)}function Lte(n){let e=new Cte,t=yte(),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 ne);let r=new ne,s=new li,a=new li;function o(c){let f=0,h=0,d=0;for(let y=0;y<9;y++)i.probe[y].set(0,0,0);let u=0,m=0,p=0,_=0,g=0,v=0,x=0,A=0,S=0,E=0,R=0;c.sort(Dte);for(let y=0,M=c.length;y0&&(n.has("OES_texture_float_linear")===!0?(i.rectAreaLTC1=pt.LTC_FLOAT_1,i.rectAreaLTC2=pt.LTC_FLOAT_2):(i.rectAreaLTC1=pt.LTC_HALF_1,i.rectAreaLTC2=pt.LTC_HALF_2)),i.ambient[0]=f,i.ambient[1]=h,i.ambient[2]=d;let I=i.hash;(I.directionalLength!==u||I.pointLength!==m||I.spotLength!==p||I.rectAreaLength!==_||I.hemiLength!==g||I.numDirectionalShadows!==v||I.numPointShadows!==x||I.numSpotShadows!==A||I.numSpotMaps!==S||I.numLightProbes!==R)&&(i.directional.length=u,i.spot.length=p,i.rectArea.length=_,i.point.length=m,i.hemi.length=g,i.directionalShadow.length=v,i.directionalShadowMap.length=v,i.pointShadow.length=x,i.pointShadowMap.length=x,i.spotShadow.length=A,i.spotShadowMap.length=A,i.directionalShadowMatrix.length=v,i.pointShadowMatrix.length=x,i.spotLightMatrix.length=A+S-E,i.spotLightMap.length=S,i.numSpotLightShadowsWithMaps=E,i.numLightProbes=R,I.directionalLength=u,I.pointLength=m,I.spotLength=p,I.rectAreaLength=_,I.hemiLength=g,I.numDirectionalShadows=v,I.numPointShadows=x,I.numSpotShadows=A,I.numSpotMaps=S,I.numLightProbes=R,i.version=Pte++)}function l(c,f){let h=0,d=0,u=0,m=0,p=0,_=f.matrixWorldInverse;for(let g=0,v=c.length;g=a.length?(o=new c1(n),a.push(o)):o=a[s],o}function i(){e=new WeakMap}return{get:t,dispose:i}}function Ute(n,e,t){let i=new gu,r=new It,s=new It,a=new Qi,o=new _E,l=new gE,c={},f=t.maxTextureSize,h={[Vs]:pn,[pn]:Vs,[ua]:ua},d=new ks({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new It},radius:{value:4}},vertexShader:Nte,fragmentShader:wte}),u=d.clone();u.defines.HORIZONTAL_PASS=1;let m=new Vi;m.setAttribute("position",new lr(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let p=new ri(m,d),_=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=h_;let g=this.type;this.render=function(E,R,I){if(_.enabled===!1||_.autoUpdate===!1&&_.needsUpdate===!1||E.length===0)return;this.type===yE&&(Ct("WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead."),this.type=h_);let y=n.getRenderTarget(),M=n.getActiveCubeFace(),D=n.getActiveMipmapLevel(),O=n.state;O.setBlending(ko),O.buffers.depth.getReversed()===!0?O.buffers.color.setClear(0,0,0,0):O.buffers.color.setClear(1,1,1,1),O.buffers.depth.setTest(!0),O.setScissorTest(!1);let V=g!==this.type;V&&R.traverse(function(N){N.material&&(Array.isArray(N.material)?N.material.forEach(F=>F.needsUpdate=!0):N.material.needsUpdate=!0)});for(let N=0,F=E.length;Nf||r.y>f)&&(r.x>f&&(s.x=Math.floor(f/ee.x),r.x=s.x*ee.x,G.mapSize.x=s.x),r.y>f&&(s.y=Math.floor(f/ee.y),r.y=s.y*ee.y,G.mapSize.y=s.y));let j=n.state.buffers.depth.getReversed();if(G.camera._reversedDepth=j,G.map===null||V===!0){if(G.map!==null&&(G.map.depthTexture!==null&&(G.map.depthTexture.dispose(),G.map.depthTexture=null),G.map.dispose()),this.type===xu){if(U.isPointLight){Ct("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}G.map=new Gs(r.x,r.y,{format:$c,type:Wo,minFilter:Lr,magFilter:Lr,generateMipmaps:!1}),G.map.texture.name=U.name+".shadowMap",G.map.depthTexture=new Ml(r.x,r.y,Hs),G.map.depthTexture.name=U.name+".shadowMapDepth",G.map.depthTexture.format=Lo,G.map.depthTexture.compareFunction=null,G.map.depthTexture.minFilter=Dr,G.map.depthTexture.magFilter=Dr}else U.isPointLight?(G.map=new AS(r.x),G.map.depthTexture=new mE(r.x,Za)):(G.map=new Gs(r.x,r.y),G.map.depthTexture=new Ml(r.x,r.y,Za)),G.map.depthTexture.name=U.name+".shadowMap",G.map.depthTexture.format=Lo,this.type===h_?(G.map.depthTexture.compareFunction=j?vS:gS,G.map.depthTexture.minFilter=Lr,G.map.depthTexture.magFilter=Lr):(G.map.depthTexture.compareFunction=null,G.map.depthTexture.minFilter=Dr,G.map.depthTexture.magFilter=Dr);G.camera.updateProjectionMatrix()}let Z=G.map.isWebGLCubeRenderTarget?6:1;for(let X=0;X0||R.map&&R.alphaTest>0||R.alphaToCoverage===!0){let O=M.uuid,V=R.uuid,N=c[O];N===void 0&&(N={},c[O]=N);let F=N[V];F===void 0&&(F=M.clone(),N[V]=F,R.addEventListener("dispose",S)),M=F}if(M.visible=R.visible,M.wireframe=R.wireframe,y===xu?M.side=R.shadowSide!==null?R.shadowSide:R.side:M.side=R.shadowSide!==null?R.shadowSide:h[R.side],M.alphaMap=R.alphaMap,M.alphaTest=R.alphaToCoverage===!0?.5:R.alphaTest,M.map=R.map,M.clipShadows=R.clipShadows,M.clippingPlanes=R.clippingPlanes,M.clipIntersection=R.clipIntersection,M.displacementMap=R.displacementMap,M.displacementScale=R.displacementScale,M.displacementBias=R.displacementBias,M.wireframeLinewidth=R.wireframeLinewidth,M.linewidth=R.linewidth,I.isPointLight===!0&&M.isMeshDistanceMaterial===!0){let O=n.properties.get(M);O.light=I}return M}function A(E,R,I,y,M){if(E.visible===!1)return;if(E.layers.test(R.layers)&&(E.isMesh||E.isLine||E.isPoints)&&(E.castShadow||E.receiveShadow&&M===xu)&&(!E.frustumCulled||i.intersectsObject(E))){E.modelViewMatrix.multiplyMatrices(I.matrixWorldInverse,E.matrixWorld);let V=e.update(E),N=E.material;if(Array.isArray(N)){let F=V.groups;for(let U=0,G=F.length;U=1):j.indexOf("OpenGL ES")!==-1&&(ee=parseFloat(/^OpenGL ES (\d)/.exec(j)[1]),G=ee>=2);let Z=null,X={},Y=n.getParameter(n.SCISSOR_BOX),ue=n.getParameter(n.VIEWPORT),Re=new Qi().fromArray(Y),Be=new Qi().fromArray(ue);function ae(Q,Le,Ae,Je){let Ke=new Uint8Array(4),Fe=n.createTexture();n.bindTexture(Q,Fe),n.texParameteri(Q,n.TEXTURE_MIN_FILTER,n.NEAREST),n.texParameteri(Q,n.TEXTURE_MAG_FILTER,n.NEAREST);for(let At=0;Atpe||Ve.height>pe)&&(Pe=pe/Math.max(Ve.width,Ve.height)),Pe<1)if(typeof HTMLImageElement!="undefined"&&z instanceof HTMLImageElement||typeof HTMLCanvasElement!="undefined"&&z instanceof HTMLCanvasElement||typeof ImageBitmap!="undefined"&&z instanceof ImageBitmap||typeof VideoFrame!="undefined"&&z instanceof VideoFrame){let $e=Math.floor(Pe*Ve.width),rt=Math.floor(Pe*Ve.height);d===void 0&&(d=p($e,rt));let ye=B?p($e,rt):d;return ye.width=$e,ye.height=rt,ye.getContext("2d").drawImage(z,0,0,$e,rt),Ct("WebGLRenderer: Texture has been resized from ("+Ve.width+"x"+Ve.height+") to ("+$e+"x"+rt+")."),ye}else return"data"in z&&Ct("WebGLRenderer: Image in DataTexture is too big ("+Ve.width+"x"+Ve.height+")."),z;return z}function g(z){return z.generateMipmaps}function v(z){n.generateMipmap(z)}function x(z){return z.isWebGLCubeRenderTarget?n.TEXTURE_CUBE_MAP:z.isWebGL3DRenderTarget?n.TEXTURE_3D:z.isWebGLArrayRenderTarget||z.isCompressedArrayTexture?n.TEXTURE_2D_ARRAY:n.TEXTURE_2D}function A(z,B,pe,Pe,Ve,$e=!1){if(z!==null){if(n[z]!==void 0)return n[z];Ct("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+z+"'")}let rt;Pe&&(rt=e.get("EXT_texture_norm16"),rt||Ct("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let ye=B;if(B===n.RED&&(pe===n.FLOAT&&(ye=n.R32F),pe===n.HALF_FLOAT&&(ye=n.R16F),pe===n.UNSIGNED_BYTE&&(ye=n.R8),pe===n.UNSIGNED_SHORT&&rt&&(ye=rt.R16_EXT),pe===n.SHORT&&rt&&(ye=rt.R16_SNORM_EXT)),B===n.RED_INTEGER&&(pe===n.UNSIGNED_BYTE&&(ye=n.R8UI),pe===n.UNSIGNED_SHORT&&(ye=n.R16UI),pe===n.UNSIGNED_INT&&(ye=n.R32UI),pe===n.BYTE&&(ye=n.R8I),pe===n.SHORT&&(ye=n.R16I),pe===n.INT&&(ye=n.R32I)),B===n.RG&&(pe===n.FLOAT&&(ye=n.RG32F),pe===n.HALF_FLOAT&&(ye=n.RG16F),pe===n.UNSIGNED_BYTE&&(ye=n.RG8),pe===n.UNSIGNED_SHORT&&rt&&(ye=rt.RG16_EXT),pe===n.SHORT&&rt&&(ye=rt.RG16_SNORM_EXT)),B===n.RG_INTEGER&&(pe===n.UNSIGNED_BYTE&&(ye=n.RG8UI),pe===n.UNSIGNED_SHORT&&(ye=n.RG16UI),pe===n.UNSIGNED_INT&&(ye=n.RG32UI),pe===n.BYTE&&(ye=n.RG8I),pe===n.SHORT&&(ye=n.RG16I),pe===n.INT&&(ye=n.RG32I)),B===n.RGB_INTEGER&&(pe===n.UNSIGNED_BYTE&&(ye=n.RGB8UI),pe===n.UNSIGNED_SHORT&&(ye=n.RGB16UI),pe===n.UNSIGNED_INT&&(ye=n.RGB32UI),pe===n.BYTE&&(ye=n.RGB8I),pe===n.SHORT&&(ye=n.RGB16I),pe===n.INT&&(ye=n.RGB32I)),B===n.RGBA_INTEGER&&(pe===n.UNSIGNED_BYTE&&(ye=n.RGBA8UI),pe===n.UNSIGNED_SHORT&&(ye=n.RGBA16UI),pe===n.UNSIGNED_INT&&(ye=n.RGBA32UI),pe===n.BYTE&&(ye=n.RGBA8I),pe===n.SHORT&&(ye=n.RGBA16I),pe===n.INT&&(ye=n.RGBA32I)),B===n.RGB&&(pe===n.UNSIGNED_SHORT&&rt&&(ye=rt.RGB16_EXT),pe===n.SHORT&&rt&&(ye=rt.RGB16_SNORM_EXT),pe===n.UNSIGNED_INT_5_9_9_9_REV&&(ye=n.RGB9_E5),pe===n.UNSIGNED_INT_10F_11F_11F_REV&&(ye=n.R11F_G11F_B10F)),B===n.RGBA){let be=$e?Hp:oi.getTransfer(Ve);pe===n.FLOAT&&(ye=n.RGBA32F),pe===n.HALF_FLOAT&&(ye=n.RGBA16F),pe===n.UNSIGNED_BYTE&&(ye=be===Xi?n.SRGB8_ALPHA8:n.RGBA8),pe===n.UNSIGNED_SHORT&&rt&&(ye=rt.RGBA16_EXT),pe===n.SHORT&&rt&&(ye=rt.RGBA16_SNORM_EXT),pe===n.UNSIGNED_SHORT_4_4_4_4&&(ye=n.RGBA4),pe===n.UNSIGNED_SHORT_5_5_5_1&&(ye=n.RGB5_A1)}return(ye===n.R16F||ye===n.R32F||ye===n.RG16F||ye===n.RG32F||ye===n.RGBA16F||ye===n.RGBA32F)&&e.get("EXT_color_buffer_float"),ye}function S(z,B){let pe;return z?B===null||B===Za||B===Iu?pe=n.DEPTH24_STENCIL8:B===Hs?pe=n.DEPTH32F_STENCIL8:B===bu&&(pe=n.DEPTH24_STENCIL8,Ct("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):B===null||B===Za||B===Iu?pe=n.DEPTH_COMPONENT24:B===Hs?pe=n.DEPTH_COMPONENT32F:B===bu&&(pe=n.DEPTH_COMPONENT16),pe}function E(z,B){return g(z)===!0||z.isFramebufferTexture&&z.minFilter!==Dr&&z.minFilter!==Lr?Math.log2(Math.max(B.width,B.height))+1:z.mipmaps!==void 0&&z.mipmaps.length>0?z.mipmaps.length:z.isCompressedTexture&&Array.isArray(z.image)?B.mipmaps.length:1}function R(z){let B=z.target;B.removeEventListener("dispose",R),y(B),B.isVideoTexture&&f.delete(B),B.isHTMLTexture&&h.delete(B)}function I(z){let B=z.target;B.removeEventListener("dispose",I),D(B)}function y(z){let B=i.get(z);if(B.__webglInit===void 0)return;let pe=z.source,Pe=u.get(pe);if(Pe){let Ve=Pe[B.__cacheKey];Ve.usedTimes--,Ve.usedTimes===0&&M(z),Object.keys(Pe).length===0&&u.delete(pe)}i.remove(z)}function M(z){let B=i.get(z);n.deleteTexture(B.__webglTexture);let pe=z.source,Pe=u.get(pe);delete Pe[B.__cacheKey],a.memory.textures--}function D(z){let B=i.get(z);if(z.depthTexture&&(z.depthTexture.dispose(),i.remove(z.depthTexture)),z.isWebGLCubeRenderTarget)for(let Pe=0;Pe<6;Pe++){if(Array.isArray(B.__webglFramebuffer[Pe]))for(let Ve=0;Ve=r.maxTextures&&Ct("WebGLTextures: Trying to use "+z+" texture units while this GPU supports only "+r.maxTextures),O+=1,z}function G(z){let B=[];return B.push(z.wrapS),B.push(z.wrapT),B.push(z.wrapR||0),B.push(z.magFilter),B.push(z.minFilter),B.push(z.anisotropy),B.push(z.internalFormat),B.push(z.format),B.push(z.type),B.push(z.generateMipmaps),B.push(z.premultiplyAlpha),B.push(z.flipY),B.push(z.unpackAlignment),B.push(z.colorSpace),B.join()}function ee(z,B){let pe=i.get(z);if(z.isVideoTexture&&Ni(z),z.isRenderTargetTexture===!1&&z.isExternalTexture!==!0&&z.version>0&&pe.__version!==z.version){let Pe=z.image;if(Pe===null)Ct("WebGLRenderer: Texture marked for update but no image data found.");else if(Pe.complete===!1)Ct("WebGLRenderer: Texture marked for update but image is incomplete");else{de(pe,z,B);return}}else z.isExternalTexture&&(pe.__webglTexture=z.sourceTexture?z.sourceTexture:null);t.bindTexture(n.TEXTURE_2D,pe.__webglTexture,n.TEXTURE0+B)}function j(z,B){let pe=i.get(z);if(z.isRenderTargetTexture===!1&&z.version>0&&pe.__version!==z.version){de(pe,z,B);return}else z.isExternalTexture&&(pe.__webglTexture=z.sourceTexture?z.sourceTexture:null);t.bindTexture(n.TEXTURE_2D_ARRAY,pe.__webglTexture,n.TEXTURE0+B)}function Z(z,B){let pe=i.get(z);if(z.isRenderTargetTexture===!1&&z.version>0&&pe.__version!==z.version){de(pe,z,B);return}t.bindTexture(n.TEXTURE_3D,pe.__webglTexture,n.TEXTURE0+B)}function X(z,B){let pe=i.get(z);if(z.isCubeDepthTexture!==!0&&z.version>0&&pe.__version!==z.version){De(pe,z,B);return}t.bindTexture(n.TEXTURE_CUBE_MAP,pe.__webglTexture,n.TEXTURE0+B)}let Y={[Do]:n.REPEAT,[fa]:n.CLAMP_TO_EDGE,[ou]:n.MIRRORED_REPEAT},ue={[Dr]:n.NEAREST,[LE]:n.NEAREST_MIPMAP_NEAREST,[Ah]:n.NEAREST_MIPMAP_LINEAR,[Lr]:n.LINEAR,[Ru]:n.LINEAR_MIPMAP_NEAREST,[qa]:n.LINEAR_MIPMAP_LINEAR},Re={[yF]:n.NEVER,[NF]:n.ALWAYS,[PF]:n.LESS,[gS]:n.LEQUAL,[DF]:n.EQUAL,[vS]:n.GEQUAL,[LF]:n.GREATER,[OF]:n.NOTEQUAL};function Be(z,B){if(B.type===Hs&&e.has("OES_texture_float_linear")===!1&&(B.magFilter===Lr||B.magFilter===Ru||B.magFilter===Ah||B.magFilter===qa||B.minFilter===Lr||B.minFilter===Ru||B.minFilter===Ah||B.minFilter===qa)&&Ct("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),n.texParameteri(z,n.TEXTURE_WRAP_S,Y[B.wrapS]),n.texParameteri(z,n.TEXTURE_WRAP_T,Y[B.wrapT]),(z===n.TEXTURE_3D||z===n.TEXTURE_2D_ARRAY)&&n.texParameteri(z,n.TEXTURE_WRAP_R,Y[B.wrapR]),n.texParameteri(z,n.TEXTURE_MAG_FILTER,ue[B.magFilter]),n.texParameteri(z,n.TEXTURE_MIN_FILTER,ue[B.minFilter]),B.compareFunction&&(n.texParameteri(z,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE),n.texParameteri(z,n.TEXTURE_COMPARE_FUNC,Re[B.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(B.magFilter===Dr||B.minFilter!==Ah&&B.minFilter!==qa||B.type===Hs&&e.has("OES_texture_float_linear")===!1)return;if(B.anisotropy>1||i.get(B).__currentAnisotropy){let pe=e.get("EXT_texture_filter_anisotropic");n.texParameterf(z,pe.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(B.anisotropy,r.getMaxAnisotropy())),i.get(B).__currentAnisotropy=B.anisotropy}}}function ae(z,B){let pe=!1;z.__webglInit===void 0&&(z.__webglInit=!0,B.addEventListener("dispose",R));let Pe=B.source,Ve=u.get(Pe);Ve===void 0&&(Ve={},u.set(Pe,Ve));let $e=G(B);if($e!==z.__cacheKey){Ve[$e]===void 0&&(Ve[$e]={texture:n.createTexture(),usedTimes:0},a.memory.textures++,pe=!0),Ve[$e].usedTimes++;let rt=Ve[z.__cacheKey];rt!==void 0&&(Ve[z.__cacheKey].usedTimes--,rt.usedTimes===0&&M(B)),z.__cacheKey=$e,z.__webglTexture=Ve[$e].texture}return pe}function me(z,B,pe){return Math.floor(Math.floor(z/pe)/B)}function re(z,B,pe,Pe){let $e=z.updateRanges;if($e.length===0)t.texSubImage2D(n.TEXTURE_2D,0,0,0,B.width,B.height,pe,Pe,B.data);else{$e.sort((Tt,nt)=>Tt.start-nt.start);let rt=0;for(let Tt=1;Tt<$e.length;Tt++){let nt=$e[rt],Ze=$e[Tt],Wt=nt.start+nt.count,jt=me(Ze.start,B.width,4),se=me(nt.start,B.width,4);Ze.start<=Wt+1&&jt===se&&me(Ze.start+Ze.count-1,B.width,4)===jt?nt.count=Math.max(nt.count,Ze.start+Ze.count-nt.start):(++rt,$e[rt]=Ze)}$e.length=rt+1;let ye=t.getParameter(n.UNPACK_ROW_LENGTH),be=t.getParameter(n.UNPACK_SKIP_PIXELS),ct=t.getParameter(n.UNPACK_SKIP_ROWS);t.pixelStorei(n.UNPACK_ROW_LENGTH,B.width);for(let Tt=0,nt=$e.length;Tt0){jt&&se&&t.texStorage2D(n.TEXTURE_2D,Le,nt,Wt[0].width,Wt[0].height);for(let Ae=0,Je=Wt.length;Ae0){let Ke=Z0(Ze.width,Ze.height,B.format,B.type);for(let Fe of B.layerUpdates){let At=Ze.data.subarray(Fe*Ke/Ze.data.BYTES_PER_ELEMENT,(Fe+1)*Ke/Ze.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,Ae,0,0,Fe,Ze.width,Ze.height,1,ct,At)}B.clearLayerUpdates()}else t.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,Ae,0,0,0,Ze.width,Ze.height,be.depth,ct,Ze.data)}else t.compressedTexImage3D(n.TEXTURE_2D_ARRAY,Ae,nt,Ze.width,Ze.height,be.depth,0,Ze.data,0,0);else Ct("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else jt?Q&&t.texSubImage3D(n.TEXTURE_2D_ARRAY,Ae,0,0,0,Ze.width,Ze.height,be.depth,ct,Tt,Ze.data):t.texImage3D(n.TEXTURE_2D_ARRAY,Ae,nt,Ze.width,Ze.height,be.depth,0,ct,Tt,Ze.data)}else{jt&&se&&t.texStorage2D(n.TEXTURE_2D,Le,nt,Wt[0].width,Wt[0].height);for(let Ae=0,Je=Wt.length;Ae0){let Ae=Z0(be.width,be.height,B.format,B.type);for(let Je of B.layerUpdates){let Ke=be.data.subarray(Je*Ae/be.data.BYTES_PER_ELEMENT,(Je+1)*Ae/be.data.BYTES_PER_ELEMENT);t.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,Je,be.width,be.height,1,ct,Tt,Ke)}B.clearLayerUpdates()}else t.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,0,be.width,be.height,be.depth,ct,Tt,be.data)}else t.texImage3D(n.TEXTURE_2D_ARRAY,0,nt,be.width,be.height,be.depth,0,ct,Tt,be.data);else if(B.isData3DTexture)jt?(se&&t.texStorage3D(n.TEXTURE_3D,Le,nt,be.width,be.height,be.depth),Q&&t.texSubImage3D(n.TEXTURE_3D,0,0,0,0,be.width,be.height,be.depth,ct,Tt,be.data)):t.texImage3D(n.TEXTURE_3D,0,nt,be.width,be.height,be.depth,0,ct,Tt,be.data);else if(B.isFramebufferTexture){if(se)if(jt)t.texStorage2D(n.TEXTURE_2D,Le,nt,be.width,be.height);else{let Ae=be.width,Je=be.height;for(let Ke=0;Ke>=1,Je>>=1}}else if(B.isHTMLTexture){if("texElementImage2D"in n){let Ae=n.canvas;if(Ae.hasAttribute("layoutsubtree")||Ae.setAttribute("layoutsubtree","true"),be.parentNode!==Ae){Ae.appendChild(be),h.add(B),Ae.onpaint=qt=>{let Ji=qt.changedElements;for(let vi of h)Ji.includes(vi.image)&&(vi.needsUpdate=!0)},Ae.requestPaint();return}let Je=0,Ke=n.RGBA,Fe=n.RGBA,At=n.UNSIGNED_BYTE;n.texElementImage2D(n.TEXTURE_2D,Je,Ke,Fe,At,be),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE)}}else if(Wt.length>0){if(jt&&se){let Ae=yi(Wt[0]);t.texStorage2D(n.TEXTURE_2D,Le,nt,Ae.width,Ae.height)}for(let Ae=0,Je=Wt.length;Ae0&&Je++;let Fe=yi(nt[0]);t.texStorage2D(n.TEXTURE_CUBE_MAP,Je,se,Fe.width,Fe.height)}for(let Fe=0;Fe<6;Fe++)if(Tt){Q?Ae&&t.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+Fe,0,0,0,nt[Fe].width,nt[Fe].height,Wt,jt,nt[Fe].data):t.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+Fe,0,se,nt[Fe].width,nt[Fe].height,0,Wt,jt,nt[Fe].data);for(let At=0;At>$e),Ze=Math.max(1,B.height>>$e);Ve===n.TEXTURE_3D||Ve===n.TEXTURE_2D_ARRAY?t.texImage3D(Ve,$e,be,nt,Ze,B.depth,0,rt,ye,null):t.texImage2D(Ve,$e,be,nt,Ze,0,rt,ye,null)}t.bindFramebuffer(n.FRAMEBUFFER,z),ti(B)?o.framebufferTexture2DMultisampleEXT(n.FRAMEBUFFER,Pe,Ve,Tt.__webglTexture,0,Ui(B)):(Ve===n.TEXTURE_2D||Ve>=n.TEXTURE_CUBE_MAP_POSITIVE_X&&Ve<=n.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&n.framebufferTexture2D(n.FRAMEBUFFER,Pe,Ve,Tt.__webglTexture,$e),t.bindFramebuffer(n.FRAMEBUFFER,null)}function Ie(z,B,pe){if(n.bindRenderbuffer(n.RENDERBUFFER,z),B.depthBuffer){let Pe=B.depthTexture,Ve=Pe&&Pe.isDepthTexture?Pe.type:null,$e=S(B.stencilBuffer,Ve),rt=B.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT;ti(B)?o.renderbufferStorageMultisampleEXT(n.RENDERBUFFER,Ui(B),$e,B.width,B.height):pe?n.renderbufferStorageMultisample(n.RENDERBUFFER,Ui(B),$e,B.width,B.height):n.renderbufferStorage(n.RENDERBUFFER,$e,B.width,B.height),n.framebufferRenderbuffer(n.FRAMEBUFFER,rt,n.RENDERBUFFER,z)}else{let Pe=B.textures;for(let Ve=0;Ve{delete B.__boundDepthTexture,delete B.__depthDisposeCallback,Pe.removeEventListener("dispose",Ve)};Pe.addEventListener("dispose",Ve),B.__depthDisposeCallback=Ve}B.__boundDepthTexture=Pe}if(z.depthTexture&&!B.__autoAllocateDepthBuffer)if(pe)for(let Pe=0;Pe<6;Pe++)ze(B.__webglFramebuffer[Pe],z,Pe);else{let Pe=z.texture.mipmaps;Pe&&Pe.length>0?ze(B.__webglFramebuffer[0],z,0):ze(B.__webglFramebuffer,z,0)}else if(pe){B.__webglDepthbuffer=[];for(let Pe=0;Pe<6;Pe++)if(t.bindFramebuffer(n.FRAMEBUFFER,B.__webglFramebuffer[Pe]),B.__webglDepthbuffer[Pe]===void 0)B.__webglDepthbuffer[Pe]=n.createRenderbuffer(),Ie(B.__webglDepthbuffer[Pe],z,!1);else{let Ve=z.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,$e=B.__webglDepthbuffer[Pe];n.bindRenderbuffer(n.RENDERBUFFER,$e),n.framebufferRenderbuffer(n.FRAMEBUFFER,Ve,n.RENDERBUFFER,$e)}}else{let Pe=z.texture.mipmaps;if(Pe&&Pe.length>0?t.bindFramebuffer(n.FRAMEBUFFER,B.__webglFramebuffer[0]):t.bindFramebuffer(n.FRAMEBUFFER,B.__webglFramebuffer),B.__webglDepthbuffer===void 0)B.__webglDepthbuffer=n.createRenderbuffer(),Ie(B.__webglDepthbuffer,z,!1);else{let Ve=z.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,$e=B.__webglDepthbuffer;n.bindRenderbuffer(n.RENDERBUFFER,$e),n.framebufferRenderbuffer(n.FRAMEBUFFER,Ve,n.RENDERBUFFER,$e)}}t.bindFramebuffer(n.FRAMEBUFFER,null)}function Ye(z,B,pe){let Pe=i.get(z);B!==void 0&&he(Pe.__webglFramebuffer,z,z.texture,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,0),pe!==void 0&&St(z)}function je(z){let B=z.texture,pe=i.get(z),Pe=i.get(B);z.addEventListener("dispose",I);let Ve=z.textures,$e=z.isWebGLCubeRenderTarget===!0,rt=Ve.length>1;if(rt||(Pe.__webglTexture===void 0&&(Pe.__webglTexture=n.createTexture()),Pe.__version=B.version,a.memory.textures++),$e){pe.__webglFramebuffer=[];for(let ye=0;ye<6;ye++)if(B.mipmaps&&B.mipmaps.length>0){pe.__webglFramebuffer[ye]=[];for(let be=0;be0){pe.__webglFramebuffer=[];for(let ye=0;ye0&&ti(z)===!1){pe.__webglMultisampledFramebuffer=n.createFramebuffer(),pe.__webglColorRenderbuffer=[],t.bindFramebuffer(n.FRAMEBUFFER,pe.__webglMultisampledFramebuffer);for(let ye=0;ye0)for(let be=0;be0)for(let be=0;be0){if(ti(z)===!1){let B=z.textures,pe=z.width,Pe=z.height,Ve=n.COLOR_BUFFER_BIT,$e=z.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,rt=i.get(z),ye=B.length>1;if(ye)for(let ct=0;ct0?t.bindFramebuffer(n.DRAW_FRAMEBUFFER,rt.__webglFramebuffer[0]):t.bindFramebuffer(n.DRAW_FRAMEBUFFER,rt.__webglFramebuffer);for(let ct=0;ct0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&B.__useRenderToTexture!==!1}function Ni(z){let B=a.render.frame;f.get(z)!==B&&(f.set(z,B),z.update())}function ot(z,B){let pe=z.colorSpace,Pe=z.format,Ve=z.type;return z.isCompressedTexture===!0||z.isVideoTexture===!0||pe!==Kn&&pe!==Ll&&(oi.getTransfer(pe)===Xi?(Pe!==zs||Ve!==ps)&&Ct("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):Bt("WebGLTextures: Unsupported texture color space:",pe)),B}function yi(z){return typeof HTMLImageElement!="undefined"&&z instanceof HTMLImageElement?(c.width=z.naturalWidth||z.width,c.height=z.naturalHeight||z.height):typeof VideoFrame!="undefined"&&z instanceof VideoFrame?(c.width=z.displayWidth,c.height=z.displayHeight):(c.width=z.width,c.height=z.height),c}this.allocateTextureUnit=U,this.resetTextureUnits=V,this.getTextureUnits=N,this.setTextureUnits=F,this.setTexture2D=ee,this.setTexture2DArray=j,this.setTexture3D=Z,this.setTextureCube=X,this.rebindTextures=Ye,this.setupRenderTarget=je,this.updateRenderTargetMipmap=$t,this.updateMultisampleRenderTarget=oe,this.setupDepthRenderbuffer=St,this.setupFrameBufferTexture=he,this.useMultisampledRTT=ti,this.isReversedDepthBuffer=function(){return t.buffers.depth.getReversed()}}function kte(n,e){function t(i,r=Ll){let s,a=oi.getTransfer(r);if(i===ps)return n.UNSIGNED_BYTE;if(i===NE)return n.UNSIGNED_SHORT_4_4_4_4;if(i===wE)return n.UNSIGNED_SHORT_5_5_5_1;if(i===G0)return n.UNSIGNED_INT_5_9_9_9_REV;if(i===k0)return n.UNSIGNED_INT_10F_11F_11F_REV;if(i===U0)return n.BYTE;if(i===V0)return n.SHORT;if(i===bu)return n.UNSIGNED_SHORT;if(i===OE)return n.INT;if(i===Za)return n.UNSIGNED_INT;if(i===Hs)return n.FLOAT;if(i===Wo)return n.HALF_FLOAT;if(i===W0)return n.ALPHA;if(i===H0)return n.RGB;if(i===zs)return n.RGBA;if(i===Lo)return n.DEPTH_COMPONENT;if(i===Qc)return n.DEPTH_STENCIL;if(i===FE)return n.RED;if(i===BE)return n.RED_INTEGER;if(i===$c)return n.RG;if(i===UE)return n.RG_INTEGER;if(i===VE)return n.RGBA_INTEGER;if(i===m_||i===p_||i===__||i===g_)if(a===Xi)if(s=e.get("WEBGL_compressed_texture_s3tc_srgb"),s!==null){if(i===m_)return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===p_)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===__)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===g_)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(s=e.get("WEBGL_compressed_texture_s3tc"),s!==null){if(i===m_)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===p_)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===__)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===g_)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(i===GE||i===kE||i===WE||i===HE)if(s=e.get("WEBGL_compressed_texture_pvrtc"),s!==null){if(i===GE)return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(i===kE)return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===WE)return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(i===HE)return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(i===zE||i===XE||i===YE||i===KE||i===jE||i===v_||i===qE)if(s=e.get("WEBGL_compressed_texture_etc"),s!==null){if(i===zE||i===XE)return a===Xi?s.COMPRESSED_SRGB8_ETC2:s.COMPRESSED_RGB8_ETC2;if(i===YE)return a===Xi?s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:s.COMPRESSED_RGBA8_ETC2_EAC;if(i===KE)return s.COMPRESSED_R11_EAC;if(i===jE)return s.COMPRESSED_SIGNED_R11_EAC;if(i===v_)return s.COMPRESSED_RG11_EAC;if(i===qE)return s.COMPRESSED_SIGNED_RG11_EAC}else return null;if(i===ZE||i===QE||i===$E||i===JE||i===eS||i===tS||i===iS||i===rS||i===nS||i===sS||i===aS||i===oS||i===lS||i===cS)if(s=e.get("WEBGL_compressed_texture_astc"),s!==null){if(i===ZE)return a===Xi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:s.COMPRESSED_RGBA_ASTC_4x4_KHR;if(i===QE)return a===Xi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:s.COMPRESSED_RGBA_ASTC_5x4_KHR;if(i===$E)return a===Xi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:s.COMPRESSED_RGBA_ASTC_5x5_KHR;if(i===JE)return a===Xi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:s.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===eS)return a===Xi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:s.COMPRESSED_RGBA_ASTC_6x6_KHR;if(i===tS)return a===Xi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:s.COMPRESSED_RGBA_ASTC_8x5_KHR;if(i===iS)return a===Xi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:s.COMPRESSED_RGBA_ASTC_8x6_KHR;if(i===rS)return a===Xi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:s.COMPRESSED_RGBA_ASTC_8x8_KHR;if(i===nS)return a===Xi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:s.COMPRESSED_RGBA_ASTC_10x5_KHR;if(i===sS)return a===Xi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:s.COMPRESSED_RGBA_ASTC_10x6_KHR;if(i===aS)return a===Xi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:s.COMPRESSED_RGBA_ASTC_10x8_KHR;if(i===oS)return a===Xi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:s.COMPRESSED_RGBA_ASTC_10x10_KHR;if(i===lS)return a===Xi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:s.COMPRESSED_RGBA_ASTC_12x10_KHR;if(i===cS)return a===Xi?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:s.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(i===fS||i===hS||i===dS)if(s=e.get("EXT_texture_compression_bptc"),s!==null){if(i===fS)return a===Xi?s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:s.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(i===hS)return s.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(i===dS)return s.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(i===uS||i===mS||i===E_||i===pS)if(s=e.get("EXT_texture_compression_rgtc"),s!==null){if(i===uS)return s.COMPRESSED_RED_RGTC1_EXT;if(i===mS)return s.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(i===E_)return s.COMPRESSED_RED_GREEN_RGTC2_EXT;if(i===pS)return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return i===Iu?n.UNSIGNED_INT_24_8:n[i]!==void 0?n[i]:null}return{convert:t}}function Xte(n,e){function t(_,g){_.matrixAutoUpdate===!0&&_.updateMatrix(),g.value.copy(_.matrix)}function i(_,g){g.color.getRGB(_.fogColor.value,K0(n)),g.isFog?(_.fogNear.value=g.near,_.fogFar.value=g.far):g.isFogExp2&&(_.fogDensity.value=g.density)}function r(_,g,v,x,A){g.isNodeMaterial?g.uniformsNeedUpdate=!1:g.isMeshBasicMaterial?s(_,g):g.isMeshLambertMaterial?(s(_,g),g.envMap&&(_.envMapIntensity.value=g.envMapIntensity)):g.isMeshToonMaterial?(s(_,g),h(_,g)):g.isMeshPhongMaterial?(s(_,g),f(_,g),g.envMap&&(_.envMapIntensity.value=g.envMapIntensity)):g.isMeshStandardMaterial?(s(_,g),d(_,g),g.isMeshPhysicalMaterial&&u(_,g,A)):g.isMeshMatcapMaterial?(s(_,g),m(_,g)):g.isMeshDepthMaterial?s(_,g):g.isMeshDistanceMaterial?(s(_,g),p(_,g)):g.isMeshNormalMaterial?s(_,g):g.isLineBasicMaterial?(a(_,g),g.isLineDashedMaterial&&o(_,g)):g.isPointsMaterial?l(_,g,v,x):g.isSpriteMaterial?c(_,g):g.isShadowMaterial?(_.color.value.copy(g.color),_.opacity.value=g.opacity):g.isShaderMaterial&&(g.uniformsNeedUpdate=!1)}function s(_,g){_.opacity.value=g.opacity,g.color&&_.diffuse.value.copy(g.color),g.emissive&&_.emissive.value.copy(g.emissive).multiplyScalar(g.emissiveIntensity),g.map&&(_.map.value=g.map,t(g.map,_.mapTransform)),g.alphaMap&&(_.alphaMap.value=g.alphaMap,t(g.alphaMap,_.alphaMapTransform)),g.bumpMap&&(_.bumpMap.value=g.bumpMap,t(g.bumpMap,_.bumpMapTransform),_.bumpScale.value=g.bumpScale,g.side===pn&&(_.bumpScale.value*=-1)),g.normalMap&&(_.normalMap.value=g.normalMap,t(g.normalMap,_.normalMapTransform),_.normalScale.value.copy(g.normalScale),g.side===pn&&_.normalScale.value.negate()),g.displacementMap&&(_.displacementMap.value=g.displacementMap,t(g.displacementMap,_.displacementMapTransform),_.displacementScale.value=g.displacementScale,_.displacementBias.value=g.displacementBias),g.emissiveMap&&(_.emissiveMap.value=g.emissiveMap,t(g.emissiveMap,_.emissiveMapTransform)),g.specularMap&&(_.specularMap.value=g.specularMap,t(g.specularMap,_.specularMapTransform)),g.alphaTest>0&&(_.alphaTest.value=g.alphaTest);let v=e.get(g),x=v.envMap,A=v.envMapRotation;x&&(_.envMap.value=x,_.envMapRotation.value.setFromMatrix4(zte.makeRotationFromEuler(A)).transpose(),x.isCubeTexture&&x.isRenderTargetTexture===!1&&_.envMapRotation.value.premultiply(g1),_.reflectivity.value=g.reflectivity,_.ior.value=g.ior,_.refractionRatio.value=g.refractionRatio),g.lightMap&&(_.lightMap.value=g.lightMap,_.lightMapIntensity.value=g.lightMapIntensity,t(g.lightMap,_.lightMapTransform)),g.aoMap&&(_.aoMap.value=g.aoMap,_.aoMapIntensity.value=g.aoMapIntensity,t(g.aoMap,_.aoMapTransform))}function a(_,g){_.diffuse.value.copy(g.color),_.opacity.value=g.opacity,g.map&&(_.map.value=g.map,t(g.map,_.mapTransform))}function o(_,g){_.dashSize.value=g.dashSize,_.totalSize.value=g.dashSize+g.gapSize,_.scale.value=g.scale}function l(_,g,v,x){_.diffuse.value.copy(g.color),_.opacity.value=g.opacity,_.size.value=g.size*v,_.scale.value=x*.5,g.map&&(_.map.value=g.map,t(g.map,_.uvTransform)),g.alphaMap&&(_.alphaMap.value=g.alphaMap,t(g.alphaMap,_.alphaMapTransform)),g.alphaTest>0&&(_.alphaTest.value=g.alphaTest)}function c(_,g){_.diffuse.value.copy(g.color),_.opacity.value=g.opacity,_.rotation.value=g.rotation,g.map&&(_.map.value=g.map,t(g.map,_.mapTransform)),g.alphaMap&&(_.alphaMap.value=g.alphaMap,t(g.alphaMap,_.alphaMapTransform)),g.alphaTest>0&&(_.alphaTest.value=g.alphaTest)}function f(_,g){_.specular.value.copy(g.specular),_.shininess.value=Math.max(g.shininess,1e-4)}function h(_,g){g.gradientMap&&(_.gradientMap.value=g.gradientMap)}function d(_,g){_.metalness.value=g.metalness,g.metalnessMap&&(_.metalnessMap.value=g.metalnessMap,t(g.metalnessMap,_.metalnessMapTransform)),_.roughness.value=g.roughness,g.roughnessMap&&(_.roughnessMap.value=g.roughnessMap,t(g.roughnessMap,_.roughnessMapTransform)),g.envMap&&(_.envMapIntensity.value=g.envMapIntensity)}function u(_,g,v){_.ior.value=g.ior,g.sheen>0&&(_.sheenColor.value.copy(g.sheenColor).multiplyScalar(g.sheen),_.sheenRoughness.value=g.sheenRoughness,g.sheenColorMap&&(_.sheenColorMap.value=g.sheenColorMap,t(g.sheenColorMap,_.sheenColorMapTransform)),g.sheenRoughnessMap&&(_.sheenRoughnessMap.value=g.sheenRoughnessMap,t(g.sheenRoughnessMap,_.sheenRoughnessMapTransform))),g.clearcoat>0&&(_.clearcoat.value=g.clearcoat,_.clearcoatRoughness.value=g.clearcoatRoughness,g.clearcoatMap&&(_.clearcoatMap.value=g.clearcoatMap,t(g.clearcoatMap,_.clearcoatMapTransform)),g.clearcoatRoughnessMap&&(_.clearcoatRoughnessMap.value=g.clearcoatRoughnessMap,t(g.clearcoatRoughnessMap,_.clearcoatRoughnessMapTransform)),g.clearcoatNormalMap&&(_.clearcoatNormalMap.value=g.clearcoatNormalMap,t(g.clearcoatNormalMap,_.clearcoatNormalMapTransform),_.clearcoatNormalScale.value.copy(g.clearcoatNormalScale),g.side===pn&&_.clearcoatNormalScale.value.negate())),g.dispersion>0&&(_.dispersion.value=g.dispersion),g.iridescence>0&&(_.iridescence.value=g.iridescence,_.iridescenceIOR.value=g.iridescenceIOR,_.iridescenceThicknessMinimum.value=g.iridescenceThicknessRange[0],_.iridescenceThicknessMaximum.value=g.iridescenceThicknessRange[1],g.iridescenceMap&&(_.iridescenceMap.value=g.iridescenceMap,t(g.iridescenceMap,_.iridescenceMapTransform)),g.iridescenceThicknessMap&&(_.iridescenceThicknessMap.value=g.iridescenceThicknessMap,t(g.iridescenceThicknessMap,_.iridescenceThicknessMapTransform))),g.transmission>0&&(_.transmission.value=g.transmission,_.transmissionSamplerMap.value=v.texture,_.transmissionSamplerSize.value.set(v.width,v.height),g.transmissionMap&&(_.transmissionMap.value=g.transmissionMap,t(g.transmissionMap,_.transmissionMapTransform)),_.thickness.value=g.thickness,g.thicknessMap&&(_.thicknessMap.value=g.thicknessMap,t(g.thicknessMap,_.thicknessMapTransform)),_.attenuationDistance.value=g.attenuationDistance,_.attenuationColor.value.copy(g.attenuationColor)),g.anisotropy>0&&(_.anisotropyVector.value.set(g.anisotropy*Math.cos(g.anisotropyRotation),g.anisotropy*Math.sin(g.anisotropyRotation)),g.anisotropyMap&&(_.anisotropyMap.value=g.anisotropyMap,t(g.anisotropyMap,_.anisotropyMapTransform))),_.specularIntensity.value=g.specularIntensity,_.specularColor.value.copy(g.specularColor),g.specularColorMap&&(_.specularColorMap.value=g.specularColorMap,t(g.specularColorMap,_.specularColorMapTransform)),g.specularIntensityMap&&(_.specularIntensityMap.value=g.specularIntensityMap,t(g.specularIntensityMap,_.specularIntensityMapTransform))}function m(_,g){g.matcap&&(_.matcap.value=g.matcap)}function p(_,g){let v=e.get(g).light;_.referencePosition.value.setFromMatrixPosition(v.matrixWorld),_.nearDistance.value=v.shadow.camera.near,_.farDistance.value=v.shadow.camera.far}return{refreshFogUniforms:i,refreshMaterialUniforms:r}}function Yte(n,e,t,i){let r={},s={},a=[],o=n.getParameter(n.MAX_UNIFORM_BUFFER_BINDINGS);function l(v,x){let A=x.program;i.uniformBlockBinding(v,A)}function c(v,x){let A=r[v.id];A===void 0&&(m(v),A=f(v),r[v.id]=A,v.addEventListener("dispose",_));let S=x.program;i.updateUBOMapping(v,S);let E=e.render.frame;s[v.id]!==E&&(d(v),s[v.id]=E)}function f(v){let x=h();v.__bindingPointIndex=x;let A=n.createBuffer(),S=v.__size,E=v.usage;return n.bindBuffer(n.UNIFORM_BUFFER,A),n.bufferData(n.UNIFORM_BUFFER,S,E),n.bindBuffer(n.UNIFORM_BUFFER,null),n.bindBufferBase(n.UNIFORM_BUFFER,x,A),A}function h(){for(let v=0;v0&&(A+=S-E),v.__size=A,v.__cache={},this}function p(v){let x={boundary:0,storage:0};return typeof v=="number"||typeof v=="boolean"?(x.boundary=4,x.storage=4):v.isVector2?(x.boundary=8,x.storage=8):v.isVector3||v.isColor?(x.boundary=16,x.storage=12):v.isVector4?(x.boundary=16,x.storage=16):v.isMatrix3?(x.boundary=48,x.storage=48):v.isMatrix4?(x.boundary=64,x.storage=64):v.isTexture?Ct("WebGLRenderer: Texture samplers can not be part of an uniforms group."):ArrayBuffer.isView(v)?(x.boundary=16,x.storage=v.byteLength):Ct("WebGLRenderer: Unsupported uniform value type.",v),x}function _(v){let x=v.target;x.removeEventListener("dispose",_);let A=a.indexOf(x.__bindingPointIndex);a.splice(A,1),n.deleteBuffer(r[x.id]),delete r[x.id],delete s[x.id]}function g(){for(let v in r)n.deleteBuffer(r[v]);a=[],r={},s={}}return{bind:l,update:c,dispose:g}}function jte(){return Ho===null&&(Ho=new _u(Kte,16,16,$c,Wo),Ho.name="DFG_LUT",Ho.minFilter=Lr,Ho.magFilter=Lr,Ho.wrapS=fa,Ho.wrapT=fa,Ho.generateMipmaps=!1,Ho.needsUpdate=!0),Ho}var cQ,fQ,hQ,dQ,uQ,mQ,pQ,_Q,gQ,vQ,EQ,SQ,TQ,AQ,xQ,RQ,bQ,IQ,MQ,CQ,yQ,PQ,DQ,LQ,OQ,NQ,wQ,FQ,BQ,UQ,VQ,GQ,kQ,WQ,HQ,zQ,XQ,YQ,KQ,jQ,qQ,ZQ,QQ,$Q,JQ,e$,t$,i$,r$,n$,s$,a$,o$,l$,c$,f$,h$,d$,u$,m$,p$,_$,g$,v$,E$,S$,T$,A$,x$,R$,b$,I$,M$,C$,y$,P$,D$,L$,O$,N$,w$,F$,B$,U$,V$,G$,k$,W$,H$,z$,X$,Y$,K$,j$,q$,Z$,Q$,$$,J$,eJ,tJ,iJ,rJ,nJ,sJ,aJ,oJ,lJ,cJ,fJ,hJ,dJ,uJ,mJ,pJ,_J,gJ,vJ,EJ,SJ,TJ,AJ,xJ,RJ,bJ,IJ,MJ,CJ,yJ,PJ,DJ,LJ,OJ,NJ,wJ,FJ,BJ,UJ,VJ,GJ,kJ,WJ,hi,pt,zo,SS,HJ,d1,Jc,HF,Rh,qJ,A_,zF,rI,nI,sI,aI,ZJ,Du,AS,oee,u1,cI,m1,p1,_1,jF,qF,ZF,QF,$F,fI,hI,dI,oI,Pu,Zee,Qee,t1,tte,TS,ote,lte,fte,dte,mte,_te,vte,Ate,mI,pI,Pte,Nte,wte,Fte,Bte,f1,x_,lI,Wte,Hte,_I,gI,zte,g1,Kte,Ho,xS,Xs=C(()=>{iI();iI();cQ=`#ifdef USE_ALPHAHASH if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard; #endif`,fQ=`#ifdef USE_ALPHAHASH const float ALPHA_HASH_SCALE = 0.05; @@ -4017,7 +4017,7 @@ void main() { #include #include #include -}`,fi={alphahash_fragment:cQ,alphahash_pars_fragment:fQ,alphamap_fragment:hQ,alphamap_pars_fragment:dQ,alphatest_fragment:uQ,alphatest_pars_fragment:mQ,aomap_fragment:pQ,aomap_pars_fragment:_Q,batching_pars_vertex:gQ,batching_vertex:vQ,begin_vertex:EQ,beginnormal_vertex:SQ,bsdfs:TQ,iridescence_fragment:AQ,bumpmap_pars_fragment:xQ,clipping_planes_fragment:RQ,clipping_planes_pars_fragment:bQ,clipping_planes_pars_vertex:IQ,clipping_planes_vertex:MQ,color_fragment:CQ,color_pars_fragment:yQ,color_pars_vertex:PQ,color_vertex:DQ,common:LQ,cube_uv_reflection_fragment:OQ,defaultnormal_vertex:NQ,displacementmap_pars_vertex:wQ,displacementmap_vertex:FQ,emissivemap_fragment:BQ,emissivemap_pars_fragment:UQ,colorspace_fragment:VQ,colorspace_pars_fragment:GQ,envmap_fragment:kQ,envmap_common_pars_fragment:WQ,envmap_pars_fragment:HQ,envmap_pars_vertex:zQ,envmap_physical_pars_fragment:t$,envmap_vertex:XQ,fog_vertex:YQ,fog_pars_vertex:KQ,fog_fragment:jQ,fog_pars_fragment:qQ,gradientmap_pars_fragment:ZQ,lightmap_pars_fragment:QQ,lights_lambert_fragment:$Q,lights_lambert_pars_fragment:JQ,lights_pars_begin:e$,lights_toon_fragment:i$,lights_toon_pars_fragment:r$,lights_phong_fragment:n$,lights_phong_pars_fragment:s$,lights_physical_fragment:a$,lights_physical_pars_fragment:o$,lights_fragment_begin:l$,lights_fragment_maps:c$,lights_fragment_end:f$,lightprobes_pars_fragment:h$,logdepthbuf_fragment:d$,logdepthbuf_pars_fragment:u$,logdepthbuf_pars_vertex:m$,logdepthbuf_vertex:p$,map_fragment:_$,map_pars_fragment:g$,map_particle_fragment:v$,map_particle_pars_fragment:E$,metalnessmap_fragment:S$,metalnessmap_pars_fragment:T$,morphinstance_vertex:A$,morphcolor_vertex:x$,morphnormal_vertex:R$,morphtarget_pars_vertex:b$,morphtarget_vertex:I$,normal_fragment_begin:M$,normal_fragment_maps:C$,normal_pars_fragment:y$,normal_pars_vertex:P$,normal_vertex:D$,normalmap_pars_fragment:L$,clearcoat_normal_fragment_begin:O$,clearcoat_normal_fragment_maps:N$,clearcoat_pars_fragment:w$,iridescence_pars_fragment:F$,opaque_fragment:B$,packing:U$,premultiplied_alpha_fragment:V$,project_vertex:G$,dithering_fragment:k$,dithering_pars_fragment:W$,roughnessmap_fragment:H$,roughnessmap_pars_fragment:z$,shadowmap_pars_fragment:X$,shadowmap_pars_vertex:Y$,shadowmap_vertex:K$,shadowmask_pars_fragment:j$,skinbase_vertex:q$,skinning_pars_vertex:Z$,skinning_vertex:Q$,skinnormal_vertex:$$,specularmap_fragment:J$,specularmap_pars_fragment:eJ,tonemapping_fragment:tJ,tonemapping_pars_fragment:iJ,transmission_fragment:rJ,transmission_pars_fragment:nJ,uv_pars_fragment:sJ,uv_pars_vertex:aJ,uv_vertex:oJ,worldpos_vertex:lJ,background_vert:cJ,background_frag:fJ,backgroundCube_vert:hJ,backgroundCube_frag:dJ,cube_vert:uJ,cube_frag:mJ,depth_vert:pJ,depth_frag:_J,distance_vert:gJ,distance_frag:vJ,equirect_vert:EJ,equirect_frag:SJ,linedashed_vert:TJ,linedashed_frag:AJ,meshbasic_vert:xJ,meshbasic_frag:RJ,meshlambert_vert:bJ,meshlambert_frag:IJ,meshmatcap_vert:MJ,meshmatcap_frag:CJ,meshnormal_vert:yJ,meshnormal_frag:PJ,meshphong_vert:DJ,meshphong_frag:LJ,meshphysical_vert:OJ,meshphysical_frag:NJ,meshtoon_vert:wJ,meshtoon_frag:FJ,points_vert:BJ,points_frag:UJ,shadow_vert:VJ,shadow_frag:GJ,sprite_vert:kJ,sprite_frag:WJ},mt={common:{diffuse:{value:new ct(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new ti},alphaMap:{value:null},alphaMapTransform:{value:new ti},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new ti}},envmap:{envMap:{value:null},envMapRotation:{value:new ti},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new ti}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new ti}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new ti},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new ti},normalScale:{value:new bt(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new ti},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new ti}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new ti}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new ti}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new ct(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null},probesSH:{value:null},probesMin:{value:new ne},probesMax:{value:new ne},probesResolution:{value:new ne}},points:{diffuse:{value:new ct(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new ti},alphaTest:{value:0},uvTransform:{value:new ti}},sprite:{diffuse:{value:new ct(16777215)},opacity:{value:1},center:{value:new bt(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new ti},alphaMap:{value:null},alphaMapTransform:{value:new ti},alphaTest:{value:0}}},zo={basic:{uniforms:yn([mt.common,mt.specularmap,mt.envmap,mt.aomap,mt.lightmap,mt.fog]),vertexShader:fi.meshbasic_vert,fragmentShader:fi.meshbasic_frag},lambert:{uniforms:yn([mt.common,mt.specularmap,mt.envmap,mt.aomap,mt.lightmap,mt.emissivemap,mt.bumpmap,mt.normalmap,mt.displacementmap,mt.fog,mt.lights,{emissive:{value:new ct(0)},envMapIntensity:{value:1}}]),vertexShader:fi.meshlambert_vert,fragmentShader:fi.meshlambert_frag},phong:{uniforms:yn([mt.common,mt.specularmap,mt.envmap,mt.aomap,mt.lightmap,mt.emissivemap,mt.bumpmap,mt.normalmap,mt.displacementmap,mt.fog,mt.lights,{emissive:{value:new ct(0)},specular:{value:new ct(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:fi.meshphong_vert,fragmentShader:fi.meshphong_frag},standard:{uniforms:yn([mt.common,mt.envmap,mt.aomap,mt.lightmap,mt.emissivemap,mt.bumpmap,mt.normalmap,mt.displacementmap,mt.roughnessmap,mt.metalnessmap,mt.fog,mt.lights,{emissive:{value:new ct(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:fi.meshphysical_vert,fragmentShader:fi.meshphysical_frag},toon:{uniforms:yn([mt.common,mt.aomap,mt.lightmap,mt.emissivemap,mt.bumpmap,mt.normalmap,mt.displacementmap,mt.gradientmap,mt.fog,mt.lights,{emissive:{value:new ct(0)}}]),vertexShader:fi.meshtoon_vert,fragmentShader:fi.meshtoon_frag},matcap:{uniforms:yn([mt.common,mt.bumpmap,mt.normalmap,mt.displacementmap,mt.fog,{matcap:{value:null}}]),vertexShader:fi.meshmatcap_vert,fragmentShader:fi.meshmatcap_frag},points:{uniforms:yn([mt.points,mt.fog]),vertexShader:fi.points_vert,fragmentShader:fi.points_frag},dashed:{uniforms:yn([mt.common,mt.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:fi.linedashed_vert,fragmentShader:fi.linedashed_frag},depth:{uniforms:yn([mt.common,mt.displacementmap]),vertexShader:fi.depth_vert,fragmentShader:fi.depth_frag},normal:{uniforms:yn([mt.common,mt.bumpmap,mt.normalmap,mt.displacementmap,{opacity:{value:1}}]),vertexShader:fi.meshnormal_vert,fragmentShader:fi.meshnormal_frag},sprite:{uniforms:yn([mt.sprite,mt.fog]),vertexShader:fi.sprite_vert,fragmentShader:fi.sprite_frag},background:{uniforms:{uvTransform:{value:new ti},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:fi.background_vert,fragmentShader:fi.background_frag},backgroundCube:{uniforms:{envMap:{value:null},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new ti}},vertexShader:fi.backgroundCube_vert,fragmentShader:fi.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:fi.cube_vert,fragmentShader:fi.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:fi.equirect_vert,fragmentShader:fi.equirect_frag},distance:{uniforms:yn([mt.common,mt.displacementmap,{referencePosition:{value:new ne},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:fi.distance_vert,fragmentShader:fi.distance_frag},shadow:{uniforms:yn([mt.lights,mt.fog,{color:{value:new ct(0)},opacity:{value:1}}]),vertexShader:fi.shadow_vert,fragmentShader:fi.shadow_frag}};zo.physical={uniforms:yn([zo.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new ti},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new ti},clearcoatNormalScale:{value:new bt(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new ti},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new ti},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new ti},sheen:{value:0},sheenColor:{value:new ct(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new ti},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new ti},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new ti},transmissionSamplerSize:{value:new bt},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new ti},attenuationDistance:{value:0},attenuationColor:{value:new ct(0)},specularColor:{value:new ct(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new ti},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new ti},anisotropyVector:{value:new bt},anisotropyMap:{value:null},anisotropyMapTransform:{value:new ti}}]),vertexShader:fi.meshphysical_vert,fragmentShader:fi.meshphysical_frag};ES={r:0,b:0,g:0},HJ=new oi,d1=new ti;d1.set(-1,0,0,0,1,0,0,0,1);ef=4,HF=[.125,.215,.35,.446,.526,.582],Rh=20,qJ=256,A_=new Vo,zF=new ct,rI=null,nI=0,sI=0,aI=!1,ZJ=new ne,Lu=class{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}fromScene(e,t=0,i=.1,r=100,s={}){let{size:a=256,position:o=ZJ}=s;rI=this._renderer.getRenderTarget(),nI=this._renderer.getActiveCubeFace(),sI=this._renderer.getActiveMipmapLevel(),aI=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(a);let l=this._allocateTargets();return l.depthBuffer=!0,this._sceneToCubeUV(e,i,r,l,o),t>0&&this._blur(l,0,0,t),this._applyPMREM(l),this._cleanup(l),l}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=KF(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=YF(),this._compileMaterial(this._equirectMaterial))}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())}_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;e2?S:0,S,S),h.setRenderTarget(r),g&&h.render(p,l),h.render(e,l)}h.toneMapping=u,h.autoClear=d,e.background=v}_textureToCubeUV(e,t){let i=this._renderer,r=e.mapping===Qc||e.mapping===Th;r?(this._cubemapMaterial===null&&(this._cubemapMaterial=KF()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=YF());let s=r?this._cubemapMaterial:this._equirectMaterial,a=this._lodMeshes[0];a.material=s;let o=s.uniforms;o.envMap.value=e;let l=this._cubeSize;Pu(t,0,0,3*l,2*l),i.setRenderTarget(t),i.render(a,A_)}_applyPMREM(e){let t=this._renderer,i=t.autoClear;t.autoClear=!1;let r=this._lodMeshes.length;for(let s=1;sm-ef?i-m+ef:0),g=4*(this._cubeSize-p);l.envMap.value=e.texture,l.roughness.value=u,l.mipInt.value=m-t,Pu(s,_,g,3*p,2*p),r.setRenderTarget(s),r.render(o,A_),l.envMap.value=s.texture,l.roughness.value=0,l.mipInt.value=m-i,Pu(e,_,g,3*p,2*p),r.setRenderTarget(e),r.render(o,A_)}_blur(e,t,i,r,s){let a=this._pingPongRenderTarget;this._halfBlur(e,a,t,i,r,"latitudinal",s),this._halfBlur(a,e,i,i,r,"longitudinal",s)}_halfBlur(e,t,i,r,s,a,o){let l=this._renderer,c=this._blurMaterial;a!=="latitudinal"&&a!=="longitudinal"&&Ft("blur direction must be either latitudinal or longitudinal!");let f=3,h=this._lodMeshes[r];h.material=c;let d=c.uniforms,u=this._sizeLods[i]-1,m=isFinite(s)?Math.PI/(2*u):2*Math.PI/(2*Rh-1),p=s/m,_=isFinite(s)?1+Math.floor(f*p):Rh;_>Rh&&Mt(`sigmaRadians, ${s}, is too large and will clip, as it requested ${_} samples when the maximum is set to ${Rh}`);let g=[],v=0;for(let R=0;Rx-ef?r-x+ef:0),E=4*(this._cubeSize-A);Pu(t,S,E,3*A,2*A),l.setRenderTarget(t),l.render(h,A_)}};TS=class extends ks{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;let i={width:e,height:e,depth:1},r=[i,i,i,i,i,i];this.texture=new $p(r),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}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;let i={uniforms:{tEquirect:{value:null}},vertexShader:` +}`,hi={alphahash_fragment:cQ,alphahash_pars_fragment:fQ,alphamap_fragment:hQ,alphamap_pars_fragment:dQ,alphatest_fragment:uQ,alphatest_pars_fragment:mQ,aomap_fragment:pQ,aomap_pars_fragment:_Q,batching_pars_vertex:gQ,batching_vertex:vQ,begin_vertex:EQ,beginnormal_vertex:SQ,bsdfs:TQ,iridescence_fragment:AQ,bumpmap_pars_fragment:xQ,clipping_planes_fragment:RQ,clipping_planes_pars_fragment:bQ,clipping_planes_pars_vertex:IQ,clipping_planes_vertex:MQ,color_fragment:CQ,color_pars_fragment:yQ,color_pars_vertex:PQ,color_vertex:DQ,common:LQ,cube_uv_reflection_fragment:OQ,defaultnormal_vertex:NQ,displacementmap_pars_vertex:wQ,displacementmap_vertex:FQ,emissivemap_fragment:BQ,emissivemap_pars_fragment:UQ,colorspace_fragment:VQ,colorspace_pars_fragment:GQ,envmap_fragment:kQ,envmap_common_pars_fragment:WQ,envmap_pars_fragment:HQ,envmap_pars_vertex:zQ,envmap_physical_pars_fragment:t$,envmap_vertex:XQ,fog_vertex:YQ,fog_pars_vertex:KQ,fog_fragment:jQ,fog_pars_fragment:qQ,gradientmap_pars_fragment:ZQ,lightmap_pars_fragment:QQ,lights_lambert_fragment:$Q,lights_lambert_pars_fragment:JQ,lights_pars_begin:e$,lights_toon_fragment:i$,lights_toon_pars_fragment:r$,lights_phong_fragment:n$,lights_phong_pars_fragment:s$,lights_physical_fragment:a$,lights_physical_pars_fragment:o$,lights_fragment_begin:l$,lights_fragment_maps:c$,lights_fragment_end:f$,lightprobes_pars_fragment:h$,logdepthbuf_fragment:d$,logdepthbuf_pars_fragment:u$,logdepthbuf_pars_vertex:m$,logdepthbuf_vertex:p$,map_fragment:_$,map_pars_fragment:g$,map_particle_fragment:v$,map_particle_pars_fragment:E$,metalnessmap_fragment:S$,metalnessmap_pars_fragment:T$,morphinstance_vertex:A$,morphcolor_vertex:x$,morphnormal_vertex:R$,morphtarget_pars_vertex:b$,morphtarget_vertex:I$,normal_fragment_begin:M$,normal_fragment_maps:C$,normal_pars_fragment:y$,normal_pars_vertex:P$,normal_vertex:D$,normalmap_pars_fragment:L$,clearcoat_normal_fragment_begin:O$,clearcoat_normal_fragment_maps:N$,clearcoat_pars_fragment:w$,iridescence_pars_fragment:F$,opaque_fragment:B$,packing:U$,premultiplied_alpha_fragment:V$,project_vertex:G$,dithering_fragment:k$,dithering_pars_fragment:W$,roughnessmap_fragment:H$,roughnessmap_pars_fragment:z$,shadowmap_pars_fragment:X$,shadowmap_pars_vertex:Y$,shadowmap_vertex:K$,shadowmask_pars_fragment:j$,skinbase_vertex:q$,skinning_pars_vertex:Z$,skinning_vertex:Q$,skinnormal_vertex:$$,specularmap_fragment:J$,specularmap_pars_fragment:eJ,tonemapping_fragment:tJ,tonemapping_pars_fragment:iJ,transmission_fragment:rJ,transmission_pars_fragment:nJ,uv_pars_fragment:sJ,uv_pars_vertex:aJ,uv_vertex:oJ,worldpos_vertex:lJ,background_vert:cJ,background_frag:fJ,backgroundCube_vert:hJ,backgroundCube_frag:dJ,cube_vert:uJ,cube_frag:mJ,depth_vert:pJ,depth_frag:_J,distance_vert:gJ,distance_frag:vJ,equirect_vert:EJ,equirect_frag:SJ,linedashed_vert:TJ,linedashed_frag:AJ,meshbasic_vert:xJ,meshbasic_frag:RJ,meshlambert_vert:bJ,meshlambert_frag:IJ,meshmatcap_vert:MJ,meshmatcap_frag:CJ,meshnormal_vert:yJ,meshnormal_frag:PJ,meshphong_vert:DJ,meshphong_frag:LJ,meshphysical_vert:OJ,meshphysical_frag:NJ,meshtoon_vert:wJ,meshtoon_frag:FJ,points_vert:BJ,points_frag:UJ,shadow_vert:VJ,shadow_frag:GJ,sprite_vert:kJ,sprite_frag:WJ},pt={common:{diffuse:{value:new ft(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new ii},alphaMap:{value:null},alphaMapTransform:{value:new ii},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new ii}},envmap:{envMap:{value:null},envMapRotation:{value:new ii},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new ii}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new ii}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new ii},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new ii},normalScale:{value:new It(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new ii},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new ii}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new ii}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new ii}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new ft(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null},probesSH:{value:null},probesMin:{value:new ne},probesMax:{value:new ne},probesResolution:{value:new ne}},points:{diffuse:{value:new ft(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new ii},alphaTest:{value:0},uvTransform:{value:new ii}},sprite:{diffuse:{value:new ft(16777215)},opacity:{value:1},center:{value:new It(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new ii},alphaMap:{value:null},alphaMapTransform:{value:new ii},alphaTest:{value:0}}},zo={basic:{uniforms:yn([pt.common,pt.specularmap,pt.envmap,pt.aomap,pt.lightmap,pt.fog]),vertexShader:hi.meshbasic_vert,fragmentShader:hi.meshbasic_frag},lambert:{uniforms:yn([pt.common,pt.specularmap,pt.envmap,pt.aomap,pt.lightmap,pt.emissivemap,pt.bumpmap,pt.normalmap,pt.displacementmap,pt.fog,pt.lights,{emissive:{value:new ft(0)},envMapIntensity:{value:1}}]),vertexShader:hi.meshlambert_vert,fragmentShader:hi.meshlambert_frag},phong:{uniforms:yn([pt.common,pt.specularmap,pt.envmap,pt.aomap,pt.lightmap,pt.emissivemap,pt.bumpmap,pt.normalmap,pt.displacementmap,pt.fog,pt.lights,{emissive:{value:new ft(0)},specular:{value:new ft(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:hi.meshphong_vert,fragmentShader:hi.meshphong_frag},standard:{uniforms:yn([pt.common,pt.envmap,pt.aomap,pt.lightmap,pt.emissivemap,pt.bumpmap,pt.normalmap,pt.displacementmap,pt.roughnessmap,pt.metalnessmap,pt.fog,pt.lights,{emissive:{value:new ft(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:hi.meshphysical_vert,fragmentShader:hi.meshphysical_frag},toon:{uniforms:yn([pt.common,pt.aomap,pt.lightmap,pt.emissivemap,pt.bumpmap,pt.normalmap,pt.displacementmap,pt.gradientmap,pt.fog,pt.lights,{emissive:{value:new ft(0)}}]),vertexShader:hi.meshtoon_vert,fragmentShader:hi.meshtoon_frag},matcap:{uniforms:yn([pt.common,pt.bumpmap,pt.normalmap,pt.displacementmap,pt.fog,{matcap:{value:null}}]),vertexShader:hi.meshmatcap_vert,fragmentShader:hi.meshmatcap_frag},points:{uniforms:yn([pt.points,pt.fog]),vertexShader:hi.points_vert,fragmentShader:hi.points_frag},dashed:{uniforms:yn([pt.common,pt.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:hi.linedashed_vert,fragmentShader:hi.linedashed_frag},depth:{uniforms:yn([pt.common,pt.displacementmap]),vertexShader:hi.depth_vert,fragmentShader:hi.depth_frag},normal:{uniforms:yn([pt.common,pt.bumpmap,pt.normalmap,pt.displacementmap,{opacity:{value:1}}]),vertexShader:hi.meshnormal_vert,fragmentShader:hi.meshnormal_frag},sprite:{uniforms:yn([pt.sprite,pt.fog]),vertexShader:hi.sprite_vert,fragmentShader:hi.sprite_frag},background:{uniforms:{uvTransform:{value:new ii},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:hi.background_vert,fragmentShader:hi.background_frag},backgroundCube:{uniforms:{envMap:{value:null},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new ii}},vertexShader:hi.backgroundCube_vert,fragmentShader:hi.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:hi.cube_vert,fragmentShader:hi.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:hi.equirect_vert,fragmentShader:hi.equirect_frag},distance:{uniforms:yn([pt.common,pt.displacementmap,{referencePosition:{value:new ne},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:hi.distance_vert,fragmentShader:hi.distance_frag},shadow:{uniforms:yn([pt.lights,pt.fog,{color:{value:new ft(0)},opacity:{value:1}}]),vertexShader:hi.shadow_vert,fragmentShader:hi.shadow_frag}};zo.physical={uniforms:yn([zo.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new ii},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new ii},clearcoatNormalScale:{value:new It(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new ii},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new ii},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new ii},sheen:{value:0},sheenColor:{value:new ft(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new ii},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new ii},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new ii},transmissionSamplerSize:{value:new It},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new ii},attenuationDistance:{value:0},attenuationColor:{value:new ft(0)},specularColor:{value:new ft(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new ii},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new ii},anisotropyVector:{value:new It},anisotropyMap:{value:null},anisotropyMapTransform:{value:new ii}}]),vertexShader:hi.meshphysical_vert,fragmentShader:hi.meshphysical_frag};SS={r:0,b:0,g:0},HJ=new li,d1=new ii;d1.set(-1,0,0,0,1,0,0,0,1);Jc=4,HF=[.125,.215,.35,.446,.526,.582],Rh=20,qJ=256,A_=new Vo,zF=new ft,rI=null,nI=0,sI=0,aI=!1,ZJ=new ne,Du=class{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}fromScene(e,t=0,i=.1,r=100,s={}){let{size:a=256,position:o=ZJ}=s;rI=this._renderer.getRenderTarget(),nI=this._renderer.getActiveCubeFace(),sI=this._renderer.getActiveMipmapLevel(),aI=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(a);let l=this._allocateTargets();return l.depthBuffer=!0,this._sceneToCubeUV(e,i,r,l,o),t>0&&this._blur(l,0,0,t),this._applyPMREM(l),this._cleanup(l),l}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=KF(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=YF(),this._compileMaterial(this._equirectMaterial))}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())}_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;e2?S:0,S,S),h.setRenderTarget(r),g&&h.render(p,l),h.render(e,l)}h.toneMapping=u,h.autoClear=d,e.background=v}_textureToCubeUV(e,t){let i=this._renderer,r=e.mapping===Zc||e.mapping===Th;r?(this._cubemapMaterial===null&&(this._cubemapMaterial=KF()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=YF());let s=r?this._cubemapMaterial:this._equirectMaterial,a=this._lodMeshes[0];a.material=s;let o=s.uniforms;o.envMap.value=e;let l=this._cubeSize;yu(t,0,0,3*l,2*l),i.setRenderTarget(t),i.render(a,A_)}_applyPMREM(e){let t=this._renderer,i=t.autoClear;t.autoClear=!1;let r=this._lodMeshes.length;for(let s=1;sm-Jc?i-m+Jc:0),g=4*(this._cubeSize-p);l.envMap.value=e.texture,l.roughness.value=u,l.mipInt.value=m-t,yu(s,_,g,3*p,2*p),r.setRenderTarget(s),r.render(o,A_),l.envMap.value=s.texture,l.roughness.value=0,l.mipInt.value=m-i,yu(e,_,g,3*p,2*p),r.setRenderTarget(e),r.render(o,A_)}_blur(e,t,i,r,s){let a=this._pingPongRenderTarget;this._halfBlur(e,a,t,i,r,"latitudinal",s),this._halfBlur(a,e,i,i,r,"longitudinal",s)}_halfBlur(e,t,i,r,s,a,o){let l=this._renderer,c=this._blurMaterial;a!=="latitudinal"&&a!=="longitudinal"&&Bt("blur direction must be either latitudinal or longitudinal!");let f=3,h=this._lodMeshes[r];h.material=c;let d=c.uniforms,u=this._sizeLods[i]-1,m=isFinite(s)?Math.PI/(2*u):2*Math.PI/(2*Rh-1),p=s/m,_=isFinite(s)?1+Math.floor(f*p):Rh;_>Rh&&Ct(`sigmaRadians, ${s}, is too large and will clip, as it requested ${_} samples when the maximum is set to ${Rh}`);let g=[],v=0;for(let R=0;Rx-Jc?r-x+Jc:0),E=4*(this._cubeSize-A);yu(t,S,E,3*A,2*A),l.setRenderTarget(t),l.render(h,A_)}};AS=class extends Gs{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;let i={width:e,height:e,depth:1},r=[i,i,i,i,i,i];this.texture=new $p(r),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}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;let i={uniforms:{tEquirect:{value:null}},vertexShader:` varying vec3 vWorldDirection; @@ -4052,7 +4052,7 @@ void main() { gl_FragColor = texture2D( tEquirect, sampleUV ); } - `},r=new Yc(5,5,5),s=new Ws({name:"CubemapFromEquirect",uniforms:xh(i.uniforms),vertexShader:i.vertexShader,fragmentShader:i.fragmentShader,side:pn,blending:ko});s.uniforms.tEquirect.value=t;let a=new ii(r,s),o=t.minFilter;return t.minFilter===qa&&(t.minFilter=Lr),new xE(1,10,this).update(e,a),t.minFilter=o,a.geometry.dispose(),a.material.dispose(),this}clear(e,t=!0,i=!0,r=!0){let s=e.getRenderTarget();for(let a=0;a<6;a++)e.setRenderTarget(this,a),e.clear(t,i,r);e.setRenderTarget(s)}};oee={[P0]:"LINEAR_TONE_MAPPING",[D0]:"REINHARD_TONE_MAPPING",[L0]:"CINEON_TONE_MAPPING",[O0]:"ACES_FILMIC_TONE_MAPPING",[w0]:"AGX_TONE_MAPPING",[F0]:"NEUTRAL_TONE_MAPPING",[N0]:"CUSTOM_TONE_MAPPING"};u1=new Ar,cI=new Cl(1,1),m1=new Xp,p1=new fE,_1=new $p,jF=[],qF=[],ZF=new Float32Array(16),QF=new Float32Array(9),$F=new Float32Array(4);fI=class{constructor(e,t,i){this.id=e,this.addr=i,this.cache=[],this.type=t.type,this.setValue=Cee(t.type)}},hI=class{constructor(e,t,i){this.id=e,this.addr=i,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=jee(t.type)}},dI=class{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,i){let r=this.seq;for(let s=0,a=r.length;s!==a;++s){let o=r[s];o.setValue(e,t[o.id],i)}}},oI=/(\w+)(\])?(\[|\.)?/g;Du=class{constructor(e,t){this.seq=[],this.map={};let i=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let a=0;a0&&(this.seq=r.concat(s))}setValue(e,t,i,r){let s=this.map[t];s!==void 0&&s.setValue(e,i,r)}setOptional(e,t,i){let r=t[i];r!==void 0&&this.setValue(e,i,r)}static upload(e,t,i,r){for(let s=0,a=t.length;s!==a;++s){let o=t[s],l=i[o.id];l.needsUpdate!==!1&&o.setValue(e,l.value,r)}}static seqWithValue(e,t){let i=[];for(let r=0,s=e.length;r!==s;++r){let a=e[r];a.id in t&&i.push(a)}return i}};Zee=37297,Qee=0;t1=new ti;tte={[P0]:"Linear",[D0]:"Reinhard",[L0]:"Cineon",[O0]:"ACESFilmic",[w0]:"AgX",[F0]:"Neutral",[N0]:"Custom"};SS=new ne;ote=/^[ \t]*#include +<([\w\d./]+)>/gm;lte=new Map;fte=/#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;dte={[h_]:"SHADOWMAP_TYPE_PCF",[Ru]:"SHADOWMAP_TYPE_VSM"};mte={[Qc]:"ENVMAP_TYPE_CUBE",[Th]:"ENVMAP_TYPE_CUBE",[u_]:"ENVMAP_TYPE_CUBE_UV"};_te={[Th]:"ENVMAP_MODE_REFRACTION"};vte={[d_]:"ENVMAP_BLENDING_MULTIPLY",[SF]:"ENVMAP_BLENDING_MIX",[TF]:"ENVMAP_BLENDING_ADD"};Ate=0,mI=class{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){let t=e.vertexShader,i=e.fragmentShader,r=this._getShaderStage(t),s=this._getShaderStage(i),a=this._getShaderCacheForMaterial(e);return a.has(r)===!1&&(a.add(r),r.usedTimes++),a.has(s)===!1&&(a.add(s),s.usedTimes++),this}remove(e){let t=this.materialCache.get(e);for(let 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){let t=this.materialCache,i=t.get(e);return i===void 0&&(i=new Set,t.set(e,i)),i}_getShaderStage(e){let t=this.shaderCache,i=t.get(e);return i===void 0&&(i=new pI(e),t.set(e,i)),i}},pI=class{constructor(e){this.id=Ate++,this.code=e,this.usedTimes=0}};Pte=0;Nte=`void main() { + `},r=new Xc(5,5,5),s=new ks({name:"CubemapFromEquirect",uniforms:xh(i.uniforms),vertexShader:i.vertexShader,fragmentShader:i.fragmentShader,side:pn,blending:ko});s.uniforms.tEquirect.value=t;let a=new ri(r,s),o=t.minFilter;return t.minFilter===qa&&(t.minFilter=Lr),new RE(1,10,this).update(e,a),t.minFilter=o,a.geometry.dispose(),a.material.dispose(),this}clear(e,t=!0,i=!0,r=!0){let s=e.getRenderTarget();for(let a=0;a<6;a++)e.setRenderTarget(this,a),e.clear(t,i,r);e.setRenderTarget(s)}};oee={[P0]:"LINEAR_TONE_MAPPING",[D0]:"REINHARD_TONE_MAPPING",[L0]:"CINEON_TONE_MAPPING",[O0]:"ACES_FILMIC_TONE_MAPPING",[w0]:"AGX_TONE_MAPPING",[F0]:"NEUTRAL_TONE_MAPPING",[N0]:"CUSTOM_TONE_MAPPING"};u1=new Ar,cI=new Ml(1,1),m1=new Xp,p1=new hE,_1=new $p,jF=[],qF=[],ZF=new Float32Array(16),QF=new Float32Array(9),$F=new Float32Array(4);fI=class{constructor(e,t,i){this.id=e,this.addr=i,this.cache=[],this.type=t.type,this.setValue=Cee(t.type)}},hI=class{constructor(e,t,i){this.id=e,this.addr=i,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=jee(t.type)}},dI=class{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,i){let r=this.seq;for(let s=0,a=r.length;s!==a;++s){let o=r[s];o.setValue(e,t[o.id],i)}}},oI=/(\w+)(\])?(\[|\.)?/g;Pu=class{constructor(e,t){this.seq=[],this.map={};let i=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let a=0;a0&&(this.seq=r.concat(s))}setValue(e,t,i,r){let s=this.map[t];s!==void 0&&s.setValue(e,i,r)}setOptional(e,t,i){let r=t[i];r!==void 0&&this.setValue(e,i,r)}static upload(e,t,i,r){for(let s=0,a=t.length;s!==a;++s){let o=t[s],l=i[o.id];l.needsUpdate!==!1&&o.setValue(e,l.value,r)}}static seqWithValue(e,t){let i=[];for(let r=0,s=e.length;r!==s;++r){let a=e[r];a.id in t&&i.push(a)}return i}};Zee=37297,Qee=0;t1=new ii;tte={[P0]:"Linear",[D0]:"Reinhard",[L0]:"Cineon",[O0]:"ACESFilmic",[w0]:"AgX",[F0]:"Neutral",[N0]:"Custom"};TS=new ne;ote=/^[ \t]*#include +<([\w\d./]+)>/gm;lte=new Map;fte=/#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;dte={[h_]:"SHADOWMAP_TYPE_PCF",[xu]:"SHADOWMAP_TYPE_VSM"};mte={[Zc]:"ENVMAP_TYPE_CUBE",[Th]:"ENVMAP_TYPE_CUBE",[u_]:"ENVMAP_TYPE_CUBE_UV"};_te={[Th]:"ENVMAP_MODE_REFRACTION"};vte={[d_]:"ENVMAP_BLENDING_MULTIPLY",[SF]:"ENVMAP_BLENDING_MIX",[TF]:"ENVMAP_BLENDING_ADD"};Ate=0,mI=class{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){let t=e.vertexShader,i=e.fragmentShader,r=this._getShaderStage(t),s=this._getShaderStage(i),a=this._getShaderCacheForMaterial(e);return a.has(r)===!1&&(a.add(r),r.usedTimes++),a.has(s)===!1&&(a.add(s),s.usedTimes++),this}remove(e){let t=this.materialCache.get(e);for(let 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){let t=this.materialCache,i=t.get(e);return i===void 0&&(i=new Set,t.set(e,i)),i}_getShaderStage(e){let t=this.shaderCache,i=t.get(e);return i===void 0&&(i=new pI(e),t.set(e,i)),i}},pI=class{constructor(e){this.id=Ate++,this.code=e,this.usedTimes=0}};Pte=0;Nte=`void main() { gl_Position = vec4( position, 1.0 ); }`,wte=`uniform sampler2D shadow_pass; uniform vec2 resolution; @@ -4079,7 +4079,7 @@ void main() { squared_mean = squared_mean / samples; float std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) ); gl_FragColor = vec4( mean, std_dev, 0.0, 1.0 ); -}`,Fte=[new ne(1,0,0),new ne(-1,0,0),new ne(0,1,0),new ne(0,-1,0),new ne(0,0,1),new ne(0,0,-1)],Bte=[new ne(0,-1,0),new ne(0,-1,0),new ne(0,0,1),new ne(0,0,-1),new ne(0,-1,0),new ne(0,-1,0)],f1=new oi,x_=new ne,lI=new ne;Wte=` +}`,Fte=[new ne(1,0,0),new ne(-1,0,0),new ne(0,1,0),new ne(0,-1,0),new ne(0,0,1),new ne(0,0,-1)],Bte=[new ne(0,-1,0),new ne(0,-1,0),new ne(0,0,1),new ne(0,0,-1),new ne(0,-1,0),new ne(0,-1,0)],f1=new li,x_=new ne,lI=new ne;Wte=` void main() { gl_Position = vec4( position, 1.0 ); @@ -4103,51 +4103,51 @@ void main() { } -}`,_I=class{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){let i=new e_(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=i}}getMesh(e){if(this.texture!==null&&this.mesh===null){let t=e.cameras[0].viewport,i=new Ws({vertexShader:Wte,fragmentShader:Hte,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new ii(new gh(20,20),i)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}},gI=class extends da{constructor(e,t){super();let i=this,r=null,s=1,a=null,o="local-floor",l=1,c=null,f=null,h=null,d=null,u=null,m=null,p=typeof XRWebGLBinding!="undefined",_=new _I,g={},v=t.getContextAttributes(),x=null,A=null,S=[],E=[],R=new bt,I=null,y=new kr;y.viewport=new Zi;let M=new kr;M.viewport=new Zi;let D=[y,M],O=new RE,V=null,N=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(se){let ue=S[se];return ue===void 0&&(ue=new mu,S[se]=ue),ue.getTargetRaySpace()},this.getControllerGrip=function(se){let ue=S[se];return ue===void 0&&(ue=new mu,S[se]=ue),ue.getGripSpace()},this.getHand=function(se){let ue=S[se];return ue===void 0&&(ue=new mu,S[se]=ue),ue.getHandSpace()};function F(se){let ue=E.indexOf(se.inputSource);if(ue===-1)return;let re=S[ue];re!==void 0&&(re.update(se.inputSource,se.frame,c||a),re.dispatchEvent({type:se.type,data:se.inputSource}))}function U(){r.removeEventListener("select",F),r.removeEventListener("selectstart",F),r.removeEventListener("selectend",F),r.removeEventListener("squeeze",F),r.removeEventListener("squeezestart",F),r.removeEventListener("squeezeend",F),r.removeEventListener("end",U),r.removeEventListener("inputsourceschange",k);for(let se=0;se=0&&(E[he]=null,S[he].disconnect(re))}for(let ue=0;ue=E.length){E.push(re),he=fe;break}else if(E[fe]===null){E[fe]=re,he=fe;break}if(he===-1)break}let De=S[he];De&&De.connect(re)}}let ee=new ne,q=new ne;function Q(se,ue,re){ee.setFromMatrixPosition(ue.matrixWorld),q.setFromMatrixPosition(re.matrixWorld);let he=ee.distanceTo(q),De=ue.projectionMatrix.elements,fe=re.projectionMatrix.elements,be=De[14]/(De[10]-1),Xe=De[14]/(De[10]+1),Et=(De[9]+1)/De[5],Ke=(De[9]-1)/De[5],qe=(De[8]-1)/De[0],Qt=(fe[8]+1)/fe[0],Dt=be*qe,Fi=be*Qt,ae=he/(-qe+Qt),Bi=ae*-qe;if(ue.matrixWorld.decompose(se.position,se.quaternion,se.scale),se.translateX(Bi),se.translateZ(ae),se.matrixWorld.compose(se.position,se.quaternion,se.scale),se.matrixWorldInverse.copy(se.matrixWorld).invert(),De[10]===-1)se.projectionMatrix.copy(ue.projectionMatrix),se.projectionMatrixInverse.copy(ue.projectionMatrixInverse);else{let ei=be+ae,Wi=Xe+ae,ot=Dt-Bi,Ci=Fi+(he-Bi),X=Et*Xe/Wi*ei,B=Ke*Xe/Wi*ei;se.projectionMatrix.makePerspective(ot,Ci,X,B,ei,Wi),se.projectionMatrixInverse.copy(se.projectionMatrix).invert()}}function Y(se,ue){ue===null?se.matrixWorld.copy(se.matrix):se.matrixWorld.multiplyMatrices(ue.matrixWorld,se.matrix),se.matrixWorldInverse.copy(se.matrixWorld).invert()}this.updateCamera=function(se){if(r===null)return;let ue=se.near,re=se.far;_.texture!==null&&(_.depthNear>0&&(ue=_.depthNear),_.depthFar>0&&(re=_.depthFar)),O.near=M.near=y.near=ue,O.far=M.far=y.far=re,(V!==O.near||N!==O.far)&&(r.updateRenderState({depthNear:O.near,depthFar:O.far}),V=O.near,N=O.far),O.layers.mask=se.layers.mask|6,y.layers.mask=O.layers.mask&-5,M.layers.mask=O.layers.mask&-3;let he=se.parent,De=O.cameras;Y(O,he);for(let fe=0;fe{function vt(){if(Se.forEach(function(xt){X.get(xt).currentProgram.isReady()&&Se.delete(xt)}),Se.size===0){Te(z);return}setTimeout(vt,10)}ei.get("KHR_parallel_shader_compile")!==null?vt():setTimeout(vt,10)})};let Xn=null;function Pb(z){Xn&&Xn(z)}function Id(){_l.stop()}function Db(){_l.start()}let _l=new h1;_l.setAnimationLoop(Pb),typeof self!="undefined"&&_l.setContext(self),this.setAnimationLoop=function(z){Xn=z,ke.setAnimationLoop(z),z===null?_l.stop():_l.start()},ke.addEventListener("sessionstart",Id),ke.addEventListener("sessionend",Db),this.render=function(z,ce){if(ce!==void 0&&ce.isCamera!==!0){Ft("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(D===!0)return;O!==null&&O.renderStart(z,ce);let xe=ke.enabled===!0&&ke.isPresenting===!0,Se=y!==null&&(F===null||xe)&&y.begin(M,F);if(z.matrixWorldAutoUpdate===!0&&z.updateMatrixWorld(),ce.parent===null&&ce.matrixWorldAutoUpdate===!0&&ce.updateMatrixWorld(),ke.enabled===!0&&ke.isPresenting===!0&&(y===null||y.isCompositing()===!1)&&(ke.cameraAutoUpdate===!0&&ke.updateCamera(ce),ce=ke.getCamera()),z.isScene===!0&&z.onBeforeRender(M,z,ce,F),E=je.get(z,I.length),E.init(ce),E.state.textureUnits=B.getTextureUnits(),I.push(E),Et.multiplyMatrices(ce.projectionMatrix,ce.matrixWorldInverse),fe.setFromProjectionMatrix(Et,Ha,ce.reversedDepth),Xe=this.localClippingEnabled,be=St.init(this.clippingPlanes,Xe),S=Pe.get(z,R.length),S.init(),R.push(S),ke.enabled===!0&&ke.isPresenting===!0){let xt=M.xr.getDepthSensingMesh();xt!==null&&Lb(xt,ce,-1/0,M.sortObjects)}Lb(z,ce,0,M.sortObjects),S.finish(),M.sortObjects===!0&&S.sort(se,ue),Dt=ke.enabled===!1||ke.isPresenting===!1||ke.hasDepthSensing()===!1,Dt&&et.addToRenderList(S,z),this.info.render.frame++,be===!0&&St.beginShadows();let Te=E.state.shadowsArray;if(nt.render(Te,z,ce),be===!0&&St.endShadows(),this.info.autoReset===!0&&this.info.reset(),(Se&&y.hasRenderPass())===!1){let xt=S.opaque,pt=S.transmissive;if(E.setupLights(),ce.isArrayCamera){let Ct=ce.cameras;if(pt.length>0)for(let Pt=0,li=Ct.length;Pt0&&ON(xt,pt,z,ce),Dt&&et.render(z),LN(S,z,ce)}F!==null&&N===0&&(B.updateMultisampleRenderTarget(F),B.updateRenderTargetMipmap(F)),Se&&y.end(M),z.isScene===!0&&z.onAfterRender(M,z,ce),ve.resetDefaultState(),U=-1,k=null,I.pop(),I.length>0?(E=I[I.length-1],B.setTextureUnits(E.state.textureUnits),be===!0&&St.setGlobalState(M.clippingPlanes,E.state.camera)):E=null,R.pop(),R.length>0?S=R[R.length-1]:S=null,O!==null&&O.renderEnd()};function Lb(z,ce,xe,Se){if(z.visible===!1)return;if(z.layers.test(ce.layers)){if(z.isGroup)xe=z.renderOrder;else if(z.isLOD)z.autoUpdate===!0&&z.update(ce);else if(z.isLightProbeGrid)E.pushLightProbeGrid(z);else if(z.isLight)E.pushLight(z),z.castShadow&&E.pushShadow(z);else if(z.isSprite){if(!z.frustumCulled||fe.intersectsSprite(z)){Se&&qe.setFromMatrixPosition(z.matrixWorld).applyMatrix4(Et);let xt=Je.update(z),pt=z.material;pt.visible&&S.push(z,xt,pt,xe,qe.z,null)}}else if((z.isMesh||z.isLine||z.isPoints)&&(!z.frustumCulled||fe.intersectsObject(z))){let xt=Je.update(z),pt=z.material;if(Se&&(z.boundingSphere!==void 0?(z.boundingSphere===null&&z.computeBoundingSphere(),qe.copy(z.boundingSphere.center)):(xt.boundingSphere===null&&xt.computeBoundingSphere(),qe.copy(xt.boundingSphere.center)),qe.applyMatrix4(z.matrixWorld).applyMatrix4(Et)),Array.isArray(pt)){let Ct=xt.groups;for(let Pt=0,li=Ct.length;Pt0&&fv(Te,ce,xe),vt.length>0&&fv(vt,ce,xe),xt.length>0&&fv(xt,ce,xe),ot.buffers.depth.setTest(!0),ot.buffers.depth.setMask(!0),ot.buffers.color.setMask(!0),ot.setPolygonOffset(!1)}function ON(z,ce,xe,Se){if((xe.isScene===!0?xe.overrideMaterial:null)!==null)return;if(E.state.transmissionRenderTarget[Se.id]===void 0){let Lt=ei.has("EXT_color_buffer_half_float")||ei.has("EXT_color_buffer_float");E.state.transmissionRenderTarget[Se.id]=new ks(1,1,{generateMipmaps:!0,type:Lt?Wo:_s,minFilter:qa,samples:Math.max(4,Wi.samples),stencilBuffer:s,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:ai.workingColorSpace})}let vt=E.state.transmissionRenderTarget[Se.id],xt=Se.viewport||ee;vt.setSize(xt.z*M.transmissionResolutionScale,xt.w*M.transmissionResolutionScale);let pt=M.getRenderTarget(),Ct=M.getActiveCubeFace(),Pt=M.getActiveMipmapLevel();M.setRenderTarget(vt),M.getClearColor(Y),K=M.getClearAlpha(),K<1&&M.setClearColor(16777215,.5),M.clear(),Dt&&et.render(xe);let li=M.toneMapping;M.toneMapping=Hs;let ui=Se.viewport;if(Se.viewport!==void 0&&(Se.viewport=void 0),E.setupLightsView(Se),be===!0&&St.setGlobalState(M.clippingPlanes,Se),fv(z,xe,Se),B.updateMultisampleRenderTarget(vt),B.updateRenderTargetMipmap(vt),ei.has("WEBGL_multisampled_render_to_texture")===!1){let Lt=!1;for(let ji=0,yr=ce.length;ji0,Se.currentProgram=ui,Se.uniformsList=null,ui}function wN(z){if(z.uniformsList===null){let ce=z.currentProgram.getUniforms();z.uniformsList=Du.seqWithValue(ce.seq,z.uniforms)}return z.uniformsList}function FN(z,ce){let xe=X.get(z);xe.outputColorSpace=ce.outputColorSpace,xe.batching=ce.batching,xe.batchingColor=ce.batchingColor,xe.instancing=ce.instancing,xe.instancingColor=ce.instancingColor,xe.instancingMorph=ce.instancingMorph,xe.skinning=ce.skinning,xe.morphTargets=ce.morphTargets,xe.morphNormals=ce.morphNormals,xe.morphColors=ce.morphColors,xe.morphTargetsCount=ce.morphTargetsCount,xe.numClippingPlanes=ce.numClippingPlanes,xe.numIntersection=ce.numClipIntersection,xe.vertexAlphas=ce.vertexAlphas,xe.vertexTangents=ce.vertexTangents,xe.toneMapping=ce.toneMapping}function xq(z,ce){if(z.length===0)return null;if(z.length===1)return z[0].texture!==null?z[0]:null;A.setFromMatrixPosition(ce.matrixWorld);for(let xe=0,Se=z.length;xe0),Lt=!!xe.morphAttributes.position,ji=!!xe.morphAttributes.normal,yr=!!xe.morphAttributes.color,br=Hs;Se.toneMapped&&(F===null||F.isXRRenderTarget===!0)&&(br=M.toneMapping);let $i=xe.morphAttributes.position||xe.morphAttributes.normal||xe.morphAttributes.color,Rn=$i!==void 0?$i.length:0,At=X.get(Se),Ns=E.state.lights;if(be===!0&&(Xe===!0||z!==k)){let sr=z===k&&Se.id===U;St.setState(Se,z,sr)}let Oi=!1;Se.version===At.__version?(At.needsLights&&At.lightsStateVersion!==Ns.state.version||At.outputColorSpace!==pt||Te.isBatchedMesh&&At.batching===!1||!Te.isBatchedMesh&&At.batching===!0||Te.isBatchedMesh&&At.batchingColor===!0&&Te.colorTexture===null||Te.isBatchedMesh&&At.batchingColor===!1&&Te.colorTexture!==null||Te.isInstancedMesh&&At.instancing===!1||!Te.isInstancedMesh&&At.instancing===!0||Te.isSkinnedMesh&&At.skinning===!1||!Te.isSkinnedMesh&&At.skinning===!0||Te.isInstancedMesh&&At.instancingColor===!0&&Te.instanceColor===null||Te.isInstancedMesh&&At.instancingColor===!1&&Te.instanceColor!==null||Te.isInstancedMesh&&At.instancingMorph===!0&&Te.morphTexture===null||Te.isInstancedMesh&&At.instancingMorph===!1&&Te.morphTexture!==null||At.envMap!==Pt||Se.fog===!0&&At.fog!==vt||At.numClippingPlanes!==void 0&&(At.numClippingPlanes!==St.numPlanes||At.numIntersection!==St.numIntersection)||At.vertexAlphas!==li||At.vertexTangents!==ui||At.morphTargets!==Lt||At.morphNormals!==ji||At.morphColors!==yr||At.toneMapping!==br||At.morphTargetsCount!==Rn||!!At.lightProbeGrid!=E.state.lightProbeGridArray.length>0)&&(Oi=!0):(Oi=!0,At.__version=Se.version);let ia=At.currentProgram;Oi===!0&&(ia=hv(Se,ce,Te),O&&Se.isNodeMaterial&&O.onUpdateProgram(Se,ia,At));let bo=!1,Pc=!1,Md=!1,Ji=ia.getUniforms(),Pr=At.uniforms;if(ot.useProgram(ia.program)&&(bo=!0,Pc=!0,Md=!0),Se.id!==U&&(U=Se.id,Pc=!0),At.needsLights){let sr=xq(E.state.lightProbeGridArray,Te);At.lightProbeGrid!==sr&&(At.lightProbeGrid=sr,Pc=!0)}if(bo||k!==z){ot.buffers.depth.getReversed()&&z.reversedDepth!==!0&&(z._reversedDepth=!0,z.updateProjectionMatrix()),Ji.setValue(ae,"projectionMatrix",z.projectionMatrix),Ji.setValue(ae,"viewMatrix",z.matrixWorldInverse);let Lc=Ji.map.cameraPosition;Lc!==void 0&&Lc.setValue(ae,Ke.setFromMatrixPosition(z.matrixWorld)),Wi.logarithmicDepthBuffer&&Ji.setValue(ae,"logDepthBufFC",2/(Math.log(z.far+1)/Math.LN2)),(Se.isMeshPhongMaterial||Se.isMeshToonMaterial||Se.isMeshLambertMaterial||Se.isMeshBasicMaterial||Se.isMeshStandardMaterial||Se.isShaderMaterial)&&Ji.setValue(ae,"isOrthographic",z.isOrthographicCamera===!0),k!==z&&(k=z,Pc=!0,Md=!0)}if(At.needsLights&&(Ns.state.directionalShadowMap.length>0&&Ji.setValue(ae,"directionalShadowMap",Ns.state.directionalShadowMap,B),Ns.state.spotShadowMap.length>0&&Ji.setValue(ae,"spotShadowMap",Ns.state.spotShadowMap,B),Ns.state.pointShadowMap.length>0&&Ji.setValue(ae,"pointShadowMap",Ns.state.pointShadowMap,B)),Te.isSkinnedMesh){Ji.setOptional(ae,Te,"bindMatrix"),Ji.setOptional(ae,Te,"bindMatrixInverse");let sr=Te.skeleton;sr&&(sr.boneTexture===null&&sr.computeBoneTexture(),Ji.setValue(ae,"boneTexture",sr.boneTexture,B))}Te.isBatchedMesh&&(Ji.setOptional(ae,Te,"batchingTexture"),Ji.setValue(ae,"batchingTexture",Te._matricesTexture,B),Ji.setOptional(ae,Te,"batchingIdTexture"),Ji.setValue(ae,"batchingIdTexture",Te._indirectTexture,B),Ji.setOptional(ae,Te,"batchingColorTexture"),Te._colorsTexture!==null&&Ji.setValue(ae,"batchingColorTexture",Te._colorsTexture,B));let Dc=xe.morphAttributes;if((Dc.position!==void 0||Dc.normal!==void 0||Dc.color!==void 0)&&Vt.update(Te,xe,ia),(Pc||At.receiveShadow!==Te.receiveShadow)&&(At.receiveShadow=Te.receiveShadow,Ji.setValue(ae,"receiveShadow",Te.receiveShadow)),(Se.isMeshStandardMaterial||Se.isMeshLambertMaterial||Se.isMeshPhongMaterial)&&Se.envMap===null&&ce.environment!==null&&(Pr.envMapIntensity.value=ce.environmentIntensity),Pr.dfgLUT!==void 0&&(Pr.dfgLUT.value=jte()),Pc){if(Ji.setValue(ae,"toneMappingExposure",M.toneMappingExposure),At.needsLights&&bq(Pr,Md),vt&&Se.fog===!0&&Ce.refreshFogUniforms(Pr,vt),Ce.refreshMaterialUniforms(Pr,Se,Fe,Re,E.state.transmissionRenderTarget[z.id]),At.needsLights&&At.lightProbeGrid){let sr=At.lightProbeGrid;Pr.probesSH.value=sr.texture,Pr.probesMin.value.copy(sr.boundingBox.min),Pr.probesMax.value.copy(sr.boundingBox.max),Pr.probesResolution.value.copy(sr.resolution)}Du.upload(ae,wN(At),Pr,B)}if(Se.isShaderMaterial&&Se.uniformsNeedUpdate===!0&&(Du.upload(ae,wN(At),Pr,B),Se.uniformsNeedUpdate=!1),Se.isSpriteMaterial&&Ji.setValue(ae,"center",Te.center),Ji.setValue(ae,"modelViewMatrix",Te.modelViewMatrix),Ji.setValue(ae,"normalMatrix",Te.normalMatrix),Ji.setValue(ae,"modelMatrix",Te.matrixWorld),Se.uniformsGroups!==void 0){let sr=Se.uniformsGroups;for(let Lc=0,Cd=sr.length;Lc0&&B.useMultisampledRTT(z)===!1?Se=X.get(z).__webglMultisampledFramebuffer:Array.isArray(Pt)?Se=Pt[xe]:Se=Pt,ee.copy(z.viewport),q.copy(z.scissor),Q=z.scissorTest}else ee.copy(re).multiplyScalar(Fe).floor(),q.copy(he).multiplyScalar(Fe).floor(),Q=De;if(xe!==0&&(Se=Mq),ot.bindFramebuffer(ae.FRAMEBUFFER,Se)&&ot.drawBuffers(z,Se),ot.viewport(ee),ot.scissor(q),ot.setScissorTest(Q),Te){let pt=X.get(z.texture);ae.framebufferTexture2D(ae.FRAMEBUFFER,ae.COLOR_ATTACHMENT0,ae.TEXTURE_CUBE_MAP_POSITIVE_X+ce,pt.__webglTexture,xe)}else if(vt){let pt=ce;for(let Ct=0;Ct1&&ae.readBuffer(ae.COLOR_ATTACHMENT0+pt),!Wi.textureFormatReadable(li)){Ft("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!Wi.textureTypeReadable(ui)){Ft("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}ce>=0&&ce<=z.width-Se&&xe>=0&&xe<=z.height-Te&&ae.readPixels(ce,xe,Se,Te,G.convert(li),G.convert(ui),vt)}finally{let Pt=F!==null?X.get(F).__webglFramebuffer:null;ot.bindFramebuffer(ae.FRAMEBUFFER,Pt)}}},this.readRenderTargetPixelsAsync=async function(z,ce,xe,Se,Te,vt,xt,pt=0){if(!(z&&z.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Ct=X.get(z).__webglFramebuffer;if(z.isWebGLCubeRenderTarget&&xt!==void 0&&(Ct=Ct[xt]),Ct)if(ce>=0&&ce<=z.width-Se&&xe>=0&&xe<=z.height-Te){ot.bindFramebuffer(ae.FRAMEBUFFER,Ct);let Pt=z.textures[pt],li=Pt.format,ui=Pt.type;if(z.textures.length>1&&ae.readBuffer(ae.COLOR_ATTACHMENT0+pt),!Wi.textureFormatReadable(li))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!Wi.textureTypeReadable(ui))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");let Lt=ae.createBuffer();ae.bindBuffer(ae.PIXEL_PACK_BUFFER,Lt),ae.bufferData(ae.PIXEL_PACK_BUFFER,vt.byteLength,ae.STREAM_READ),ae.readPixels(ce,xe,Se,Te,G.convert(li),G.convert(ui),0);let ji=F!==null?X.get(F).__webglFramebuffer:null;ot.bindFramebuffer(ae.FRAMEBUFFER,ji);let yr=ae.fenceSync(ae.SYNC_GPU_COMMANDS_COMPLETE,0);return ae.flush(),await BF(ae,yr,4),ae.bindBuffer(ae.PIXEL_PACK_BUFFER,Lt),ae.getBufferSubData(ae.PIXEL_PACK_BUFFER,0,vt),ae.deleteBuffer(Lt),ae.deleteSync(yr),vt}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(z,ce=null,xe=0){let Se=Math.pow(2,-xe),Te=Math.floor(z.image.width*Se),vt=Math.floor(z.image.height*Se),xt=ce!==null?ce.x:0,pt=ce!==null?ce.y:0;B.setTexture2D(z,0),ae.copyTexSubImage2D(ae.TEXTURE_2D,xe,0,0,xt,pt,Te,vt),ot.unbindTexture()};let Cq=ae.createFramebuffer(),yq=ae.createFramebuffer();this.copyTextureToTexture=function(z,ce,xe=null,Se=null,Te=0,vt=0){let xt,pt,Ct,Pt,li,ui,Lt,ji,yr,br=z.isCompressedTexture?z.mipmaps[vt]:z.image;if(xe!==null)xt=xe.max.x-xe.min.x,pt=xe.max.y-xe.min.y,Ct=xe.isBox3?xe.max.z-xe.min.z:1,Pt=xe.min.x,li=xe.min.y,ui=xe.isBox3?xe.min.z:0;else{let Pr=Math.pow(2,-Te);xt=Math.floor(br.width*Pr),pt=Math.floor(br.height*Pr),z.isDataArrayTexture?Ct=br.depth:z.isData3DTexture?Ct=Math.floor(br.depth*Pr):Ct=1,Pt=0,li=0,ui=0}Se!==null?(Lt=Se.x,ji=Se.y,yr=Se.z):(Lt=0,ji=0,yr=0);let $i=G.convert(ce.format),Rn=G.convert(ce.type),At;ce.isData3DTexture?(B.setTexture3D(ce,0),At=ae.TEXTURE_3D):ce.isDataArrayTexture||ce.isCompressedArrayTexture?(B.setTexture2DArray(ce,0),At=ae.TEXTURE_2D_ARRAY):(B.setTexture2D(ce,0),At=ae.TEXTURE_2D),ot.activeTexture(ae.TEXTURE0),ot.pixelStorei(ae.UNPACK_FLIP_Y_WEBGL,ce.flipY),ot.pixelStorei(ae.UNPACK_PREMULTIPLY_ALPHA_WEBGL,ce.premultiplyAlpha),ot.pixelStorei(ae.UNPACK_ALIGNMENT,ce.unpackAlignment);let Ns=ot.getParameter(ae.UNPACK_ROW_LENGTH),Oi=ot.getParameter(ae.UNPACK_IMAGE_HEIGHT),ia=ot.getParameter(ae.UNPACK_SKIP_PIXELS),bo=ot.getParameter(ae.UNPACK_SKIP_ROWS),Pc=ot.getParameter(ae.UNPACK_SKIP_IMAGES);ot.pixelStorei(ae.UNPACK_ROW_LENGTH,br.width),ot.pixelStorei(ae.UNPACK_IMAGE_HEIGHT,br.height),ot.pixelStorei(ae.UNPACK_SKIP_PIXELS,Pt),ot.pixelStorei(ae.UNPACK_SKIP_ROWS,li),ot.pixelStorei(ae.UNPACK_SKIP_IMAGES,ui);let Md=z.isDataArrayTexture||z.isData3DTexture,Ji=ce.isDataArrayTexture||ce.isData3DTexture;if(z.isDepthTexture){let Pr=X.get(z),Dc=X.get(ce),sr=X.get(Pr.__renderTarget),Lc=X.get(Dc.__renderTarget);ot.bindFramebuffer(ae.READ_FRAMEBUFFER,sr.__webglFramebuffer),ot.bindFramebuffer(ae.DRAW_FRAMEBUFFER,Lc.__webglFramebuffer);for(let Cd=0;Cd{Ys();v1={type:"change"},EI={type:"start"},S1={type:"end"},bS=new Oo,E1=new fa,qte=Math.cos(70*T_.DEG2RAD),Jr=new ne,gs=2*Math.PI,Qi={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},vI=1e-6,IS=class extends f_{constructor(e,t=null){super(e,t),this.state=Qi.NONE,this.target=new ne,this.cursor=new ne,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=.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:qc.ROTATE,MIDDLE:qc.DOLLY,RIGHT:qc.PAN},this.touches={ONE:Zc.ROTATE,TWO:Zc.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._cursorStyle="auto",this._domElementKeyEvents=null,this._lastPosition=new ne,this._lastQuaternion=new Zr,this._lastTargetPosition=new ne,this._quat=new Zr().setFromUnitVectors(e.up,new ne(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new Au,this._sphericalDelta=new Au,this._scale=1,this._panOffset=new ne,this._rotateStart=new bt,this._rotateEnd=new bt,this._rotateDelta=new bt,this._panStart=new bt,this._panEnd=new bt,this._panDelta=new bt,this._dollyStart=new bt,this._dollyEnd=new bt,this._dollyDelta=new bt,this._dollyDirection=new ne,this._mouse=new bt,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=Qte.bind(this),this._onPointerDown=Zte.bind(this),this._onPointerUp=$te.bind(this),this._onContextMenu=sie.bind(this),this._onMouseWheel=tie.bind(this),this._onKeyDown=iie.bind(this),this._onTouchStart=rie.bind(this),this._onTouchMove=nie.bind(this),this._onMouseDown=Jte.bind(this),this._onMouseMove=eie.bind(this),this._interceptControlDown=aie.bind(this),this._interceptControlUp=oie.bind(this),this.domElement!==null&&this.connect(this.domElement),this.update()}set cursorStyle(e){this._cursorStyle=e,e==="grab"?this.domElement.style.cursor="grab":this.domElement.style.cursor="auto"}get cursorStyle(){return this._cursorStyle}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.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.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=""}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){this._domElementKeyEvents!==null&&(this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null)}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(v1),this.update(),this.state=Qi.NONE}pan(e,t){this._pan(e,t),this.update()}dollyIn(e){this._dollyIn(e),this.update()}dollyOut(e){this._dollyOut(e),this.update()}rotateLeft(e){this._rotateLeft(e),this.update()}rotateUp(e){this._rotateUp(e),this.update()}update(e=null){let t=this.object.position;Jr.copy(t).sub(this.target),Jr.applyQuaternion(this._quat),this._spherical.setFromVector3(Jr),this.autoRotate&&this.state===Qi.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,r=this.maxAzimuthAngle;isFinite(i)&&isFinite(r)&&(i<-Math.PI?i+=gs:i>Math.PI&&(i-=gs),r<-Math.PI?r+=gs:r>Math.PI&&(r-=gs),i<=r?this._spherical.theta=Math.max(i,Math.min(r,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(i+r)/2?Math.max(i,this._spherical.theta):Math.min(r,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let s=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{let a=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),s=a!=this._spherical.radius}if(Jr.setFromSpherical(this._spherical),Jr.applyQuaternion(this._quatInverse),t.copy(this.target).add(Jr),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){let o=Jr.length();a=this._clampDistance(o*this._scale);let l=o-a;this.object.position.addScaledVector(this._dollyDirection,l),this.object.updateMatrixWorld(),s=!!l}else if(this.object.isOrthographicCamera){let o=new ne(this._mouse.x,this._mouse.y,0);o.unproject(this.object);let l=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),s=l!==this.object.zoom;let c=new ne(this._mouse.x,this._mouse.y,0);c.unproject(this.object),this.object.position.sub(c).add(o),this.object.updateMatrixWorld(),a=Jr.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):(bS.origin.copy(this.object.position),bS.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(bS.direction))vI||8*(1-this._lastQuaternion.dot(this.object.quaternion))>vI||this._lastTargetPosition.distanceToSquared(this.target)>vI?(this.dispatchEvent(v1),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?gs/60*this.autoRotateSpeed*e:gs/60/60*this.autoRotateSpeed}_getZoomScale(e){let t=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){Jr.setFromMatrixColumn(t,0),Jr.multiplyScalar(-e),this._panOffset.add(Jr)}_panUp(e,t){this.screenSpacePanning===!0?Jr.setFromMatrixColumn(t,1):(Jr.setFromMatrixColumn(t,0),Jr.crossVectors(this.object.up,Jr)),Jr.multiplyScalar(e),this._panOffset.add(Jr)}_pan(e,t){let i=this.domElement;if(this.object.isPerspectiveCamera){let r=this.object.position;Jr.copy(r).sub(this.target);let s=Jr.length();s*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*s/i.clientHeight,this.object.matrix),this._panUp(2*t*s/i.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/i.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/i.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;let i=this.domElement.getBoundingClientRect(),r=e-i.left,s=t-i.top,a=i.width,o=i.height;this._mouse.x=r/a*2-1,this._mouse.y=-(s/o)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_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);let t=this.domElement;this._rotateLeft(gs*this._rotateDelta.x/t.clientHeight),this._rotateUp(gs*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(gs*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(-gs*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(gs*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(-gs*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{let t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),r=.5*(e.pageY+t.y);this._rotateStart.set(i,r)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{let t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),r=.5*(e.pageY+t.y);this._panStart.set(i,r)}}_handleTouchStartDolly(e){let t=this._getSecondPointerPosition(e),i=e.pageX-t.x,r=e.pageY-t.y,s=Math.sqrt(i*i+r*r);this._dollyStart.set(0,s)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{let i=this._getSecondPointerPosition(e),r=.5*(e.pageX+i.x),s=.5*(e.pageY+i.y);this._rotateEnd.set(r,s)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);let t=this.domElement;this._rotateLeft(gs*this._rotateDelta.x/t.clientHeight),this._rotateUp(gs*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{let t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),r=.5*(e.pageY+t.y);this._panEnd.set(i,r)}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){let t=this._getSecondPointerPosition(e),i=e.pageX-t.x,r=e.pageY-t.y,s=Math.sqrt(i*i+r*r);this._dollyEnd.set(0,s),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);let a=(e.pageX+t.x)*.5,o=(e.pageY+t.y)*.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)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t{Ys();MS=class extends mh{constructor(){super(),this.name="RoomEnvironment",this.position.y=-3.5;let e=new Yc;e.deleteAttribute("uv");let t=new Cn({side:pn}),i=new Cn,r=new Ka(16777215,900,28,2);r.position.set(.418,16.199,.3),this.add(r);let s=new ii(e,t);s.position.set(-.757,13.219,.717),s.scale.set(31.713,28.305,28.591),this.add(s);let a=new _h(e,i,6),o=new er;o.position.set(-10.906,2.009,1.846),o.rotation.set(0,-.195,0),o.scale.set(2.328,7.905,4.651),o.updateMatrix(),a.setMatrixAt(0,o.matrix),o.position.set(-5.607,-.754,-.758),o.rotation.set(0,.994,0),o.scale.set(1.97,1.534,3.955),o.updateMatrix(),a.setMatrixAt(1,o.matrix),o.position.set(6.167,.857,7.803),o.rotation.set(0,.561,0),o.scale.set(3.927,6.285,3.687),o.updateMatrix(),a.setMatrixAt(2,o.matrix),o.position.set(-2.017,.018,6.124),o.rotation.set(0,.333,0),o.scale.set(2.002,4.566,2.064),o.updateMatrix(),a.setMatrixAt(3,o.matrix),o.position.set(2.291,-.756,-2.621),o.rotation.set(0,-.286,0),o.scale.set(1.546,1.552,1.496),o.updateMatrix(),a.setMatrixAt(4,o.matrix),o.position.set(-2.193,-.369,-5.547),o.rotation.set(0,.516,0),o.scale.set(3.875,3.487,2.986),o.updateMatrix(),a.setMatrixAt(5,o.matrix),this.add(a);let l=new ii(e,Nu(50));l.position.set(-16.116,14.37,8.208),l.scale.set(.1,2.428,2.739),this.add(l);let c=new ii(e,Nu(50));c.position.set(-16.109,18.021,-8.207),c.scale.set(.1,2.425,2.751),this.add(c);let f=new ii(e,Nu(17));f.position.set(14.904,12.198,-1.832),f.scale.set(.15,4.265,6.331),this.add(f);let h=new ii(e,Nu(43));h.position.set(-.462,8.89,14.52),h.scale.set(4.38,5.441,.088),this.add(h);let d=new ii(e,Nu(20));d.position.set(3.235,11.486,-12.541),d.scale.set(2.5,2,.1),this.add(d);let u=new ii(e,Nu(100));u.position.set(0,20,0),u.scale.set(1,.1,1),this.add(u)}dispose(){let e=new Set;this.traverse(t=>{t.isMesh&&(e.add(t.geometry),e.add(t.material))});for(let t of e)t.dispose()}}});var CS,SI,x1=C(()=>{Ys();CS=class extends cn{constructor(e){super(e)}load(e,t,i,r){let s=this,a=this.path===""?ja.extractUrlBase(e):this.path,o=new ps(this.manager);o.setPath(this.path),o.setRequestHeader(this.requestHeader),o.setWithCredentials(this.withCredentials),o.load(e,function(l){try{t(s.parse(l,a))}catch(c){r?r(c):console.error(c),s.manager.itemError(e)}},i,r)}setMaterialOptions(e){return this.materialOptions=e,this}parse(e,t){let i=e.split(` -`),r={},s=/\s+/,a={};for(let l=0;l=0?c.substring(0,f):c;h=h.toLowerCase();let d=f>=0?c.substring(f+1):"";if(d=d.trim(),h==="newmtl")r={name:d},a[d]=r;else if(h==="ka"||h==="kd"||h==="ks"||h==="ke"){let u=d.split(s,3);r[h]=[parseFloat(u[0]),parseFloat(u[1]),parseFloat(u[2])]}else r[h]=d}let o=new SI(this.resourcePath||t,this.materialOptions);return o.setCrossOrigin(this.crossOrigin),o.setManager(this.manager),o.setMaterials(a),o}},SI=class{constructor(e="",t={}){this.baseUrl=e,this.options=t,this.materialsInfo={},this.materials={},this.materialsArray=[],this.nameLookup={},this.crossOrigin="anonymous",this.side=this.options.side!==void 0?this.options.side:Gs,this.wrap=this.options.wrap!==void 0?this.options.wrap:Do}setCrossOrigin(e){return this.crossOrigin=e,this}setManager(e){this.manager=e}setMaterials(e){this.materialsInfo=this.convert(e),this.materials={},this.materialsArray=[],this.nameLookup={}}convert(e){if(!this.options)return e;let t={};for(let i in e){let r=e[i],s={};t[i]=s;for(let a in r){let o=!0,l=r[a],c=a.toLowerCase();switch(c){case"kd":case"ka":case"ks":this.options&&this.options.normalizeRGB&&(l=[l[0]/255,l[1]/255,l[2]/255]),this.options&&this.options.ignoreZeroRGBs&&l[0]===0&&l[1]===0&&l[2]===0&&(o=!1);break;default:break}o&&(s[c]=l)}}return t}preload(){for(let e in this.materialsInfo)this.create(e)}getIndex(e){return this.nameLookup[e]}getAsArray(){let e=0;for(let t in this.materialsInfo)this.materialsArray[e]=this.create(t),this.nameLookup[t]=e,e++;return this.materialsArray}create(e){return this.materials[e]===void 0&&this.createMaterial_(e),this.materials[e]}createMaterial_(e){let t=this,i=this.materialsInfo[e],r={name:e,side:this.side};function s(o,l){return typeof l!="string"||l===""?"":/^https?:\/\//i.test(l)?l:o+l}function a(o,l){if(r[o])return;let c=t.getTextureParams(l,r),f=t.loadTexture(s(t.baseUrl,c.url));f.repeat.copy(c.scale),f.offset.copy(c.offset),f.wrapS=t.wrap,f.wrapT=t.wrap,(o==="map"||o==="emissiveMap")&&(f.colorSpace=Ni),r[o]=f}for(let o in i){let l=i[o],c;if(l!=="")switch(o.toLowerCase()){case"kd":r.color=ai.colorSpaceToWorking(new ct().fromArray(l),Ni);break;case"ks":r.specular=ai.colorSpaceToWorking(new ct().fromArray(l),Ni);break;case"ke":r.emissive=ai.colorSpaceToWorking(new ct().fromArray(l),Ni);break;case"map_kd":a("map",l);break;case"map_ks":a("specularMap",l);break;case"map_ke":a("emissiveMap",l);break;case"norm":a("normalMap",l);break;case"map_bump":case"bump":a("bumpMap",l);break;case"disp":a("displacementMap",l);break;case"map_d":a("alphaMap",l),r.transparent=!0;break;case"ns":r.shininess=parseFloat(l);break;case"d":c=parseFloat(l),c<1&&(r.opacity=c,r.transparent=!0);break;case"tr":c=parseFloat(l),this.options&&this.options.invertTrProperty&&(c=1-c),c>0&&(r.opacity=1-c,r.transparent=!0);break;default:break}}return this.materials[e]=new vh(r),this.materials[e]}getTextureParams(e,t){let i={scale:new bt(1,1),offset:new bt(0,0)},r=e.split(/\s+/),s;return s=r.indexOf("-bm"),s>=0&&(t.bumpScale=parseFloat(r[s+1]),r.splice(s,2)),s=r.indexOf("-mm"),s>=0&&(t.displacementBias=parseFloat(r[s+1]),t.displacementScale=parseFloat(r[s+2]),r.splice(s,3)),s=r.indexOf("-s"),s>=0&&(i.scale.set(parseFloat(r[s+1]),parseFloat(r[s+2])),r.splice(s,4)),s=r.indexOf("-o"),s>=0&&(i.offset.set(parseFloat(r[s+1]),parseFloat(r[s+2])),r.splice(s,4)),i.url=r.join(" ").trim(),i}loadTexture(e,t,i,r,s){let a=this.manager!==void 0?this.manager:vS,o=a.getHandler(e);o===null&&(o=new Sh(a)),o.setCrossOrigin&&o.setCrossOrigin(this.crossOrigin);let l=o.load(e,i,r,s);return t!==void 0&&(l.mapping=t),l}}});function die(){let n={objects:[],object:{},vertices:[],normals:[],colors:[],uvs:[],materials:{},materialLibraries:[],startObject:function(e,t){if(this.object&&this.object.fromDeclaration===!1){this.object.name=e,this.object.fromDeclaration=t!==!1;return}let i=this.object&&typeof this.object.currentMaterial=="function"?this.object.currentMaterial():void 0;if(this.object&&typeof this.object._finalize=="function"&&this.object._finalize(!0),this.object={name:e||"",fromDeclaration:t!==!1,geometry:{vertices:[],normals:[],colors:[],uvs:[],hasUVIndices:!1},materials:[],smooth:!0,startMaterial:function(r,s){let a=this._finalize(!1);a&&(a.inherited||a.groupCount<=0)&&this.materials.splice(a.index,1);let o={index:this.materials.length,name:r||"",mtllib:Array.isArray(s)&&s.length>0?s[s.length-1]:"",smooth:a!==void 0?a.smooth:this.smooth,groupStart:a!==void 0?a.groupEnd:0,groupEnd:-1,groupCount:-1,inherited:!1,clone:function(l){let c={index:typeof l=="number"?l:this.index,name:this.name,mtllib:this.mtllib,smooth:this.smooth,groupStart:0,groupEnd:-1,groupCount:-1,inherited:!1};return c.clone=this.clone.bind(c),c}};return this.materials.push(o),o},currentMaterial:function(){if(this.materials.length>0)return this.materials[this.materials.length-1]},_finalize:function(r){let s=this.currentMaterial();if(s&&s.groupEnd===-1&&(s.groupEnd=this.geometry.vertices.length/3,s.groupCount=s.groupEnd-s.groupStart,s.inherited=!1),r&&this.materials.length>1)for(let a=this.materials.length-1;a>=0;a--)this.materials[a].groupCount<=0&&this.materials.splice(a,1);return r&&this.materials.length===0&&this.materials.push({name:"",smooth:this.smooth}),s}},i&&i.name&&typeof i.clone=="function"){let r=i.clone(0);r.inherited=!0,this.object.materials.push(r)}this.objects.push(this.object)},finalize:function(){this.object&&typeof this.object._finalize=="function"&&this.object._finalize(!0)},parseVertexIndex:function(e,t){let i=parseInt(e,10);return(i>=0?i-1:i+t/3)*3},parseNormalIndex:function(e,t){let i=parseInt(e,10);return(i>=0?i-1:i+t/3)*3},parseUVIndex:function(e,t){let i=parseInt(e,10);return(i>=0?i-1:i+t/2)*2},addVertex:function(e,t,i){let r=this.vertices,s=this.object.geometry.vertices;s.push(r[e+0],r[e+1],r[e+2]),s.push(r[t+0],r[t+1],r[t+2]),s.push(r[i+0],r[i+1],r[i+2])},addVertexPoint:function(e){let t=this.vertices;this.object.geometry.vertices.push(t[e+0],t[e+1],t[e+2])},addVertexLine:function(e){let t=this.vertices;this.object.geometry.vertices.push(t[e+0],t[e+1],t[e+2])},addNormal:function(e,t,i){let r=this.normals,s=this.object.geometry.normals;s.push(r[e+0],r[e+1],r[e+2]),s.push(r[t+0],r[t+1],r[t+2]),s.push(r[i+0],r[i+1],r[i+2])},addFaceNormal:function(e,t,i){let r=this.vertices,s=this.object.geometry.normals;b1.fromArray(r,e),TI.fromArray(r,t),I1.fromArray(r,i),pa.subVectors(I1,TI),M1.subVectors(b1,TI),pa.cross(M1),pa.normalize(),s.push(pa.x,pa.y,pa.z),s.push(pa.x,pa.y,pa.z),s.push(pa.x,pa.y,pa.z)},addColor:function(e,t,i){let r=this.colors,s=this.object.geometry.colors;r[e]!==void 0&&s.push(r[e+0],r[e+1],r[e+2]),r[t]!==void 0&&s.push(r[t+0],r[t+1],r[t+2]),r[i]!==void 0&&s.push(r[i+0],r[i+1],r[i+2])},addUV:function(e,t,i){let r=this.uvs,s=this.object.geometry.uvs;s.push(r[e+0],r[e+1]),s.push(r[t+0],r[t+1]),s.push(r[i+0],r[i+1])},addDefaultUV:function(){let e=this.object.geometry.uvs;e.push(0,0),e.push(0,0),e.push(0,0)},addUVLine:function(e){let t=this.uvs;this.object.geometry.uvs.push(t[e+0],t[e+1])},addFace:function(e,t,i,r,s,a,o,l,c){let f=this.vertices.length,h=this.parseVertexIndex(e,f),d=this.parseVertexIndex(t,f),u=this.parseVertexIndex(i,f);if(this.addVertex(h,d,u),this.addColor(h,d,u),o!==void 0&&o!==""){let m=this.normals.length;h=this.parseNormalIndex(o,m),d=this.parseNormalIndex(l,m),u=this.parseNormalIndex(c,m),this.addNormal(h,d,u)}else this.addFaceNormal(h,d,u);if(r!==void 0&&r!==""){let m=this.uvs.length;h=this.parseUVIndex(r,m),d=this.parseUVIndex(s,m),u=this.parseUVIndex(a,m),this.addUV(h,d,u),this.object.geometry.hasUVIndices=!0}else this.addDefaultUV()},addPointGeometry:function(e){this.object.geometry.type="Points";let t=this.vertices.length;for(let i=0,r=e.length;i{Ys();lie=/^[og]\s*(.+)?/,cie=/^mtllib /,fie=/^usemtl /,hie=/^usemap /,R1=/\s+/,b1=new ne,TI=new ne,I1=new ne,M1=new ne,pa=new ne,yS=new ct;PS=class extends cn{constructor(e){super(e),this.materials=null}load(e,t,i,r){let s=this,a=new ps(this.manager);a.setPath(this.path),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(o){try{t(s.parse(o))}catch(l){r?r(l):console.error(l),s.manager.itemError(e)}},i,r)}setMaterials(e){return this.materials=e,this}parse(e){let t=new die;e.indexOf(`\r +}`,_I=class{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){let i=new e_(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=i}}getMesh(e){if(this.texture!==null&&this.mesh===null){let t=e.cameras[0].viewport,i=new ks({vertexShader:Wte,fragmentShader:Hte,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new ri(new gh(20,20),i)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}},gI=class extends ha{constructor(e,t){super();let i=this,r=null,s=1,a=null,o="local-floor",l=1,c=null,f=null,h=null,d=null,u=null,m=null,p=typeof XRWebGLBinding!="undefined",_=new _I,g={},v=t.getContextAttributes(),x=null,A=null,S=[],E=[],R=new It,I=null,y=new kr;y.viewport=new Qi;let M=new kr;M.viewport=new Qi;let D=[y,M],O=new bE,V=null,N=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(ae){let me=S[ae];return me===void 0&&(me=new uu,S[ae]=me),me.getTargetRaySpace()},this.getControllerGrip=function(ae){let me=S[ae];return me===void 0&&(me=new uu,S[ae]=me),me.getGripSpace()},this.getHand=function(ae){let me=S[ae];return me===void 0&&(me=new uu,S[ae]=me),me.getHandSpace()};function F(ae){let me=E.indexOf(ae.inputSource);if(me===-1)return;let re=S[me];re!==void 0&&(re.update(ae.inputSource,ae.frame,c||a),re.dispatchEvent({type:ae.type,data:ae.inputSource}))}function U(){r.removeEventListener("select",F),r.removeEventListener("selectstart",F),r.removeEventListener("selectend",F),r.removeEventListener("squeeze",F),r.removeEventListener("squeezestart",F),r.removeEventListener("squeezeend",F),r.removeEventListener("end",U),r.removeEventListener("inputsourceschange",G);for(let ae=0;ae=0&&(E[de]=null,S[de].disconnect(re))}for(let me=0;me=E.length){E.push(re),de=he;break}else if(E[he]===null){E[he]=re,de=he;break}if(de===-1)break}let De=S[de];De&&De.connect(re)}}let ee=new ne,j=new ne;function Z(ae,me,re){ee.setFromMatrixPosition(me.matrixWorld),j.setFromMatrixPosition(re.matrixWorld);let de=ee.distanceTo(j),De=me.projectionMatrix.elements,he=re.projectionMatrix.elements,Ie=De[14]/(De[10]-1),ze=De[14]/(De[10]+1),St=(De[9]+1)/De[5],Ye=(De[9]-1)/De[5],je=(De[8]-1)/De[0],$t=(he[8]+1)/he[0],Lt=Ie*je,xi=Ie*$t,oe=de/(-je+$t),Ui=oe*-je;if(me.matrixWorld.decompose(ae.position,ae.quaternion,ae.scale),ae.translateX(Ui),ae.translateZ(oe),ae.matrixWorld.compose(ae.position,ae.quaternion,ae.scale),ae.matrixWorldInverse.copy(ae.matrixWorld).invert(),De[10]===-1)ae.projectionMatrix.copy(me.projectionMatrix),ae.projectionMatrixInverse.copy(me.projectionMatrixInverse);else{let ti=Ie+oe,Ni=ze+oe,ot=Lt-Ui,yi=xi+(de-Ui),z=St*ze/Ni*ti,B=Ye*ze/Ni*ti;ae.projectionMatrix.makePerspective(ot,yi,z,B,ti,Ni),ae.projectionMatrixInverse.copy(ae.projectionMatrix).invert()}}function X(ae,me){me===null?ae.matrixWorld.copy(ae.matrix):ae.matrixWorld.multiplyMatrices(me.matrixWorld,ae.matrix),ae.matrixWorldInverse.copy(ae.matrixWorld).invert()}this.updateCamera=function(ae){if(r===null)return;let me=ae.near,re=ae.far;_.texture!==null&&(_.depthNear>0&&(me=_.depthNear),_.depthFar>0&&(re=_.depthFar)),O.near=M.near=y.near=me,O.far=M.far=y.far=re,(V!==O.near||N!==O.far)&&(r.updateRenderState({depthNear:O.near,depthFar:O.far}),V=O.near,N=O.far),O.layers.mask=ae.layers.mask|6,y.layers.mask=O.layers.mask&-5,M.layers.mask=O.layers.mask&-3;let de=ae.parent,De=O.cameras;X(O,de);for(let he=0;he{function Et(){if(Se.forEach(function(Rt){z.get(Rt).currentProgram.isReady()&&Se.delete(Rt)}),Se.size===0){Te(H);return}setTimeout(Et,10)}ti.get("KHR_parallel_shader_compile")!==null?Et():setTimeout(Et,10)})};let Fa=null;function Tp(H){Fa&&Fa(H)}function Db(){Jf.stop()}function fv(){Jf.start()}let Jf=new h1;Jf.setAnimationLoop(Tp),typeof self!="undefined"&&Jf.setContext(self),this.setAnimationLoop=function(H){Fa=H,Ke.setAnimationLoop(H),H===null?Jf.stop():Jf.start()},Ke.addEventListener("sessionstart",Db),Ke.addEventListener("sessionend",fv),this.render=function(H,fe){if(fe!==void 0&&fe.isCamera!==!0){Bt("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(D===!0)return;O!==null&&O.renderStart(H,fe);let xe=Ke.enabled===!0&&Ke.isPresenting===!0,Se=y!==null&&(F===null||xe)&&y.begin(M,F);if(H.matrixWorldAutoUpdate===!0&&H.updateMatrixWorld(),fe.parent===null&&fe.matrixWorldAutoUpdate===!0&&fe.updateMatrixWorld(),Ke.enabled===!0&&Ke.isPresenting===!0&&(y===null||y.isCompositing()===!1)&&(Ke.cameraAutoUpdate===!0&&Ke.updateCamera(fe),fe=Ke.getCamera()),H.isScene===!0&&H.onBeforeRender(M,H,fe,F),E=ct.get(H,I.length),E.init(fe),E.state.textureUnits=B.getTextureUnits(),I.push(E),St.multiplyMatrices(fe.projectionMatrix,fe.matrixWorldInverse),he.setFromProjectionMatrix(St,Ha,fe.reversedDepth),ze=this.localClippingEnabled,Ie=Tt.init(this.clippingPlanes,ze),S=be.get(H,R.length),S.init(),R.push(S),Ke.enabled===!0&&Ke.isPresenting===!0){let Rt=M.xr.getDepthSensingMesh();Rt!==null&&Lb(Rt,fe,-1/0,M.sortObjects)}Lb(H,fe,0,M.sortObjects),S.finish(),M.sortObjects===!0&&S.sort(ae,me),Lt=Ke.enabled===!1||Ke.isPresenting===!1||Ke.hasDepthSensing()===!1,Lt&&Ze.addToRenderList(S,H),this.info.render.frame++,Ie===!0&&Tt.beginShadows();let Te=E.state.shadowsArray;if(nt.render(Te,H,fe),Ie===!0&&Tt.endShadows(),this.info.autoReset===!0&&this.info.reset(),(Se&&y.hasRenderPass())===!1){let Rt=S.opaque,_t=S.transmissive;if(E.setupLights(),fe.isArrayCamera){let yt=fe.cameras;if(_t.length>0)for(let Dt=0,ci=yt.length;Dt0&&ON(Rt,_t,H,fe),Lt&&Ze.render(H),LN(S,H,fe)}F!==null&&N===0&&(B.updateMultisampleRenderTarget(F),B.updateRenderTargetMipmap(F)),Se&&y.end(M),H.isScene===!0&&H.onAfterRender(M,H,fe),Le.resetDefaultState(),U=-1,G=null,I.pop(),I.length>0?(E=I[I.length-1],B.setTextureUnits(E.state.textureUnits),Ie===!0&&Tt.setGlobalState(M.clippingPlanes,E.state.camera)):E=null,R.pop(),R.length>0?S=R[R.length-1]:S=null,O!==null&&O.renderEnd()};function Lb(H,fe,xe,Se){if(H.visible===!1)return;if(H.layers.test(fe.layers)){if(H.isGroup)xe=H.renderOrder;else if(H.isLOD)H.autoUpdate===!0&&H.update(fe);else if(H.isLightProbeGrid)E.pushLightProbeGrid(H);else if(H.isLight)E.pushLight(H),H.castShadow&&E.pushShadow(H);else if(H.isSprite){if(!H.frustumCulled||he.intersectsSprite(H)){Se&&je.setFromMatrixPosition(H.matrixWorld).applyMatrix4(St);let Rt=$e.update(H),_t=H.material;_t.visible&&S.push(H,Rt,_t,xe,je.z,null)}}else if((H.isMesh||H.isLine||H.isPoints)&&(!H.frustumCulled||he.intersectsObject(H))){let Rt=$e.update(H),_t=H.material;if(Se&&(H.boundingSphere!==void 0?(H.boundingSphere===null&&H.computeBoundingSphere(),je.copy(H.boundingSphere.center)):(Rt.boundingSphere===null&&Rt.computeBoundingSphere(),je.copy(Rt.boundingSphere.center)),je.applyMatrix4(H.matrixWorld).applyMatrix4(St)),Array.isArray(_t)){let yt=Rt.groups;for(let Dt=0,ci=yt.length;Dt0&&hv(Te,fe,xe),Et.length>0&&hv(Et,fe,xe),Rt.length>0&&hv(Rt,fe,xe),ot.buffers.depth.setTest(!0),ot.buffers.depth.setMask(!0),ot.buffers.color.setMask(!0),ot.setPolygonOffset(!1)}function ON(H,fe,xe,Se){if((xe.isScene===!0?xe.overrideMaterial:null)!==null)return;if(E.state.transmissionRenderTarget[Se.id]===void 0){let Ot=ti.has("EXT_color_buffer_half_float")||ti.has("EXT_color_buffer_float");E.state.transmissionRenderTarget[Se.id]=new Gs(1,1,{generateMipmaps:!0,type:Ot?Wo:ps,minFilter:qa,samples:Math.max(4,Ni.samples),stencilBuffer:s,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:oi.workingColorSpace})}let Et=E.state.transmissionRenderTarget[Se.id],Rt=Se.viewport||ee;Et.setSize(Rt.z*M.transmissionResolutionScale,Rt.w*M.transmissionResolutionScale);let _t=M.getRenderTarget(),yt=M.getActiveCubeFace(),Dt=M.getActiveMipmapLevel();M.setRenderTarget(Et),M.getClearColor(X),Y=M.getClearAlpha(),Y<1&&M.setClearColor(16777215,.5),M.clear(),Lt&&Ze.render(xe);let ci=M.toneMapping;M.toneMapping=Ws;let ui=Se.viewport;if(Se.viewport!==void 0&&(Se.viewport=void 0),E.setupLightsView(Se),Ie===!0&&Tt.setGlobalState(M.clippingPlanes,Se),hv(H,xe,Se),B.updateMultisampleRenderTarget(Et),B.updateRenderTargetMipmap(Et),ti.has("WEBGL_multisampled_render_to_texture")===!1){let Ot=!1;for(let qi=0,yr=fe.length;qi0,Se.currentProgram=ui,Se.uniformsList=null,ui}function wN(H){if(H.uniformsList===null){let fe=H.currentProgram.getUniforms();H.uniformsList=Pu.seqWithValue(fe.seq,H.uniforms)}return H.uniformsList}function FN(H,fe){let xe=z.get(H);xe.outputColorSpace=fe.outputColorSpace,xe.batching=fe.batching,xe.batchingColor=fe.batchingColor,xe.instancing=fe.instancing,xe.instancingColor=fe.instancingColor,xe.instancingMorph=fe.instancingMorph,xe.skinning=fe.skinning,xe.morphTargets=fe.morphTargets,xe.morphNormals=fe.morphNormals,xe.morphColors=fe.morphColors,xe.morphTargetsCount=fe.morphTargetsCount,xe.numClippingPlanes=fe.numClippingPlanes,xe.numIntersection=fe.numClipIntersection,xe.vertexAlphas=fe.vertexAlphas,xe.vertexTangents=fe.vertexTangents,xe.toneMapping=fe.toneMapping}function xq(H,fe){if(H.length===0)return null;if(H.length===1)return H[0].texture!==null?H[0]:null;A.setFromMatrixPosition(fe.matrixWorld);for(let xe=0,Se=H.length;xe0),Ot=!!xe.morphAttributes.position,qi=!!xe.morphAttributes.normal,yr=!!xe.morphAttributes.color,br=Ws;Se.toneMapped&&(F===null||F.isXRRenderTarget===!0)&&(br=M.toneMapping);let er=xe.morphAttributes.position||xe.morphAttributes.normal||xe.morphAttributes.color,Rn=er!==void 0?er.length:0,xt=z.get(Se),Os=E.state.lights;if(Ie===!0&&(ze===!0||H!==G)){let ar=H===G&&Se.id===U;Tt.setState(Se,H,ar)}let wi=!1;Se.version===xt.__version?(xt.needsLights&&xt.lightsStateVersion!==Os.state.version||xt.outputColorSpace!==_t||Te.isBatchedMesh&&xt.batching===!1||!Te.isBatchedMesh&&xt.batching===!0||Te.isBatchedMesh&&xt.batchingColor===!0&&Te.colorTexture===null||Te.isBatchedMesh&&xt.batchingColor===!1&&Te.colorTexture!==null||Te.isInstancedMesh&&xt.instancing===!1||!Te.isInstancedMesh&&xt.instancing===!0||Te.isSkinnedMesh&&xt.skinning===!1||!Te.isSkinnedMesh&&xt.skinning===!0||Te.isInstancedMesh&&xt.instancingColor===!0&&Te.instanceColor===null||Te.isInstancedMesh&&xt.instancingColor===!1&&Te.instanceColor!==null||Te.isInstancedMesh&&xt.instancingMorph===!0&&Te.morphTexture===null||Te.isInstancedMesh&&xt.instancingMorph===!1&&Te.morphTexture!==null||xt.envMap!==Dt||Se.fog===!0&&xt.fog!==Et||xt.numClippingPlanes!==void 0&&(xt.numClippingPlanes!==Tt.numPlanes||xt.numIntersection!==Tt.numIntersection)||xt.vertexAlphas!==ci||xt.vertexTangents!==ui||xt.morphTargets!==Ot||xt.morphNormals!==qi||xt.morphColors!==yr||xt.toneMapping!==br||xt.morphTargetsCount!==Rn||!!xt.lightProbeGrid!=E.state.lightProbeGridArray.length>0)&&(wi=!0):(wi=!0,xt.__version=Se.version);let ta=xt.currentProgram;wi===!0&&(ta=dv(Se,fe,Te),O&&Se.isNodeMaterial&&O.onUpdateProgram(Se,ta,xt));let bo=!1,yc=!1,Id=!1,tr=ta.getUniforms(),Pr=xt.uniforms;if(ot.useProgram(ta.program)&&(bo=!0,yc=!0,Id=!0),Se.id!==U&&(U=Se.id,yc=!0),xt.needsLights){let ar=xq(E.state.lightProbeGridArray,Te);xt.lightProbeGrid!==ar&&(xt.lightProbeGrid=ar,yc=!0)}if(bo||G!==H){ot.buffers.depth.getReversed()&&H.reversedDepth!==!0&&(H._reversedDepth=!0,H.updateProjectionMatrix()),tr.setValue(oe,"projectionMatrix",H.projectionMatrix),tr.setValue(oe,"viewMatrix",H.matrixWorldInverse);let Dc=tr.map.cameraPosition;Dc!==void 0&&Dc.setValue(oe,Ye.setFromMatrixPosition(H.matrixWorld)),Ni.logarithmicDepthBuffer&&tr.setValue(oe,"logDepthBufFC",2/(Math.log(H.far+1)/Math.LN2)),(Se.isMeshPhongMaterial||Se.isMeshToonMaterial||Se.isMeshLambertMaterial||Se.isMeshBasicMaterial||Se.isMeshStandardMaterial||Se.isShaderMaterial)&&tr.setValue(oe,"isOrthographic",H.isOrthographicCamera===!0),G!==H&&(G=H,yc=!0,Id=!0)}if(xt.needsLights&&(Os.state.directionalShadowMap.length>0&&tr.setValue(oe,"directionalShadowMap",Os.state.directionalShadowMap,B),Os.state.spotShadowMap.length>0&&tr.setValue(oe,"spotShadowMap",Os.state.spotShadowMap,B),Os.state.pointShadowMap.length>0&&tr.setValue(oe,"pointShadowMap",Os.state.pointShadowMap,B)),Te.isSkinnedMesh){tr.setOptional(oe,Te,"bindMatrix"),tr.setOptional(oe,Te,"bindMatrixInverse");let ar=Te.skeleton;ar&&(ar.boneTexture===null&&ar.computeBoneTexture(),tr.setValue(oe,"boneTexture",ar.boneTexture,B))}Te.isBatchedMesh&&(tr.setOptional(oe,Te,"batchingTexture"),tr.setValue(oe,"batchingTexture",Te._matricesTexture,B),tr.setOptional(oe,Te,"batchingIdTexture"),tr.setValue(oe,"batchingIdTexture",Te._indirectTexture,B),tr.setOptional(oe,Te,"batchingColorTexture"),Te._colorsTexture!==null&&tr.setValue(oe,"batchingColorTexture",Te._colorsTexture,B));let Pc=xe.morphAttributes;if((Pc.position!==void 0||Pc.normal!==void 0||Pc.color!==void 0)&&Wt.update(Te,xe,ta),(yc||xt.receiveShadow!==Te.receiveShadow)&&(xt.receiveShadow=Te.receiveShadow,tr.setValue(oe,"receiveShadow",Te.receiveShadow)),(Se.isMeshStandardMaterial||Se.isMeshLambertMaterial||Se.isMeshPhongMaterial)&&Se.envMap===null&&fe.environment!==null&&(Pr.envMapIntensity.value=fe.environmentIntensity),Pr.dfgLUT!==void 0&&(Pr.dfgLUT.value=jte()),yc){if(tr.setValue(oe,"toneMappingExposure",M.toneMappingExposure),xt.needsLights&&bq(Pr,Id),Et&&Se.fog===!0&&ye.refreshFogUniforms(Pr,Et),ye.refreshMaterialUniforms(Pr,Se,Be,Re,E.state.transmissionRenderTarget[H.id]),xt.needsLights&&xt.lightProbeGrid){let ar=xt.lightProbeGrid;Pr.probesSH.value=ar.texture,Pr.probesMin.value.copy(ar.boundingBox.min),Pr.probesMax.value.copy(ar.boundingBox.max),Pr.probesResolution.value.copy(ar.resolution)}Pu.upload(oe,wN(xt),Pr,B)}if(Se.isShaderMaterial&&Se.uniformsNeedUpdate===!0&&(Pu.upload(oe,wN(xt),Pr,B),Se.uniformsNeedUpdate=!1),Se.isSpriteMaterial&&tr.setValue(oe,"center",Te.center),tr.setValue(oe,"modelViewMatrix",Te.modelViewMatrix),tr.setValue(oe,"normalMatrix",Te.normalMatrix),tr.setValue(oe,"modelMatrix",Te.matrixWorld),Se.uniformsGroups!==void 0){let ar=Se.uniformsGroups;for(let Dc=0,Md=ar.length;Dc0&&B.useMultisampledRTT(H)===!1?Se=z.get(H).__webglMultisampledFramebuffer:Array.isArray(Dt)?Se=Dt[xe]:Se=Dt,ee.copy(H.viewport),j.copy(H.scissor),Z=H.scissorTest}else ee.copy(re).multiplyScalar(Be).floor(),j.copy(de).multiplyScalar(Be).floor(),Z=De;if(xe!==0&&(Se=Mq),ot.bindFramebuffer(oe.FRAMEBUFFER,Se)&&ot.drawBuffers(H,Se),ot.viewport(ee),ot.scissor(j),ot.setScissorTest(Z),Te){let _t=z.get(H.texture);oe.framebufferTexture2D(oe.FRAMEBUFFER,oe.COLOR_ATTACHMENT0,oe.TEXTURE_CUBE_MAP_POSITIVE_X+fe,_t.__webglTexture,xe)}else if(Et){let _t=fe;for(let yt=0;yt1&&oe.readBuffer(oe.COLOR_ATTACHMENT0+_t),!Ni.textureFormatReadable(ci)){Bt("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!Ni.textureTypeReadable(ui)){Bt("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}fe>=0&&fe<=H.width-Se&&xe>=0&&xe<=H.height-Te&&oe.readPixels(fe,xe,Se,Te,Q.convert(ci),Q.convert(ui),Et)}finally{let Dt=F!==null?z.get(F).__webglFramebuffer:null;ot.bindFramebuffer(oe.FRAMEBUFFER,Dt)}}},this.readRenderTargetPixelsAsync=async function(H,fe,xe,Se,Te,Et,Rt,_t=0){if(!(H&&H.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let yt=z.get(H).__webglFramebuffer;if(H.isWebGLCubeRenderTarget&&Rt!==void 0&&(yt=yt[Rt]),yt)if(fe>=0&&fe<=H.width-Se&&xe>=0&&xe<=H.height-Te){ot.bindFramebuffer(oe.FRAMEBUFFER,yt);let Dt=H.textures[_t],ci=Dt.format,ui=Dt.type;if(H.textures.length>1&&oe.readBuffer(oe.COLOR_ATTACHMENT0+_t),!Ni.textureFormatReadable(ci))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!Ni.textureTypeReadable(ui))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");let Ot=oe.createBuffer();oe.bindBuffer(oe.PIXEL_PACK_BUFFER,Ot),oe.bufferData(oe.PIXEL_PACK_BUFFER,Et.byteLength,oe.STREAM_READ),oe.readPixels(fe,xe,Se,Te,Q.convert(ci),Q.convert(ui),0);let qi=F!==null?z.get(F).__webglFramebuffer:null;ot.bindFramebuffer(oe.FRAMEBUFFER,qi);let yr=oe.fenceSync(oe.SYNC_GPU_COMMANDS_COMPLETE,0);return oe.flush(),await BF(oe,yr,4),oe.bindBuffer(oe.PIXEL_PACK_BUFFER,Ot),oe.getBufferSubData(oe.PIXEL_PACK_BUFFER,0,Et),oe.deleteBuffer(Ot),oe.deleteSync(yr),Et}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(H,fe=null,xe=0){let Se=Math.pow(2,-xe),Te=Math.floor(H.image.width*Se),Et=Math.floor(H.image.height*Se),Rt=fe!==null?fe.x:0,_t=fe!==null?fe.y:0;B.setTexture2D(H,0),oe.copyTexSubImage2D(oe.TEXTURE_2D,xe,0,0,Rt,_t,Te,Et),ot.unbindTexture()};let Cq=oe.createFramebuffer(),yq=oe.createFramebuffer();this.copyTextureToTexture=function(H,fe,xe=null,Se=null,Te=0,Et=0){let Rt,_t,yt,Dt,ci,ui,Ot,qi,yr,br=H.isCompressedTexture?H.mipmaps[Et]:H.image;if(xe!==null)Rt=xe.max.x-xe.min.x,_t=xe.max.y-xe.min.y,yt=xe.isBox3?xe.max.z-xe.min.z:1,Dt=xe.min.x,ci=xe.min.y,ui=xe.isBox3?xe.min.z:0;else{let Pr=Math.pow(2,-Te);Rt=Math.floor(br.width*Pr),_t=Math.floor(br.height*Pr),H.isDataArrayTexture?yt=br.depth:H.isData3DTexture?yt=Math.floor(br.depth*Pr):yt=1,Dt=0,ci=0,ui=0}Se!==null?(Ot=Se.x,qi=Se.y,yr=Se.z):(Ot=0,qi=0,yr=0);let er=Q.convert(fe.format),Rn=Q.convert(fe.type),xt;fe.isData3DTexture?(B.setTexture3D(fe,0),xt=oe.TEXTURE_3D):fe.isDataArrayTexture||fe.isCompressedArrayTexture?(B.setTexture2DArray(fe,0),xt=oe.TEXTURE_2D_ARRAY):(B.setTexture2D(fe,0),xt=oe.TEXTURE_2D),ot.activeTexture(oe.TEXTURE0),ot.pixelStorei(oe.UNPACK_FLIP_Y_WEBGL,fe.flipY),ot.pixelStorei(oe.UNPACK_PREMULTIPLY_ALPHA_WEBGL,fe.premultiplyAlpha),ot.pixelStorei(oe.UNPACK_ALIGNMENT,fe.unpackAlignment);let Os=ot.getParameter(oe.UNPACK_ROW_LENGTH),wi=ot.getParameter(oe.UNPACK_IMAGE_HEIGHT),ta=ot.getParameter(oe.UNPACK_SKIP_PIXELS),bo=ot.getParameter(oe.UNPACK_SKIP_ROWS),yc=ot.getParameter(oe.UNPACK_SKIP_IMAGES);ot.pixelStorei(oe.UNPACK_ROW_LENGTH,br.width),ot.pixelStorei(oe.UNPACK_IMAGE_HEIGHT,br.height),ot.pixelStorei(oe.UNPACK_SKIP_PIXELS,Dt),ot.pixelStorei(oe.UNPACK_SKIP_ROWS,ci),ot.pixelStorei(oe.UNPACK_SKIP_IMAGES,ui);let Id=H.isDataArrayTexture||H.isData3DTexture,tr=fe.isDataArrayTexture||fe.isData3DTexture;if(H.isDepthTexture){let Pr=z.get(H),Pc=z.get(fe),ar=z.get(Pr.__renderTarget),Dc=z.get(Pc.__renderTarget);ot.bindFramebuffer(oe.READ_FRAMEBUFFER,ar.__webglFramebuffer),ot.bindFramebuffer(oe.DRAW_FRAMEBUFFER,Dc.__webglFramebuffer);for(let Md=0;Md{Xs();v1={type:"change"},EI={type:"start"},S1={type:"end"},IS=new Oo,E1=new ca,qte=Math.cos(70*T_.DEG2RAD),Jr=new ne,_s=2*Math.PI,$i={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},vI=1e-6,MS=class extends f_{constructor(e,t=null){super(e,t),this.state=$i.NONE,this.target=new ne,this.cursor=new ne,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=.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:jc.ROTATE,MIDDLE:jc.DOLLY,RIGHT:jc.PAN},this.touches={ONE:qc.ROTATE,TWO:qc.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._cursorStyle="auto",this._domElementKeyEvents=null,this._lastPosition=new ne,this._lastQuaternion=new Zr,this._lastTargetPosition=new ne,this._quat=new Zr().setFromUnitVectors(e.up,new ne(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new Tu,this._sphericalDelta=new Tu,this._scale=1,this._panOffset=new ne,this._rotateStart=new It,this._rotateEnd=new It,this._rotateDelta=new It,this._panStart=new It,this._panEnd=new It,this._panDelta=new It,this._dollyStart=new It,this._dollyEnd=new It,this._dollyDelta=new It,this._dollyDirection=new ne,this._mouse=new It,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=Qte.bind(this),this._onPointerDown=Zte.bind(this),this._onPointerUp=$te.bind(this),this._onContextMenu=sie.bind(this),this._onMouseWheel=tie.bind(this),this._onKeyDown=iie.bind(this),this._onTouchStart=rie.bind(this),this._onTouchMove=nie.bind(this),this._onMouseDown=Jte.bind(this),this._onMouseMove=eie.bind(this),this._interceptControlDown=aie.bind(this),this._interceptControlUp=oie.bind(this),this.domElement!==null&&this.connect(this.domElement),this.update()}set cursorStyle(e){this._cursorStyle=e,e==="grab"?this.domElement.style.cursor="grab":this.domElement.style.cursor="auto"}get cursorStyle(){return this._cursorStyle}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.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.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=""}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){this._domElementKeyEvents!==null&&(this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null)}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(v1),this.update(),this.state=$i.NONE}pan(e,t){this._pan(e,t),this.update()}dollyIn(e){this._dollyIn(e),this.update()}dollyOut(e){this._dollyOut(e),this.update()}rotateLeft(e){this._rotateLeft(e),this.update()}rotateUp(e){this._rotateUp(e),this.update()}update(e=null){let t=this.object.position;Jr.copy(t).sub(this.target),Jr.applyQuaternion(this._quat),this._spherical.setFromVector3(Jr),this.autoRotate&&this.state===$i.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,r=this.maxAzimuthAngle;isFinite(i)&&isFinite(r)&&(i<-Math.PI?i+=_s:i>Math.PI&&(i-=_s),r<-Math.PI?r+=_s:r>Math.PI&&(r-=_s),i<=r?this._spherical.theta=Math.max(i,Math.min(r,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(i+r)/2?Math.max(i,this._spherical.theta):Math.min(r,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let s=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{let a=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),s=a!=this._spherical.radius}if(Jr.setFromSpherical(this._spherical),Jr.applyQuaternion(this._quatInverse),t.copy(this.target).add(Jr),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){let o=Jr.length();a=this._clampDistance(o*this._scale);let l=o-a;this.object.position.addScaledVector(this._dollyDirection,l),this.object.updateMatrixWorld(),s=!!l}else if(this.object.isOrthographicCamera){let o=new ne(this._mouse.x,this._mouse.y,0);o.unproject(this.object);let l=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),s=l!==this.object.zoom;let c=new ne(this._mouse.x,this._mouse.y,0);c.unproject(this.object),this.object.position.sub(c).add(o),this.object.updateMatrixWorld(),a=Jr.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):(IS.origin.copy(this.object.position),IS.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(IS.direction))vI||8*(1-this._lastQuaternion.dot(this.object.quaternion))>vI||this._lastTargetPosition.distanceToSquared(this.target)>vI?(this.dispatchEvent(v1),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?_s/60*this.autoRotateSpeed*e:_s/60/60*this.autoRotateSpeed}_getZoomScale(e){let t=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){Jr.setFromMatrixColumn(t,0),Jr.multiplyScalar(-e),this._panOffset.add(Jr)}_panUp(e,t){this.screenSpacePanning===!0?Jr.setFromMatrixColumn(t,1):(Jr.setFromMatrixColumn(t,0),Jr.crossVectors(this.object.up,Jr)),Jr.multiplyScalar(e),this._panOffset.add(Jr)}_pan(e,t){let i=this.domElement;if(this.object.isPerspectiveCamera){let r=this.object.position;Jr.copy(r).sub(this.target);let s=Jr.length();s*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*s/i.clientHeight,this.object.matrix),this._panUp(2*t*s/i.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/i.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/i.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;let i=this.domElement.getBoundingClientRect(),r=e-i.left,s=t-i.top,a=i.width,o=i.height;this._mouse.x=r/a*2-1,this._mouse.y=-(s/o)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_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);let t=this.domElement;this._rotateLeft(_s*this._rotateDelta.x/t.clientHeight),this._rotateUp(_s*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(_s*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(-_s*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(_s*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(-_s*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{let t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),r=.5*(e.pageY+t.y);this._rotateStart.set(i,r)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{let t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),r=.5*(e.pageY+t.y);this._panStart.set(i,r)}}_handleTouchStartDolly(e){let t=this._getSecondPointerPosition(e),i=e.pageX-t.x,r=e.pageY-t.y,s=Math.sqrt(i*i+r*r);this._dollyStart.set(0,s)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{let i=this._getSecondPointerPosition(e),r=.5*(e.pageX+i.x),s=.5*(e.pageY+i.y);this._rotateEnd.set(r,s)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);let t=this.domElement;this._rotateLeft(_s*this._rotateDelta.x/t.clientHeight),this._rotateUp(_s*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{let t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),r=.5*(e.pageY+t.y);this._panEnd.set(i,r)}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){let t=this._getSecondPointerPosition(e),i=e.pageX-t.x,r=e.pageY-t.y,s=Math.sqrt(i*i+r*r);this._dollyEnd.set(0,s),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);let a=(e.pageX+t.x)*.5,o=(e.pageY+t.y)*.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)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t{Xs();CS=class extends mh{constructor(){super(),this.name="RoomEnvironment",this.position.y=-3.5;let e=new Xc;e.deleteAttribute("uv");let t=new Cn({side:pn}),i=new Cn,r=new Ka(16777215,900,28,2);r.position.set(.418,16.199,.3),this.add(r);let s=new ri(e,t);s.position.set(-.757,13.219,.717),s.scale.set(31.713,28.305,28.591),this.add(s);let a=new _h(e,i,6),o=new ir;o.position.set(-10.906,2.009,1.846),o.rotation.set(0,-.195,0),o.scale.set(2.328,7.905,4.651),o.updateMatrix(),a.setMatrixAt(0,o.matrix),o.position.set(-5.607,-.754,-.758),o.rotation.set(0,.994,0),o.scale.set(1.97,1.534,3.955),o.updateMatrix(),a.setMatrixAt(1,o.matrix),o.position.set(6.167,.857,7.803),o.rotation.set(0,.561,0),o.scale.set(3.927,6.285,3.687),o.updateMatrix(),a.setMatrixAt(2,o.matrix),o.position.set(-2.017,.018,6.124),o.rotation.set(0,.333,0),o.scale.set(2.002,4.566,2.064),o.updateMatrix(),a.setMatrixAt(3,o.matrix),o.position.set(2.291,-.756,-2.621),o.rotation.set(0,-.286,0),o.scale.set(1.546,1.552,1.496),o.updateMatrix(),a.setMatrixAt(4,o.matrix),o.position.set(-2.193,-.369,-5.547),o.rotation.set(0,.516,0),o.scale.set(3.875,3.487,2.986),o.updateMatrix(),a.setMatrixAt(5,o.matrix),this.add(a);let l=new ri(e,Ou(50));l.position.set(-16.116,14.37,8.208),l.scale.set(.1,2.428,2.739),this.add(l);let c=new ri(e,Ou(50));c.position.set(-16.109,18.021,-8.207),c.scale.set(.1,2.425,2.751),this.add(c);let f=new ri(e,Ou(17));f.position.set(14.904,12.198,-1.832),f.scale.set(.15,4.265,6.331),this.add(f);let h=new ri(e,Ou(43));h.position.set(-.462,8.89,14.52),h.scale.set(4.38,5.441,.088),this.add(h);let d=new ri(e,Ou(20));d.position.set(3.235,11.486,-12.541),d.scale.set(2.5,2,.1),this.add(d);let u=new ri(e,Ou(100));u.position.set(0,20,0),u.scale.set(1,.1,1),this.add(u)}dispose(){let e=new Set;this.traverse(t=>{t.isMesh&&(e.add(t.geometry),e.add(t.material))});for(let t of e)t.dispose()}}});var yS,SI,x1=C(()=>{Xs();yS=class extends cn{constructor(e){super(e)}load(e,t,i,r){let s=this,a=this.path===""?ja.extractUrlBase(e):this.path,o=new ms(this.manager);o.setPath(this.path),o.setRequestHeader(this.requestHeader),o.setWithCredentials(this.withCredentials),o.load(e,function(l){try{t(s.parse(l,a))}catch(c){r?r(c):console.error(c),s.manager.itemError(e)}},i,r)}setMaterialOptions(e){return this.materialOptions=e,this}parse(e,t){let i=e.split(` +`),r={},s=/\s+/,a={};for(let l=0;l=0?c.substring(0,f):c;h=h.toLowerCase();let d=f>=0?c.substring(f+1):"";if(d=d.trim(),h==="newmtl")r={name:d},a[d]=r;else if(h==="ka"||h==="kd"||h==="ks"||h==="ke"){let u=d.split(s,3);r[h]=[parseFloat(u[0]),parseFloat(u[1]),parseFloat(u[2])]}else r[h]=d}let o=new SI(this.resourcePath||t,this.materialOptions);return o.setCrossOrigin(this.crossOrigin),o.setManager(this.manager),o.setMaterials(a),o}},SI=class{constructor(e="",t={}){this.baseUrl=e,this.options=t,this.materialsInfo={},this.materials={},this.materialsArray=[],this.nameLookup={},this.crossOrigin="anonymous",this.side=this.options.side!==void 0?this.options.side:Vs,this.wrap=this.options.wrap!==void 0?this.options.wrap:Do}setCrossOrigin(e){return this.crossOrigin=e,this}setManager(e){this.manager=e}setMaterials(e){this.materialsInfo=this.convert(e),this.materials={},this.materialsArray=[],this.nameLookup={}}convert(e){if(!this.options)return e;let t={};for(let i in e){let r=e[i],s={};t[i]=s;for(let a in r){let o=!0,l=r[a],c=a.toLowerCase();switch(c){case"kd":case"ka":case"ks":this.options&&this.options.normalizeRGB&&(l=[l[0]/255,l[1]/255,l[2]/255]),this.options&&this.options.ignoreZeroRGBs&&l[0]===0&&l[1]===0&&l[2]===0&&(o=!1);break;default:break}o&&(s[c]=l)}}return t}preload(){for(let e in this.materialsInfo)this.create(e)}getIndex(e){return this.nameLookup[e]}getAsArray(){let e=0;for(let t in this.materialsInfo)this.materialsArray[e]=this.create(t),this.nameLookup[t]=e,e++;return this.materialsArray}create(e){return this.materials[e]===void 0&&this.createMaterial_(e),this.materials[e]}createMaterial_(e){let t=this,i=this.materialsInfo[e],r={name:e,side:this.side};function s(o,l){return typeof l!="string"||l===""?"":/^https?:\/\//i.test(l)?l:o+l}function a(o,l){if(r[o])return;let c=t.getTextureParams(l,r),f=t.loadTexture(s(t.baseUrl,c.url));f.repeat.copy(c.scale),f.offset.copy(c.offset),f.wrapS=t.wrap,f.wrapT=t.wrap,(o==="map"||o==="emissiveMap")&&(f.colorSpace=Fi),r[o]=f}for(let o in i){let l=i[o],c;if(l!=="")switch(o.toLowerCase()){case"kd":r.color=oi.colorSpaceToWorking(new ft().fromArray(l),Fi);break;case"ks":r.specular=oi.colorSpaceToWorking(new ft().fromArray(l),Fi);break;case"ke":r.emissive=oi.colorSpaceToWorking(new ft().fromArray(l),Fi);break;case"map_kd":a("map",l);break;case"map_ks":a("specularMap",l);break;case"map_ke":a("emissiveMap",l);break;case"norm":a("normalMap",l);break;case"map_bump":case"bump":a("bumpMap",l);break;case"disp":a("displacementMap",l);break;case"map_d":a("alphaMap",l),r.transparent=!0;break;case"ns":r.shininess=parseFloat(l);break;case"d":c=parseFloat(l),c<1&&(r.opacity=c,r.transparent=!0);break;case"tr":c=parseFloat(l),this.options&&this.options.invertTrProperty&&(c=1-c),c>0&&(r.opacity=1-c,r.transparent=!0);break;default:break}}return this.materials[e]=new vh(r),this.materials[e]}getTextureParams(e,t){let i={scale:new It(1,1),offset:new It(0,0)},r=e.split(/\s+/),s;return s=r.indexOf("-bm"),s>=0&&(t.bumpScale=parseFloat(r[s+1]),r.splice(s,2)),s=r.indexOf("-mm"),s>=0&&(t.displacementBias=parseFloat(r[s+1]),t.displacementScale=parseFloat(r[s+2]),r.splice(s,3)),s=r.indexOf("-s"),s>=0&&(i.scale.set(parseFloat(r[s+1]),parseFloat(r[s+2])),r.splice(s,4)),s=r.indexOf("-o"),s>=0&&(i.offset.set(parseFloat(r[s+1]),parseFloat(r[s+2])),r.splice(s,4)),i.url=r.join(" ").trim(),i}loadTexture(e,t,i,r,s){let a=this.manager!==void 0?this.manager:ES,o=a.getHandler(e);o===null&&(o=new Sh(a)),o.setCrossOrigin&&o.setCrossOrigin(this.crossOrigin);let l=o.load(e,i,r,s);return t!==void 0&&(l.mapping=t),l}}});function die(){let n={objects:[],object:{},vertices:[],normals:[],colors:[],uvs:[],materials:{},materialLibraries:[],startObject:function(e,t){if(this.object&&this.object.fromDeclaration===!1){this.object.name=e,this.object.fromDeclaration=t!==!1;return}let i=this.object&&typeof this.object.currentMaterial=="function"?this.object.currentMaterial():void 0;if(this.object&&typeof this.object._finalize=="function"&&this.object._finalize(!0),this.object={name:e||"",fromDeclaration:t!==!1,geometry:{vertices:[],normals:[],colors:[],uvs:[],hasUVIndices:!1},materials:[],smooth:!0,startMaterial:function(r,s){let a=this._finalize(!1);a&&(a.inherited||a.groupCount<=0)&&this.materials.splice(a.index,1);let o={index:this.materials.length,name:r||"",mtllib:Array.isArray(s)&&s.length>0?s[s.length-1]:"",smooth:a!==void 0?a.smooth:this.smooth,groupStart:a!==void 0?a.groupEnd:0,groupEnd:-1,groupCount:-1,inherited:!1,clone:function(l){let c={index:typeof l=="number"?l:this.index,name:this.name,mtllib:this.mtllib,smooth:this.smooth,groupStart:0,groupEnd:-1,groupCount:-1,inherited:!1};return c.clone=this.clone.bind(c),c}};return this.materials.push(o),o},currentMaterial:function(){if(this.materials.length>0)return this.materials[this.materials.length-1]},_finalize:function(r){let s=this.currentMaterial();if(s&&s.groupEnd===-1&&(s.groupEnd=this.geometry.vertices.length/3,s.groupCount=s.groupEnd-s.groupStart,s.inherited=!1),r&&this.materials.length>1)for(let a=this.materials.length-1;a>=0;a--)this.materials[a].groupCount<=0&&this.materials.splice(a,1);return r&&this.materials.length===0&&this.materials.push({name:"",smooth:this.smooth}),s}},i&&i.name&&typeof i.clone=="function"){let r=i.clone(0);r.inherited=!0,this.object.materials.push(r)}this.objects.push(this.object)},finalize:function(){this.object&&typeof this.object._finalize=="function"&&this.object._finalize(!0)},parseVertexIndex:function(e,t){let i=parseInt(e,10);return(i>=0?i-1:i+t/3)*3},parseNormalIndex:function(e,t){let i=parseInt(e,10);return(i>=0?i-1:i+t/3)*3},parseUVIndex:function(e,t){let i=parseInt(e,10);return(i>=0?i-1:i+t/2)*2},addVertex:function(e,t,i){let r=this.vertices,s=this.object.geometry.vertices;s.push(r[e+0],r[e+1],r[e+2]),s.push(r[t+0],r[t+1],r[t+2]),s.push(r[i+0],r[i+1],r[i+2])},addVertexPoint:function(e){let t=this.vertices;this.object.geometry.vertices.push(t[e+0],t[e+1],t[e+2])},addVertexLine:function(e){let t=this.vertices;this.object.geometry.vertices.push(t[e+0],t[e+1],t[e+2])},addNormal:function(e,t,i){let r=this.normals,s=this.object.geometry.normals;s.push(r[e+0],r[e+1],r[e+2]),s.push(r[t+0],r[t+1],r[t+2]),s.push(r[i+0],r[i+1],r[i+2])},addFaceNormal:function(e,t,i){let r=this.vertices,s=this.object.geometry.normals;b1.fromArray(r,e),TI.fromArray(r,t),I1.fromArray(r,i),ma.subVectors(I1,TI),M1.subVectors(b1,TI),ma.cross(M1),ma.normalize(),s.push(ma.x,ma.y,ma.z),s.push(ma.x,ma.y,ma.z),s.push(ma.x,ma.y,ma.z)},addColor:function(e,t,i){let r=this.colors,s=this.object.geometry.colors;r[e]!==void 0&&s.push(r[e+0],r[e+1],r[e+2]),r[t]!==void 0&&s.push(r[t+0],r[t+1],r[t+2]),r[i]!==void 0&&s.push(r[i+0],r[i+1],r[i+2])},addUV:function(e,t,i){let r=this.uvs,s=this.object.geometry.uvs;s.push(r[e+0],r[e+1]),s.push(r[t+0],r[t+1]),s.push(r[i+0],r[i+1])},addDefaultUV:function(){let e=this.object.geometry.uvs;e.push(0,0),e.push(0,0),e.push(0,0)},addUVLine:function(e){let t=this.uvs;this.object.geometry.uvs.push(t[e+0],t[e+1])},addFace:function(e,t,i,r,s,a,o,l,c){let f=this.vertices.length,h=this.parseVertexIndex(e,f),d=this.parseVertexIndex(t,f),u=this.parseVertexIndex(i,f);if(this.addVertex(h,d,u),this.addColor(h,d,u),o!==void 0&&o!==""){let m=this.normals.length;h=this.parseNormalIndex(o,m),d=this.parseNormalIndex(l,m),u=this.parseNormalIndex(c,m),this.addNormal(h,d,u)}else this.addFaceNormal(h,d,u);if(r!==void 0&&r!==""){let m=this.uvs.length;h=this.parseUVIndex(r,m),d=this.parseUVIndex(s,m),u=this.parseUVIndex(a,m),this.addUV(h,d,u),this.object.geometry.hasUVIndices=!0}else this.addDefaultUV()},addPointGeometry:function(e){this.object.geometry.type="Points";let t=this.vertices.length;for(let i=0,r=e.length;i{Xs();lie=/^[og]\s*(.+)?/,cie=/^mtllib /,fie=/^usemtl /,hie=/^usemap /,R1=/\s+/,b1=new ne,TI=new ne,I1=new ne,M1=new ne,ma=new ne,PS=new ft;DS=class extends cn{constructor(e){super(e),this.materials=null}load(e,t,i,r){let s=this,a=new ms(this.manager);a.setPath(this.path),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(o){try{t(s.parse(o))}catch(l){r?r(l):console.error(l),s.manager.itemError(e)}},i,r)}setMaterials(e){return this.materials=e,this}parse(e){let t=new die;e.indexOf(`\r `)!==-1&&(e=e.replace(/\r\n/g,` `)),e.indexOf(`\\ `)!==-1&&(e=e.replace(/\\\n/g,""));let i=e.split(` -`),r=[];for(let o=0,l=i.length;o=7?(yS.setRGB(parseFloat(h[4]),parseFloat(h[5]),parseFloat(h[6]),Ni),t.colors.push(yS.r,yS.g,yS.b)):t.colors.push(void 0,void 0,void 0);break;case"vn":t.normals.push(parseFloat(h[1]),parseFloat(h[2]),parseFloat(h[3]));break;case"vt":t.uvs.push(parseFloat(h[1]),parseFloat(h[2]));break}}else if(f==="f"){let d=c.slice(1).trim().split(R1),u=[];for(let p=0,_=d.length;p<_;p++){let g=d[p];if(g.length>0){let v=g.split("/");u.push(v)}}let m=u[0];for(let p=1,_=u.length-1;p<_;p++){let g=u[p],v=u[p+1];t.addFace(m[0],g[0],v[0],m[1],g[1],v[1],m[2],g[2],v[2])}}else if(f==="l"){let h=c.substring(1).trim().split(" "),d=[],u=[];if(c.indexOf("/")===-1)d=h;else for(let m=0,p=h.length;m1){let d=r[1].trim().toLowerCase();t.object.smooth=d!=="0"&&d!=="off"}else t.object.smooth=!0;let h=t.object.currentMaterial();h&&(h.smooth=t.object.smooth)}else{if(c==="\0")continue;console.warn('THREE.OBJLoader: Unexpected line: "'+c+'"')}}t.finalize();let s=new Vs;if(s.materialLibraries=[].concat(t.materialLibraries),!(t.objects.length===1&&t.objects[0].geometry.vertices.length===0)===!0)for(let o=0,l=t.objects.length;o0&&p.setAttribute("normal",new ci(f.normals,3)),f.colors.length>0&&(m=!0,p.setAttribute("color",new ci(f.colors,3))),f.hasUVIndices===!0&&p.setAttribute("uv",new ci(f.uvs,2));let _=[];for(let v=0,x=h.length;v1){for(let v=0,x=h.length;v0){let o=new ds({size:1,sizeAttenuation:!1}),l=new Ui;l.setAttribute("position",new ci(t.vertices,3)),t.colors.length>0&&t.colors[0]!==void 0&&(l.setAttribute("color",new ci(t.colors,3)),o.vertexColors=!0);let c=new ua(l,o);s.add(c)}return s}}});var vs,DS,AI,y1=C(()=>{Ys();vs=new ct,DS=class extends cn{constructor(e){super(e),this.propertyNameMapping={},this.customPropertyMapping={}}load(e,t,i,r){let s=this,a=new ps(this.manager);a.setPath(this.path),a.setResponseType("arraybuffer"),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(o){try{t(s.parse(o))}catch(l){r?r(l):console.error(l),s.manager.itemError(e)}},i,r)}setPropertyNameMapping(e){this.propertyNameMapping=e}setCustomPropertyNameMapping(e){this.customPropertyMapping=e}parse(e){function t(_,g=0){let v=/^ply([\s\S]*)end_header(\r\n|\r|\n)/,x="",A=v.exec(_);A!==null&&(x=A[1]);let S={comments:[],elements:[],headerLength:g,objInfo:""},E=x.split(/\r\n|\r|\n/),R;function I(y,M){let D={type:y[0]};return D.type==="list"?(D.name=y[3],D.countType=y[1],D.itemType=y[2]):D.name=y[1],D.name in M&&(D.name=M[D.name]),D}for(let y=0;yx.name);function v(x){for(let A=0,S=x.length;A0&&g.setIndex(_.indices),g.setAttribute("position",new ci(_.vertices,3)),_.normals.length>0&&g.setAttribute("normal",new ci(_.normals,3)),_.uvs.length>0&&g.setAttribute("uv",new ci(_.uvs,2)),_.colors.length>0&&g.setAttribute("color",new ci(_.colors,3)),(_.faceVertexUvs.length>0||_.faceVertexColors.length>0)&&(g=g.toNonIndexed(),_.faceVertexUvs.length>0&&g.setAttribute("uv",new ci(_.faceVertexUvs,2)),_.faceVertexColors.length>0&&g.setAttribute("color",new ci(_.faceVertexColors,3)));for(let v of Object.keys(p.customPropertyMapping))_[v].length>0&&g.setAttribute(v,new ci(_[v],p.customPropertyMapping[v].length));return g.computeBoundingSphere(),g}function c(_,g,v,x){if(g==="vertex"){_.vertices.push(v[x.attrX],v[x.attrY],v[x.attrZ]),x.attrNX!==null&&x.attrNY!==null&&x.attrNZ!==null&&_.normals.push(v[x.attrNX],v[x.attrNY],v[x.attrNZ]),x.attrS!==null&&x.attrT!==null&&_.uvs.push(v[x.attrS],v[x.attrT]),x.attrR!==null&&x.attrG!==null&&x.attrB!==null&&(vs.setRGB(v[x.attrR]/255,v[x.attrG]/255,v[x.attrB]/255,Ni),_.colors.push(vs.r,vs.g,vs.b));for(let A of Object.keys(p.customPropertyMapping))for(let S of p.customPropertyMapping[A])_[A].push(v[S])}else if(g==="face"){let A=v.vertex_indices||v.vertex_index,S=v.texcoord;A.length===3?(_.indices.push(A[0],A[1],A[2]),S&&S.length===6&&(_.faceVertexUvs.push(S[0],S[1]),_.faceVertexUvs.push(S[2],S[3]),_.faceVertexUvs.push(S[4],S[5]))):A.length===4&&(_.indices.push(A[0],A[1],A[3]),_.indices.push(A[1],A[2],A[3])),x.attrR!==null&&x.attrG!==null&&x.attrB!==null&&(vs.setRGB(v[x.attrR]/255,v[x.attrG]/255,v[x.attrB]/255,Ni),_.faceVertexColors.push(vs.r,vs.g,vs.b),_.faceVertexColors.push(vs.r,vs.g,vs.b),_.faceVertexColors.push(vs.r,vs.g,vs.b))}}function f(_,g){let v={},x=0;for(let A=0;AA.getInt8(R),size:1};case"uint8":case"uchar":return{read:R=>A.getUint8(R),size:1};case"int16":case"short":return{read:R=>A.getInt16(R,E),size:2};case"uint16":case"ushort":return{read:R=>A.getUint16(R,E),size:2};case"int32":case"int":return{read:R=>A.getInt32(R,E),size:4};case"uint32":case"uint":return{read:R=>A.getUint32(R,E),size:4};case"float32":case"float":return{read:R=>A.getFloat32(R,E),size:4};case"float64":case"double":return{read:R=>A.getFloat64(R,E),size:8}}}for(let A=0,S=_.length;A=this.arr.length}next(){return this.arr[this.i++]}}});var LS,P1=C(()=>{Ys();LS=class extends cn{constructor(e){super(e)}load(e,t,i,r){let s=this,a=new ps(this.manager);a.setPath(this.path),a.setResponseType("arraybuffer"),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(o){try{t(s.parse(o))}catch(l){r?r(l):console.error(l),s.manager.itemError(e)}},i,r)}parse(e){function t(c){let f=new DataView(c),h=32/8*3+32/8*3*3+16/8,d=f.getUint32(80,!0);if(80+32/8+d*h===f.byteLength)return!0;let m=[115,111,108,105,100];for(let p=0;p<5;p++)if(i(m,f,p))return!1;return!0}function i(c,f,h){for(let d=0,u=c.length;d>5&31)/31,m=(U>>10&31)/31):(d=g,u=v,m=x)}for(let U=1;U<=3;U++){let k=O+U*12,ee=D*3*3+(U-1)*3;I[ee]=f.getFloat32(k,!0),I[ee+1]=f.getFloat32(k+4,!0),I[ee+2]=f.getFloat32(k+8,!0),y[ee]=V,y[ee+1]=N,y[ee+2]=F,p&&(M.setRGB(d,u,m,Ni),_[ee]=M.r,_[ee+1]=M.g,_[ee+2]=M.b)}}return R.setAttribute("position",new or(I,3)),R.setAttribute("normal",new or(y,3)),p&&(R.setAttribute("color",new or(_,3)),R.hasColors=!0,R.alpha=A),R}function s(c){let f=new Ui,h=/solid([\s\S]*?)endsolid/g,d=/facet([\s\S]*?)endfacet/g,u=/solid\s(.+)/,m=0,p=/[\s]+([+-]?(?:\d*)(?:\.\d*)?(?:[eE][+-]?\d+)?)/.source,_=new RegExp("vertex"+p+p+p,"g"),g=new RegExp("normal"+p+p+p,"g"),v=[],x=[],A=[],S=new ne,E,R=0,I=0,y=0;for(;(E=h.exec(c))!==null;){I=y;let M=E[0],D=(E=u.exec(M))!==null?E[1]:"";for(A.push(D);(E=d.exec(M))!==null;){let N=0,F=0,U=E[0];for(;(E=g.exec(U))!==null;)S.x=parseFloat(E[1]),S.y=parseFloat(E[2]),S.z=parseFloat(E[3]),F++;for(;(E=_.exec(U))!==null;)v.push(parseFloat(E[1]),parseFloat(E[2]),parseFloat(E[3])),x.push(S.x,S.y,S.z),N++,y++;F!==1&&console.error("THREE.STLLoader: Something isn't right with the normal of face number "+m),N!==3&&console.error("THREE.STLLoader: Something isn't right with the vertices of face number "+m),m++}let O=I,V=y-I;f.userData.groupNames=A,f.addGroup(O,V,R),R++}return f.setAttribute("position",new ci(v,3)),f.setAttribute("normal",new ci(x,3)),f}function a(c){return typeof c!="string"?new TextDecoder().decode(c):c}function o(c){if(typeof c=="string"){let f=new Uint8Array(c.length);for(let h=0;h{Ys()});function L1(n){let e=new Map,t=new Map,i=n.clone();return O1(n,i,function(r,s){e.set(s,r),t.set(r,s)}),i.traverse(function(r){if(!r.isSkinnedMesh)return;let s=r,a=e.get(r),o=a.skeleton.bones;s.skeleton=a.skeleton.clone(),s.bindMatrix.copy(a.bindMatrix),s.skeleton.bones=o.map(function(l){return t.get(l)}),s.bind(s.skeleton,s.bindMatrix)}),i}function O1(n,e,t){t(n,e);for(let i=0;i{});function uie(){let n={};return{get:function(e){return n[e]},add:function(e,t){n[e]=t},remove:function(e){delete n[e]},removeAll:function(){n={}}}}function Nr(n,e,t){let i=n.json.materials[e];return i.extensions&&i.extensions[t]?i.extensions[t]:null}function _ie(n){return n.DefaultMaterial===void 0&&(n.DefaultMaterial=new Cn({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:Gs})),n.DefaultMaterial}function bh(n,e,t){for(let i in t.extensions)n[i]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[i]=t.extensions[i])}function Xo(n,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(n.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function gie(n,e,t){let i=!1,r=!1,s=!1;for(let c=0,f=e.length;c0||n.search(/^data\:image\/jpeg/)===0?"image/jpeg":n.search(/\.webp($|\?)/i)>0||n.search(/^data\:image\/webp/)===0?"image/webp":n.search(/\.ktx2($|\?)/i)>0||n.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}function Aie(n,e,t){let i=e.attributes,r=new Sr;if(i.POSITION!==void 0){let o=t.json.accessors[i.POSITION],l=o.min,c=o.max;if(l!==void 0&&c!==void 0){if(r.set(new ne(l[0],l[1],l[2]),new ne(c[0],c[1],c[2])),o.normalized){let f=ZI(wu[o.componentType]);r.min.multiplyScalar(f),r.max.multiplyScalar(f)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;let s=e.targets;if(s!==void 0){let o=new ne,l=new ne;for(let c=0,f=s.length;c{Ys();D1();N1();OS=class extends cn{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new PI(t)}),this.register(function(t){return new DI(t)}),this.register(function(t){return new GI(t)}),this.register(function(t){return new kI(t)}),this.register(function(t){return new WI(t)}),this.register(function(t){return new OI(t)}),this.register(function(t){return new NI(t)}),this.register(function(t){return new wI(t)}),this.register(function(t){return new FI(t)}),this.register(function(t){return new yI(t)}),this.register(function(t){return new BI(t)}),this.register(function(t){return new LI(t)}),this.register(function(t){return new VI(t)}),this.register(function(t){return new UI(t)}),this.register(function(t){return new MI(t)}),this.register(function(t){return new NS(t,Ei.EXT_MESHOPT_COMPRESSION)}),this.register(function(t){return new NS(t,Ei.KHR_MESHOPT_COMPRESSION)}),this.register(function(t){return new HI(t)})}load(e,t,i,r){let s=this,a;if(this.resourcePath!=="")a=this.resourcePath;else if(this.path!==""){let c=ja.extractUrlBase(e);a=ja.resolveURL(c,this.path)}else a=ja.extractUrlBase(e);this.manager.itemStart(e);let o=function(c){r?r(c):console.error(c),s.manager.itemError(e),s.manager.itemEnd(e)},l=new ps(this.manager);l.setPath(this.path),l.setResponseType("arraybuffer"),l.setRequestHeader(this.requestHeader),l.setWithCredentials(this.withCredentials),l.load(e,function(c){try{s.parse(c,a,function(f){t(f),s.manager.itemEnd(e)},o)}catch(f){o(f)}},i,o)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,i,r){let s,a={},o={},l=new TextDecoder;if(typeof e=="string")s=JSON.parse(e);else if(e instanceof ArrayBuffer)if(l.decode(new Uint8Array(e,0,4))===V1){try{a[Ei.KHR_BINARY_GLTF]=new zI(e)}catch(h){r&&r(h);return}s=JSON.parse(a[Ei.KHR_BINARY_GLTF].content)}else s=JSON.parse(l.decode(e));else s=e;if(s.asset===void 0||s.asset.version[0]<2){r&&r(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}let c=new QI(s,{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 f=0;f=0&&o[h]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+h+'".')}}c.setExtensions(a),c.setPlugins(o),c.parse(i,r)}parseAsync(e,t){let i=this;return new Promise(function(r,s){i.parse(e,t,r,s)})}};Ei={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",KHR_MESHOPT_COMPRESSION:"KHR_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"},MI=class{constructor(e){this.parser=e,this.name=Ei.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){let e=this.parser,t=this.parser.json.nodes||[];for(let i=0,r=t.length;i=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,s.source,a)}},kI=class{constructor(e){this.parser=e,this.name=Ei.EXT_TEXTURE_WEBP}loadTexture(e){let t=this.name,i=this.parser,r=i.json,s=r.textures[e];if(!s.extensions||!s.extensions[t])return null;let a=s.extensions[t],o=r.images[a.source],l=i.textureLoader;if(o.uri){let c=i.options.manager.getHandler(o.uri);c!==null&&(l=c)}return i.loadTextureImage(e,a.source,l)}},WI=class{constructor(e){this.parser=e,this.name=Ei.EXT_TEXTURE_AVIF}loadTexture(e){let t=this.name,i=this.parser,r=i.json,s=r.textures[e];if(!s.extensions||!s.extensions[t])return null;let a=s.extensions[t],o=r.images[a.source],l=i.textureLoader;if(o.uri){let c=i.options.manager.getHandler(o.uri);c!==null&&(l=c)}return i.loadTextureImage(e,a.source,l)}},NS=class{constructor(e,t){this.name=t,this.parser=e}loadBufferView(e){let t=this.parser.json,i=t.bufferViews[e];if(i.extensions&&i.extensions[this.name]){let r=i.extensions[this.name],s=this.parser.getDependency("buffer",r.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 s.then(function(o){let l=r.byteOffset||0,c=r.byteLength||0,f=r.count,h=r.byteStride,d=new Uint8Array(o,l,c);return a.decodeGltfBufferAsync?a.decodeGltfBufferAsync(f,h,d,r.mode,r.filter).then(function(u){return u.buffer}):a.ready.then(function(){let u=new ArrayBuffer(f*h);return a.decodeGltfBuffer(new Uint8Array(u),f,h,d,r.mode,r.filter),u})})}else return null}},HI=class{constructor(e){this.name=Ei.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){let t=this.parser.json,i=t.nodes[e];if(!i.extensions||!i.extensions[this.name]||i.mesh===void 0)return null;let r=t.meshes[i.mesh];for(let c of r.primitives)if(c.mode!==_a.TRIANGLES&&c.mode!==_a.TRIANGLE_STRIP&&c.mode!==_a.TRIANGLE_FAN&&c.mode!==void 0)return null;let a=i.extensions[this.name].attributes,o=[],l={};for(let c in a)o.push(this.parser.getDependency("accessor",a[c]).then(f=>(l[c]=f,l[c])));return o.length<1?null:(o.push(this.parser.createNodeMesh(e)),Promise.all(o).then(c=>{let f=c.pop(),h=f.isGroup?f.children:[f],d=c[0].count,u=[];for(let m of h){let p=new oi,_=new ne,g=new Zr,v=new ne(1,1,1),x=new _h(m.geometry,m.material,d);for(let A=0;A-1,a=s?o.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap=="undefined"||i&&r<17||s&&a<98?this.textureLoader=new Sh(this.options.manager):this.textureLoader=new o_(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new ps(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){let i=this,r=this.json,s=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){let o={scene:a[0][r.scene||0],scenes:a[0],animations:a[1],cameras:a[2],asset:r.asset,parser:i,userData:{}};return bh(s,o,r),Xo(o,r),Promise.all(i._invokeAll(function(l){return l.afterRoot&&l.afterRoot(o)})).then(function(){for(let l of o.scenes)l.updateMatrixWorld();e(o)})}).catch(t)}_markDefs(){let e=this.json.nodes||[],t=this.json.skins||[],i=this.json.meshes||[];for(let r=0,s=t.length;r{let l=this.associations.get(a);l!=null&&this.associations.set(o,l);for(let[c,f]of a.children.entries())s(f,o.children[c])};return s(i,r),r.name+="_instance_"+e.uses[t]++,r}_invokeOne(e){let t=Object.values(this.plugins);t.push(this);for(let i=0;i=2&&_.setY(y,E[R*l+1]),l>=3&&_.setZ(y,E[R*l+2]),l>=4&&_.setW(y,E[R*l+3]),l>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}_.normalized=m}return _})}loadTexture(e){let t=this.json,i=this.options,s=t.textures[e].source,a=t.images[s],o=this.textureLoader;if(a.uri){let l=i.manager.getHandler(a.uri);l!==null&&(o=l)}return this.loadTextureImage(e,s,o)}loadTextureImage(e,t,i){let r=this,s=this.json,a=s.textures[e],o=s.images[t],l=(o.uri||o.bufferView)+":"+a.sampler;if(this.textureCache[l])return this.textureCache[l];let c=this.loadImageSource(t,i).then(function(f){f.flipY=!1,f.name=a.name||o.name||"",f.name===""&&typeof o.uri=="string"&&o.uri.startsWith("data:image/")===!1&&(f.name=o.uri);let d=(s.samplers||{})[a.sampler]||{};return f.magFilter=F1[d.magFilter]||Lr,f.minFilter=F1[d.minFilter]||qa,f.wrapS=B1[d.wrapS]||Do,f.wrapT=B1[d.wrapT]||Do,f.generateMipmaps=!f.isCompressedTexture&&f.minFilter!==Dr&&f.minFilter!==Lr,r.associations.set(f,{textures:e}),f}).catch(function(){return null});return this.textureCache[l]=c,c}loadImageSource(e,t){let i=this,r=this.json,s=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(h=>h.clone());let a=r.images[e],o=self.URL||self.webkitURL,l=a.uri||"",c=!1;if(a.bufferView!==void 0)l=i.getDependency("bufferView",a.bufferView).then(function(h){c=!0;let d=new Blob([h],{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");let f=Promise.resolve(l).then(function(h){return new Promise(function(d,u){let m=d;t.isImageBitmapLoader===!0&&(m=function(p){let _=new Ar(p);_.needsUpdate=!0,d(_)}),t.load(ja.resolveURL(h,s.path),m,void 0,u)})}).then(function(h){return c===!0&&o.revokeObjectURL(l),Xo(h,a),h.userData.mimeType=a.mimeType||Sie(a.uri),h}).catch(function(h){throw console.error("THREE.GLTFLoader: Couldn't load texture",l),h});return this.sourceCache[e]=f,f}assignTexture(e,t,i,r){let s=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),s.extensions[Ei.KHR_TEXTURE_TRANSFORM]){let o=i.extensions!==void 0?i.extensions[Ei.KHR_TEXTURE_TRANSFORM]:void 0;if(o){let l=s.associations.get(a);a=s.extensions[Ei.KHR_TEXTURE_TRANSFORM].extendTexture(a,o),s.associations.set(a,l)}}return r!==void 0&&(a.colorSpace=r),e[t]=a,a})}assignFinalMaterial(e){let t=e.geometry,i=e.material,r=t.attributes.tangent===void 0,s=t.attributes.color!==void 0,a=t.attributes.normal===void 0;if(e.isPoints){let o="PointsMaterial:"+i.uuid,l=this.cache.get(o);l||(l=new ds,Or.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){let o="LineBasicMaterial:"+i.uuid,l=this.cache.get(o);l||(l=new Mn,Or.prototype.copy.call(l,i),l.color.copy(i.color),l.map=i.map,this.cache.add(o,l)),i=l}if(r||s||a){let o="ClonedMaterial:"+i.uuid+":";r&&(o+="derivative-tangents:"),s&&(o+="vertex-colors:"),a&&(o+="flat-shading:");let l=this.cache.get(o);l||(l=i.clone(),s&&(l.vertexColors=!0),a&&(l.flatShading=!0),r&&(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 Cn}loadMaterial(e){let t=this,i=this.json,r=this.extensions,s=i.materials[e],a,o={},l=s.extensions||{},c=[];if(l[Ei.KHR_MATERIALS_UNLIT]){let h=r[Ei.KHR_MATERIALS_UNLIT];a=h.getMaterialType(),c.push(h.extendParams(o,s,t))}else{let h=s.pbrMetallicRoughness||{};if(o.color=new ct(1,1,1),o.opacity=1,Array.isArray(h.baseColorFactor)){let d=h.baseColorFactor;o.color.setRGB(d[0],d[1],d[2],jn),o.opacity=d[3]}h.baseColorTexture!==void 0&&c.push(t.assignTexture(o,"map",h.baseColorTexture,Ni)),o.metalness=h.metallicFactor!==void 0?h.metallicFactor:1,o.roughness=h.roughnessFactor!==void 0?h.roughnessFactor:1,h.metallicRoughnessTexture!==void 0&&(c.push(t.assignTexture(o,"metalnessMap",h.metallicRoughnessTexture)),c.push(t.assignTexture(o,"roughnessMap",h.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)})))}s.doubleSided===!0&&(o.side=ma);let f=s.alphaMode||bI.OPAQUE;if(f===bI.BLEND?(o.transparent=!0,o.depthWrite=!1):(o.transparent=!1,f===bI.MASK&&(o.alphaTest=s.alphaCutoff!==void 0?s.alphaCutoff:.5)),s.normalTexture!==void 0&&a!==qn&&(c.push(t.assignTexture(o,"normalMap",s.normalTexture)),o.normalScale=new bt(1,1),s.normalTexture.scale!==void 0)){let h=s.normalTexture.scale;o.normalScale.set(h,h)}if(s.occlusionTexture!==void 0&&a!==qn&&(c.push(t.assignTexture(o,"aoMap",s.occlusionTexture)),s.occlusionTexture.strength!==void 0&&(o.aoMapIntensity=s.occlusionTexture.strength)),s.emissiveFactor!==void 0&&a!==qn){let h=s.emissiveFactor;o.emissive=new ct().setRGB(h[0],h[1],h[2],jn)}return s.emissiveTexture!==void 0&&a!==qn&&c.push(t.assignTexture(o,"emissiveMap",s.emissiveTexture,Ni)),Promise.all(c).then(function(){let h=new a(o);return s.name&&(h.name=s.name),Xo(h,s),t.associations.set(h,{materials:e}),s.extensions&&bh(r,h,s),h})}createUniqueName(e){let t=qi.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){let t=this,i=this.extensions,r=this.primitiveCache;function s(o){return i[Ei.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(o,t).then(function(l){return U1(l,o,t)})}let a=[];for(let o=0,l=e.length;o0&&vie(g,s),g.name=t.createUniqueName(s.name||"mesh_"+e),Xo(g,s),_.extensions&&bh(r,g,_),t.assignFinalMaterial(g),h.push(g)}for(let u=0,m=h.length;u0){let u=f.userData.pivot,m=h[0];f.pivot=new ne().fromArray(u),f.position.x-=u[0],f.position.y-=u[1],f.position.z-=u[2],m.position.set(0,0,0),delete f.userData.pivot}return f})}_loadNodeShallow(e){let t=this.json,i=this.extensions,r=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];let s=t.nodes[e],a=s.name?r.createUniqueName(s.name):"",o=[],l=r._invokeOne(function(c){return c.createNodeMesh&&c.createNodeMesh(e)});return l&&o.push(l),s.camera!==void 0&&o.push(r.getDependency("camera",s.camera).then(function(c){return r._getNodeRef(r.cameraCache,s.camera,c)})),r._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 f;if(s.isBone===!0?f=new _u:c.length>1?f=new Vs:c.length===1?f=c[0]:f=new er,f!==c[0])for(let h=0,d=c.length;h1){let h=r.associations.get(f);r.associations.set(f,{...h})}return r.associations.get(f).nodes=e,f}),this.nodeCache[e]}loadScene(e){let t=this.extensions,i=this.json.scenes[e],r=this,s=new Vs;i.name&&(s.name=r.createUniqueName(i.name)),Xo(s,i),i.extensions&&bh(t,s,i);let a=i.nodes||[],o=[];for(let l=0,c=a.length;l{let h=new Map;for(let[d,u]of r.associations)(d instanceof Or||d instanceof Ar)&&h.set(d,u);return f.traverse(d=>{let u=r.associations.get(d);u!=null&&h.set(d,u)}),h};return r.associations=c(s),s})}_createAnimationTracks(e,t,i,r,s){let a=[],o=e.name?e.name:e.uuid,l=[];function c(u){u.morphTargetInfluences&&l.push(u.name?u.name:u.uuid)}tf[s.path]===tf.weights?(c(e),e.isGroup&&e.children.forEach(c)):l.push(o);let f;switch(tf[s.path]){case tf.weights:f=Fo;break;case tf.rotation:f=Bo;break;case tf.translation:case tf.scale:f=Uo;break;default:i.itemSize===1?f=Fo:f=Uo;break}let h=r.interpolation!==void 0?pie[r.interpolation]:dh,d=this._getArrayFromAccessor(i);for(let u=0,m=l.length;u{"use strict"});function H1(n){var t,i,r;let e=(i=(t=n.split(".").pop())==null?void 0:t.toLowerCase())!=null?i:"png";return(r=xie[e])!=null?r:`image/${e}`}function bie(n){let e=n.replace(/\s+#.*$/,"").trim();if(e.startsWith('"')){let t=e.indexOf('"',1);if(t>1)return e.slice(1,t)}return e}function Iie(n){let e=n.trim().split(/\s+/),t=e.findIndex(i=>!i.startsWith("-")&&!/^[-+]?\d*\.?\d+$/.test(i));return e.slice(Math.max(0,t)).join(" ").replace(/^"|"$/g,"")}async function W1(n,e,t){let i=ws(e,t);try{return{data:await n(i),path:i}}catch(r){throw new Error(`Missing external model resource: ${i}`)}}function Mie(n,e,t){let i=oa(e),r=i.replace(/\.[^.]+$/,""),s=jr(t),a=[ws(n,e),ws(n,i)];if(s)for(let o of k1)a.push(ws(n,`${s}.${o}`));for(let o of k1){let l=`${r}.${o}`;l!==i&&a.push(ws(n,l))}return a}async function z1(n,e,t,i){var l,c;let r=new OS,s=[];if(e==="gltf"&&t&&i){let f=new TextDecoder().decode(new Uint8Array(n)),h=JSON.parse(f),d=Ip(i);if(h.buffers){for(let g of h.buffers)if(g.uri&&!g.uri.startsWith("data:")){let v=await W1(t,d,g.uri);g.uri=`data:application/octet-stream;base64,${Nl(v.data)}`}}if(h.images){for(let g of h.images)if(g.uri&&!g.uri.startsWith("data:")){let v=await W1(t,d,g.uri);g.uri=`data:${H1(v.path)};base64,${Nl(v.data)}`}}let u=JSON.stringify(h),m=new TextEncoder().encode(u),p=await r.parseAsync(m.buffer,d?`${d}/`:""),_=p.scene||((l=p.scenes)==null?void 0:l[0]);if(!_)throw new Error("GLTF did not contain a scene");return{scene:_,animations:p.animations,warnings:s}}let a=await r.parseAsync(n.slice(0),""),o=a.scene||((c=a.scenes)==null?void 0:c[0]);if(!o)throw new Error("GLB did not contain a scene");return{scene:o,animations:a.animations,warnings:s}}async function X1(n){let t=new LS().parse(n),i=new Cn({color:13421772}),r=new ii(t,i);return r.name=oa("")||"stl-model",r}async function Y1(n){let t=new DS().parse(n);if(t.hasAttribute("color")){if(t.index){let s=new Cn({vertexColors:!0});return new ii(t,s)}let r=new ds({size:.02,vertexColors:!0});return new ua(t,r)}if(t.index){let r=new Cn({color:13421772});return new ii(t,r)}let i=new ds({size:.02,color:13421772});return new ua(t,i)}async function K1(n,e,t){let i=new TextDecoder().decode(new Uint8Array(n)),r=[],s=null,a=i.match(/mtllib\s+(.+)/);if(a&&e&&t){let l=bie(a[1]),c=Ip(t),f=ws(c,l);try{let h=await e(f),u=new TextDecoder().decode(new Uint8Array(h)).split(` -`),m=new Map;for(let x=0;xx!=="");if(!p.some(x=>/^\s*Kd\s+/i.test(x))){let x=p.findIndex(A=>/^\s*newmtl\s+/i.test(A));p.splice(x>=0?x+1:0,0,"Kd 0.80 0.80 0.80")}let v=new CS().parse(p.join(` -`),c?`${c}/`:"");v.preload(),s=v}catch(h){r.push(`OBJ material library not found: ${f}`)}}else a&&(!e||!t)&&r.push("OBJ material library could not be resolved without a model path.");let o=new PS;return s&&o.setMaterials(s),{object:o.parse(i),warnings:r}}var xie,k1,Rie,j1=C(()=>{"use strict";x1();C1();y1();P1();G1();Ys();la();FS();xie={jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",bmp:"image/bmp",tga:"image/x-tga",webp:"image/webp",tif:"image/tiff",tiff:"image/tiff"},k1=["jpg","jpeg","png","bmp","tga","webp","tif","tiff"],Rie=/^\s*(map_Kd|map_Ka|map_Ks|map_Ns|map_d|map_bump|bump|disp|decal)\s+(.+)/i});function ur(){return q1.Platform.isMobile}var q1,Ks=C(()=>{"use strict";q1=require("obsidian")});function I_(n,e){return{min:qr(n),max:qr(e)}}function Z1(n,e){return n?{min:{x:Math.min(n.min.x,e.min.x),y:Math.min(n.min.y,e.min.y),z:Math.min(n.min.z,e.min.z)},max:{x:Math.max(n.max.x,e.max.x),y:Math.max(n.max.y,e.max.y),z:Math.max(n.max.z,e.max.z)}}:I_(e.min,e.max)}function Wr(n){return Ud(n.max,n.min)}function fn(n){return th(n.min,Mp(Wr(n),.5))}function Q1(n){return nw(n.min,n.max)}function M_(n){return Q1(n)/2}function $1(n){let e=Wr(n);return Math.max(e.x,e.y,e.z)}function $I(n){let e=Wr(n),t=Q1(n);return{center:th(n.min,Mp(e,.5)),size:e,diagonalLength:t,radius:t/2,maxSpan:Math.max(e.x,e.y,e.z)}}var rf=C(()=>{"use strict";Fs()});function JI(n,e,t={}){var s,a,o,l,c;let i=Math.max(e,Number.EPSILON),r=(s=t.radiusMultiplier)!=null?s:2.5;return{target:qr(n),radius:i*r,lowerRadiusLimit:i*((a=t.lowerRadiusFactor)!=null?a:.05),upperRadiusLimit:i*((o=t.upperRadiusFactor)!=null?o:10),near:i*((l=t.nearFactor)!=null?l:.001),far:i*((c=t.farFactor)!=null?c:20)}}function BS(n,e={}){let t=$I(n);return JI(t.center,t.radius,e)}function J1(n,e={}){var r,s,a,o,l,c;let t=$I(n),i=Math.max(t.maxSpan,1)*((r=e.distanceMultiplier)!=null?r:1.8);return{target:qr(t.center),position:th(t.center,{x:i,y:i*((s=e.elevationFactor)!=null?s:.65),z:i}),near:Math.max((a=e.minNear)!=null?a:.01,t.maxSpan/((o=e.nearDivisor)!=null?o:100)),far:Math.max((l=e.minFar)!=null?l:100,t.maxSpan*((c=e.farMultiplier)!=null?c:20))}}var US=C(()=>{"use strict";rf();Fs()});function lr(n){return n.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}var VS=C(()=>{"use strict"});function GS(n){var s;let e=new Set,t=0,i=0;for(let a of n.meshes){t+=a.triangleCount,i+=a.vertexCount;for(let o of(s=a.materialKeys)!=null?s:[])o!=null&&e.add(o)}let r=Cie({triangleCount:t,splatCount:n.splatCount,meshCount:n.meshes.length,materialCount:e.size});return{meshCount:n.meshes.length,triangleCount:t,splatCount:n.splatCount,vertexCount:i,materialCount:e.size,performanceTier:r,performanceHint:yie(r,{triangleCount:t,splatCount:n.splatCount,materialCount:e.size}),resourceWarnings:n.resourceWarnings?[...n.resourceWarnings]:void 0,boundingSize:qr(n.boundingSize),rootName:n.rootName}}function Cie(n){var e,t,i;return((e=n.splatCount)!=null?e:0)>=15e5||n.triangleCount>=12e5||n.materialCount>=96||n.meshCount>=240?"extreme":((t=n.splatCount)!=null?t:0)>=65e4||n.triangleCount>=45e4||n.materialCount>=48||n.meshCount>=120?"heavy":((i=n.splatCount)!=null?i:0)>=18e4||n.triangleCount>=12e4||n.materialCount>=18||n.meshCount>=48?"medium":"light"}function yie(n,e){var r;let t=((r=e.splatCount)!=null?r:e.triangleCount).toLocaleString(),i=e.splatCount!==void 0?"splats":"triangles";return n==="extreme"?`${t} ${i}, ${e.materialCount.toLocaleString()} materials. Expect automatic quality throttling while interacting.`:n==="heavy"?`${t} ${i}, ${e.materialCount.toLocaleString()} materials. Interaction may lower shadows and resolution temporarily.`:n==="medium"?`${t} ${i}, ${e.materialCount.toLocaleString()} materials. Performance should be steady on most desktop GPUs.`:`${t} ${i}, ${e.materialCount.toLocaleString()} materials. Performance tier: light.`}function Ih(n){var e;return{name:n.name,triangleCount:n.triangleCount,vertexCount:n.vertexCount,materialName:(e=n.materialName)!=null?e:null,boundingSize:qr(n.boundingSize),center:qr(n.center),source:n.source,meshNames:n.meshNames?[...n.meshNames]:void 0,childCount:n.childCount,componentId:n.componentId,occurrenceId:n.occurrenceId,partNumber:n.partNumber,componentPath:n.componentPath}}function e3(n){return n.splatCount!==void 0?"Splats":"Triangles"}function t3(n){var e;return(e=n.splatCount)!=null?e:n.triangleCount}var C_=C(()=>{"use strict";Fs()});function Fu(n,e="-"){if(typeof n!="string")return e;let t=n.trim();return t.length>0?t:e}function i3(n,e={}){var r,s;let t=(r=e.countLabel)!=null?r:e3(n),i=(s=e.decimals)!=null?s:3;return[`| Meshes | ${n.meshCount} |`,`| ${t} | ${t3(n).toLocaleString()} |`,`| Vertices | ${n.vertexCount.toLocaleString()} |`,`| Materials | ${n.materialCount} |`,...n.performanceTier?[`| Performance Tier | ${n.performanceTier} |`]:[],`| Bounding Size | ${eM(n.boundingSize,{decimals:i})} |`]}function kS(n){return lr(n).replace(/\|/g,"\\|").replace(/\r?\n/g," ")}function eM(n,e={}){var r,s;let t=(r=e.decimals)!=null?r:3,i=(s=e.separator)!=null?s:" x ";return`${n.x.toFixed(t)}${i}${n.y.toFixed(t)}${i}${n.z.toFixed(t)}`}function r3(n,e={}){return["| Metric | Value |","|--------|-------|",...i3(n,e)]}function Pie(n,e,t={}){return["| Property | Value |","|----------|-------|",`| Format | ${n} |`,...i3(e,t)]}function WS(n){var r,s;let e=[];e.push(`## ${n.title} - Model Info`),e.push(""),e.push(...Pie(n.format,n.summary,{countLabel:n.countLabel})),e.push("");let t=(r=n.meshBreakdown)!=null?r:[];t.length>1&&t.length<=50&&(e.push("### Mesh Breakdown"),e.push(""),e.push("| # | Name | Triangles | Vertices | Material |"),e.push("|---|------|-----------|----------|----------|"),t.forEach((a,o)=>{let l=a.triangleCount===null?"-":a.triangleCount.toLocaleString();e.push(`| ${o+1} | ${kS(Fu(a.name,`mesh-${o+1}`))} | ${l} | ${a.vertexCount.toLocaleString()} | ${kS(Fu(a.materialName))} |`)}),e.push(""));let i=Array.from((s=n.materialNames)!=null?s:[]).map(a=>Fu(a,"")).filter(a=>a.length>0);if(i.length>0){let a=Array.from(new Set(i));e.push("### Materials"),e.push("");for(let o of a)e.push(`- ${lr(o)}`);e.push("")}return e.join(` -`)}function HS(n,e={}){var r;let t=lr(Fu((r=e.title)!=null?r:n.name,"Selected Part")),i=[];return i.push(`## ${t} - Part Info`),i.push(""),i.push("| Property | Value |"),i.push("|----------|-------|"),i.push(`| Mesh | ${kS(Fu(n.name))} |`),i.push(`| Triangles | ${n.triangleCount.toLocaleString()} |`),i.push(`| Vertices | ${n.vertexCount.toLocaleString()} |`),i.push(`| Material | ${kS(Fu(n.materialName))} |`),i.push(`| Bounding Size | ${eM(n.boundingSize)} |`),i.push(`| Center | ${eM(n.center,{separator:", "})} |`),i.push(""),i.join(` -`)}var zS=C(()=>{"use strict";VS();C_()});function Bie(n){return!!n&&typeof n=="object"&&!Array.isArray(n)}function XS(n){return n.toLowerCase().replace(/[^a-z0-9]+/g,"")}function Uie(n){if(typeof n=="string"){let e=n.trim();return e.length>0?e:void 0}if(typeof n=="number"&&Number.isFinite(n))return String(n)}function n3(n,e=0){if(!Bie(n)||e>2)return[];let t=[];for(let i of Fie)for(let[r,s]of Object.entries(n))XS(r)===XS(i)&&t.push(...n3(s,e+1));return t.push(n),t}function y_(n,e){let t=new Set(e.map(XS));for(let i of n)for(let[r,s]of Object.entries(i)){if(!t.has(XS(r)))continue;let a=Uie(s);if(a)return a}}function nf(n,e={}){var c,f;let t=n3(n),i=y_(t,Die),r=y_(t,Lie),s=y_(t,Oie),a=(c=y_(t,wie))!=null?c:e.path,o=(f=y_(t,Nie))!=null?f:e.name;return{componentId:i,occurrenceId:r,partNumber:s,componentPath:a,displayName:o,hasExplicitIdentity:!!(i||r||s)}}var Die,Lie,Oie,Nie,wie,Fie,tM=C(()=>{"use strict";Die=["ai3dPartId","partId","componentId","componentIdentifier","cadId","persistentId","externalId","id"],Lie=["ai3dOccurrenceId","occurrenceId","instanceId","occurrencePath","assemblyPath","pathId"],Oie=["ai3dPartNumber","partNumber","partNo","partNum","swPartNumber","solidworksPartNumber","part_number"],Nie=["displayName","partName","componentName","cadName","name"],wie=["componentPath","cadPath","assemblyPath","occurrencePath"],Fie=["ai3d","cad","solidworks","sw","metadata","properties","extras","gltf","userData"]});function KS(n){return new iM(n)}var YS,iM,rM=C(()=>{"use strict";YS=class YS{constructor(e){this.originals=new Map;this.unsubscribe=null;this.active=!1;this.drag=null;this.pendingDrag=null;this.selected=null;this.activePointerId=null;this.frameCount=0;this.adapter=e;for(let t of e.getParts())this.originals.set(e.getPartId(t),e.captureTransform(t))}isEnabled(){return this.active}setEnabled(e){var t,i,r;return this.active===e?this.active:(this.active=e,this.finishDrag(),this.setSelected(null),this.activePointerId=null,e?this.unsubscribe=this.adapter.subscribe({onPointerDown:(s,a)=>this.handlePointerDown(s,a),onPointerMove:s=>this.handlePointerMove(s),onPointerUp:s=>this.handlePointerUp(s),onRender:()=>this.handleRender()}):((t=this.unsubscribe)==null||t.call(this),this.unsubscribe=null),(r=(i=this.adapter).requestRender)==null||r.call(i),this.active)}toggle(){return this.setEnabled(!this.active)}reset(){var e,t;this.finishDrag(),this.setSelected(null);for(let i of this.adapter.getParts()){if(this.adapter.isDisposed(i))continue;let r=this.originals.get(this.adapter.getPartId(i));r&&this.adapter.restoreTransform(i,r)}this.activePointerId=null,(t=(e=this.adapter).requestRender)==null||t.call(e)}dispose(){this.setEnabled(!1),this.originals.clear()}handlePointerDown(e,t){if(t.button!==0||t.isPrimary===!1)return;let i=this.adapter.resolvePart(e);if(!i){this.drag=null,this.pendingDrag=null,this.activePointerId=null,this.setSelected(null);return}this.activePointerId=t.pointerId,this.setSelected(i),this.pendingDrag={part:i,event:t,x:t.clientX,y:t.clientY}}handlePointerMove(e){if(!(this.activePointerId!==null&&e.pointerId!==this.activePointerId)){if(!this.drag&&this.pendingDrag){if(e.pointerType==="mouse"&&(e.buttons&1)===0){this.pendingDrag=null,this.activePointerId=null;return}if(Math.hypot(e.clientX-this.pendingDrag.x,e.clientY-this.pendingDrag.y){"use strict";Ys();Fs();rM();s3=new ct(4890367),Vie=new ct(1722990),nM=class{constructor(e,t,i,r,s,a){this.raycaster=new jc;this.pointer=new bt;this.tempBox=new Sr;this.tempCenter=new ne;this.tempDirection=new ne;this.tempCameraForward=new ne;this.tempCameraRight=new ne;this.tempCameraUp=new ne;this.selectionHelper=null;this.lastOccluded=!1;this.selected=null;this.lastPointerDown=null;this.partPointerActive=!1;this.activePointerId=null;this.scene=e,this.camera=t,this.canvas=i,this.meshes=r,this.controls=s,this.invalidate=a}requestRender(){this.invalidate()}getParts(){return this.meshes}getPartId(e){return e.id}isDisposed(e){return!e.parent&&!this.meshes.includes(e)}captureTransform(e){return{parent:e.parent,position:e.position.clone(),quaternion:e.quaternion.clone(),scale:e.scale.clone()}}restoreTransform(e,t){t.parent&&t.parent.add(e),e.position.copy(t.position),e.quaternion.copy(t.quaternion),e.scale.copy(t.scale),e.updateMatrixWorld(!0),this.requestRender()}subscribe(e){this.canvas.classList.add("ai3d-disassembly-active");let t=s=>{var o,l;if(s.button!==0||s.isPrimary===!1)return;this.lastPointerDown={x:s.clientX,y:s.clientY};let a=this.resolvePickTarget(s);if(this.partPointerActive=!!a,this.partPointerActive){s.preventDefault(),s.stopPropagation(),this.controls.enabled=!1,this.activePointerId=s.pointerId;try{(l=(o=this.canvas).setPointerCapture)==null||l.call(o,s.pointerId)}catch(c){}}e.onPointerDown(a,s)},i=s=>{this.activePointerId!==null&&s.pointerId!==this.activePointerId||(this.partPointerActive&&(s.preventDefault(),s.stopPropagation()),e.onPointerMove(s))},r=s=>{var a,o;if(!(this.activePointerId!==null&&s.pointerId!==this.activePointerId)){if(this.partPointerActive&&(s.preventDefault(),s.stopPropagation()),this.lastPointerDown=null,e.onPointerUp(s),this.partPointerActive=!1,this.activePointerId!==null&&((o=(a=this.canvas).hasPointerCapture)!=null&&o.call(a,this.activePointerId)))try{this.canvas.releasePointerCapture(this.activePointerId)}catch(l){}this.activePointerId=null,this.controls.enabled=!0}};return this.canvas.addEventListener("pointerdown",t),window.addEventListener("pointermove",i),window.addEventListener("pointerup",r),()=>{var s,a;if(this.canvas.removeEventListener("pointerdown",t),window.removeEventListener("pointermove",i),window.removeEventListener("pointerup",r),this.canvas.classList.remove("ai3d-disassembly-active","ai3d-disassembly-dragging"),this.partPointerActive=!1,this.activePointerId!==null&&((a=(s=this.canvas).hasPointerCapture)!=null&&a.call(s,this.activePointerId)))try{this.canvas.releasePointerCapture(this.activePointerId)}catch(o){}this.activePointerId=null,this.controls.enabled=!0}}resolvePart(e){return e&&this.isMeshInSet(e)?e:null}setSelected(e){var t;(t=this.selectionHelper)==null||t.removeFromParent(),this.selectionHelper=null,this.selected=e,this.lastOccluded=!1,e&&!this.isDisposed(e)&&(this.selectionHelper=new Ll(e,s3),this.scene.add(this.selectionHelper)),this.requestRender()}beginDrag(e,t){let i=this.getPointOnDragPlane(e,t);if(!i)return null;t.preventDefault(),t.stopPropagation(),e.removeFromParent(),this.scene.add(e),this.canvas.classList.add("ai3d-disassembly-dragging");let r="move";t.shiftKey&&(r="rotate");let s=this.tempBox.setFromObject(e).getCenter(this.tempCenter).clone(),a=this.tempCameraForward;this.camera.getWorldDirection(a);let o=Vd(Ht(i),Ht(a));return o?(this.controls.enabled=!1,this.requestRender(),{mesh:e,mode:r,plane:o,startPoint:i.clone(),startPosition:e.position.clone(),startQuaternion:e.quaternion.clone(),pivot:s,pointerX:t.clientX,pointerY:t.clientY}):null}updateDrag(e,t){var s;if(t.preventDefault(),t.stopPropagation(),e.mode==="rotate"){this.updateRotation(e,t);return}let i=this.getRayPlanePoint(t,e.plane);if(!i)return;let r=i.clone().sub(e.startPoint);e.mesh.position.copy(e.startPosition).add(r),e.mesh.updateMatrixWorld(!0),(s=this.selectionHelper)==null||s.update(),this.requestRender()}endDrag(e){this.controls.enabled=!0,this.canvas.classList.remove("ai3d-disassembly-dragging"),this.requestRender()}updateSelectionOcclusion(e){let i=this.tempBox.setFromObject(e).getCenter(this.tempCenter),r=this.camera.position,s=wc(Ht(r),Ht(i));if(!s)return;let a=this.tempDirection.set(s.direction.x,s.direction.y,s.direction.z);this.raycaster.set(r,a),this.raycaster.far=s.distance;let o=this.raycaster.intersectObjects(this.meshes,!1)[0],l=!!o&&Nc(o.distance,s.distance,s.epsilon);l!==this.lastOccluded&&(this.lastOccluded=l,this.selectionHelper&&(this.selectionHelper.material.color.set(l?Vie:s3),this.requestRender()))}isMeshInSet(e){return this.meshes.includes(e)}updateRotation(e,t){var c;let i=t.clientX-e.pointerX,r=t.clientY-e.pointerY,s=this.tempCameraForward;this.camera.getWorldDirection(s);let a=this.tempCameraUp.copy(this.camera.up).normalize(),o=this.tempCameraRight.crossVectors(a,s).normalize(),l=gv({startPosition:Ht(e.startPosition),pivot:Ht(e.pivot),startRotationQuaternion:_v(e.startQuaternion),yawAxis:Ht(a),pitchAxis:Ht(o),deltaX:i,deltaY:r,sensitivity:.01});l&&(e.mesh.position.set(l.position.x,l.position.y,l.position.z),e.mesh.quaternion.set(l.rotationQuaternion.x,l.rotationQuaternion.y,l.rotationQuaternion.z,l.rotationQuaternion.w),e.mesh.updateMatrixWorld(!0),(c=this.selectionHelper)==null||c.update(),this.requestRender())}resolvePickTarget(e){let t=this.canvas.getBoundingClientRect();this.pointer.x=(e.clientX-t.left)/t.width*2-1,this.pointer.y=-((e.clientY-t.top)/t.height)*2+1,this.raycaster.setFromCamera(this.pointer,this.camera);let i=this.raycaster.intersectObjects(this.meshes,!1)[0];return(i==null?void 0:i.object)instanceof ii?i.object:null}getPointOnDragPlane(e,t){var o;let r=this.tempBox.setFromObject(e).getCenter(this.tempCenter),s=this.tempCameraForward;this.camera.getWorldDirection(s);let a=Vd(Ht(r),Ht(s));return a&&(o=this.getRayPlanePoint(t,a))!=null?o:r}getRayPlanePoint(e,t){let i=this.canvas.getBoundingClientRect(),r=e.clientX-i.left,s=e.clientY-i.top;this.pointer.set(r/i.width*2-1,-(s/i.height)*2+1),this.raycaster.setFromCamera(this.pointer,this.camera);let a=pv({origin:Ht(this.raycaster.ray.origin),direction:Ht(this.raycaster.ray.direction)},t);return a?new ne(a.x,a.y,a.z):null}}});function l3(n){return qr(n)}function Gie(n,e){return{originalPosition:l3(n),originalCenter:l3(e)}}function jS(n,e,t){let i=n.getRootCenter();for(let r of n.getParts()){let s=n.getPartState(r);s||(s=Gie(n.getPartPosition(r),n.getPartCenter(r)),n.setPartState(r,s));let a=(s.originalCenter[t]-i[t])*e;n.setPartPosition(r,sw(s.originalPosition,t,a))}}function qS(n){for(let e of n.getParts()){let t=n.getPartState(e);t&&n.setPartPosition(e,t.originalPosition)}}var sM=C(()=>{"use strict";Fs()});function ZS(n){return qr(n)}function kie(n){return n instanceof ii}function Wie(n){let e=[];return n.traverse(t=>{kie(t)&&t.geometry&&e.push(t)}),e}function c3(n,e,t){jS(new QS(n),e,t)}function aM(n){qS(new QS(n))}var QS,f3=C(()=>{"use strict";Ys();Fs();rf();sM();QS=class{constructor(e){this.root=e}getParts(){return Wie(this.root)}getRootCenter(){let e=new Sr().setFromObject(this.root);return fn({min:Ht(e.min),max:Ht(e.max)})}getPartPosition(e){return Ht(e.position)}getPartCenter(e){let i=new Sr().setFromObject(e).getCenter(new ne);return Ht(i)}setPartPosition(e,t){e.position.set(t.x,t.y,t.z)}getPartState(e){var i;let t=(i=e.userData)!=null?i:{};return t._previewExplodeState?{originalPosition:ZS(t._previewExplodeState.originalPosition),originalCenter:ZS(t._previewExplodeState.originalCenter)}:null}setPartState(e,t){e.userData._previewExplodeState={originalPosition:ZS(t.originalPosition),originalCenter:ZS(t.originalCenter)}}}});var m3={};tt(m3,{ThreeModelPreview:()=>iT,createThreeModelPreview:()=>ore});function Bu(n){return n instanceof ii}function h3(n){return n instanceof Go||n instanceof Ka||n instanceof Dl}function ga(n){return n?Array.isArray(n)?n:[n]:[]}function JS(n){var r,s,a,o;let e=n.geometry,t=(s=(r=e.getIndex())==null?void 0:r.count)!=null?s:0;if(t>0)return Math.floor(t/3);let i=(o=(a=e.getAttribute("position"))==null?void 0:a.count)!=null?o:0;return Math.floor(i/3)}function eT(n){var e,t;return(t=(e=n.geometry.getAttribute("position"))==null?void 0:e.count)!=null?t:0}function tT(n){return n?n.name||n.type||`material-${n.uuid}`:null}function Mh(n,e){var i;let t=(i=n.userData)==null?void 0:i.name;return typeof t=="string"&&t.trim().length>0?t:n.name||e}function oM(n,e){let t=[],i=e;for(;i&&i!==n;)t.push(Mh(i,i.type||`object-${i.id}`)),i=i.parent;return t.reverse().join("/")}function d3(n,e){var t;return((t=n.displayName)==null?void 0:t.trim())||n.partNumber||n.componentId||e}function u3(n){let e=n.clone();return e.transparent=!0,e.opacity=Math.max(0,Math.min(1,n.opacity))*Hie,e.depthWrite=!1,e.needsUpdate=!0,e}function sre(n){return Array.isArray(n)?n.map(u3):u3(n)}function are(n){for(let e of ga(n))e.dispose()}function sf(n){let e=new Sr().setFromObject(n);return I_(Ht(e.min),Ht(e.max))}function ore(n){return new iT(n)}var $S,Hie,zie,Xie,Yie,Kie,jie,P_,qie,Zie,Qie,$ie,Jie,ere,tre,ire,rre,nre,iT,p3=C(()=>{"use strict";Ys();T1();A1();j1();Ks();rf();US();zS();C_();tM();Fs();o3();f3();la();$S=new ct("#20242e"),Hie=.242,zie=.28,Xie=2.5,Yie=1.5,Kie=1.15,jie=180,P_=30,qie=8,Zie=28,Qie=18,$ie=2,Jie=28,ere=.86,tre=1.08,ire=.62,rre=.86,nre=4;iT=class{constructor(e){this.raycaster=new jc;this.occlusionRaycaster=new jc;this.renderObservers=new Set;this.pointer=new bt;this.annotationProjection=new ne;this.annotationDirection=new ne;this.clock={last:performance.now()};this.defaultLights=[];this.configLights=[];this.environmentTarget=null;this.rootObject=null;this.loadedExt="";this.resourceWarnings=[];this.renderHandle=0;this.contextLost=!1;this.quality="high";this.renderScale=1;this.interactivePixelRatioActive=!1;this.interactionPixelRatioDeadline=0;this.renderObserverSettleFrames=P_;this.frameBudgetPixelRatioScale=1;this.frameBudgetSlowStreak=0;this.frameBudgetFastStreak=0;this.frameBudgetObserverStride=1;this.frameBudgetObserverCursor=0;this.frameBudgetShadowDeferred=!1;this.lastFrameDurationMs=0;this.viewportVisible=!0;this.viewportObserver=null;this.lastDisposalAudit={reason:"initial",meshCount:0,geometryCount:0,materialCount:0,textureCount:0,objectCount:0,timestamp:performance.now()};this.axesHelper=null;this.bboxHelper=null;this.groundShadowMesh=null;this.gridHelper=null;this.bboxEnabled=!1;this.wireframeEnabled=!1;this.wireframeOriginalMaterials=new Map;this.sceneConfig={};this.focusSelectionEnabled=!1;this.focusedMesh=null;this.highlightedMesh=null;this.selectionHelper=null;this.focusHelper=null;this.mixer=null;this.animationPlaying=!1;this.initialTarget=new ne;this.initialPosition=new ne(3,2,3);this.initialFov=45;this.lastPointerDown=null;this.measurementActive=!1;this.measurementScale={x:1,y:1,z:1};this.measurementUnit="mm";this.measurementSegments=[];this.measurementMarkers=[];this.pendingPoint=null;this.pendingMarker=null;this.hoveredMarkerIndex=-1;this.lastPointerClient={x:0,y:0};this.previewLine=null;this.originalMaterials=new Map;this.focusDimMaterials=new Map;this._lastPickResult={mesh:null,pickedPoint:null,screenX:0,screenY:0};this._onPickCallbacks=[];this.disassembly=null;this.disassemblySetup=!1;this.renderDirty=!0;this.cachedMeshes=null;this.cachedMeshRoot=null;this.cameraAnimHandle=0;this.preventCanvasWheelScroll=e=>{e.preventDefault(),e.stopPropagation()};this.handleControlsChange=()=>{let e=performance.now();this.interactionPixelRatioDeadline=e+jie,this.activateInteractivePixelRatio()&&this.resizeRenderer(),this.markDirty()};this.handleViewportIntersection=e=>{let t=e[e.length-1];if(!t)return;let i=t.isIntersecting&&t.intersectionRatio>0;i!==this.viewportVisible&&(this.viewportVisible=i,i?(this.clock.last=performance.now(),this.markDirty(),this.markShadowDirty(),this.startRenderLoop()):(cancelAnimationFrame(this.renderHandle),this.renderHandle=0))};this.handlePointerDown=e=>{e.button!==0||e.isPrimary===!1||(this.lastPointerDown={x:e.clientX,y:e.clientY})};this.handlePointerUp=e=>{var i;if(e.button!==0||e.isPrimary===!1)return;let t=this.lastPointerDown;this.lastPointerDown=null,t&&(Math.hypot(e.clientX-t.x,e.clientY-t.y)>4||(i=this.disassembly)!=null&&i.isEnabled()||this.dispatchPick(e))};this.handlePointerMove=e=>{if(this.lastPointerClient={x:e.clientX,y:e.clientY},!this.measurementActive||(this.pendingPoint&&this.updatePreviewLine(),this.measurementMarkers.length===0))return;let t=this.renderer.domElement.getBoundingClientRect();this.pointer.x=(e.clientX-t.left)/t.width*2-1,this.pointer.y=-((e.clientY-t.top)/t.height)*2+1,this.raycaster.setFromCamera(this.pointer,this.camera);let i=this.raycaster.intersectObjects(this.measurementMarkers,!1),r=i.length>0?this.measurementMarkers.indexOf(i[0].object):-1;if(r!==this.hoveredMarkerIndex){if(this.hoveredMarkerIndex>=0&&this.hoveredMarkerIndex=0&&r{e.preventDefault(),this.contextLost=!0,this.renderHandle&&(cancelAnimationFrame(this.renderHandle),this.renderHandle=0)};this.handleContextRestored=()=>{this.contextLost=!1,this.markDirty(),this.startRenderLoop()};this.renderer=new AS({canvas:e,antialias:!0,alpha:!0,preserveDrawingBuffer:!0,powerPreference:"high-performance"}),this.renderer.outputColorSpace=Ni,this.renderer.toneMapping=Hs,this.renderer.toneMappingExposure=1,this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=CE,this.renderer.shadowMap.autoUpdate=!1,this.renderer.shadowMap.needsUpdate=!0,this.renderer.setClearColor($S,1),this.scene=new mh,this.installGlobalEnvironment(),this.camera=new kr(this.initialFov,1,.01,2e3),this.camera.position.copy(this.initialPosition),this.camera.lookAt(this.initialTarget),this.scene.add(this.camera),this.controls=new IS(this.camera,e),this.controls.enableDamping=!0,this.controls.dampingFactor=.08,this.controls.zoomSpeed=.85,this.controls.screenSpacePanning=!0,this.controls.target.copy(this.initialTarget),this.controls.addEventListener("change",this.handleControlsChange),this.installDefaultLighting(),this.resizeObs=new ResizeObserver(()=>this.resizeRenderer()),this.resizeObs.observe(e),typeof IntersectionObserver!="undefined"&&(this.viewportObserver=new IntersectionObserver(this.handleViewportIntersection,{root:null,threshold:[0,.01]}),this.viewportObserver.observe(e)),e.addEventListener("wheel",this.preventCanvasWheelScroll,{passive:!1}),e.addEventListener("pointerdown",this.handlePointerDown),e.addEventListener("pointerup",this.handlePointerUp),e.addEventListener("pointermove",this.handlePointerMove),e.addEventListener("webglcontextlost",this.handleContextLost),e.addEventListener("webglcontextrestored",this.handleContextRestored),this.resizeRenderer(),this.startRenderLoop()}async loadModel(e,t,i,r){var l;this.clearLoadedModel("model-switch"),this.loadedExt=t.toLowerCase(),this.resourceWarnings=[];let s,a=[];if(this.loadedExt==="glb"||this.loadedExt==="gltf"){let c=await z1(e,this.loadedExt,i,r);s=c.scene,a=c.animations,this.resourceWarnings=c.warnings}else if(this.loadedExt==="stl")s=await X1(e);else if(this.loadedExt==="ply")s=await Y1(e);else if(this.loadedExt==="obj"){let c=await K1(e,i,r);s=c.object,this.resourceWarnings=c.warnings}else throw new Error(`Three preview does not support .${this.loadedExt} format`);if(this.rootObject=s,this.scene.add(s),this.invalidateMeshCache(),this.prepareModelForQuality(s),this.updateShadowFraming(),this.syncSceneHelpers(),this.markDirty(),a.length>0){this.mixer=new l_(s);for(let c of a)this.mixer.clipAction(c).play();this.animationPlaying=!0}let o=this.computeSummary(s);return this.fitCameraToObject(s),this.bboxEnabled&&this.ensureBoundingBoxHelper(),this.disassemblySetup=!1,(l=this.disassembly)==null||l.dispose(),this.disassembly=null,o}applyConfig(e){e.camera&&this.applyCameraConfig(e.camera),e.lights&&this.applyLightConfig(e.lights),e.scene&&this.applySceneConfig(e.scene)}destroy(){var t,i;cancelAnimationFrame(this.renderHandle),cancelAnimationFrame(this.cameraAnimHandle),this._onPickCallbacks=[],this.renderObservers.clear(),(t=this.disassembly)==null||t.dispose(),this.disassembly=null,this.disassemblySetup=!1,this.clearFocusedMesh(),this.clearSelectionHighlight(),this.clearLoadedModel("destroy");for(let r of this.configLights)this.disposeConfiguredLight(r);this.configLights.length=0;for(let r of this.defaultLights)this.disposeConfiguredLight(r);this.defaultLights.length=0,this.disposeGlobalEnvironment(),this.controls.removeEventListener("change",this.handleControlsChange),this.controls.dispose();let e=this.renderer.domElement;e.removeEventListener("wheel",this.preventCanvasWheelScroll),e.removeEventListener("pointerdown",this.handlePointerDown),e.removeEventListener("pointerup",this.handlePointerUp),e.removeEventListener("pointermove",this.handlePointerMove),e.removeEventListener("webglcontextlost",this.handleContextLost),e.removeEventListener("webglcontextrestored",this.handleContextRestored),this.resizeObs.disconnect(),(i=this.viewportObserver)==null||i.disconnect(),this.viewportObserver=null,this.renderer.dispose()}getCanvas(){return this.renderer.domElement}captureSnapshot(){return this.renderNow(0),this.renderer.domElement.toDataURL("image/png")}getAnnotationProvider(){return{canvas:this.renderer.domElement,observeRender:t=>(this.renderObservers.add(t),{remove:()=>this.renderObservers.delete(t)}),getCameraStateKey:()=>this.getAnnotationCameraStateKey(),projectWorldPoint:(t,i)=>this.projectAnnotationWorldPoint(t,i),isWorldPointOccluded:t=>this.isAnnotationWorldPointOccluded(t)}}exportModelInfo(e){if(!this.rootObject)return"";let t=this.computeSummary(this.rootObject),i=this.getRenderableMeshes(this.rootObject),r=e&&oa(e)||t.rootName;return WS({title:r,format:this.loadedExt.toUpperCase(),summary:t,meshBreakdown:i.map(s=>({name:Mh(s,`mesh-${s.id}`),triangleCount:JS(s),vertexCount:eT(s),materialName:tT(ga(s.material)[0])}))})}getModelEvidence(){if(!this.rootObject)return null;let e=this.getRenderableMeshes(this.rootObject),t=this.computeComponentPartSummaries(this.rootObject,e),i=e.filter(a=>!t.groupedMeshes.has(a)).map(a=>this.computePartSummary(a)),r=t.parts.length>0?[...t.parts,...i]:i,s=new Set;for(let a of e)for(let o of ga(a.material)){let l=tT(o);l&&s.add(l)}return{summary:this.computeSummary(this.rootObject),parts:r,materialNames:Array.from(s).sort((a,o)=>a.localeCompare(o)),resourceWarnings:[...this.resourceWarnings],capturedAt:new Date().toISOString()}}getSelectedPartInfo(){var t;let e=(t=this.focusedMesh)!=null?t:Bu(this._lastPickResult.mesh)?this._lastPickResult.mesh:null;return e?this.computePartSummary(e):null}exportSelectedPartInfo(){let e=this.getSelectedPartInfo();return e?HS(e):""}getPickWorldPoint(e){return e.pickedPoint&&typeof e.pickedPoint=="object"?Ht(e.pickedPoint):e.mesh instanceof ii?fn(sf(e.mesh)):null}onPick(e){return this._onPickCallbacks.push(e),()=>{this._onPickCallbacks=this._onPickCallbacks.filter(t=>t!==e)}}resetView(){this.rootObject&&aM(this.rootObject),this.resetDisassembly(),this.clearFocusedMesh(),this.clearSelectionHighlight(),this.camera.fov=this.initialFov,this.camera.position.copy(this.initialPosition),this.camera.updateProjectionMatrix(),this.controls.target.copy(this.initialTarget),this.controls.update(),this.markDirty(),this.renderNow(performance.now())}toggleFocusSelection(){var t;let e=!this.focusSelectionEnabled;return e&&((t=this.disassembly)!=null&&t.isEnabled())&&this.disassembly.setEnabled(!1),this.focusSelectionEnabled=e,this.focusSelectionEnabled?(this.clearSelectionHighlight(),this._lastPickResult.mesh instanceof ii&&this.setFocusedMesh(this._lastPickResult.mesh)):this.clearFocusedMesh(),this.markDirty(),this.focusSelectionEnabled}isFocusSelectionEnabled(){return this.focusSelectionEnabled}toggleWireframe(){if(this.wireframeEnabled=!this.wireframeEnabled,!this.rootObject)return this.wireframeEnabled;for(let e of this.getRenderableMeshes(this.rootObject))if(this.wireframeEnabled){this.wireframeOriginalMaterials.set(e.id,e.material);let i=ga(e.material).map(r=>{if(r instanceof Cn){let s=new qn({color:r.color,transparent:r.transparent,opacity:r.opacity,side:r.side,visible:r.visible});return s.wireframe=!0,s}if("wireframe"in r){let s=r.clone();return s.wireframe=!0,s}return r});e.material=Array.isArray(e.material)?i:i[0]}else{let t=this.wireframeOriginalMaterials.get(e.id);t&&(e.material=t),this.wireframeOriginalMaterials.delete(e.id)}return this.markDirty(),this.wireframeEnabled}toggleOrientationGizmo(){if(!this.axesHelper){this.axesHelper=new xu(1.2),this.axesHelper.visible=!1;let e=this.axesHelper.material;e.depthTest=!1,e.depthWrite=!1,this.axesHelper.renderOrder=999,this.scene.add(this.axesHelper)}return this.axesHelper.visible=!this.axesHelper.visible,this.axesHelper.position.copy(this.controls.target),this.markDirty(),this.axesHelper.visible}isOrientationGizmoEnabled(){var e;return!!((e=this.axesHelper)!=null&&e.visible)}toggleBoundingBox(){var e;return this.bboxEnabled=!this.bboxEnabled,this.bboxEnabled?(this.ensureBoundingBoxHelper(),this.markDirty(),!!this.bboxHelper):((e=this.bboxHelper)==null||e.removeFromParent(),this.bboxHelper=null,this.markDirty(),!1)}hasAnimations(){return this.mixer!==null}toggleAnimation(){return this.mixer?(this.animationPlaying=!this.animationPlaying,this.mixer.timeScale=this.animationPlaying?1:0,this.markDirty(),this.animationPlaying):!1}toggleMeasurement(){return this.measurementActive=!this.measurementActive,this.measurementActive||this.clearMeasurements(),this.measurementActive}isMeasurementActive(){return this.measurementActive}clearMeasurements(){var e;this.measurementActive=!1,this.pendingPoint=null,this.pendingMarker=null,this.hoveredMarkerIndex=-1,this.removePreviewLine();for(let t of this.measurementSegments){t.line.removeFromParent(),t.line.geometry.dispose(),t.line.material.dispose(),t.label.removeFromParent();let i=t.label.material;(e=i.map)==null||e.dispose(),i.dispose()}this.measurementSegments=[];for(let t of this.measurementMarkers){t.removeFromParent(),t.geometry.dispose();let i=t.material;if(Array.isArray(i))for(let r of i)r.dispose();else i.dispose()}this.measurementMarkers=[],this.markDirty()}setMeasurementScale(e){this.measurementScale={...e},this.updateMeasurementLabels()}getMeasurementScale(){return{...this.measurementScale}}getMeasurementBounds(){if(!this.rootObject)return null;let e=sf(this.rootObject);return Wr(e)}getRealDistance(e,t){let i=(t.x-e.x)*this.measurementScale.x,r=(t.y-e.y)*this.measurementScale.y,s=(t.z-e.z)*this.measurementScale.z;return Math.sqrt(i*i+r*r+s*s)}formatMeasurementDistance(e){let t=this.measurementUnit;return t==="um"||t==="\u03BCm"?e<1e3?`${e.toFixed(2)} \u03BCm`:`${(e/1e3).toFixed(2)} mm`:t==="mm"?e<1?`${(e*1e3).toFixed(2)} \u03BCm`:e<1e3?`${e.toFixed(2)} mm`:`${(e/1e3).toFixed(3)} m`:t==="cm"?e<1?`${(e*10).toFixed(2)} mm`:e<100?`${e.toFixed(2)} cm`:`${(e/100).toFixed(3)} m`:t==="m"?e<.01?`${(e*1e3).toFixed(2)} mm`:e<1?`${e.toFixed(3)} m`:`${e.toFixed(2)} m`:`${e.toFixed(3)} ${t}`}updateMeasurementLabels(){var t;if(this.measurementSegments.length===0)return;let e=this.getMeasurementMarkerSize()*4;for(let i of this.measurementSegments){let r=this.getRealDistance(i.start,i.end),s=this.formatMeasurementDistance(r);i.label.removeFromParent();let a=i.label.material;(t=a.map)==null||t.dispose(),a.dispose();let o=new ne().addVectors(i.start,i.end).multiplyScalar(.5);i.label=this.createMeasurementLabelSprite(s,o,e),this.scene.add(i.label)}this.markDirty()}setRenderQuality(e,t=this.renderScale){this.quality=e,this.renderScale=t,this.applyShadowQuality(),this.resizeRenderer()}setRenderScale(e){return this.renderScale=Math.min(2,Math.max(.25,e)),this.resizeRenderer(),Number(this.renderScale.toFixed(2))}getPerformanceSnapshot(){return{backend:"three",renderScale:Number(this.renderScale.toFixed(2)),quality:this.quality,pixelRatio:Number(this.renderer.getPixelRatio().toFixed(2)),interactivePixelRatioActive:this.interactivePixelRatioActive,renderDirty:this.renderDirty,renderObserverCount:this.renderObservers.size,renderObserverSettleFrames:this.renderObserverSettleFrames,frameBudgetPixelRatioScale:Number(this.frameBudgetPixelRatioScale.toFixed(2)),frameBudgetObserverStride:this.frameBudgetObserverStride,frameBudgetShadowDeferred:this.frameBudgetShadowDeferred,lastFrameDurationMs:Number(this.lastFrameDurationMs.toFixed(2)),viewportVisible:this.viewportVisible,disposalAudit:{...this.lastDisposalAudit},meshCount:this.rootObject?this.getRenderableMeshes(this.rootObject).length:0}}setExplode(e,t){this.rootObject&&(c3(this.rootObject,e,t),this.markShadowDirty(),this.markDirty())}resetExplode(){this.rootObject&&(aM(this.rootObject),this.markShadowDirty(),this.markDirty())}focusWorldPoint(e){let t=new ne(e.x,e.y,e.z),i=this.camera.position.distanceTo(this.controls.target),r=t.clone().sub(this.camera.position).normalize(),s=t.clone().sub(r.multiplyScalar(i));this.animateCamera(s,t)}toggleDisassembly(){if(this.ensureDisassembly(),!this.disassembly)return!1;let e=!this.disassembly.isEnabled();e&&(this.focusSelectionEnabled=!1,this.clearFocusedMesh(),this.clearSelectionHighlight());let t=this.disassembly.setEnabled(e);return t||this.disassembly.reset(),t}resetDisassembly(){var e;(e=this.disassembly)==null||e.reset()}isDisassemblyEnabled(){var e,t;return(t=(e=this.disassembly)==null?void 0:e.isEnabled())!=null?t:!1}ensureDisassembly(){if(this.disassemblySetup||(this.disassemblySetup=!0,!this.rootObject))return;let e=this.getRenderableMeshes(this.rootObject);e.length!==0&&(this.disassembly=a3(this.scene,this.camera,this.renderer.domElement,e,this.controls,()=>{this.markShadowDirty(),this.markDirty()}))}animateCamera(e,t){cancelAnimationFrame(this.cameraAnimHandle);let i=this.camera.position.clone(),r=this.controls.target.clone(),s=500,a=performance.now(),o=()=>{let l=performance.now()-a,c=Math.min(1,l/s),f=c<.5?4*c*c*c:1-Math.pow(-2*c+2,3)/2;this.camera.position.lerpVectors(i,e,f),this.controls.target.lerpVectors(r,t,f),this.controls.update(),this.markDirty(),c<1&&(this.cameraAnimHandle=window.requestAnimationFrame(o))};this.cameraAnimHandle=window.requestAnimationFrame(o)}startRenderLoop(){if(this.renderHandle||!this.viewportVisible||this.contextLost)return;let e=()=>{if(!this.viewportVisible||this.contextLost){this.renderHandle=0;return}this.renderHandle=window.requestAnimationFrame(e),this.renderNow(performance.now())};this.renderHandle=window.requestAnimationFrame(e)}renderNow(e){var o,l,c;let t=this.renderer.domElement;if(!this.viewportVisible||!t.isConnected||t.clientWidth<=0||t.clientHeight<=0)return;let i=Math.max(0,(e-this.clock.last)/1e3);this.clock.last=e;let r=this.controls.update(),s=!!this.mixer&&this.animationPlaying;if(s&&this.mixer&&(this.mixer.update(i),this.markShadowDirty()),this.restoreInteractivePixelRatioIfIdle(e,r),!r&&!s&&!this.renderDirty){this.renderObserverSettleFrames>0&&(this.renderObserverSettleFrames--,this.notifyRenderObservers());return}this.renderDirty=!1,this.renderObserverSettleFrames=P_,(o=this.bboxHelper)==null||o.update(),(l=this.selectionHelper)==null||l.update(),(c=this.focusHelper)==null||c.update(),this.axesHelper&&this.axesHelper.visible&&this.axesHelper.position.copy(this.controls.target);let a=performance.now();this.renderer.render(this.scene,this.camera),this.updateFrameBudget(performance.now()-a),this.notifyRenderObservers()}notifyRenderObservers(){if(!(this.frameBudgetObserverStride>1&&(this.frameBudgetObserverCursor=(this.frameBudgetObserverCursor+1)%this.frameBudgetObserverStride,this.frameBudgetObserverCursor!==0)))for(let e of this.renderObservers)e()}markDirty(){this.renderDirty=!0,this.startRenderLoop()}markShadowDirty(){if(this.shouldDeferShadowRefresh()){this.frameBudgetShadowDeferred=!0;return}this.frameBudgetShadowDeferred=!1,this.renderer.shadowMap.needsUpdate=!0}activateInteractivePixelRatio(){if(this.interactivePixelRatioActive)return!1;let e=this.computePixelRatio(!1);return this.computePixelRatio(!0)>=e?!1:(this.interactivePixelRatioActive=!0,!0)}restoreInteractivePixelRatioIfIdle(e,t){!this.interactivePixelRatioActive||t||e=Zie?(this.frameBudgetSlowStreak++,this.frameBudgetFastStreak=0):e<=Qie?(this.frameBudgetFastStreak++,this.frameBudgetSlowStreak=0):(this.frameBudgetSlowStreak=0,this.frameBudgetFastStreak=0),this.frameBudgetSlowStreak>=$ie){this.frameBudgetSlowStreak=0;let t=Math.max(ire,this.frameBudgetPixelRatioScale*ere);t=Jie&&this.frameBudgetPixelRatioScale<1&&(this.frameBudgetFastStreak=0,this.frameBudgetPixelRatioScale=Math.min(1,this.frameBudgetPixelRatioScale*tre),this.frameBudgetObserverStride=Math.max(1,this.frameBudgetObserverStride-1),this.renderObserverSettleFrames=P_,this.resizeRenderer())}}resetFrameBudget(){let e=this.frameBudgetPixelRatioScale!==1||this.frameBudgetObserverStride!==1;this.frameBudgetPixelRatioScale=1,this.frameBudgetSlowStreak=0,this.frameBudgetFastStreak=0,this.frameBudgetObserverStride=1,this.frameBudgetObserverCursor=0,this.renderObserverSettleFrames=P_,e&&this.markDirty()}shouldDeferShadowRefresh(){return this.interactivePixelRatioActive&&this.frameBudgetPixelRatioScale<=rre}resizeRenderer(){let e=this.renderer.domElement,t=Math.max(1,Math.round(e.clientWidth||e.width||1)),i=Math.max(1,Math.round(e.clientHeight||e.height||1));this.renderer.setPixelRatio(this.computePixelRatio()),this.renderer.setSize(t,i,!1),this.camera.aspect=t/i,this.camera.updateProjectionMatrix(),this.markDirty()}applyCameraConfig(e){typeof e.fov=="number"&&Number.isFinite(e.fov)&&(this.camera.fov=e.fov,this.camera.updateProjectionMatrix()),e.position&&this.camera.position.set(...e.position),e.lookAt&&(this.controls.target.set(...e.lookAt),this.camera.lookAt(this.controls.target)),typeof e.near=="number"&&Number.isFinite(e.near)&&(this.camera.near=e.near),typeof e.far=="number"&&Number.isFinite(e.far)&&(this.camera.far=e.far),typeof e.zoom=="number"&&Number.isFinite(e.zoom)&&(this.camera.zoom=e.zoom),this.camera.updateProjectionMatrix(),this.controls.update(),this.markDirty()}applyLightConfig(e){for(let i of this.configLights)this.disposeConfiguredLight(i);this.configLights.length=0;let t=e.length>0;for(let i of this.defaultLights)i.visible=!t;for(let i of e){let r=this.createConfiguredLight(i);r&&(this.configLights.push(r),r.parent!==this.camera&&this.scene.add(r))}this.updateShadowFraming(),this.markShadowDirty(),this.markDirty()}applySceneConfig(e){if(this.sceneConfig={...this.sceneConfig,...e},e.transparent!==void 0||e.background!==void 0)if(this.sceneConfig.transparent)this.scene.background=null,this.renderer.setClearColor($S,0);else if(this.sceneConfig.background){let t=new ct(this.sceneConfig.background);this.scene.background=t,this.renderer.setClearColor(t,1)}else this.scene.background=$S,this.renderer.setClearColor($S,1);typeof e.autoRotate=="boolean"&&(this.controls.autoRotate=e.autoRotate),typeof e.autoRotateSpeed=="number"&&(this.controls.autoRotateSpeed=e.autoRotateSpeed),typeof e.axis=="boolean"&&this.syncAxisHelper(e.axis),this.syncSceneHelpers(),this.markDirty()}installDefaultLighting(){let e=new Tu(16777215,.96);e.name="default-global-ambient";let t=new Su(16777215,7172736,.34);t.name="default-hemi",this.defaultLights.push(e,t);for(let i of this.defaultLights)this.scene.add(i)}installGlobalEnvironment(){this.disposeGlobalEnvironment();let e=new Lu(this.renderer),t=new MS;this.environmentTarget=e.fromScene(t,.04),this.scene.environment=this.environmentTarget.texture,this.scene.environmentIntensity=.48,t.dispose(),e.dispose()}disposeGlobalEnvironment(){var e;this.scene.environment=null,(e=this.environmentTarget)==null||e.dispose(),this.environmentTarget=null}createConfiguredLight(e){var r,s,a,o,l,c,f;let t=e.color?new ct(e.color):new ct(16777215),i=(r=e.intensity)!=null?r:1;switch(e.type){case"ambient":return new Tu(t,i);case"hemisphere":{let h=e.groundColor?new ct(e.groundColor):new ct(4473924);return new Su(t,h,i)}case"directional":{let h=new Go(t,i),d=(s=e.position)!=null?s:[-1,2,1],u=(a=e.target)!=null?a:[0,0,0];return h.position.set(...d),h.target.position.set(...u),this.scene.add(h.target),h.castShadow=!!e.castShadow,h}case"point":{let h=new Ka(t,i),d=(o=e.position)!=null?o:[0,5,0];return h.position.set(...d),h.castShadow=!!e.castShadow,typeof e.decay=="number"&&(h.decay=e.decay),h}case"spot":{let h=new Dl(t,i),d=(l=e.position)!=null?l:[0,5,0],u=(c=e.target)!=null?c:[0,0,0];return h.position.set(...d),h.target.position.set(...u),this.scene.add(h.target),h.angle=e.angle?e.angle*Math.PI/180:Math.PI/4,h.penumbra=(f=e.penumbra)!=null?f:.5,typeof e.decay=="number"&&(h.decay=e.decay),h.castShadow=!!e.castShadow,h}case"attachToCam":{let h=new Ka(t,i);return this.camera.add(h),h}default:return null}}disposeConfiguredLight(e){(e instanceof Go||e instanceof Dl)&&e.target.removeFromParent(),e.removeFromParent(),e.dispose()}prepareModelForQuality(e){let t=this.renderer.capabilities.getMaxAnisotropy();e.traverse(i=>{if(Bu(i)){i.castShadow=!0,i.receiveShadow=!0;for(let r of ga(i.material))this.prepareMaterialForQuality(r,t)}})}prepareMaterialForQuality(e,t){let i=e;for(let r of Object.values(i))r instanceof Ar&&(r.anisotropy=Math.max(r.anisotropy,t),r.needsUpdate=!0);e.needsUpdate=!0}applyShadowQuality(){let e=this.shadowMapSize();for(let t of this.allLights())!h3(t)||!t.castShadow||(t.shadow.mapSize.set(e,e),t.shadow.bias=-12e-5,t.shadow.normalBias=.018,t.shadow.needsUpdate=!0);this.markShadowDirty(),this.markDirty()}updateShadowFraming(){if(!this.rootObject)return;let e=new Sr().setFromObject(this.rootObject),t=e.getCenter(new ne),i=e.getSize(new ne),r=Math.max(i.x,i.y,i.z,1)*1.8;for(let s of this.allLights())if(!(!h3(s)||!s.castShadow)){if(s.shadow.mapSize.set(this.shadowMapSize(),this.shadowMapSize()),s.shadow.bias=-12e-5,s.shadow.normalBias=.018,s instanceof Go){let a=s.position.clone().sub(s.target.position);if(a.lengthSq()<.001&&a.set(4,7,5),s.target.position.copy(t),s.target.parent||this.scene.add(s.target),s.position.copy(t).add(a.normalize().multiplyScalar(r*2.4)),s.shadow.camera instanceof Vo){let o=s.shadow.camera;o.left=-r,o.right=r,o.top=r,o.bottom=-r,o.near=.1,o.far=r*5,o.updateProjectionMatrix()}}s.shadow.needsUpdate=!0}this.markShadowDirty()}shadowMapSize(){return this.quality==="low"?512:this.quality==="medium"?1024:2048}allLights(){return[...this.defaultLights,...this.configLights]}syncSceneHelpers(){this.sceneConfig.groundShadow?this.createGroundShadow():this.removeGroundShadow(),this.sceneConfig.grid?this.createGrid():this.removeGrid(),typeof this.sceneConfig.axis=="boolean"&&this.syncAxisHelper(this.sceneConfig.axis)}syncAxisHelper(e){if(!this.axesHelper){this.axesHelper=new xu(1.2);let t=this.axesHelper.material;t.depthTest=!1,t.depthWrite=!1,this.axesHelper.renderOrder=999,this.scene.add(this.axesHelper)}this.axesHelper.visible=e,this.axesHelper.position.copy(this.controls.target)}createGroundShadow(){if(!this.rootObject||this.groundShadowMesh)return;let e=sf(this.rootObject),t=fn(e),i=Wr(e),r=Math.max(i.x,i.z,1)*3,s=e.min.y-Math.max(r*.002,.002),a=new ii(new gh(r,r),new t_({color:0,opacity:zie,transparent:!0}));a.name="ai3d-ground-shadow",a.rotation.x=-Math.PI/2,a.position.set(t.x,s,t.z),a.receiveShadow=!0,a.renderOrder=-1,this.scene.add(a),this.groundShadowMesh=a}removeGroundShadow(){if(this.groundShadowMesh){this.groundShadowMesh.removeFromParent(),this.groundShadowMesh.geometry.dispose();for(let e of ga(this.groundShadowMesh.material))e.dispose();this.groundShadowMesh=null}}createGrid(){if(!this.rootObject||this.gridHelper)return;let e=sf(this.rootObject),t=fn(e),i=Wr(e),r=Math.max(i.x,i.z,1)*2,s=new c_(r,20,7305093,3423046);s.name="ai3d-grid",s.position.set(t.x,e.min.y-Math.max(r*.003,.003),t.z);for(let a of ga(s.material))a.transparent=!0,a.opacity=.42;this.scene.add(s),this.gridHelper=s}removeGrid(){if(this.gridHelper){this.gridHelper.removeFromParent(),this.gridHelper.geometry.dispose();for(let e of ga(this.gridHelper.material))e.dispose();this.gridHelper=null}}dispatchPick(e){var a,o,l;if(!this.rootObject||(a=this.disassembly)!=null&&a.isEnabled())return;let t=this.renderer.domElement.getBoundingClientRect();this.pointer.x=(e.clientX-t.left)/t.width*2-1,this.pointer.y=-((e.clientY-t.top)/t.height)*2+1,this.raycaster.setFromCamera(this.pointer,this.camera);let i=this.raycaster.intersectObjects(this.getRenderableMeshes(this.rootObject),!1)[0],r=(i==null?void 0:i.object)instanceof ii?i.object:null,s={mesh:r,pickedPoint:(l=(o=i==null?void 0:i.point)==null?void 0:o.clone())!=null?l:null,screenX:e.clientX,screenY:e.clientY};if(this._lastPickResult=s,this.measurementActive&&(i!=null&&i.point)){this.addMeasurementPoint(i.point.clone());return}this.focusSelectionEnabled&&r?(this.clearSelectionHighlight(),this.focusedMesh!==r&&this.setFocusedMesh(r)):this.focusSelectionEnabled?this.clearSelectionHighlight():this.updateSelectionHighlight(r),this._onPickCallbacks.forEach(c=>c(s))}clearLoadedModel(e="model-switch"){var t,i;if((t=this.disassembly)==null||t.dispose(),this.disassembly=null,this.disassemblySetup=!1,this.invalidateMeshCache(),this.markDirty(),this.clearFocusedMesh(),this.clearSelectionHighlight(),this.clearMeasurements(),this.wireframeEnabled=!1,this.wireframeOriginalMaterials.clear(),(i=this.bboxHelper)==null||i.removeFromParent(),this.bboxHelper=null,this.bboxEnabled=!1,this.removeGroundShadow(),this.removeGrid(),this.mixer=null,this.animationPlaying=!1,!this.rootObject){this.lastDisposalAudit={reason:e,meshCount:0,geometryCount:0,materialCount:0,textureCount:0,objectCount:0,timestamp:performance.now()};return}this.scene.remove(this.rootObject),this.lastDisposalAudit=this.disposeObjectGraph(this.rootObject,e),this.rootObject=null,this.markShadowDirty()}disposeObjectGraph(e,t){let i=new Set,r=new Set,s=new Set,a=0,o=0;return e.traverse(l=>{if(o++,!Bu(l))return;a++;let c=l.geometry;c&&!i.has(c.uuid)&&(c.dispose(),i.add(c.uuid));for(let f of ga(l.material))this.disposeMaterialWithTextures(f,r,s)}),{reason:t,meshCount:a,geometryCount:i.size,materialCount:r.size,textureCount:s.size,objectCount:o,timestamp:performance.now()}}disposeMaterialWithTextures(e,t,i){let r=e;for(let s of Object.values(r))if(s instanceof Ar&&!i.has(s.uuid))s.dispose(),i.add(s.uuid);else if(Array.isArray(s))for(let a of s)a instanceof Ar&&!i.has(a.uuid)&&(a.dispose(),i.add(a.uuid));t.has(e.uuid)||(e.dispose(),t.add(e.uuid))}fitCameraToObject(e){let t=sf(e),i=J1(t);this.initialTarget.set(i.target.x,i.target.y,i.target.z),this.initialPosition.set(i.position.x,i.position.y,i.position.z),this.initialFov=45;let r=Wr(t),s=Math.max(r.x,r.y,r.z,1),a=this.initialPosition.distanceTo(this.initialTarget);this.controls.minDistance=Math.max(i.near*4,s*.02,.001),this.controls.maxDistance=Math.max(a*8,this.controls.minDistance*10),this.resetView(),this.axesHelper&&(this.axesHelper.position.copy(this.controls.target),this.axesHelper.scale.setScalar(Math.max(.5,s*.25))),this.camera.near=i.near,this.camera.far=i.far,this.camera.updateProjectionMatrix(),this.markDirty()}getAnnotationCameraStateKey(){return[this.camera.position.x.toFixed(3),this.camera.position.y.toFixed(3),this.camera.position.z.toFixed(3),this.controls.target.x.toFixed(2),this.controls.target.y.toFixed(2),this.controls.target.z.toFixed(2),this.camera.fov.toFixed(2)].join("_")}projectAnnotationWorldPoint(e,t){let i=this.renderer.domElement;return!i.isConnected||i.clientWidth===0||i.clientHeight===0||(this.scene.updateMatrixWorld(),this.camera.updateMatrixWorld(),this.annotationProjection.set(e.x,e.y,e.z).project(this.camera),!Number.isFinite(this.annotationProjection.x)||!Number.isFinite(this.annotationProjection.y)||!Number.isFinite(this.annotationProjection.z))?!1:(t.screenX=(this.annotationProjection.x+1)/2*i.clientWidth,t.screenY=(1-this.annotationProjection.y)/2*i.clientHeight,t.depth=(this.annotationProjection.z+1)/2,!0)}isAnnotationWorldPointOccluded(e){if(!this.rootObject)return!1;let t=wc(Ht(this.camera.position),e);if(!t)return!1;this.rootObject.updateWorldMatrix(!0,!0),this.annotationDirection.set(t.direction.x,t.direction.y,t.direction.z),this.occlusionRaycaster.set(this.camera.position,this.annotationDirection),this.occlusionRaycaster.far=t.distance;let i=this.occlusionRaycaster.intersectObjects(this.getRenderableMeshes(this.rootObject),!1)[0];return!!i&&Nc(i.distance,t.distance,t.epsilon)}getRenderableMeshes(e){if(this.cachedMeshes&&this.cachedMeshRoot===e)return this.cachedMeshes;let t=[];return e.traverse(i=>{Bu(i)&&i.geometry&&t.push(i)}),this.cachedMeshes=t,this.cachedMeshRoot=e,t}invalidateMeshCache(){this.cachedMeshes=null,this.cachedMeshRoot=null}ensureBoundingBoxHelper(){var e;this.rootObject&&((e=this.bboxHelper)==null||e.removeFromParent(),this.bboxHelper=new Ll(this.rootObject,16436245),this.scene.add(this.bboxHelper))}updateSelectionHighlight(e){var t;if(!this.rootObject||!e){this.clearSelectionHighlight();return}this.highlightedMesh===e&&this.selectionHelper||((t=this.selectionHelper)==null||t.removeFromParent(),this.selectionHelper=new Ll(e,4890367),this.scene.add(this.selectionHelper),this.highlightedMesh=e,this.markDirty())}setFocusedMesh(e){var i,r,s;if(!this.rootObject||!e){this.clearFocusedMesh();return}if(this.focusedMesh===e)return;let t=this.getRenderableMeshes(this.rootObject);if(!t.includes(e)){this.clearFocusedMesh();return}this.restoreFocusedMaterials(),this.disposeFocusDimMaterials();for(let a of t){if(this.originalMaterials.has(a.id)||this.originalMaterials.set(a.id,a.material),a===e){a.material=(i=this.originalMaterials.get(a.id))!=null?i:a.material;continue}let o=(r=this.originalMaterials.get(a.id))!=null?r:a.material,l=sre(o);this.focusDimMaterials.set(a.id,l),a.material=l}(s=this.focusHelper)==null||s.removeFromParent(),this.focusHelper=new Ll(e,3065087),this.scene.add(this.focusHelper),this.focusedMesh=e,this.markDirty()}clearFocusedMesh(){var e;this.restoreFocusedMaterials(),this.disposeFocusDimMaterials(),this.originalMaterials.clear(),(e=this.focusHelper)==null||e.removeFromParent(),this.focusHelper=null,this.focusedMesh=null,this.markDirty()}restoreFocusedMaterials(){if(this.rootObject)for(let e of this.getRenderableMeshes(this.rootObject)){let t=this.originalMaterials.get(e.id);t&&(e.material=t)}}disposeFocusDimMaterials(){for(let e of this.focusDimMaterials.values())are(e);this.focusDimMaterials.clear()}clearSelectionHighlight(){var e;(e=this.selectionHelper)==null||e.removeFromParent(),this.selectionHelper=null,this.highlightedMesh=null,this.markDirty()}getMeasurementMarkerSize(){if(!this.rootObject)return .02;let e=sf(this.rootObject),t=Wr(e);return Math.max(t.x,t.y,t.z,.001)*.015}findNearestMarkerIndex(e){let t=this.getMeasurementMarkerSize()*2.5;for(let i=0;i=0?this.measurementMarkers[t].position.clone():e;if(this.pendingPoint){if(i.distanceTo(this.pendingPoint)<1e-4)return;if(t<0){let r=this.getMeasurementMarkerSize(),s=new Eu(r,16,16),a=new qn({color:16739179,depthTest:!1}),o=new ii(s,a);o.position.copy(i),o.renderOrder=999,this.scene.add(o),this.measurementMarkers.push(o)}this.createMeasurementSegment(this.pendingPoint,i),this.pendingMarker&&(this.pendingMarker.scale.setScalar(1),this.pendingMarker.material.color.setHex(16739179)),this.pendingPoint=null,this.pendingMarker=null,this.removePreviewLine()}else{if(t<0){let r=this.getMeasurementMarkerSize(),s=new Eu(r,16,16),a=new qn({color:16739179,depthTest:!1}),o=new ii(s,a);o.position.copy(i),o.renderOrder=999,this.scene.add(o),this.measurementMarkers.push(o),this.pendingMarker=o}else this.pendingMarker=this.measurementMarkers[t];this.pendingMarker.scale.setScalar(1.6),this.pendingMarker.material.color.setHex(5361510),this.pendingPoint=i,this.ensurePreviewLine()}this.markDirty()}createMeasurementSegment(e,t){let i=new Ui().setFromPoints([e,t]),r=new No(i,new Mn({color:16739179,depthTest:!1}));r.renderOrder=998,this.scene.add(r);let s=this.getRealDistance(e,t),a=this.formatMeasurementDistance(s),o=new ne().addVectors(e,t).multiplyScalar(.5),l=this.createMeasurementLabelSprite(a,o,this.getMeasurementMarkerSize()*4);this.scene.add(l),this.measurementSegments.push({start:e,end:t,line:r,label:l})}createMeasurementLabelSprite(e,t,i){let r=document.createElement("canvas"),s=r.getContext("2d");r.width=512,r.height=128,s.fillStyle="rgba(32, 36, 46, 0.9)",s.beginPath(),s.roundRect(0,0,512,128,16),s.fill(),s.strokeStyle="#ff6b6b",s.lineWidth=4,s.stroke(),s.fillStyle="#ffffff",s.font="bold 48px sans-serif",s.textAlign="center",s.textBaseline="middle",s.fillText(e,256,64);let a=new Jp(r),o=new pu({map:a,depthTest:!1}),l=new jp(o);return l.position.copy(t),l.scale.set(i*4,i,1),l.renderOrder=1e3,l}ensurePreviewLine(){if(this.previewLine)return;let e=new Ui().setFromPoints([new ne,new ne]);this.previewLine=new No(e,new Mn({color:16777215,transparent:!0,opacity:.5,depthTest:!1})),this.previewLine.renderOrder=997,this.scene.add(this.previewLine)}updatePreviewLine(){if(!this.pendingPoint||!this.previewLine||!this.rootObject)return;let e=this.renderer.domElement.getBoundingClientRect();this.pointer.x=(this.lastPointerClient.x-e.left)/e.width*2-1,this.pointer.y=-((this.lastPointerClient.y-e.top)/e.height)*2+1,this.raycaster.setFromCamera(this.pointer,this.camera);let t=this.raycaster.intersectObjects(this.getRenderableMeshes(this.rootObject),!1)[0],i;t!=null&&t.point?i=t.point.clone():i=this.pendingPoint.clone().add(this.raycaster.ray.direction.clone().multiplyScalar(5));let r=this.previewLine.geometry;this.previewLine.geometry=new Ui().setFromPoints([this.pendingPoint,i]),r.dispose(),this.markDirty()}removePreviewLine(){this.previewLine&&(this.previewLine.removeFromParent(),this.previewLine.geometry.dispose(),this.previewLine.material.dispose(),this.previewLine=null)}computePartSummary(e){e.updateWorldMatrix(!0,!1);let t=sf(e),i=Mh(e,`mesh-${e.id}`),r=nf(e.userData,{name:i,path:this.rootObject?oM(this.rootObject,e):i});return Ih({name:d3(r,i),triangleCount:JS(e),vertexCount:eT(e),materialName:tT(ga(e.material)[0]),boundingSize:Wr(t),center:fn(t),source:r.hasExplicitIdentity?"component":"mesh",meshNames:[i],childCount:1,componentId:r.componentId,occurrenceId:r.occurrenceId,partNumber:r.partNumber,componentPath:r.componentPath})}computeComponentPartSummaries(e,t){let i=new Set(t),r=[],s=new Set,a=[];return e.updateWorldMatrix(!0,!0),e.traverse(o=>{if(o===e||Bu(o))return;let l=[];if(o.traverse(f=>{Bu(f)&&i.has(f)&&l.push(f)}),l.length<2||l.length===t.length){let f=nf(o.userData,{name:Mh(o,`component-${o.id}`),path:oM(e,o)});if(!f.hasExplicitIdentity||l.length<1||l.length===t.length)return;a.push({object:o,childMeshes:l,identity:f});return}let c=nf(o.userData,{name:Mh(o,`group-${o.id}`),path:oM(e,o)});!c.hasExplicitIdentity&&!o.name.trim()||a.push({object:o,childMeshes:l,identity:c})}),a.sort((o,l)=>o.childMeshes.length-l.childMeshes.length).forEach(({object:o,childMeshes:l,identity:c})=>{let f=l.filter(p=>!s.has(p));if(f.length<1||!c.hasExplicitIdentity&&f.length<2)return;for(let p of f)s.add(p);let h=new Sr;for(let p of f)p.updateWorldMatrix(!0,!1),h.union(new Sr().setFromObject(p));let d=new Set,u=0,m=0;for(let p of f){u+=JS(p),m+=eT(p);for(let _ of ga(p.material)){let g=tT(_);g&&d.add(g)}}r.push(Ih({name:d3(c,Mh(o,`group-${o.id}`)),triangleCount:u,vertexCount:m,materialName:d.size===0?null:d.size===1?Array.from(d)[0]:`${d.size} materials`,boundingSize:Wr({min:Ht(h.min),max:Ht(h.max)}),center:fn({min:Ht(h.min),max:Ht(h.max)}),source:c.hasExplicitIdentity?"component":"group",meshNames:f.map(p=>Mh(p,`mesh-${p.id}`)),childCount:f.length,componentId:c.componentId,occurrenceId:c.occurrenceId,partNumber:c.partNumber,componentPath:c.componentPath}))}),{parts:r,groupedMeshes:s}}computeSummary(e){let t=this.getRenderableMeshes(e);return GS({rootName:e.name||"__root__",boundingSize:Wr(sf(e)),meshes:t.map(i=>({triangleCount:JS(i),vertexCount:eT(i),materialKeys:ga(i.material).map(r=>r.uuid)})),resourceWarnings:this.resourceWarnings})}}});var lre,lM,cM,ie,hi=C(()=>{lre=typeof WeakRef!="undefined",lM=class{constructor(e,t=!1,i,r){this.initialize(e,t,i,r)}initialize(e,t=!1,i,r){return this.mask=e,this.skipNextObservers=t,this.target=i,this.currentTarget=r,this}},cM=class{constructor(e,t,i=null){this.callback=e,this.mask=t,this.scope=i,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1,this._remove=null}remove(e=!1){this._remove&&this._remove(e)}},ie=class n{static FromPromise(e,t){let i=new n;return e.then(r=>{i.notifyObservers(r)}).catch(r=>{if(t)t.notifyObservers(r);else throw r}),i}get observers(){return this._observers}constructor(e,t=!1){this.notifyIfTriggered=t,this._observers=new Array,this._numObserversMarkedAsDeleted=0,this._hasNotified=!1,this._eventState=new lM(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,r=null,s=!1){if(!e)return null;let a=new cM(e,t,r);a.unregisterOnNextCall=s,i?this._observers.unshift(a):this._observers.push(a),this._onObserverAdded&&this._onObserverAdded(a),this._hasNotified&&this.notifyIfTriggered&&this._lastNotifiedValue!==void 0&&this.notifyObserver(a,this._lastNotifiedValue);let o=lre?new WeakRef(this):{deref:()=>this};return a._remove=(l=!1)=>{let c=o.deref();c&&(l?c.remove(a):c._remove(a))},a}addOnce(e){return this.add(e,void 0,void 0,void 0,!0)}remove(e){return e?(e._remove=null,this._observers.indexOf(e)!==-1?(this._deferUnregister(e),!0):!1):!1}removeCallback(e,t){for(let i=0;i{this._remove(e)},0))}_remove(e,t=!0){if(!e)return!1;let i=this._observers.indexOf(e);return i!==-1?(t&&this._numObserversMarkedAsDeleted--,this._observers.splice(i,1),!0):!1}makeObserverTopPriority(e){this._remove(e,!1),this._observers.unshift(e)}makeObserverBottomPriority(e){this._remove(e,!1),this._observers.push(e)}notifyObservers(e,t=-1,i,r,s){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=e),!this._observers.length)return!0;let a=this._eventState;a.mask=t,a.target=i,a.currentTarget=r,a.skipNextObservers=!1,a.lastReturnValue=e,a.userInfo=s;for(let o of this._observers)if(!o._willBeUnregistered&&(o.mask&t&&(o.unregisterOnNextCall&&this._deferUnregister(o),o.scope?a.lastReturnValue=o.callback.apply(o.scope,[e,a]):a.lastReturnValue=o.callback(e,a)),a.skipNextObservers))return!1;return!0}notifyObserver(e,t,i=-1){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=t),e._willBeUnregistered)return;let r=this._eventState;r.mask=i,r.skipNextObservers=!1,e.unregisterOnNextCall&&this._deferUnregister(e),e.callback(t,r)}hasObservers(){return this._observers.length-this._numObserversMarkedAsDeleted>0}clear(){for(;this._observers.length;){let e=this._observers.pop();e&&(e._remove=null)}this._onObserverAdded=null,this._numObserversMarkedAsDeleted=0,this.cleanLastNotifiedState()}cleanLastNotifiedState(){this._hasNotified=!1,this._lastNotifiedValue=void 0}clone(){let e=new n;return e._observers=this._observers.slice(0),e}hasSpecificMask(e=-1){for(let t of this._observers)if(t.mask&e||t.mask===e)return!0;return!1}}});var rT,_3=C(()=>{rT=class{get wrapU(){return this._cachedWrapU}set wrapU(e){this._cachedWrapU=e}get wrapV(){return this._cachedWrapV}set wrapV(e){this._cachedWrapV=e}get wrapR(){return this._cachedWrapR}set wrapR(e){this._cachedWrapR=e}get anisotropicFilteringLevel(){return this._cachedAnisotropicFilteringLevel}set anisotropicFilteringLevel(e){this._cachedAnisotropicFilteringLevel=e}get comparisonFunction(){return this._comparisonFunction}set comparisonFunction(e){this._comparisonFunction=e}get useMipMaps(){return this._useMipMaps}set useMipMaps(e){this._useMipMaps=e}constructor(){this.samplingMode=-1,this._useMipMaps=!0,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this._comparisonFunction=0}setParameters(e=1,t=1,i=1,r=1,s=2,a=0){return this._cachedWrapU=e,this._cachedWrapV=t,this._cachedWrapR=i,this._cachedAnisotropicFilteringLevel=r,this.samplingMode=s,this._comparisonFunction=a,this}compareSampler(e){return this._cachedWrapU===e._cachedWrapU&&this._cachedWrapV===e._cachedWrapV&&this._cachedWrapR===e._cachedWrapR&&this._cachedAnisotropicFilteringLevel===e._cachedAnisotropicFilteringLevel&&this.samplingMode===e.samplingMode&&this._comparisonFunction===e._comparisonFunction&&this._useMipMaps===e._useMipMaps}}});var g3,yi,Es=C(()=>{hi();_3();(function(n){n[n.Unknown=0]="Unknown",n[n.Url=1]="Url",n[n.Temp=2]="Temp",n[n.Raw=3]="Raw",n[n.Dynamic=4]="Dynamic",n[n.RenderTarget=5]="RenderTarget",n[n.MultiRenderTarget=6]="MultiRenderTarget",n[n.Cube=7]="Cube",n[n.CubeRaw=8]="CubeRaw",n[n.CubePrefiltered=9]="CubePrefiltered",n[n.Raw3D=10]="Raw3D",n[n.Raw2DArray=11]="Raw2DArray",n[n.DepthStencil=12]="DepthStencil",n[n.CubeRawRGBD=13]="CubeRawRGBD",n[n.Depth=14]="Depth"})(g3||(g3={}));yi=class n extends rT{get useMipMaps(){return this._useMipMaps===null?this.generateMipMaps:this._useMipMaps}set useMipMaps(e){this._useMipMaps=e}get uniqueId(){return this._uniqueId}_setUniqueId(e){this._uniqueId=e}getEngine(){return this._engine}get source(){return this._source}constructor(e,t,i=!1){super(),this.isReady=!1,this.isCube=!1,this.is3D=!1,this.is2DArray=!1,this.isMultiview=!1,this.url="",this.generateMipMaps=!1,this._useMipMaps=null,this.mipLevelCount=1,this.samples=0,this.type=-1,this.format=-1,this.onLoadedObservable=new ie,this.onErrorObservable=new ie,this.onRebuildCallback=null,this.width=0,this.height=0,this.depth=0,this.baseWidth=0,this.baseHeight=0,this.baseDepth=0,this.invertY=!1,this._invertVScale=!1,this._associatedChannel=-1,this._source=0,this._buffer=null,this._bufferView=null,this._bufferViewArray=null,this._bufferViewArrayArray=null,this._size=0,this._extension="",this._files=null,this._workingCanvas=null,this._workingContext=null,this._cachedCoordinatesMode=null,this._isDisabled=!1,this._compression=null,this._sphericalPolynomial=null,this._sphericalPolynomialPromise=null,this._sphericalPolynomialComputed=!1,this._lodGenerationScale=0,this._lodGenerationOffset=0,this._useSRGBBuffer=!1,this._creationFlags=0,this._lodTextureHigh=null,this._lodTextureMid=null,this._lodTextureLow=null,this._isRGBD=!1,this._linearSpecularLOD=!1,this._irradianceTexture=null,this._hardwareTexture=null,this._maxLodLevel=null,this._references=1,this._gammaSpace=null,this._premulAlpha=!1,this._dynamicTextureSource=null,this._autoMSAAManagement=!1,this._engine=e,this._source=t,this._uniqueId=n._Counter++,i||(this._hardwareTexture=e._createHardwareTexture())}incrementReferences(){this._references++}updateSize(e,t,i=1){this._engine.updateTextureDimensions(this,e,t,i),this.width=e,this.height=t,this.depth=i,this.baseWidth=e,this.baseHeight=t,this.baseDepth=i,this._size=e*t*i}_rebuild(){var t,i;if(this.isReady=!1,this._cachedCoordinatesMode=null,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this.onRebuildCallback){let r=this.onRebuildCallback(this),s=a=>{a._swapAndDie(this,!1),this.isReady=r.isReady};r.isAsync?r.proxy.then(s):s(r.proxy);return}let e;switch(this.source){case 2:break;case 1:e=this._engine.createTexture((t=this._originalUrl)!=null?t:this.url,!this.generateMipMaps,this.invertY,null,this.samplingMode,r=>{r._swapAndDie(this,!1),this.isReady=!0},null,this._buffer,void 0,this.format,this._extension,void 0,void 0,void 0,this._useSRGBBuffer);return;case 3:if(e=this._engine.createRawTexture(this._bufferView,this.baseWidth,this.baseHeight,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type,this._creationFlags,this._useSRGBBuffer,this.mipLevelCount),e._swapAndDie(this,!1),this._bufferViewArray)for(let r=0;r{e._swapAndDie(this,!1),this.isReady=!0},null,this.format,this._extension,!1,0,0,null,void 0,this._useSRGBBuffer,ArrayBuffer.isView(this._buffer)?this._buffer:null);return;case 8:e=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,(i=this._originalFormat)!=null?i:this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression),e._swapAndDie(this,!1),this.isReady=!0;break;case 13:return;case 9:e=this._engine.createPrefilteredCubeTexture(this.url,null,this._lodGenerationScale,this._lodGenerationOffset,r=>{r&&r._swapAndDie(this,!1),this.isReady=!0},null,this.format,this._extension),e._sphericalPolynomial=this._sphericalPolynomial;return;case 12:case 14:break}}_swapAndDie(e,t=!0){var s;(s=this._hardwareTexture)==null||s.setUsage(e._source,this.generateMipMaps,this.is2DArray,this.isCube,this.is3D,this.width,this.height,this.depth),e._hardwareTexture=this._hardwareTexture,t&&(e._isRGBD=this._isRGBD),this._lodTextureHigh&&(e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureHigh=this._lodTextureHigh),this._lodTextureMid&&(e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureMid=this._lodTextureMid),this._lodTextureLow&&(e._lodTextureLow&&e._lodTextureLow.dispose(),e._lodTextureLow=this._lodTextureLow),this._irradianceTexture&&(e._irradianceTexture&&e._irradianceTexture.dispose(),e._irradianceTexture=this._irradianceTexture);let i=this._engine.getLoadedTexturesCache(),r=i.indexOf(this);r!==-1&&i.splice(r,1),r=i.indexOf(e),r===-1&&i.push(e)}dispose(){this._references--,this._references===0&&(this.onLoadedObservable.clear(),this.onErrorObservable.clear(),this._engine._releaseTexture(this),this._hardwareTexture=null,this._dynamicTextureSource=null)}};yi._Counter=0});var Le,Pi=C(()=>{hi();Le=class{static get LastCreatedEngine(){return this.Instances.length===0?null:this.Instances[this.Instances.length-1]}static get LastCreatedScene(){return this._LastCreatedScene}};Le.Instances=[];Le.OnEnginesDisposedObservable=new ie;Le._LastCreatedScene=null;Le.UseFallbackTexture=!0;Le.FallbackTexture=""});var te,yt=C(()=>{te=class n{static _CheckLimit(e,t){let i=n._LogLimitOutputs[e];return i?i.current++:(i={limit:t,current:1},n._LogLimitOutputs[e]=i),i.current<=i.limit}static _GenerateLimitMessage(e,t=1){var s;let i=n._LogLimitOutputs[e];if(!i||!n.MessageLimitReached)return;let r=this._Levels[t];i.current===i.limit&&n[r.name](n.MessageLimitReached.replace(/%LIMIT%/g,""+i.limit).replace(/%TYPE%/g,(s=r.name)!=null?s:""))}static _AddLogEntry(e){n._LogCache=e+n._LogCache,n.OnNewCacheEntry&&n.OnNewCacheEntry(e)}static _FormatMessage(e){let t=r=>r<10?"0"+r:""+r,i=new Date;return"["+t(i.getHours())+":"+t(i.getMinutes())+":"+t(i.getSeconds())+"]: "+e}static _LogDisabled(e,t){}static _LogEnabled(e=1,t,i){let r=Array.isArray(t)?t[0]:t;if(i!==void 0&&!n._CheckLimit(r,i))return;let s=n._FormatMessage(r),a=this._Levels[e],o=Array.isArray(t)?t.slice(1):[];a.logFunc&&a.logFunc("BJS - "+s,...o);let l=`
${s}

`;n._AddLogEntry(l),n._GenerateLimitMessage(r,e)}static get LogCache(){return n._LogCache}static ClearLogCache(){n._LogCache="",n._LogLimitOutputs={},n.errorsCount=0}static set LogLevels(e){n.Log=n._LogDisabled,n.Warn=n._LogDisabled,n.Error=n._LogDisabled;let t=[n.MessageLogLevel,n.WarningLogLevel,n.ErrorLogLevel];for(let i of t)if((e&i)===i){let r=this._Levels[i];n[r.name]=n._LogEnabled.bind(n,i)}}};te.NoneLogLevel=0;te.MessageLogLevel=1;te.WarningLogLevel=2;te.ErrorLogLevel=4;te.AllLogLevel=7;te.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.";te._LogCache="";te._LogLimitOutputs={};te._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}];te.errorsCount=0;te.Log=te._LogEnabled.bind(te,te.MessageLogLevel);te.Warn=te._LogEnabled.bind(te,te.WarningLogLevel);te.Error=te._LogEnabled.bind(te,te.ErrorLogLevel)});var T,W=C(()=>{T=class n{static GetShadersRepository(e=0){return e===0?n.ShadersRepository:n.ShadersRepositoryWGSL}static GetShadersStore(e=0){return e===0?n.ShadersStore:n.ShadersStoreWGSL}static GetIncludesShadersStore(e=0){return e===0?n.IncludesShadersStore:n.IncludesShadersStoreWGSL}};T.ShadersRepository="src/Shaders/";T.ShadersStore={};T.IncludesShadersStore={};T.ShadersRepositoryWGSL="src/ShadersWGSL/";T.ShadersStoreWGSL={};T.IncludesShadersStoreWGSL={}});function cr(){return typeof window!="undefined"}function wl(){return typeof navigator!="undefined"}function af(){return typeof document!="undefined"}function nT(n){let e="",t=n.firstChild;for(;t;)t.nodeType===3&&(e+=t.textContent),t=t.nextSibling;return e}var va=C(()=>{});var sT,v3=C(()=>{sT=class{constructor(){this._valueCache={},this.vertexCompilationError=null,this.fragmentCompilationError=null,this.programLinkError=null,this.programValidationError=null,this._isDisposed=!1}get isAsync(){return this.isParallelCompiled}get isReady(){return this.program?this.isParallelCompiled?this.engine._isRenderingStateCompiled(this):!0:!1}_handlesSpectorRebuildCallback(e){e&&this.program&&e(this.program)}setEngine(e){this.engine=e}_fillEffectInformation(e,t,i,r,s,a,o,l){let c=this.engine;if(c.supportsUniformBuffers)for(let d in t)e.bindUniformBlock(d,t[d]);this.engine.getUniforms(this,i).forEach((d,u)=>{r[i[u]]=d}),this._uniforms=r;let h;for(h=0;h{a[d]=u});for(let d of c.getAttributes(this,o))l.push(d)}dispose(){this._uniforms={},this._isDisposed=!0}_cacheMatrix(e,t){let i=this._valueCache[e],r=t.updateFlag;return i!==void 0&&i===r?!1:(this._valueCache[e]=r,!0)}_cacheFloat2(e,t,i){let r=this._valueCache[e];if(!r||r.length!==2)return r=[t,i],this._valueCache[e]=r,!0;let s=!1;return r[0]!==t&&(r[0]=t,s=!0),r[1]!==i&&(r[1]=i,s=!0),s}_cacheFloat3(e,t,i,r){let s=this._valueCache[e];if(!s||s.length!==3)return s=[t,i,r],this._valueCache[e]=s,!0;let a=!1;return s[0]!==t&&(s[0]=t,a=!0),s[1]!==i&&(s[1]=i,a=!0),s[2]!==r&&(s[2]=r,a=!0),a}_cacheFloat4(e,t,i,r,s){let a=this._valueCache[e];if(!a||a.length!==4)return a=[t,i,r,s],this._valueCache[e]=a,!0;let o=!1;return a[0]!==t&&(a[0]=t,o=!0),a[1]!==i&&(a[1]=i,o=!0),a[2]!==r&&(a[2]=r,o=!0),a[3]!==s&&(a[3]=s,o=!0),o}setInt(e,t){let i=this._valueCache[e];i!==void 0&&i===t||this.engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this.engine.setInt3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))}setInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&(this.engine.setInt4(this._uniforms[e],t,i,r,s)||(this._valueCache[e]=null))}setIntArray(e,t){this._valueCache[e]=null,this.engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this.engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this.engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this.engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){let i=this._valueCache[e];i!==void 0&&i===t||this.engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setUInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setUInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this.engine.setUInt3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))}setUInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&(this.engine.setUInt4(this._uniforms[e],t,i,r,s)||(this._valueCache[e]=null))}setUIntArray(e,t){this._valueCache[e]=null,this.engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this.engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this.engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this.engine.setUIntArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this.engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this.engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this.engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this.engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this.engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&(this.engine.setMatrices(this._uniforms[e],t.asArray())||(this._valueCache[e]=null))}setMatrix3x3(e,t){this._valueCache[e]=null,this.engine.setMatrix3x3(this._uniforms[e],t)}setMatrix2x2(e,t){this._valueCache[e]=null,this.engine.setMatrix2x2(this._uniforms[e],t)}setFloat(e,t){let i=this._valueCache[e];i!==void 0&&i===t||this.engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&(this.engine.setFloat2(this._uniforms[e],t.x,t.y)||(this._valueCache[e]=null))}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setFloat2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&(this.engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)||(this._valueCache[e]=null))}setFloat3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this.engine.setFloat3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setFloat4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&(this.engine.setFloat4(this._uniforms[e],t,i,r,s)||(this._valueCache[e]=null))}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this.engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(this._valueCache[e]=null))}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))}_getVertexShaderCode(){return this.vertexShader?this.engine._getShaderSource(this.vertexShader):null}_getFragmentShaderCode(){return this.fragmentShader?this.engine._getShaderSource(this.fragmentShader):null}}});function Ze(n,e=!1){if(!(e&&E3[n]))return E3[n]=!0,`${n} needs to be imported before as it contains a side-effect required by your code.`}var E3,hn=C(()=>{E3={}});function aT(n,e,t=""){return t+(e?e+` -`:"")+n}function oT(n,e,t,i,r,s,a){let o=a||Uu.loadFile;if(o)return o(n,e,t,i,r,s);throw Ze("FileTools")}function lT(n,e,t,i){if(n){e?n.IS_NDC_HALF_ZRANGE="":delete n.IS_NDC_HALF_ZRANGE,t?n.USE_REVERSE_DEPTHBUFFER="":delete n.USE_REVERSE_DEPTHBUFFER,i?n.USE_EXACT_SRGB_CONVERSIONS="":delete n.USE_EXACT_SRGB_CONVERSIONS;return}else{let r="";return e&&(r+="#define IS_NDC_HALF_ZRANGE"),t&&(r&&(r+=` +`),r=[];for(let o=0,l=i.length;o=7?(PS.setRGB(parseFloat(h[4]),parseFloat(h[5]),parseFloat(h[6]),Fi),t.colors.push(PS.r,PS.g,PS.b)):t.colors.push(void 0,void 0,void 0);break;case"vn":t.normals.push(parseFloat(h[1]),parseFloat(h[2]),parseFloat(h[3]));break;case"vt":t.uvs.push(parseFloat(h[1]),parseFloat(h[2]));break}}else if(f==="f"){let d=c.slice(1).trim().split(R1),u=[];for(let p=0,_=d.length;p<_;p++){let g=d[p];if(g.length>0){let v=g.split("/");u.push(v)}}let m=u[0];for(let p=1,_=u.length-1;p<_;p++){let g=u[p],v=u[p+1];t.addFace(m[0],g[0],v[0],m[1],g[1],v[1],m[2],g[2],v[2])}}else if(f==="l"){let h=c.substring(1).trim().split(" "),d=[],u=[];if(c.indexOf("/")===-1)d=h;else for(let m=0,p=h.length;m1){let d=r[1].trim().toLowerCase();t.object.smooth=d!=="0"&&d!=="off"}else t.object.smooth=!0;let h=t.object.currentMaterial();h&&(h.smooth=t.object.smooth)}else{if(c==="\0")continue;console.warn('THREE.OBJLoader: Unexpected line: "'+c+'"')}}t.finalize();let s=new Us;if(s.materialLibraries=[].concat(t.materialLibraries),!(t.objects.length===1&&t.objects[0].geometry.vertices.length===0)===!0)for(let o=0,l=t.objects.length;o0&&p.setAttribute("normal",new fi(f.normals,3)),f.colors.length>0&&(m=!0,p.setAttribute("color",new fi(f.colors,3))),f.hasUVIndices===!0&&p.setAttribute("uv",new fi(f.uvs,2));let _=[];for(let v=0,x=h.length;v1){for(let v=0,x=h.length;v0){let o=new hs({size:1,sizeAttenuation:!1}),l=new Vi;l.setAttribute("position",new fi(t.vertices,3)),t.colors.length>0&&t.colors[0]!==void 0&&(l.setAttribute("color",new fi(t.colors,3)),o.vertexColors=!0);let c=new da(l,o);s.add(c)}return s}}});var gs,LS,AI,y1=C(()=>{Xs();gs=new ft,LS=class extends cn{constructor(e){super(e),this.propertyNameMapping={},this.customPropertyMapping={}}load(e,t,i,r){let s=this,a=new ms(this.manager);a.setPath(this.path),a.setResponseType("arraybuffer"),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(o){try{t(s.parse(o))}catch(l){r?r(l):console.error(l),s.manager.itemError(e)}},i,r)}setPropertyNameMapping(e){this.propertyNameMapping=e}setCustomPropertyNameMapping(e){this.customPropertyMapping=e}parse(e){function t(_,g=0){let v=/^ply([\s\S]*)end_header(\r\n|\r|\n)/,x="",A=v.exec(_);A!==null&&(x=A[1]);let S={comments:[],elements:[],headerLength:g,objInfo:""},E=x.split(/\r\n|\r|\n/),R;function I(y,M){let D={type:y[0]};return D.type==="list"?(D.name=y[3],D.countType=y[1],D.itemType=y[2]):D.name=y[1],D.name in M&&(D.name=M[D.name]),D}for(let y=0;yx.name);function v(x){for(let A=0,S=x.length;A0&&g.setIndex(_.indices),g.setAttribute("position",new fi(_.vertices,3)),_.normals.length>0&&g.setAttribute("normal",new fi(_.normals,3)),_.uvs.length>0&&g.setAttribute("uv",new fi(_.uvs,2)),_.colors.length>0&&g.setAttribute("color",new fi(_.colors,3)),(_.faceVertexUvs.length>0||_.faceVertexColors.length>0)&&(g=g.toNonIndexed(),_.faceVertexUvs.length>0&&g.setAttribute("uv",new fi(_.faceVertexUvs,2)),_.faceVertexColors.length>0&&g.setAttribute("color",new fi(_.faceVertexColors,3)));for(let v of Object.keys(p.customPropertyMapping))_[v].length>0&&g.setAttribute(v,new fi(_[v],p.customPropertyMapping[v].length));return g.computeBoundingSphere(),g}function c(_,g,v,x){if(g==="vertex"){_.vertices.push(v[x.attrX],v[x.attrY],v[x.attrZ]),x.attrNX!==null&&x.attrNY!==null&&x.attrNZ!==null&&_.normals.push(v[x.attrNX],v[x.attrNY],v[x.attrNZ]),x.attrS!==null&&x.attrT!==null&&_.uvs.push(v[x.attrS],v[x.attrT]),x.attrR!==null&&x.attrG!==null&&x.attrB!==null&&(gs.setRGB(v[x.attrR]/255,v[x.attrG]/255,v[x.attrB]/255,Fi),_.colors.push(gs.r,gs.g,gs.b));for(let A of Object.keys(p.customPropertyMapping))for(let S of p.customPropertyMapping[A])_[A].push(v[S])}else if(g==="face"){let A=v.vertex_indices||v.vertex_index,S=v.texcoord;A.length===3?(_.indices.push(A[0],A[1],A[2]),S&&S.length===6&&(_.faceVertexUvs.push(S[0],S[1]),_.faceVertexUvs.push(S[2],S[3]),_.faceVertexUvs.push(S[4],S[5]))):A.length===4&&(_.indices.push(A[0],A[1],A[3]),_.indices.push(A[1],A[2],A[3])),x.attrR!==null&&x.attrG!==null&&x.attrB!==null&&(gs.setRGB(v[x.attrR]/255,v[x.attrG]/255,v[x.attrB]/255,Fi),_.faceVertexColors.push(gs.r,gs.g,gs.b),_.faceVertexColors.push(gs.r,gs.g,gs.b),_.faceVertexColors.push(gs.r,gs.g,gs.b))}}function f(_,g){let v={},x=0;for(let A=0;AA.getInt8(R),size:1};case"uint8":case"uchar":return{read:R=>A.getUint8(R),size:1};case"int16":case"short":return{read:R=>A.getInt16(R,E),size:2};case"uint16":case"ushort":return{read:R=>A.getUint16(R,E),size:2};case"int32":case"int":return{read:R=>A.getInt32(R,E),size:4};case"uint32":case"uint":return{read:R=>A.getUint32(R,E),size:4};case"float32":case"float":return{read:R=>A.getFloat32(R,E),size:4};case"float64":case"double":return{read:R=>A.getFloat64(R,E),size:8}}}for(let A=0,S=_.length;A=this.arr.length}next(){return this.arr[this.i++]}}});var OS,P1=C(()=>{Xs();OS=class extends cn{constructor(e){super(e)}load(e,t,i,r){let s=this,a=new ms(this.manager);a.setPath(this.path),a.setResponseType("arraybuffer"),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(o){try{t(s.parse(o))}catch(l){r?r(l):console.error(l),s.manager.itemError(e)}},i,r)}parse(e){function t(c){let f=new DataView(c),h=32/8*3+32/8*3*3+16/8,d=f.getUint32(80,!0);if(80+32/8+d*h===f.byteLength)return!0;let m=[115,111,108,105,100];for(let p=0;p<5;p++)if(i(m,f,p))return!1;return!0}function i(c,f,h){for(let d=0,u=c.length;d>5&31)/31,m=(U>>10&31)/31):(d=g,u=v,m=x)}for(let U=1;U<=3;U++){let G=O+U*12,ee=D*3*3+(U-1)*3;I[ee]=f.getFloat32(G,!0),I[ee+1]=f.getFloat32(G+4,!0),I[ee+2]=f.getFloat32(G+8,!0),y[ee]=V,y[ee+1]=N,y[ee+2]=F,p&&(M.setRGB(d,u,m,Fi),_[ee]=M.r,_[ee+1]=M.g,_[ee+2]=M.b)}}return R.setAttribute("position",new lr(I,3)),R.setAttribute("normal",new lr(y,3)),p&&(R.setAttribute("color",new lr(_,3)),R.hasColors=!0,R.alpha=A),R}function s(c){let f=new Vi,h=/solid([\s\S]*?)endsolid/g,d=/facet([\s\S]*?)endfacet/g,u=/solid\s(.+)/,m=0,p=/[\s]+([+-]?(?:\d*)(?:\.\d*)?(?:[eE][+-]?\d+)?)/.source,_=new RegExp("vertex"+p+p+p,"g"),g=new RegExp("normal"+p+p+p,"g"),v=[],x=[],A=[],S=new ne,E,R=0,I=0,y=0;for(;(E=h.exec(c))!==null;){I=y;let M=E[0],D=(E=u.exec(M))!==null?E[1]:"";for(A.push(D);(E=d.exec(M))!==null;){let N=0,F=0,U=E[0];for(;(E=g.exec(U))!==null;)S.x=parseFloat(E[1]),S.y=parseFloat(E[2]),S.z=parseFloat(E[3]),F++;for(;(E=_.exec(U))!==null;)v.push(parseFloat(E[1]),parseFloat(E[2]),parseFloat(E[3])),x.push(S.x,S.y,S.z),N++,y++;F!==1&&console.error("THREE.STLLoader: Something isn't right with the normal of face number "+m),N!==3&&console.error("THREE.STLLoader: Something isn't right with the vertices of face number "+m),m++}let O=I,V=y-I;f.userData.groupNames=A,f.addGroup(O,V,R),R++}return f.setAttribute("position",new fi(v,3)),f.setAttribute("normal",new fi(x,3)),f}function a(c){return typeof c!="string"?new TextDecoder().decode(c):c}function o(c){if(typeof c=="string"){let f=new Uint8Array(c.length);for(let h=0;h{Xs()});function L1(n){let e=new Map,t=new Map,i=n.clone();return O1(n,i,function(r,s){e.set(s,r),t.set(r,s)}),i.traverse(function(r){if(!r.isSkinnedMesh)return;let s=r,a=e.get(r),o=a.skeleton.bones;s.skeleton=a.skeleton.clone(),s.bindMatrix.copy(a.bindMatrix),s.skeleton.bones=o.map(function(l){return t.get(l)}),s.bind(s.skeleton,s.bindMatrix)}),i}function O1(n,e,t){t(n,e);for(let i=0;i{});function uie(){let n={};return{get:function(e){return n[e]},add:function(e,t){n[e]=t},remove:function(e){delete n[e]},removeAll:function(){n={}}}}function Nr(n,e,t){let i=n.json.materials[e];return i.extensions&&i.extensions[t]?i.extensions[t]:null}function _ie(n){return n.DefaultMaterial===void 0&&(n.DefaultMaterial=new Cn({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:Vs})),n.DefaultMaterial}function bh(n,e,t){for(let i in t.extensions)n[i]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[i]=t.extensions[i])}function Xo(n,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(n.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function gie(n,e,t){let i=!1,r=!1,s=!1;for(let c=0,f=e.length;c0||n.search(/^data\:image\/jpeg/)===0?"image/jpeg":n.search(/\.webp($|\?)/i)>0||n.search(/^data\:image\/webp/)===0?"image/webp":n.search(/\.ktx2($|\?)/i)>0||n.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}function Aie(n,e,t){let i=e.attributes,r=new Sr;if(i.POSITION!==void 0){let o=t.json.accessors[i.POSITION],l=o.min,c=o.max;if(l!==void 0&&c!==void 0){if(r.set(new ne(l[0],l[1],l[2]),new ne(c[0],c[1],c[2])),o.normalized){let f=ZI(Nu[o.componentType]);r.min.multiplyScalar(f),r.max.multiplyScalar(f)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;let s=e.targets;if(s!==void 0){let o=new ne,l=new ne;for(let c=0,f=s.length;c{Xs();D1();N1();NS=class extends cn{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new PI(t)}),this.register(function(t){return new DI(t)}),this.register(function(t){return new GI(t)}),this.register(function(t){return new kI(t)}),this.register(function(t){return new WI(t)}),this.register(function(t){return new OI(t)}),this.register(function(t){return new NI(t)}),this.register(function(t){return new wI(t)}),this.register(function(t){return new FI(t)}),this.register(function(t){return new yI(t)}),this.register(function(t){return new BI(t)}),this.register(function(t){return new LI(t)}),this.register(function(t){return new VI(t)}),this.register(function(t){return new UI(t)}),this.register(function(t){return new MI(t)}),this.register(function(t){return new wS(t,Ei.EXT_MESHOPT_COMPRESSION)}),this.register(function(t){return new wS(t,Ei.KHR_MESHOPT_COMPRESSION)}),this.register(function(t){return new HI(t)})}load(e,t,i,r){let s=this,a;if(this.resourcePath!=="")a=this.resourcePath;else if(this.path!==""){let c=ja.extractUrlBase(e);a=ja.resolveURL(c,this.path)}else a=ja.extractUrlBase(e);this.manager.itemStart(e);let o=function(c){r?r(c):console.error(c),s.manager.itemError(e),s.manager.itemEnd(e)},l=new ms(this.manager);l.setPath(this.path),l.setResponseType("arraybuffer"),l.setRequestHeader(this.requestHeader),l.setWithCredentials(this.withCredentials),l.load(e,function(c){try{s.parse(c,a,function(f){t(f),s.manager.itemEnd(e)},o)}catch(f){o(f)}},i,o)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,i,r){let s,a={},o={},l=new TextDecoder;if(typeof e=="string")s=JSON.parse(e);else if(e instanceof ArrayBuffer)if(l.decode(new Uint8Array(e,0,4))===V1){try{a[Ei.KHR_BINARY_GLTF]=new zI(e)}catch(h){r&&r(h);return}s=JSON.parse(a[Ei.KHR_BINARY_GLTF].content)}else s=JSON.parse(l.decode(e));else s=e;if(s.asset===void 0||s.asset.version[0]<2){r&&r(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}let c=new QI(s,{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 f=0;f=0&&o[h]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+h+'".')}}c.setExtensions(a),c.setPlugins(o),c.parse(i,r)}parseAsync(e,t){let i=this;return new Promise(function(r,s){i.parse(e,t,r,s)})}};Ei={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",KHR_MESHOPT_COMPRESSION:"KHR_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"},MI=class{constructor(e){this.parser=e,this.name=Ei.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){let e=this.parser,t=this.parser.json.nodes||[];for(let i=0,r=t.length;i=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,s.source,a)}},kI=class{constructor(e){this.parser=e,this.name=Ei.EXT_TEXTURE_WEBP}loadTexture(e){let t=this.name,i=this.parser,r=i.json,s=r.textures[e];if(!s.extensions||!s.extensions[t])return null;let a=s.extensions[t],o=r.images[a.source],l=i.textureLoader;if(o.uri){let c=i.options.manager.getHandler(o.uri);c!==null&&(l=c)}return i.loadTextureImage(e,a.source,l)}},WI=class{constructor(e){this.parser=e,this.name=Ei.EXT_TEXTURE_AVIF}loadTexture(e){let t=this.name,i=this.parser,r=i.json,s=r.textures[e];if(!s.extensions||!s.extensions[t])return null;let a=s.extensions[t],o=r.images[a.source],l=i.textureLoader;if(o.uri){let c=i.options.manager.getHandler(o.uri);c!==null&&(l=c)}return i.loadTextureImage(e,a.source,l)}},wS=class{constructor(e,t){this.name=t,this.parser=e}loadBufferView(e){let t=this.parser.json,i=t.bufferViews[e];if(i.extensions&&i.extensions[this.name]){let r=i.extensions[this.name],s=this.parser.getDependency("buffer",r.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 s.then(function(o){let l=r.byteOffset||0,c=r.byteLength||0,f=r.count,h=r.byteStride,d=new Uint8Array(o,l,c);return a.decodeGltfBufferAsync?a.decodeGltfBufferAsync(f,h,d,r.mode,r.filter).then(function(u){return u.buffer}):a.ready.then(function(){let u=new ArrayBuffer(f*h);return a.decodeGltfBuffer(new Uint8Array(u),f,h,d,r.mode,r.filter),u})})}else return null}},HI=class{constructor(e){this.name=Ei.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){let t=this.parser.json,i=t.nodes[e];if(!i.extensions||!i.extensions[this.name]||i.mesh===void 0)return null;let r=t.meshes[i.mesh];for(let c of r.primitives)if(c.mode!==pa.TRIANGLES&&c.mode!==pa.TRIANGLE_STRIP&&c.mode!==pa.TRIANGLE_FAN&&c.mode!==void 0)return null;let a=i.extensions[this.name].attributes,o=[],l={};for(let c in a)o.push(this.parser.getDependency("accessor",a[c]).then(f=>(l[c]=f,l[c])));return o.length<1?null:(o.push(this.parser.createNodeMesh(e)),Promise.all(o).then(c=>{let f=c.pop(),h=f.isGroup?f.children:[f],d=c[0].count,u=[];for(let m of h){let p=new li,_=new ne,g=new Zr,v=new ne(1,1,1),x=new _h(m.geometry,m.material,d);for(let A=0;A-1,a=s?o.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap=="undefined"||i&&r<17||s&&a<98?this.textureLoader=new Sh(this.options.manager):this.textureLoader=new o_(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new ms(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){let i=this,r=this.json,s=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){let o={scene:a[0][r.scene||0],scenes:a[0],animations:a[1],cameras:a[2],asset:r.asset,parser:i,userData:{}};return bh(s,o,r),Xo(o,r),Promise.all(i._invokeAll(function(l){return l.afterRoot&&l.afterRoot(o)})).then(function(){for(let l of o.scenes)l.updateMatrixWorld();e(o)})}).catch(t)}_markDefs(){let e=this.json.nodes||[],t=this.json.skins||[],i=this.json.meshes||[];for(let r=0,s=t.length;r{let l=this.associations.get(a);l!=null&&this.associations.set(o,l);for(let[c,f]of a.children.entries())s(f,o.children[c])};return s(i,r),r.name+="_instance_"+e.uses[t]++,r}_invokeOne(e){let t=Object.values(this.plugins);t.push(this);for(let i=0;i=2&&_.setY(y,E[R*l+1]),l>=3&&_.setZ(y,E[R*l+2]),l>=4&&_.setW(y,E[R*l+3]),l>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}_.normalized=m}return _})}loadTexture(e){let t=this.json,i=this.options,s=t.textures[e].source,a=t.images[s],o=this.textureLoader;if(a.uri){let l=i.manager.getHandler(a.uri);l!==null&&(o=l)}return this.loadTextureImage(e,s,o)}loadTextureImage(e,t,i){let r=this,s=this.json,a=s.textures[e],o=s.images[t],l=(o.uri||o.bufferView)+":"+a.sampler;if(this.textureCache[l])return this.textureCache[l];let c=this.loadImageSource(t,i).then(function(f){f.flipY=!1,f.name=a.name||o.name||"",f.name===""&&typeof o.uri=="string"&&o.uri.startsWith("data:image/")===!1&&(f.name=o.uri);let d=(s.samplers||{})[a.sampler]||{};return f.magFilter=F1[d.magFilter]||Lr,f.minFilter=F1[d.minFilter]||qa,f.wrapS=B1[d.wrapS]||Do,f.wrapT=B1[d.wrapT]||Do,f.generateMipmaps=!f.isCompressedTexture&&f.minFilter!==Dr&&f.minFilter!==Lr,r.associations.set(f,{textures:e}),f}).catch(function(){return null});return this.textureCache[l]=c,c}loadImageSource(e,t){let i=this,r=this.json,s=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(h=>h.clone());let a=r.images[e],o=self.URL||self.webkitURL,l=a.uri||"",c=!1;if(a.bufferView!==void 0)l=i.getDependency("bufferView",a.bufferView).then(function(h){c=!0;let d=new Blob([h],{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");let f=Promise.resolve(l).then(function(h){return new Promise(function(d,u){let m=d;t.isImageBitmapLoader===!0&&(m=function(p){let _=new Ar(p);_.needsUpdate=!0,d(_)}),t.load(ja.resolveURL(h,s.path),m,void 0,u)})}).then(function(h){return c===!0&&o.revokeObjectURL(l),Xo(h,a),h.userData.mimeType=a.mimeType||Sie(a.uri),h}).catch(function(h){throw console.error("THREE.GLTFLoader: Couldn't load texture",l),h});return this.sourceCache[e]=f,f}assignTexture(e,t,i,r){let s=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),s.extensions[Ei.KHR_TEXTURE_TRANSFORM]){let o=i.extensions!==void 0?i.extensions[Ei.KHR_TEXTURE_TRANSFORM]:void 0;if(o){let l=s.associations.get(a);a=s.extensions[Ei.KHR_TEXTURE_TRANSFORM].extendTexture(a,o),s.associations.set(a,l)}}return r!==void 0&&(a.colorSpace=r),e[t]=a,a})}assignFinalMaterial(e){let t=e.geometry,i=e.material,r=t.attributes.tangent===void 0,s=t.attributes.color!==void 0,a=t.attributes.normal===void 0;if(e.isPoints){let o="PointsMaterial:"+i.uuid,l=this.cache.get(o);l||(l=new hs,Or.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){let o="LineBasicMaterial:"+i.uuid,l=this.cache.get(o);l||(l=new Mn,Or.prototype.copy.call(l,i),l.color.copy(i.color),l.map=i.map,this.cache.add(o,l)),i=l}if(r||s||a){let o="ClonedMaterial:"+i.uuid+":";r&&(o+="derivative-tangents:"),s&&(o+="vertex-colors:"),a&&(o+="flat-shading:");let l=this.cache.get(o);l||(l=i.clone(),s&&(l.vertexColors=!0),a&&(l.flatShading=!0),r&&(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 Cn}loadMaterial(e){let t=this,i=this.json,r=this.extensions,s=i.materials[e],a,o={},l=s.extensions||{},c=[];if(l[Ei.KHR_MATERIALS_UNLIT]){let h=r[Ei.KHR_MATERIALS_UNLIT];a=h.getMaterialType(),c.push(h.extendParams(o,s,t))}else{let h=s.pbrMetallicRoughness||{};if(o.color=new ft(1,1,1),o.opacity=1,Array.isArray(h.baseColorFactor)){let d=h.baseColorFactor;o.color.setRGB(d[0],d[1],d[2],Kn),o.opacity=d[3]}h.baseColorTexture!==void 0&&c.push(t.assignTexture(o,"map",h.baseColorTexture,Fi)),o.metalness=h.metallicFactor!==void 0?h.metallicFactor:1,o.roughness=h.roughnessFactor!==void 0?h.roughnessFactor:1,h.metallicRoughnessTexture!==void 0&&(c.push(t.assignTexture(o,"metalnessMap",h.metallicRoughnessTexture)),c.push(t.assignTexture(o,"roughnessMap",h.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)})))}s.doubleSided===!0&&(o.side=ua);let f=s.alphaMode||bI.OPAQUE;if(f===bI.BLEND?(o.transparent=!0,o.depthWrite=!1):(o.transparent=!1,f===bI.MASK&&(o.alphaTest=s.alphaCutoff!==void 0?s.alphaCutoff:.5)),s.normalTexture!==void 0&&a!==jn&&(c.push(t.assignTexture(o,"normalMap",s.normalTexture)),o.normalScale=new It(1,1),s.normalTexture.scale!==void 0)){let h=s.normalTexture.scale;o.normalScale.set(h,h)}if(s.occlusionTexture!==void 0&&a!==jn&&(c.push(t.assignTexture(o,"aoMap",s.occlusionTexture)),s.occlusionTexture.strength!==void 0&&(o.aoMapIntensity=s.occlusionTexture.strength)),s.emissiveFactor!==void 0&&a!==jn){let h=s.emissiveFactor;o.emissive=new ft().setRGB(h[0],h[1],h[2],Kn)}return s.emissiveTexture!==void 0&&a!==jn&&c.push(t.assignTexture(o,"emissiveMap",s.emissiveTexture,Fi)),Promise.all(c).then(function(){let h=new a(o);return s.name&&(h.name=s.name),Xo(h,s),t.associations.set(h,{materials:e}),s.extensions&&bh(r,h,s),h})}createUniqueName(e){let t=Zi.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){let t=this,i=this.extensions,r=this.primitiveCache;function s(o){return i[Ei.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(o,t).then(function(l){return U1(l,o,t)})}let a=[];for(let o=0,l=e.length;o0&&vie(g,s),g.name=t.createUniqueName(s.name||"mesh_"+e),Xo(g,s),_.extensions&&bh(r,g,_),t.assignFinalMaterial(g),h.push(g)}for(let u=0,m=h.length;u0){let u=f.userData.pivot,m=h[0];f.pivot=new ne().fromArray(u),f.position.x-=u[0],f.position.y-=u[1],f.position.z-=u[2],m.position.set(0,0,0),delete f.userData.pivot}return f})}_loadNodeShallow(e){let t=this.json,i=this.extensions,r=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];let s=t.nodes[e],a=s.name?r.createUniqueName(s.name):"",o=[],l=r._invokeOne(function(c){return c.createNodeMesh&&c.createNodeMesh(e)});return l&&o.push(l),s.camera!==void 0&&o.push(r.getDependency("camera",s.camera).then(function(c){return r._getNodeRef(r.cameraCache,s.camera,c)})),r._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 f;if(s.isBone===!0?f=new pu:c.length>1?f=new Us:c.length===1?f=c[0]:f=new ir,f!==c[0])for(let h=0,d=c.length;h1){let h=r.associations.get(f);r.associations.set(f,{...h})}return r.associations.get(f).nodes=e,f}),this.nodeCache[e]}loadScene(e){let t=this.extensions,i=this.json.scenes[e],r=this,s=new Us;i.name&&(s.name=r.createUniqueName(i.name)),Xo(s,i),i.extensions&&bh(t,s,i);let a=i.nodes||[],o=[];for(let l=0,c=a.length;l{let h=new Map;for(let[d,u]of r.associations)(d instanceof Or||d instanceof Ar)&&h.set(d,u);return f.traverse(d=>{let u=r.associations.get(d);u!=null&&h.set(d,u)}),h};return r.associations=c(s),s})}_createAnimationTracks(e,t,i,r,s){let a=[],o=e.name?e.name:e.uuid,l=[];function c(u){u.morphTargetInfluences&&l.push(u.name?u.name:u.uuid)}ef[s.path]===ef.weights?(c(e),e.isGroup&&e.children.forEach(c)):l.push(o);let f;switch(ef[s.path]){case ef.weights:f=Fo;break;case ef.rotation:f=Bo;break;case ef.translation:case ef.scale:f=Uo;break;default:i.itemSize===1?f=Fo:f=Uo;break}let h=r.interpolation!==void 0?pie[r.interpolation]:dh,d=this._getArrayFromAccessor(i);for(let u=0,m=l.length;u{"use strict"});function H1(n){var t,i,r;let e=(i=(t=n.split(".").pop())==null?void 0:t.toLowerCase())!=null?i:"png";return(r=xie[e])!=null?r:`image/${e}`}function bie(n){let e=n.replace(/\s+#.*$/,"").trim();if(e.startsWith('"')){let t=e.indexOf('"',1);if(t>1)return e.slice(1,t)}return e}function Iie(n){let e=n.trim().split(/\s+/),t=e.findIndex(i=>!i.startsWith("-")&&!/^[-+]?\d*\.?\d+$/.test(i));return e.slice(Math.max(0,t)).join(" ").replace(/^"|"$/g,"")}async function W1(n,e,t){let i=Ns(e,t);try{return{data:await n(i),path:i}}catch(r){throw new Error(`Missing external model resource: ${i}`)}}function Mie(n,e,t){let i=aa(e),r=i.replace(/\.[^.]+$/,""),s=jr(t),a=[Ns(n,e),Ns(n,i)];if(s)for(let o of k1)a.push(Ns(n,`${s}.${o}`));for(let o of k1){let l=`${r}.${o}`;l!==i&&a.push(Ns(n,l))}return a}async function z1(n,e,t,i){var l,c;let r=new NS,s=[];if(e==="gltf"&&t&&i){let f=new TextDecoder().decode(new Uint8Array(n)),h=JSON.parse(f),d=Ip(i);if(h.buffers){for(let g of h.buffers)if(g.uri&&!g.uri.startsWith("data:")){let v=await W1(t,d,g.uri);g.uri=`data:application/octet-stream;base64,${Ol(v.data)}`}}if(h.images){for(let g of h.images)if(g.uri&&!g.uri.startsWith("data:")){let v=await W1(t,d,g.uri);g.uri=`data:${H1(v.path)};base64,${Ol(v.data)}`}}let u=JSON.stringify(h),m=new TextEncoder().encode(u),p=await r.parseAsync(m.buffer,d?`${d}/`:""),_=p.scene||((l=p.scenes)==null?void 0:l[0]);if(!_)throw new Error("GLTF did not contain a scene");return{scene:_,animations:p.animations,warnings:s}}let a=await r.parseAsync(n.slice(0),""),o=a.scene||((c=a.scenes)==null?void 0:c[0]);if(!o)throw new Error("GLB did not contain a scene");return{scene:o,animations:a.animations,warnings:s}}async function X1(n){let t=new OS().parse(n),i=new Cn({color:13421772}),r=new ri(t,i);return r.name=aa("")||"stl-model",r}async function Y1(n){let t=new LS().parse(n);if(t.hasAttribute("color")){if(t.index){let s=new Cn({vertexColors:!0});return new ri(t,s)}let r=new hs({size:.02,vertexColors:!0});return new da(t,r)}if(t.index){let r=new Cn({color:13421772});return new ri(t,r)}let i=new hs({size:.02,color:13421772});return new da(t,i)}async function K1(n,e,t){let i=new TextDecoder().decode(new Uint8Array(n)),r=[],s=null,a=i.match(/mtllib\s+(.+)/);if(a&&e&&t){let l=bie(a[1]),c=Ip(t),f=Ns(c,l);try{let h=await e(f),u=new TextDecoder().decode(new Uint8Array(h)).split(` +`),m=new Map;for(let x=0;xx!=="");if(!p.some(x=>/^\s*Kd\s+/i.test(x))){let x=p.findIndex(A=>/^\s*newmtl\s+/i.test(A));p.splice(x>=0?x+1:0,0,"Kd 0.80 0.80 0.80")}let v=new yS().parse(p.join(` +`),c?`${c}/`:"");v.preload(),s=v}catch(h){r.push(`OBJ material library not found: ${f}`)}}else a&&(!e||!t)&&r.push("OBJ material library could not be resolved without a model path.");let o=new DS;return s&&o.setMaterials(s),{object:o.parse(i),warnings:r}}var xie,k1,Rie,j1=C(()=>{"use strict";x1();C1();y1();P1();G1();Xs();oa();BS();xie={jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",bmp:"image/bmp",tga:"image/x-tga",webp:"image/webp",tif:"image/tiff",tiff:"image/tiff"},k1=["jpg","jpeg","png","bmp","tga","webp","tif","tiff"],Rie=/^\s*(map_Kd|map_Ka|map_Ks|map_Ns|map_d|map_bump|bump|disp|decal)\s+(.+)/i});function mr(){return q1.Platform.isMobile}var q1,Ys=C(()=>{"use strict";q1=require("obsidian")});function I_(n,e){return{min:qr(n),max:qr(e)}}function Z1(n,e){return n?{min:{x:Math.min(n.min.x,e.min.x),y:Math.min(n.min.y,e.min.y),z:Math.min(n.min.z,e.min.z)},max:{x:Math.max(n.max.x,e.max.x),y:Math.max(n.max.y,e.max.y),z:Math.max(n.max.z,e.max.z)}}:I_(e.min,e.max)}function Wr(n){return Bd(n.max,n.min)}function fn(n){return th(n.min,Mp(Wr(n),.5))}function Q1(n){return nw(n.min,n.max)}function M_(n){return Q1(n)/2}function $1(n){let e=Wr(n);return Math.max(e.x,e.y,e.z)}function $I(n){let e=Wr(n),t=Q1(n);return{center:th(n.min,Mp(e,.5)),size:e,diagonalLength:t,radius:t/2,maxSpan:Math.max(e.x,e.y,e.z)}}var tf=C(()=>{"use strict";ws()});function JI(n,e,t={}){var s,a,o,l,c;let i=Math.max(e,Number.EPSILON),r=(s=t.radiusMultiplier)!=null?s:2.5;return{target:qr(n),radius:i*r,lowerRadiusLimit:i*((a=t.lowerRadiusFactor)!=null?a:.05),upperRadiusLimit:i*((o=t.upperRadiusFactor)!=null?o:10),near:i*((l=t.nearFactor)!=null?l:.001),far:i*((c=t.farFactor)!=null?c:20)}}function US(n,e={}){let t=$I(n);return JI(t.center,t.radius,e)}function J1(n,e={}){var r,s,a,o,l,c;let t=$I(n),i=Math.max(t.maxSpan,1)*((r=e.distanceMultiplier)!=null?r:1.8);return{target:qr(t.center),position:th(t.center,{x:i,y:i*((s=e.elevationFactor)!=null?s:.65),z:i}),near:Math.max((a=e.minNear)!=null?a:.01,t.maxSpan/((o=e.nearDivisor)!=null?o:100)),far:Math.max((l=e.minFar)!=null?l:100,t.maxSpan*((c=e.farMultiplier)!=null?c:20))}}var VS=C(()=>{"use strict";tf();ws()});function cr(n){return n.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}var GS=C(()=>{"use strict"});function kS(n){var s;let e=new Set,t=0,i=0;for(let a of n.meshes){t+=a.triangleCount,i+=a.vertexCount;for(let o of(s=a.materialKeys)!=null?s:[])o!=null&&e.add(o)}let r=Cie({triangleCount:t,splatCount:n.splatCount,meshCount:n.meshes.length,materialCount:e.size});return{meshCount:n.meshes.length,triangleCount:t,splatCount:n.splatCount,vertexCount:i,materialCount:e.size,performanceTier:r,performanceHint:yie(r,{triangleCount:t,splatCount:n.splatCount,materialCount:e.size}),resourceWarnings:n.resourceWarnings?[...n.resourceWarnings]:void 0,boundingSize:qr(n.boundingSize),rootName:n.rootName}}function Cie(n){var e,t,i;return((e=n.splatCount)!=null?e:0)>=15e5||n.triangleCount>=12e5||n.materialCount>=96||n.meshCount>=240?"extreme":((t=n.splatCount)!=null?t:0)>=65e4||n.triangleCount>=45e4||n.materialCount>=48||n.meshCount>=120?"heavy":((i=n.splatCount)!=null?i:0)>=18e4||n.triangleCount>=12e4||n.materialCount>=18||n.meshCount>=48?"medium":"light"}function yie(n,e){var r;let t=((r=e.splatCount)!=null?r:e.triangleCount).toLocaleString(),i=e.splatCount!==void 0?"splats":"triangles";return n==="extreme"?`${t} ${i}, ${e.materialCount.toLocaleString()} materials. Expect automatic quality throttling while interacting.`:n==="heavy"?`${t} ${i}, ${e.materialCount.toLocaleString()} materials. Interaction may lower shadows and resolution temporarily.`:n==="medium"?`${t} ${i}, ${e.materialCount.toLocaleString()} materials. Performance should be steady on most desktop GPUs.`:`${t} ${i}, ${e.materialCount.toLocaleString()} materials. Performance tier: light.`}function Ih(n){var e;return{name:n.name,triangleCount:n.triangleCount,vertexCount:n.vertexCount,materialName:(e=n.materialName)!=null?e:null,boundingSize:qr(n.boundingSize),center:qr(n.center),source:n.source,meshNames:n.meshNames?[...n.meshNames]:void 0,childCount:n.childCount,componentId:n.componentId,occurrenceId:n.occurrenceId,partNumber:n.partNumber,componentPath:n.componentPath}}function e3(n){return n.splatCount!==void 0?"Splats":"Triangles"}function t3(n){var e;return(e=n.splatCount)!=null?e:n.triangleCount}var C_=C(()=>{"use strict";ws()});function wu(n,e="-"){if(typeof n!="string")return e;let t=n.trim();return t.length>0?t:e}function i3(n,e={}){var r,s;let t=(r=e.countLabel)!=null?r:e3(n),i=(s=e.decimals)!=null?s:3;return[`| Meshes | ${n.meshCount} |`,`| ${t} | ${t3(n).toLocaleString()} |`,`| Vertices | ${n.vertexCount.toLocaleString()} |`,`| Materials | ${n.materialCount} |`,...n.performanceTier?[`| Performance Tier | ${n.performanceTier} |`]:[],`| Bounding Size | ${eM(n.boundingSize,{decimals:i})} |`]}function WS(n){return cr(n).replace(/\|/g,"\\|").replace(/\r?\n/g," ")}function eM(n,e={}){var r,s;let t=(r=e.decimals)!=null?r:3,i=(s=e.separator)!=null?s:" x ";return`${n.x.toFixed(t)}${i}${n.y.toFixed(t)}${i}${n.z.toFixed(t)}`}function r3(n,e={}){return["| Metric | Value |","|--------|-------|",...i3(n,e)]}function Pie(n,e,t={}){return["| Property | Value |","|----------|-------|",`| Format | ${n} |`,...i3(e,t)]}function HS(n){var r,s;let e=[];e.push(`## ${n.title} - Model Info`),e.push(""),e.push(...Pie(n.format,n.summary,{countLabel:n.countLabel})),e.push("");let t=(r=n.meshBreakdown)!=null?r:[];t.length>1&&t.length<=50&&(e.push("### Mesh Breakdown"),e.push(""),e.push("| # | Name | Triangles | Vertices | Material |"),e.push("|---|------|-----------|----------|----------|"),t.forEach((a,o)=>{let l=a.triangleCount===null?"-":a.triangleCount.toLocaleString();e.push(`| ${o+1} | ${WS(wu(a.name,`mesh-${o+1}`))} | ${l} | ${a.vertexCount.toLocaleString()} | ${WS(wu(a.materialName))} |`)}),e.push(""));let i=Array.from((s=n.materialNames)!=null?s:[]).map(a=>wu(a,"")).filter(a=>a.length>0);if(i.length>0){let a=Array.from(new Set(i));e.push("### Materials"),e.push("");for(let o of a)e.push(`- ${cr(o)}`);e.push("")}return e.join(` +`)}function zS(n,e={}){var r;let t=cr(wu((r=e.title)!=null?r:n.name,"Selected Part")),i=[];return i.push(`## ${t} - Part Info`),i.push(""),i.push("| Property | Value |"),i.push("|----------|-------|"),i.push(`| Mesh | ${WS(wu(n.name))} |`),i.push(`| Triangles | ${n.triangleCount.toLocaleString()} |`),i.push(`| Vertices | ${n.vertexCount.toLocaleString()} |`),i.push(`| Material | ${WS(wu(n.materialName))} |`),i.push(`| Bounding Size | ${eM(n.boundingSize)} |`),i.push(`| Center | ${eM(n.center,{separator:", "})} |`),i.push(""),i.join(` +`)}var XS=C(()=>{"use strict";GS();C_()});function Bie(n){return!!n&&typeof n=="object"&&!Array.isArray(n)}function YS(n){return n.toLowerCase().replace(/[^a-z0-9]+/g,"")}function Uie(n){if(typeof n=="string"){let e=n.trim();return e.length>0?e:void 0}if(typeof n=="number"&&Number.isFinite(n))return String(n)}function n3(n,e=0){if(!Bie(n)||e>2)return[];let t=[];for(let i of Fie)for(let[r,s]of Object.entries(n))YS(r)===YS(i)&&t.push(...n3(s,e+1));return t.push(n),t}function y_(n,e){let t=new Set(e.map(YS));for(let i of n)for(let[r,s]of Object.entries(i)){if(!t.has(YS(r)))continue;let a=Uie(s);if(a)return a}}function rf(n,e={}){var c,f;let t=n3(n),i=y_(t,Die),r=y_(t,Lie),s=y_(t,Oie),a=(c=y_(t,wie))!=null?c:e.path,o=(f=y_(t,Nie))!=null?f:e.name;return{componentId:i,occurrenceId:r,partNumber:s,componentPath:a,displayName:o,hasExplicitIdentity:!!(i||r||s)}}var Die,Lie,Oie,Nie,wie,Fie,tM=C(()=>{"use strict";Die=["ai3dPartId","partId","componentId","componentIdentifier","cadId","persistentId","externalId","id"],Lie=["ai3dOccurrenceId","occurrenceId","instanceId","occurrencePath","assemblyPath","pathId"],Oie=["ai3dPartNumber","partNumber","partNo","partNum","swPartNumber","solidworksPartNumber","part_number"],Nie=["displayName","partName","componentName","cadName","name"],wie=["componentPath","cadPath","assemblyPath","occurrencePath"],Fie=["ai3d","cad","solidworks","sw","metadata","properties","extras","gltf","userData"]});function jS(n){return new iM(n)}var KS,iM,rM=C(()=>{"use strict";KS=class KS{constructor(e){this.originals=new Map;this.unsubscribe=null;this.active=!1;this.drag=null;this.pendingDrag=null;this.selected=null;this.activePointerId=null;this.frameCount=0;this.adapter=e;for(let t of e.getParts())this.originals.set(e.getPartId(t),e.captureTransform(t))}isEnabled(){return this.active}setEnabled(e){var t,i,r;return this.active===e?this.active:(this.active=e,this.finishDrag(),this.setSelected(null),this.activePointerId=null,e?this.unsubscribe=this.adapter.subscribe({onPointerDown:(s,a)=>this.handlePointerDown(s,a),onPointerMove:s=>this.handlePointerMove(s),onPointerUp:s=>this.handlePointerUp(s),onRender:()=>this.handleRender()}):((t=this.unsubscribe)==null||t.call(this),this.unsubscribe=null),(r=(i=this.adapter).requestRender)==null||r.call(i),this.active)}toggle(){return this.setEnabled(!this.active)}reset(){var e,t;this.finishDrag(),this.setSelected(null);for(let i of this.adapter.getParts()){if(this.adapter.isDisposed(i))continue;let r=this.originals.get(this.adapter.getPartId(i));r&&this.adapter.restoreTransform(i,r)}this.activePointerId=null,(t=(e=this.adapter).requestRender)==null||t.call(e)}dispose(){this.setEnabled(!1),this.originals.clear()}handlePointerDown(e,t){if(t.button!==0||t.isPrimary===!1)return;let i=this.adapter.resolvePart(e);if(!i){this.drag=null,this.pendingDrag=null,this.activePointerId=null,this.setSelected(null);return}this.activePointerId=t.pointerId,this.setSelected(i),this.pendingDrag={part:i,event:t,x:t.clientX,y:t.clientY}}handlePointerMove(e){if(!(this.activePointerId!==null&&e.pointerId!==this.activePointerId)){if(!this.drag&&this.pendingDrag){if(e.pointerType==="mouse"&&(e.buttons&1)===0){this.pendingDrag=null,this.activePointerId=null;return}if(Math.hypot(e.clientX-this.pendingDrag.x,e.clientY-this.pendingDrag.y){"use strict";Xs();ws();rM();s3=new ft(4890367),Vie=new ft(1722990),nM=class{constructor(e,t,i,r,s,a){this.raycaster=new Kc;this.pointer=new It;this.tempBox=new Sr;this.tempCenter=new ne;this.tempDirection=new ne;this.tempCameraForward=new ne;this.tempCameraRight=new ne;this.tempCameraUp=new ne;this.selectionHelper=null;this.lastOccluded=!1;this.selected=null;this.lastPointerDown=null;this.partPointerActive=!1;this.activePointerId=null;this.scene=e,this.camera=t,this.canvas=i,this.meshes=r,this.controls=s,this.invalidate=a}requestRender(){this.invalidate()}getParts(){return this.meshes}getPartId(e){return e.id}isDisposed(e){return!e.parent&&!this.meshes.includes(e)}captureTransform(e){return{parent:e.parent,position:e.position.clone(),quaternion:e.quaternion.clone(),scale:e.scale.clone()}}restoreTransform(e,t){t.parent&&t.parent.add(e),e.position.copy(t.position),e.quaternion.copy(t.quaternion),e.scale.copy(t.scale),e.updateMatrixWorld(!0),this.requestRender()}subscribe(e){this.canvas.classList.add("ai3d-disassembly-active");let t=s=>{var o,l;if(s.button!==0||s.isPrimary===!1)return;this.lastPointerDown={x:s.clientX,y:s.clientY};let a=this.resolvePickTarget(s);if(this.partPointerActive=!!a,this.partPointerActive){s.preventDefault(),s.stopPropagation(),this.controls.enabled=!1,this.activePointerId=s.pointerId;try{(l=(o=this.canvas).setPointerCapture)==null||l.call(o,s.pointerId)}catch(c){}}e.onPointerDown(a,s)},i=s=>{this.activePointerId!==null&&s.pointerId!==this.activePointerId||(this.partPointerActive&&(s.preventDefault(),s.stopPropagation()),e.onPointerMove(s))},r=s=>{var a,o;if(!(this.activePointerId!==null&&s.pointerId!==this.activePointerId)){if(this.partPointerActive&&(s.preventDefault(),s.stopPropagation()),this.lastPointerDown=null,e.onPointerUp(s),this.partPointerActive=!1,this.activePointerId!==null&&((o=(a=this.canvas).hasPointerCapture)!=null&&o.call(a,this.activePointerId)))try{this.canvas.releasePointerCapture(this.activePointerId)}catch(l){}this.activePointerId=null,this.controls.enabled=!0}};return this.canvas.addEventListener("pointerdown",t),window.addEventListener("pointermove",i),window.addEventListener("pointerup",r),()=>{var s,a;if(this.canvas.removeEventListener("pointerdown",t),window.removeEventListener("pointermove",i),window.removeEventListener("pointerup",r),this.canvas.classList.remove("ai3d-disassembly-active","ai3d-disassembly-dragging"),this.partPointerActive=!1,this.activePointerId!==null&&((a=(s=this.canvas).hasPointerCapture)!=null&&a.call(s,this.activePointerId)))try{this.canvas.releasePointerCapture(this.activePointerId)}catch(o){}this.activePointerId=null,this.controls.enabled=!0}}resolvePart(e){return e&&this.isMeshInSet(e)?e:null}setSelected(e){var t;(t=this.selectionHelper)==null||t.removeFromParent(),this.selectionHelper=null,this.selected=e,this.lastOccluded=!1,e&&!this.isDisposed(e)&&(this.selectionHelper=new Dl(e,s3),this.scene.add(this.selectionHelper)),this.requestRender()}beginDrag(e,t){let i=this.getPointOnDragPlane(e,t);if(!i)return null;t.preventDefault(),t.stopPropagation(),e.removeFromParent(),this.scene.add(e),this.canvas.classList.add("ai3d-disassembly-dragging");let r="move";t.shiftKey&&(r="rotate");let s=this.tempBox.setFromObject(e).getCenter(this.tempCenter).clone(),a=this.tempCameraForward;this.camera.getWorldDirection(a);let o=Ud(Ht(i),Ht(a));return o?(this.controls.enabled=!1,this.requestRender(),{mesh:e,mode:r,plane:o,startPoint:i.clone(),startPosition:e.position.clone(),startQuaternion:e.quaternion.clone(),pivot:s,pointerX:t.clientX,pointerY:t.clientY}):null}updateDrag(e,t){var s;if(t.preventDefault(),t.stopPropagation(),e.mode==="rotate"){this.updateRotation(e,t);return}let i=this.getRayPlanePoint(t,e.plane);if(!i)return;let r=i.clone().sub(e.startPoint);e.mesh.position.copy(e.startPosition).add(r),e.mesh.updateMatrixWorld(!0),(s=this.selectionHelper)==null||s.update(),this.requestRender()}endDrag(e){this.controls.enabled=!0,this.canvas.classList.remove("ai3d-disassembly-dragging"),this.requestRender()}updateSelectionOcclusion(e){let i=this.tempBox.setFromObject(e).getCenter(this.tempCenter),r=this.camera.position,s=Nc(Ht(r),Ht(i));if(!s)return;let a=this.tempDirection.set(s.direction.x,s.direction.y,s.direction.z);this.raycaster.set(r,a),this.raycaster.far=s.distance;let o=this.raycaster.intersectObjects(this.meshes,!1)[0],l=!!o&&Oc(o.distance,s.distance,s.epsilon);l!==this.lastOccluded&&(this.lastOccluded=l,this.selectionHelper&&(this.selectionHelper.material.color.set(l?Vie:s3),this.requestRender()))}isMeshInSet(e){return this.meshes.includes(e)}updateRotation(e,t){var c;let i=t.clientX-e.pointerX,r=t.clientY-e.pointerY,s=this.tempCameraForward;this.camera.getWorldDirection(s);let a=this.tempCameraUp.copy(this.camera.up).normalize(),o=this.tempCameraRight.crossVectors(a,s).normalize(),l=vv({startPosition:Ht(e.startPosition),pivot:Ht(e.pivot),startRotationQuaternion:gv(e.startQuaternion),yawAxis:Ht(a),pitchAxis:Ht(o),deltaX:i,deltaY:r,sensitivity:.01});l&&(e.mesh.position.set(l.position.x,l.position.y,l.position.z),e.mesh.quaternion.set(l.rotationQuaternion.x,l.rotationQuaternion.y,l.rotationQuaternion.z,l.rotationQuaternion.w),e.mesh.updateMatrixWorld(!0),(c=this.selectionHelper)==null||c.update(),this.requestRender())}resolvePickTarget(e){let t=this.canvas.getBoundingClientRect();this.pointer.x=(e.clientX-t.left)/t.width*2-1,this.pointer.y=-((e.clientY-t.top)/t.height)*2+1,this.raycaster.setFromCamera(this.pointer,this.camera);let i=this.raycaster.intersectObjects(this.meshes,!1)[0];return(i==null?void 0:i.object)instanceof ri?i.object:null}getPointOnDragPlane(e,t){var o;let r=this.tempBox.setFromObject(e).getCenter(this.tempCenter),s=this.tempCameraForward;this.camera.getWorldDirection(s);let a=Ud(Ht(r),Ht(s));return a&&(o=this.getRayPlanePoint(t,a))!=null?o:r}getRayPlanePoint(e,t){let i=this.canvas.getBoundingClientRect(),r=e.clientX-i.left,s=e.clientY-i.top;this.pointer.set(r/i.width*2-1,-(s/i.height)*2+1),this.raycaster.setFromCamera(this.pointer,this.camera);let a=_v({origin:Ht(this.raycaster.ray.origin),direction:Ht(this.raycaster.ray.direction)},t);return a?new ne(a.x,a.y,a.z):null}}});function l3(n){return qr(n)}function Gie(n,e){return{originalPosition:l3(n),originalCenter:l3(e)}}function qS(n,e,t){let i=n.getRootCenter();for(let r of n.getParts()){let s=n.getPartState(r);s||(s=Gie(n.getPartPosition(r),n.getPartCenter(r)),n.setPartState(r,s));let a=(s.originalCenter[t]-i[t])*e;n.setPartPosition(r,sw(s.originalPosition,t,a))}}function ZS(n){for(let e of n.getParts()){let t=n.getPartState(e);t&&n.setPartPosition(e,t.originalPosition)}}var sM=C(()=>{"use strict";ws()});function QS(n){return qr(n)}function kie(n){return n instanceof ri}function Wie(n){let e=[];return n.traverse(t=>{kie(t)&&t.geometry&&e.push(t)}),e}function c3(n,e,t){qS(new $S(n),e,t)}function aM(n){ZS(new $S(n))}var $S,f3=C(()=>{"use strict";Xs();ws();tf();sM();$S=class{constructor(e){this.root=e}getParts(){return Wie(this.root)}getRootCenter(){let e=new Sr().setFromObject(this.root);return fn({min:Ht(e.min),max:Ht(e.max)})}getPartPosition(e){return Ht(e.position)}getPartCenter(e){let i=new Sr().setFromObject(e).getCenter(new ne);return Ht(i)}setPartPosition(e,t){e.position.set(t.x,t.y,t.z)}getPartState(e){var i;let t=(i=e.userData)!=null?i:{};return t._previewExplodeState?{originalPosition:QS(t._previewExplodeState.originalPosition),originalCenter:QS(t._previewExplodeState.originalCenter)}:null}setPartState(e,t){e.userData._previewExplodeState={originalPosition:QS(t.originalPosition),originalCenter:QS(t.originalCenter)}}}});var m3={};tt(m3,{ThreeModelPreview:()=>rT,createThreeModelPreview:()=>ore});function Fu(n){return n instanceof ri}function h3(n){return n instanceof Go||n instanceof Ka||n instanceof Pl}function _a(n){return n?Array.isArray(n)?n:[n]:[]}function eT(n){var r,s,a,o;let e=n.geometry,t=(s=(r=e.getIndex())==null?void 0:r.count)!=null?s:0;if(t>0)return Math.floor(t/3);let i=(o=(a=e.getAttribute("position"))==null?void 0:a.count)!=null?o:0;return Math.floor(i/3)}function tT(n){var e,t;return(t=(e=n.geometry.getAttribute("position"))==null?void 0:e.count)!=null?t:0}function iT(n){return n?n.name||n.type||`material-${n.uuid}`:null}function Mh(n,e){var i;let t=(i=n.userData)==null?void 0:i.name;return typeof t=="string"&&t.trim().length>0?t:n.name||e}function oM(n,e){let t=[],i=e;for(;i&&i!==n;)t.push(Mh(i,i.type||`object-${i.id}`)),i=i.parent;return t.reverse().join("/")}function d3(n,e){var t;return((t=n.displayName)==null?void 0:t.trim())||n.partNumber||n.componentId||e}function u3(n){let e=n.clone();return e.transparent=!0,e.opacity=Math.max(0,Math.min(1,n.opacity))*Hie,e.depthWrite=!1,e.needsUpdate=!0,e}function sre(n){return Array.isArray(n)?n.map(u3):u3(n)}function are(n){for(let e of _a(n))e.dispose()}function nf(n){let e=new Sr().setFromObject(n);return I_(Ht(e.min),Ht(e.max))}function ore(n){return new rT(n)}var JS,Hie,zie,Xie,Yie,Kie,jie,P_,qie,Zie,Qie,$ie,Jie,ere,tre,ire,rre,nre,rT,p3=C(()=>{"use strict";Xs();T1();A1();j1();Ys();tf();VS();XS();C_();tM();ws();o3();f3();oa();JS=new ft("#20242e"),Hie=.242,zie=.28,Xie=2.5,Yie=1.5,Kie=1.15,jie=180,P_=30,qie=8,Zie=28,Qie=18,$ie=2,Jie=28,ere=.86,tre=1.08,ire=.62,rre=.86,nre=4;rT=class{constructor(e){this.raycaster=new Kc;this.occlusionRaycaster=new Kc;this.renderObservers=new Set;this.pointer=new It;this.annotationProjection=new ne;this.annotationDirection=new ne;this.clock={last:performance.now()};this.defaultLights=[];this.configLights=[];this.environmentTarget=null;this.rootObject=null;this.loadedExt="";this.resourceWarnings=[];this.renderHandle=0;this.contextLost=!1;this.quality="high";this.renderScale=1;this.interactivePixelRatioActive=!1;this.interactionPixelRatioDeadline=0;this.renderObserverSettleFrames=P_;this.frameBudgetPixelRatioScale=1;this.frameBudgetSlowStreak=0;this.frameBudgetFastStreak=0;this.frameBudgetObserverStride=1;this.frameBudgetObserverCursor=0;this.frameBudgetShadowDeferred=!1;this.lastFrameDurationMs=0;this.viewportVisible=!0;this.viewportObserver=null;this.lastDisposalAudit={reason:"initial",meshCount:0,geometryCount:0,materialCount:0,textureCount:0,objectCount:0,timestamp:performance.now()};this.axesHelper=null;this.bboxHelper=null;this.groundShadowMesh=null;this.gridHelper=null;this.bboxEnabled=!1;this.wireframeEnabled=!1;this.wireframeOriginalMaterials=new Map;this.sceneConfig={};this.focusSelectionEnabled=!1;this.focusedMesh=null;this.highlightedMesh=null;this.selectionHelper=null;this.focusHelper=null;this.mixer=null;this.animationPlaying=!1;this.initialTarget=new ne;this.initialPosition=new ne(3,2,3);this.initialFov=45;this.lastPointerDown=null;this.measurementActive=!1;this.measurementScale={x:1,y:1,z:1};this.measurementUnit="mm";this.measurementSegments=[];this.measurementMarkers=[];this.pendingPoint=null;this.pendingMarker=null;this.hoveredMarkerIndex=-1;this.lastPointerClient={x:0,y:0};this.previewLine=null;this.originalMaterials=new Map;this.focusDimMaterials=new Map;this._lastPickResult={mesh:null,pickedPoint:null,screenX:0,screenY:0};this._onPickCallbacks=[];this.disassembly=null;this.disassemblySetup=!1;this.renderDirty=!0;this.cachedMeshes=null;this.cachedMeshRoot=null;this.cameraAnimHandle=0;this.preventCanvasWheelScroll=e=>{e.preventDefault(),e.stopPropagation()};this.handleControlsChange=()=>{let e=performance.now();this.interactionPixelRatioDeadline=e+jie,this.activateInteractivePixelRatio()&&this.resizeRenderer(),this.markDirty()};this.handleViewportIntersection=e=>{let t=e[e.length-1];if(!t)return;let i=t.isIntersecting&&t.intersectionRatio>0;i!==this.viewportVisible&&(this.viewportVisible=i,i?(this.clock.last=performance.now(),this.markDirty(),this.markShadowDirty(),this.startRenderLoop()):(cancelAnimationFrame(this.renderHandle),this.renderHandle=0))};this.handlePointerDown=e=>{e.button!==0||e.isPrimary===!1||(this.lastPointerDown={x:e.clientX,y:e.clientY})};this.handlePointerUp=e=>{var i;if(e.button!==0||e.isPrimary===!1)return;let t=this.lastPointerDown;this.lastPointerDown=null,t&&(Math.hypot(e.clientX-t.x,e.clientY-t.y)>4||(i=this.disassembly)!=null&&i.isEnabled()||this.dispatchPick(e))};this.handlePointerMove=e=>{if(this.lastPointerClient={x:e.clientX,y:e.clientY},!this.measurementActive||(this.pendingPoint&&this.updatePreviewLine(),this.measurementMarkers.length===0))return;let t=this.renderer.domElement.getBoundingClientRect();this.pointer.x=(e.clientX-t.left)/t.width*2-1,this.pointer.y=-((e.clientY-t.top)/t.height)*2+1,this.raycaster.setFromCamera(this.pointer,this.camera);let i=this.raycaster.intersectObjects(this.measurementMarkers,!1),r=i.length>0?this.measurementMarkers.indexOf(i[0].object):-1;if(r!==this.hoveredMarkerIndex){if(this.hoveredMarkerIndex>=0&&this.hoveredMarkerIndex=0&&r{e.preventDefault(),this.contextLost=!0,this.renderHandle&&(cancelAnimationFrame(this.renderHandle),this.renderHandle=0)};this.handleContextRestored=()=>{this.contextLost=!1,this.markDirty(),this.startRenderLoop()};this.renderer=new xS({canvas:e,antialias:!0,alpha:!0,preserveDrawingBuffer:!0,powerPreference:"high-performance"}),this.renderer.outputColorSpace=Fi,this.renderer.toneMapping=Ws,this.renderer.toneMappingExposure=1,this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=yE,this.renderer.shadowMap.autoUpdate=!1,this.renderer.shadowMap.needsUpdate=!0,this.renderer.setClearColor(JS,1),this.scene=new mh,this.installGlobalEnvironment(),this.camera=new kr(this.initialFov,1,.01,2e3),this.camera.position.copy(this.initialPosition),this.camera.lookAt(this.initialTarget),this.scene.add(this.camera),this.controls=new MS(this.camera,e),this.controls.enableDamping=!0,this.controls.dampingFactor=.08,this.controls.zoomSpeed=.85,this.controls.screenSpacePanning=!0,this.controls.target.copy(this.initialTarget),this.controls.addEventListener("change",this.handleControlsChange),this.installDefaultLighting(),this.resizeObs=new ResizeObserver(()=>this.resizeRenderer()),this.resizeObs.observe(e),typeof IntersectionObserver!="undefined"&&(this.viewportObserver=new IntersectionObserver(this.handleViewportIntersection,{root:null,threshold:[0,.01]}),this.viewportObserver.observe(e)),e.addEventListener("wheel",this.preventCanvasWheelScroll,{passive:!1}),e.addEventListener("pointerdown",this.handlePointerDown),e.addEventListener("pointerup",this.handlePointerUp),e.addEventListener("pointermove",this.handlePointerMove),e.addEventListener("webglcontextlost",this.handleContextLost),e.addEventListener("webglcontextrestored",this.handleContextRestored),this.resizeRenderer(),this.startRenderLoop()}async loadModel(e,t,i,r){var l;this.clearLoadedModel("model-switch"),this.loadedExt=t.toLowerCase(),this.resourceWarnings=[];let s,a=[];if(this.loadedExt==="glb"||this.loadedExt==="gltf"){let c=await z1(e,this.loadedExt,i,r);s=c.scene,a=c.animations,this.resourceWarnings=c.warnings}else if(this.loadedExt==="stl")s=await X1(e);else if(this.loadedExt==="ply")s=await Y1(e);else if(this.loadedExt==="obj"){let c=await K1(e,i,r);s=c.object,this.resourceWarnings=c.warnings}else throw new Error(`Three preview does not support .${this.loadedExt} format`);if(this.rootObject=s,this.scene.add(s),this.invalidateMeshCache(),this.prepareModelForQuality(s),this.updateShadowFraming(),this.syncSceneHelpers(),this.markDirty(),a.length>0){this.mixer=new l_(s);for(let c of a)this.mixer.clipAction(c).play();this.animationPlaying=!0}let o=this.computeSummary(s);return this.fitCameraToObject(s),this.bboxEnabled&&this.ensureBoundingBoxHelper(),this.disassemblySetup=!1,(l=this.disassembly)==null||l.dispose(),this.disassembly=null,o}applyConfig(e){e.camera&&this.applyCameraConfig(e.camera),e.lights&&this.applyLightConfig(e.lights),e.scene&&this.applySceneConfig(e.scene)}destroy(){var t,i;cancelAnimationFrame(this.renderHandle),cancelAnimationFrame(this.cameraAnimHandle),this._onPickCallbacks=[],this.renderObservers.clear(),(t=this.disassembly)==null||t.dispose(),this.disassembly=null,this.disassemblySetup=!1,this.clearFocusedMesh(),this.clearSelectionHighlight(),this.clearLoadedModel("destroy");for(let r of this.configLights)this.disposeConfiguredLight(r);this.configLights.length=0;for(let r of this.defaultLights)this.disposeConfiguredLight(r);this.defaultLights.length=0,this.disposeGlobalEnvironment(),this.controls.removeEventListener("change",this.handleControlsChange),this.controls.dispose();let e=this.renderer.domElement;e.removeEventListener("wheel",this.preventCanvasWheelScroll),e.removeEventListener("pointerdown",this.handlePointerDown),e.removeEventListener("pointerup",this.handlePointerUp),e.removeEventListener("pointermove",this.handlePointerMove),e.removeEventListener("webglcontextlost",this.handleContextLost),e.removeEventListener("webglcontextrestored",this.handleContextRestored),this.resizeObs.disconnect(),(i=this.viewportObserver)==null||i.disconnect(),this.viewportObserver=null,this.renderer.dispose()}getCanvas(){return this.renderer.domElement}captureSnapshot(){return this.renderNow(0),this.renderer.domElement.toDataURL("image/png")}getAnnotationProvider(){return{canvas:this.renderer.domElement,observeRender:t=>(this.renderObservers.add(t),{remove:()=>this.renderObservers.delete(t)}),getCameraStateKey:()=>this.getAnnotationCameraStateKey(),projectWorldPoint:(t,i)=>this.projectAnnotationWorldPoint(t,i),isWorldPointOccluded:t=>this.isAnnotationWorldPointOccluded(t)}}exportModelInfo(e){if(!this.rootObject)return"";let t=this.computeSummary(this.rootObject),i=this.getRenderableMeshes(this.rootObject),r=e&&aa(e)||t.rootName;return HS({title:r,format:this.loadedExt.toUpperCase(),summary:t,meshBreakdown:i.map(s=>({name:Mh(s,`mesh-${s.id}`),triangleCount:eT(s),vertexCount:tT(s),materialName:iT(_a(s.material)[0])}))})}getModelEvidence(){if(!this.rootObject)return null;let e=this.getRenderableMeshes(this.rootObject),t=this.computeComponentPartSummaries(this.rootObject,e),i=e.filter(a=>!t.groupedMeshes.has(a)).map(a=>this.computePartSummary(a)),r=t.parts.length>0?[...t.parts,...i]:i,s=new Set;for(let a of e)for(let o of _a(a.material)){let l=iT(o);l&&s.add(l)}return{summary:this.computeSummary(this.rootObject),parts:r,materialNames:Array.from(s).sort((a,o)=>a.localeCompare(o)),resourceWarnings:[...this.resourceWarnings],capturedAt:new Date().toISOString()}}getSelectedPartInfo(){var t;let e=(t=this.focusedMesh)!=null?t:Fu(this._lastPickResult.mesh)?this._lastPickResult.mesh:null;return e?this.computePartSummary(e):null}exportSelectedPartInfo(){let e=this.getSelectedPartInfo();return e?zS(e):""}getPickWorldPoint(e){return e.pickedPoint&&typeof e.pickedPoint=="object"?Ht(e.pickedPoint):e.mesh instanceof ri?fn(nf(e.mesh)):null}onPick(e){return this._onPickCallbacks.push(e),()=>{this._onPickCallbacks=this._onPickCallbacks.filter(t=>t!==e)}}resetView(){this.rootObject&&aM(this.rootObject),this.resetDisassembly(),this.clearFocusedMesh(),this.clearSelectionHighlight(),this.camera.fov=this.initialFov,this.camera.position.copy(this.initialPosition),this.camera.updateProjectionMatrix(),this.controls.target.copy(this.initialTarget),this.controls.update(),this.markDirty(),this.renderNow(performance.now())}toggleFocusSelection(){var t;let e=!this.focusSelectionEnabled;return e&&((t=this.disassembly)!=null&&t.isEnabled())&&this.disassembly.setEnabled(!1),this.focusSelectionEnabled=e,this.focusSelectionEnabled?(this.clearSelectionHighlight(),this._lastPickResult.mesh instanceof ri&&this.setFocusedMesh(this._lastPickResult.mesh)):this.clearFocusedMesh(),this.markDirty(),this.focusSelectionEnabled}isFocusSelectionEnabled(){return this.focusSelectionEnabled}toggleWireframe(){if(this.wireframeEnabled=!this.wireframeEnabled,!this.rootObject)return this.wireframeEnabled;for(let e of this.getRenderableMeshes(this.rootObject))if(this.wireframeEnabled){this.wireframeOriginalMaterials.set(e.id,e.material);let i=_a(e.material).map(r=>{if(r instanceof Cn){let s=new jn({color:r.color,transparent:r.transparent,opacity:r.opacity,side:r.side,visible:r.visible});return s.wireframe=!0,s}if("wireframe"in r){let s=r.clone();return s.wireframe=!0,s}return r});e.material=Array.isArray(e.material)?i:i[0]}else{let t=this.wireframeOriginalMaterials.get(e.id);t&&(e.material=t),this.wireframeOriginalMaterials.delete(e.id)}return this.markDirty(),this.wireframeEnabled}toggleOrientationGizmo(){if(!this.axesHelper){this.axesHelper=new Au(1.2),this.axesHelper.visible=!1;let e=this.axesHelper.material;e.depthTest=!1,e.depthWrite=!1,this.axesHelper.renderOrder=999,this.scene.add(this.axesHelper)}return this.axesHelper.visible=!this.axesHelper.visible,this.axesHelper.position.copy(this.controls.target),this.markDirty(),this.axesHelper.visible}isOrientationGizmoEnabled(){var e;return!!((e=this.axesHelper)!=null&&e.visible)}toggleBoundingBox(){var e;return this.bboxEnabled=!this.bboxEnabled,this.bboxEnabled?(this.ensureBoundingBoxHelper(),this.markDirty(),!!this.bboxHelper):((e=this.bboxHelper)==null||e.removeFromParent(),this.bboxHelper=null,this.markDirty(),!1)}hasAnimations(){return this.mixer!==null}toggleAnimation(){return this.mixer?(this.animationPlaying=!this.animationPlaying,this.mixer.timeScale=this.animationPlaying?1:0,this.markDirty(),this.animationPlaying):!1}toggleMeasurement(){return this.measurementActive=!this.measurementActive,this.measurementActive||this.clearMeasurements(),this.measurementActive}isMeasurementActive(){return this.measurementActive}clearMeasurements(){var e;this.measurementActive=!1,this.pendingPoint=null,this.pendingMarker=null,this.hoveredMarkerIndex=-1,this.removePreviewLine();for(let t of this.measurementSegments){t.line.removeFromParent(),t.line.geometry.dispose(),t.line.material.dispose(),t.label.removeFromParent();let i=t.label.material;(e=i.map)==null||e.dispose(),i.dispose()}this.measurementSegments=[];for(let t of this.measurementMarkers){t.removeFromParent(),t.geometry.dispose();let i=t.material;if(Array.isArray(i))for(let r of i)r.dispose();else i.dispose()}this.measurementMarkers=[],this.markDirty()}setMeasurementScale(e){this.measurementScale={...e},this.updateMeasurementLabels()}getMeasurementScale(){return{...this.measurementScale}}getMeasurementBounds(){if(!this.rootObject)return null;let e=nf(this.rootObject);return Wr(e)}getRealDistance(e,t){let i=(t.x-e.x)*this.measurementScale.x,r=(t.y-e.y)*this.measurementScale.y,s=(t.z-e.z)*this.measurementScale.z;return Math.sqrt(i*i+r*r+s*s)}formatMeasurementDistance(e){let t=this.measurementUnit;return t==="um"||t==="\u03BCm"?e<1e3?`${e.toFixed(2)} \u03BCm`:`${(e/1e3).toFixed(2)} mm`:t==="mm"?e<1?`${(e*1e3).toFixed(2)} \u03BCm`:e<1e3?`${e.toFixed(2)} mm`:`${(e/1e3).toFixed(3)} m`:t==="cm"?e<1?`${(e*10).toFixed(2)} mm`:e<100?`${e.toFixed(2)} cm`:`${(e/100).toFixed(3)} m`:t==="m"?e<.01?`${(e*1e3).toFixed(2)} mm`:e<1?`${e.toFixed(3)} m`:`${e.toFixed(2)} m`:`${e.toFixed(3)} ${t}`}updateMeasurementLabels(){var t;if(this.measurementSegments.length===0)return;let e=this.getMeasurementMarkerSize()*4;for(let i of this.measurementSegments){let r=this.getRealDistance(i.start,i.end),s=this.formatMeasurementDistance(r);i.label.removeFromParent();let a=i.label.material;(t=a.map)==null||t.dispose(),a.dispose();let o=new ne().addVectors(i.start,i.end).multiplyScalar(.5);i.label=this.createMeasurementLabelSprite(s,o,e),this.scene.add(i.label)}this.markDirty()}setRenderQuality(e,t=this.renderScale){this.quality=e,this.renderScale=t,this.applyShadowQuality(),this.resizeRenderer()}setRenderScale(e){return this.renderScale=Math.min(2,Math.max(.25,e)),this.resizeRenderer(),Number(this.renderScale.toFixed(2))}getPerformanceSnapshot(){return{backend:"three",renderScale:Number(this.renderScale.toFixed(2)),quality:this.quality,pixelRatio:Number(this.renderer.getPixelRatio().toFixed(2)),interactivePixelRatioActive:this.interactivePixelRatioActive,renderDirty:this.renderDirty,renderObserverCount:this.renderObservers.size,renderObserverSettleFrames:this.renderObserverSettleFrames,frameBudgetPixelRatioScale:Number(this.frameBudgetPixelRatioScale.toFixed(2)),frameBudgetObserverStride:this.frameBudgetObserverStride,frameBudgetShadowDeferred:this.frameBudgetShadowDeferred,lastFrameDurationMs:Number(this.lastFrameDurationMs.toFixed(2)),viewportVisible:this.viewportVisible,disposalAudit:{...this.lastDisposalAudit},meshCount:this.rootObject?this.getRenderableMeshes(this.rootObject).length:0}}setExplode(e,t){this.rootObject&&(c3(this.rootObject,e,t),this.markShadowDirty(),this.markDirty())}resetExplode(){this.rootObject&&(aM(this.rootObject),this.markShadowDirty(),this.markDirty())}focusWorldPoint(e){let t=new ne(e.x,e.y,e.z),i=this.camera.position.distanceTo(this.controls.target),r=t.clone().sub(this.camera.position).normalize(),s=t.clone().sub(r.multiplyScalar(i));this.animateCamera(s,t)}toggleDisassembly(){if(this.ensureDisassembly(),!this.disassembly)return!1;let e=!this.disassembly.isEnabled();e&&(this.focusSelectionEnabled=!1,this.clearFocusedMesh(),this.clearSelectionHighlight());let t=this.disassembly.setEnabled(e);return t||this.disassembly.reset(),t}resetDisassembly(){var e;(e=this.disassembly)==null||e.reset()}isDisassemblyEnabled(){var e,t;return(t=(e=this.disassembly)==null?void 0:e.isEnabled())!=null?t:!1}ensureDisassembly(){if(this.disassemblySetup||(this.disassemblySetup=!0,!this.rootObject))return;let e=this.getRenderableMeshes(this.rootObject);e.length!==0&&(this.disassembly=a3(this.scene,this.camera,this.renderer.domElement,e,this.controls,()=>{this.markShadowDirty(),this.markDirty()}))}animateCamera(e,t){cancelAnimationFrame(this.cameraAnimHandle);let i=this.camera.position.clone(),r=this.controls.target.clone(),s=500,a=performance.now(),o=()=>{let l=performance.now()-a,c=Math.min(1,l/s),f=c<.5?4*c*c*c:1-Math.pow(-2*c+2,3)/2;this.camera.position.lerpVectors(i,e,f),this.controls.target.lerpVectors(r,t,f),this.controls.update(),this.markDirty(),c<1&&(this.cameraAnimHandle=window.requestAnimationFrame(o))};this.cameraAnimHandle=window.requestAnimationFrame(o)}startRenderLoop(){if(this.renderHandle||!this.viewportVisible||this.contextLost)return;let e=()=>{if(!this.viewportVisible||this.contextLost){this.renderHandle=0;return}this.renderHandle=window.requestAnimationFrame(e),this.renderNow(performance.now())};this.renderHandle=window.requestAnimationFrame(e)}renderNow(e){var o,l,c;let t=this.renderer.domElement;if(!this.viewportVisible||!t.isConnected||t.clientWidth<=0||t.clientHeight<=0)return;let i=Math.max(0,(e-this.clock.last)/1e3);this.clock.last=e;let r=this.controls.update(),s=!!this.mixer&&this.animationPlaying;if(s&&this.mixer&&(this.mixer.update(i),this.markShadowDirty()),this.restoreInteractivePixelRatioIfIdle(e,r),!r&&!s&&!this.renderDirty){this.renderObserverSettleFrames>0&&(this.renderObserverSettleFrames--,this.notifyRenderObservers());return}this.renderDirty=!1,this.renderObserverSettleFrames=P_,(o=this.bboxHelper)==null||o.update(),(l=this.selectionHelper)==null||l.update(),(c=this.focusHelper)==null||c.update(),this.axesHelper&&this.axesHelper.visible&&this.axesHelper.position.copy(this.controls.target);let a=performance.now();this.renderer.render(this.scene,this.camera),this.updateFrameBudget(performance.now()-a),this.notifyRenderObservers()}notifyRenderObservers(){if(!(this.frameBudgetObserverStride>1&&(this.frameBudgetObserverCursor=(this.frameBudgetObserverCursor+1)%this.frameBudgetObserverStride,this.frameBudgetObserverCursor!==0)))for(let e of this.renderObservers)e()}markDirty(){this.renderDirty=!0,this.startRenderLoop()}markShadowDirty(){if(this.shouldDeferShadowRefresh()){this.frameBudgetShadowDeferred=!0;return}this.frameBudgetShadowDeferred=!1,this.renderer.shadowMap.needsUpdate=!0}activateInteractivePixelRatio(){if(this.interactivePixelRatioActive)return!1;let e=this.computePixelRatio(!1);return this.computePixelRatio(!0)>=e?!1:(this.interactivePixelRatioActive=!0,!0)}restoreInteractivePixelRatioIfIdle(e,t){!this.interactivePixelRatioActive||t||e=Zie?(this.frameBudgetSlowStreak++,this.frameBudgetFastStreak=0):e<=Qie?(this.frameBudgetFastStreak++,this.frameBudgetSlowStreak=0):(this.frameBudgetSlowStreak=0,this.frameBudgetFastStreak=0),this.frameBudgetSlowStreak>=$ie){this.frameBudgetSlowStreak=0;let t=Math.max(ire,this.frameBudgetPixelRatioScale*ere);t=Jie&&this.frameBudgetPixelRatioScale<1&&(this.frameBudgetFastStreak=0,this.frameBudgetPixelRatioScale=Math.min(1,this.frameBudgetPixelRatioScale*tre),this.frameBudgetObserverStride=Math.max(1,this.frameBudgetObserverStride-1),this.renderObserverSettleFrames=P_,this.resizeRenderer())}}resetFrameBudget(){let e=this.frameBudgetPixelRatioScale!==1||this.frameBudgetObserverStride!==1;this.frameBudgetPixelRatioScale=1,this.frameBudgetSlowStreak=0,this.frameBudgetFastStreak=0,this.frameBudgetObserverStride=1,this.frameBudgetObserverCursor=0,this.renderObserverSettleFrames=P_,e&&this.markDirty()}shouldDeferShadowRefresh(){return this.interactivePixelRatioActive&&this.frameBudgetPixelRatioScale<=rre}resizeRenderer(){let e=this.renderer.domElement,t=Math.max(1,Math.round(e.clientWidth||e.width||1)),i=Math.max(1,Math.round(e.clientHeight||e.height||1));this.renderer.setPixelRatio(this.computePixelRatio()),this.renderer.setSize(t,i,!1),this.camera.aspect=t/i,this.camera.updateProjectionMatrix(),this.markDirty()}applyCameraConfig(e){typeof e.fov=="number"&&Number.isFinite(e.fov)&&(this.camera.fov=e.fov,this.camera.updateProjectionMatrix()),e.position&&this.camera.position.set(...e.position),e.lookAt&&(this.controls.target.set(...e.lookAt),this.camera.lookAt(this.controls.target)),typeof e.near=="number"&&Number.isFinite(e.near)&&(this.camera.near=e.near),typeof e.far=="number"&&Number.isFinite(e.far)&&(this.camera.far=e.far),typeof e.zoom=="number"&&Number.isFinite(e.zoom)&&(this.camera.zoom=e.zoom),this.camera.updateProjectionMatrix(),this.controls.update(),this.markDirty()}applyLightConfig(e){for(let i of this.configLights)this.disposeConfiguredLight(i);this.configLights.length=0;let t=e.length>0;for(let i of this.defaultLights)i.visible=!t;for(let i of e){let r=this.createConfiguredLight(i);r&&(this.configLights.push(r),r.parent!==this.camera&&this.scene.add(r))}this.updateShadowFraming(),this.markShadowDirty(),this.markDirty()}applySceneConfig(e){if(this.sceneConfig={...this.sceneConfig,...e},e.transparent!==void 0||e.background!==void 0)if(this.sceneConfig.transparent)this.scene.background=null,this.renderer.setClearColor(JS,0);else if(this.sceneConfig.background){let t=new ft(this.sceneConfig.background);this.scene.background=t,this.renderer.setClearColor(t,1)}else this.scene.background=JS,this.renderer.setClearColor(JS,1);typeof e.autoRotate=="boolean"&&(this.controls.autoRotate=e.autoRotate),typeof e.autoRotateSpeed=="number"&&(this.controls.autoRotateSpeed=e.autoRotateSpeed),typeof e.axis=="boolean"&&this.syncAxisHelper(e.axis),this.syncSceneHelpers(),this.markDirty()}installDefaultLighting(){let e=new Su(16777215,.96);e.name="default-global-ambient";let t=new Eu(16777215,7172736,.34);t.name="default-hemi",this.defaultLights.push(e,t);for(let i of this.defaultLights)this.scene.add(i)}installGlobalEnvironment(){this.disposeGlobalEnvironment();let e=new Du(this.renderer),t=new CS;this.environmentTarget=e.fromScene(t,.04),this.scene.environment=this.environmentTarget.texture,this.scene.environmentIntensity=.48,t.dispose(),e.dispose()}disposeGlobalEnvironment(){var e;this.scene.environment=null,(e=this.environmentTarget)==null||e.dispose(),this.environmentTarget=null}createConfiguredLight(e){var r,s,a,o,l,c,f;let t=e.color?new ft(e.color):new ft(16777215),i=(r=e.intensity)!=null?r:1;switch(e.type){case"ambient":return new Su(t,i);case"hemisphere":{let h=e.groundColor?new ft(e.groundColor):new ft(4473924);return new Eu(t,h,i)}case"directional":{let h=new Go(t,i),d=(s=e.position)!=null?s:[-1,2,1],u=(a=e.target)!=null?a:[0,0,0];return h.position.set(...d),h.target.position.set(...u),this.scene.add(h.target),h.castShadow=!!e.castShadow,h}case"point":{let h=new Ka(t,i),d=(o=e.position)!=null?o:[0,5,0];return h.position.set(...d),h.castShadow=!!e.castShadow,typeof e.decay=="number"&&(h.decay=e.decay),h}case"spot":{let h=new Pl(t,i),d=(l=e.position)!=null?l:[0,5,0],u=(c=e.target)!=null?c:[0,0,0];return h.position.set(...d),h.target.position.set(...u),this.scene.add(h.target),h.angle=e.angle?e.angle*Math.PI/180:Math.PI/4,h.penumbra=(f=e.penumbra)!=null?f:.5,typeof e.decay=="number"&&(h.decay=e.decay),h.castShadow=!!e.castShadow,h}case"attachToCam":{let h=new Ka(t,i);return this.camera.add(h),h}default:return null}}disposeConfiguredLight(e){(e instanceof Go||e instanceof Pl)&&e.target.removeFromParent(),e.removeFromParent(),e.dispose()}prepareModelForQuality(e){let t=this.renderer.capabilities.getMaxAnisotropy();e.traverse(i=>{if(Fu(i)){i.castShadow=!0,i.receiveShadow=!0;for(let r of _a(i.material))this.prepareMaterialForQuality(r,t)}})}prepareMaterialForQuality(e,t){let i=e;for(let r of Object.values(i))r instanceof Ar&&(r.anisotropy=Math.max(r.anisotropy,t),r.needsUpdate=!0);e.needsUpdate=!0}applyShadowQuality(){let e=this.shadowMapSize();for(let t of this.allLights())!h3(t)||!t.castShadow||(t.shadow.mapSize.set(e,e),t.shadow.bias=-12e-5,t.shadow.normalBias=.018,t.shadow.needsUpdate=!0);this.markShadowDirty(),this.markDirty()}updateShadowFraming(){if(!this.rootObject)return;let e=new Sr().setFromObject(this.rootObject),t=e.getCenter(new ne),i=e.getSize(new ne),r=Math.max(i.x,i.y,i.z,1)*1.8;for(let s of this.allLights())if(!(!h3(s)||!s.castShadow)){if(s.shadow.mapSize.set(this.shadowMapSize(),this.shadowMapSize()),s.shadow.bias=-12e-5,s.shadow.normalBias=.018,s instanceof Go){let a=s.position.clone().sub(s.target.position);if(a.lengthSq()<.001&&a.set(4,7,5),s.target.position.copy(t),s.target.parent||this.scene.add(s.target),s.position.copy(t).add(a.normalize().multiplyScalar(r*2.4)),s.shadow.camera instanceof Vo){let o=s.shadow.camera;o.left=-r,o.right=r,o.top=r,o.bottom=-r,o.near=.1,o.far=r*5,o.updateProjectionMatrix()}}s.shadow.needsUpdate=!0}this.markShadowDirty()}shadowMapSize(){return this.quality==="low"?512:this.quality==="medium"?1024:2048}allLights(){return[...this.defaultLights,...this.configLights]}syncSceneHelpers(){this.sceneConfig.groundShadow?this.createGroundShadow():this.removeGroundShadow(),this.sceneConfig.grid?this.createGrid():this.removeGrid(),typeof this.sceneConfig.axis=="boolean"&&this.syncAxisHelper(this.sceneConfig.axis)}syncAxisHelper(e){if(!this.axesHelper){this.axesHelper=new Au(1.2);let t=this.axesHelper.material;t.depthTest=!1,t.depthWrite=!1,this.axesHelper.renderOrder=999,this.scene.add(this.axesHelper)}this.axesHelper.visible=e,this.axesHelper.position.copy(this.controls.target)}createGroundShadow(){if(!this.rootObject||this.groundShadowMesh)return;let e=nf(this.rootObject),t=fn(e),i=Wr(e),r=Math.max(i.x,i.z,1)*3,s=e.min.y-Math.max(r*.002,.002),a=new ri(new gh(r,r),new t_({color:0,opacity:zie,transparent:!0}));a.name="ai3d-ground-shadow",a.rotation.x=-Math.PI/2,a.position.set(t.x,s,t.z),a.receiveShadow=!0,a.renderOrder=-1,this.scene.add(a),this.groundShadowMesh=a}removeGroundShadow(){if(this.groundShadowMesh){this.groundShadowMesh.removeFromParent(),this.groundShadowMesh.geometry.dispose();for(let e of _a(this.groundShadowMesh.material))e.dispose();this.groundShadowMesh=null}}createGrid(){if(!this.rootObject||this.gridHelper)return;let e=nf(this.rootObject),t=fn(e),i=Wr(e),r=Math.max(i.x,i.z,1)*2,s=new c_(r,20,7305093,3423046);s.name="ai3d-grid",s.position.set(t.x,e.min.y-Math.max(r*.003,.003),t.z);for(let a of _a(s.material))a.transparent=!0,a.opacity=.42;this.scene.add(s),this.gridHelper=s}removeGrid(){if(this.gridHelper){this.gridHelper.removeFromParent(),this.gridHelper.geometry.dispose();for(let e of _a(this.gridHelper.material))e.dispose();this.gridHelper=null}}dispatchPick(e){var a,o,l;if(!this.rootObject||(a=this.disassembly)!=null&&a.isEnabled())return;let t=this.renderer.domElement.getBoundingClientRect();this.pointer.x=(e.clientX-t.left)/t.width*2-1,this.pointer.y=-((e.clientY-t.top)/t.height)*2+1,this.raycaster.setFromCamera(this.pointer,this.camera);let i=this.raycaster.intersectObjects(this.getRenderableMeshes(this.rootObject),!1)[0],r=(i==null?void 0:i.object)instanceof ri?i.object:null,s={mesh:r,pickedPoint:(l=(o=i==null?void 0:i.point)==null?void 0:o.clone())!=null?l:null,screenX:e.clientX,screenY:e.clientY};if(this._lastPickResult=s,this.measurementActive&&(i!=null&&i.point)){this.addMeasurementPoint(i.point.clone());return}this.focusSelectionEnabled&&r?(this.clearSelectionHighlight(),this.focusedMesh!==r&&this.setFocusedMesh(r)):this.focusSelectionEnabled?this.clearSelectionHighlight():this.updateSelectionHighlight(r),this._onPickCallbacks.forEach(c=>c(s))}clearLoadedModel(e="model-switch"){var t,i;if((t=this.disassembly)==null||t.dispose(),this.disassembly=null,this.disassemblySetup=!1,this.invalidateMeshCache(),this.markDirty(),this.clearFocusedMesh(),this.clearSelectionHighlight(),this.clearMeasurements(),this.wireframeEnabled=!1,this.wireframeOriginalMaterials.clear(),(i=this.bboxHelper)==null||i.removeFromParent(),this.bboxHelper=null,this.bboxEnabled=!1,this.removeGroundShadow(),this.removeGrid(),this.mixer=null,this.animationPlaying=!1,!this.rootObject){this.lastDisposalAudit={reason:e,meshCount:0,geometryCount:0,materialCount:0,textureCount:0,objectCount:0,timestamp:performance.now()};return}this.scene.remove(this.rootObject),this.lastDisposalAudit=this.disposeObjectGraph(this.rootObject,e),this.rootObject=null,this.markShadowDirty()}disposeObjectGraph(e,t){let i=new Set,r=new Set,s=new Set,a=0,o=0;return e.traverse(l=>{if(o++,!Fu(l))return;a++;let c=l.geometry;c&&!i.has(c.uuid)&&(c.dispose(),i.add(c.uuid));for(let f of _a(l.material))this.disposeMaterialWithTextures(f,r,s)}),{reason:t,meshCount:a,geometryCount:i.size,materialCount:r.size,textureCount:s.size,objectCount:o,timestamp:performance.now()}}disposeMaterialWithTextures(e,t,i){let r=e;for(let s of Object.values(r))if(s instanceof Ar&&!i.has(s.uuid))s.dispose(),i.add(s.uuid);else if(Array.isArray(s))for(let a of s)a instanceof Ar&&!i.has(a.uuid)&&(a.dispose(),i.add(a.uuid));t.has(e.uuid)||(e.dispose(),t.add(e.uuid))}fitCameraToObject(e){let t=nf(e),i=J1(t);this.initialTarget.set(i.target.x,i.target.y,i.target.z),this.initialPosition.set(i.position.x,i.position.y,i.position.z),this.initialFov=45;let r=Wr(t),s=Math.max(r.x,r.y,r.z,1),a=this.initialPosition.distanceTo(this.initialTarget);this.controls.minDistance=Math.max(i.near*4,s*.02,.001),this.controls.maxDistance=Math.max(a*8,this.controls.minDistance*10),this.resetView(),this.axesHelper&&(this.axesHelper.position.copy(this.controls.target),this.axesHelper.scale.setScalar(Math.max(.5,s*.25))),this.camera.near=i.near,this.camera.far=i.far,this.camera.updateProjectionMatrix(),this.markDirty()}getAnnotationCameraStateKey(){return[this.camera.position.x.toFixed(3),this.camera.position.y.toFixed(3),this.camera.position.z.toFixed(3),this.controls.target.x.toFixed(2),this.controls.target.y.toFixed(2),this.controls.target.z.toFixed(2),this.camera.fov.toFixed(2)].join("_")}projectAnnotationWorldPoint(e,t){let i=this.renderer.domElement;return!i.isConnected||i.clientWidth===0||i.clientHeight===0||(this.scene.updateMatrixWorld(),this.camera.updateMatrixWorld(),this.annotationProjection.set(e.x,e.y,e.z).project(this.camera),!Number.isFinite(this.annotationProjection.x)||!Number.isFinite(this.annotationProjection.y)||!Number.isFinite(this.annotationProjection.z))?!1:(t.screenX=(this.annotationProjection.x+1)/2*i.clientWidth,t.screenY=(1-this.annotationProjection.y)/2*i.clientHeight,t.depth=(this.annotationProjection.z+1)/2,!0)}isAnnotationWorldPointOccluded(e){if(!this.rootObject)return!1;let t=Nc(Ht(this.camera.position),e);if(!t)return!1;this.rootObject.updateWorldMatrix(!0,!0),this.annotationDirection.set(t.direction.x,t.direction.y,t.direction.z),this.occlusionRaycaster.set(this.camera.position,this.annotationDirection),this.occlusionRaycaster.far=t.distance;let i=this.occlusionRaycaster.intersectObjects(this.getRenderableMeshes(this.rootObject),!1)[0];return!!i&&Oc(i.distance,t.distance,t.epsilon)}getRenderableMeshes(e){if(this.cachedMeshes&&this.cachedMeshRoot===e)return this.cachedMeshes;let t=[];return e.traverse(i=>{Fu(i)&&i.geometry&&t.push(i)}),this.cachedMeshes=t,this.cachedMeshRoot=e,t}invalidateMeshCache(){this.cachedMeshes=null,this.cachedMeshRoot=null}ensureBoundingBoxHelper(){var e;this.rootObject&&((e=this.bboxHelper)==null||e.removeFromParent(),this.bboxHelper=new Dl(this.rootObject,16436245),this.scene.add(this.bboxHelper))}updateSelectionHighlight(e){var t;if(!this.rootObject||!e){this.clearSelectionHighlight();return}this.highlightedMesh===e&&this.selectionHelper||((t=this.selectionHelper)==null||t.removeFromParent(),this.selectionHelper=new Dl(e,4890367),this.scene.add(this.selectionHelper),this.highlightedMesh=e,this.markDirty())}setFocusedMesh(e){var i,r,s;if(!this.rootObject||!e){this.clearFocusedMesh();return}if(this.focusedMesh===e)return;let t=this.getRenderableMeshes(this.rootObject);if(!t.includes(e)){this.clearFocusedMesh();return}this.restoreFocusedMaterials(),this.disposeFocusDimMaterials();for(let a of t){if(this.originalMaterials.has(a.id)||this.originalMaterials.set(a.id,a.material),a===e){a.material=(i=this.originalMaterials.get(a.id))!=null?i:a.material;continue}let o=(r=this.originalMaterials.get(a.id))!=null?r:a.material,l=sre(o);this.focusDimMaterials.set(a.id,l),a.material=l}(s=this.focusHelper)==null||s.removeFromParent(),this.focusHelper=new Dl(e,3065087),this.scene.add(this.focusHelper),this.focusedMesh=e,this.markDirty()}clearFocusedMesh(){var e;this.restoreFocusedMaterials(),this.disposeFocusDimMaterials(),this.originalMaterials.clear(),(e=this.focusHelper)==null||e.removeFromParent(),this.focusHelper=null,this.focusedMesh=null,this.markDirty()}restoreFocusedMaterials(){if(this.rootObject)for(let e of this.getRenderableMeshes(this.rootObject)){let t=this.originalMaterials.get(e.id);t&&(e.material=t)}}disposeFocusDimMaterials(){for(let e of this.focusDimMaterials.values())are(e);this.focusDimMaterials.clear()}clearSelectionHighlight(){var e;(e=this.selectionHelper)==null||e.removeFromParent(),this.selectionHelper=null,this.highlightedMesh=null,this.markDirty()}getMeasurementMarkerSize(){if(!this.rootObject)return .02;let e=nf(this.rootObject),t=Wr(e);return Math.max(t.x,t.y,t.z,.001)*.015}findNearestMarkerIndex(e){let t=this.getMeasurementMarkerSize()*2.5;for(let i=0;i=0?this.measurementMarkers[t].position.clone():e;if(this.pendingPoint){if(i.distanceTo(this.pendingPoint)<1e-4)return;if(t<0){let r=this.getMeasurementMarkerSize(),s=new vu(r,16,16),a=new jn({color:16739179,depthTest:!1}),o=new ri(s,a);o.position.copy(i),o.renderOrder=999,this.scene.add(o),this.measurementMarkers.push(o)}this.createMeasurementSegment(this.pendingPoint,i),this.pendingMarker&&(this.pendingMarker.scale.setScalar(1),this.pendingMarker.material.color.setHex(16739179)),this.pendingPoint=null,this.pendingMarker=null,this.removePreviewLine()}else{if(t<0){let r=this.getMeasurementMarkerSize(),s=new vu(r,16,16),a=new jn({color:16739179,depthTest:!1}),o=new ri(s,a);o.position.copy(i),o.renderOrder=999,this.scene.add(o),this.measurementMarkers.push(o),this.pendingMarker=o}else this.pendingMarker=this.measurementMarkers[t];this.pendingMarker.scale.setScalar(1.6),this.pendingMarker.material.color.setHex(5361510),this.pendingPoint=i,this.ensurePreviewLine()}this.markDirty()}createMeasurementSegment(e,t){let i=new Vi().setFromPoints([e,t]),r=new No(i,new Mn({color:16739179,depthTest:!1}));r.renderOrder=998,this.scene.add(r);let s=this.getRealDistance(e,t),a=this.formatMeasurementDistance(s),o=new ne().addVectors(e,t).multiplyScalar(.5),l=this.createMeasurementLabelSprite(a,o,this.getMeasurementMarkerSize()*4);this.scene.add(l),this.measurementSegments.push({start:e,end:t,line:r,label:l})}createMeasurementLabelSprite(e,t,i){let r=activeDocument.createEl("canvas"),s=r.getContext("2d");r.width=512,r.height=128,s.fillStyle="rgba(32, 36, 46, 0.9)",s.beginPath(),s.roundRect(0,0,512,128,16),s.fill(),s.strokeStyle="#ff6b6b",s.lineWidth=4,s.stroke(),s.fillStyle="#ffffff",s.font="bold 48px sans-serif",s.textAlign="center",s.textBaseline="middle",s.fillText(e,256,64);let a=new Jp(r),o=new mu({map:a,depthTest:!1}),l=new jp(o);return l.position.copy(t),l.scale.set(i*4,i,1),l.renderOrder=1e3,l}ensurePreviewLine(){if(this.previewLine)return;let e=new Vi().setFromPoints([new ne,new ne]);this.previewLine=new No(e,new Mn({color:16777215,transparent:!0,opacity:.5,depthTest:!1})),this.previewLine.renderOrder=997,this.scene.add(this.previewLine)}updatePreviewLine(){if(!this.pendingPoint||!this.previewLine||!this.rootObject)return;let e=this.renderer.domElement.getBoundingClientRect();this.pointer.x=(this.lastPointerClient.x-e.left)/e.width*2-1,this.pointer.y=-((this.lastPointerClient.y-e.top)/e.height)*2+1,this.raycaster.setFromCamera(this.pointer,this.camera);let t=this.raycaster.intersectObjects(this.getRenderableMeshes(this.rootObject),!1)[0],i;t!=null&&t.point?i=t.point.clone():i=this.pendingPoint.clone().add(this.raycaster.ray.direction.clone().multiplyScalar(5));let r=this.previewLine.geometry;this.previewLine.geometry=new Vi().setFromPoints([this.pendingPoint,i]),r.dispose(),this.markDirty()}removePreviewLine(){this.previewLine&&(this.previewLine.removeFromParent(),this.previewLine.geometry.dispose(),this.previewLine.material.dispose(),this.previewLine=null)}computePartSummary(e){e.updateWorldMatrix(!0,!1);let t=nf(e),i=Mh(e,`mesh-${e.id}`),r=rf(e.userData,{name:i,path:this.rootObject?oM(this.rootObject,e):i});return Ih({name:d3(r,i),triangleCount:eT(e),vertexCount:tT(e),materialName:iT(_a(e.material)[0]),boundingSize:Wr(t),center:fn(t),source:r.hasExplicitIdentity?"component":"mesh",meshNames:[i],childCount:1,componentId:r.componentId,occurrenceId:r.occurrenceId,partNumber:r.partNumber,componentPath:r.componentPath})}computeComponentPartSummaries(e,t){let i=new Set(t),r=[],s=new Set,a=[];return e.updateWorldMatrix(!0,!0),e.traverse(o=>{if(o===e||Fu(o))return;let l=[];if(o.traverse(f=>{Fu(f)&&i.has(f)&&l.push(f)}),l.length<2||l.length===t.length){let f=rf(o.userData,{name:Mh(o,`component-${o.id}`),path:oM(e,o)});if(!f.hasExplicitIdentity||l.length<1||l.length===t.length)return;a.push({object:o,childMeshes:l,identity:f});return}let c=rf(o.userData,{name:Mh(o,`group-${o.id}`),path:oM(e,o)});!c.hasExplicitIdentity&&!o.name.trim()||a.push({object:o,childMeshes:l,identity:c})}),a.sort((o,l)=>o.childMeshes.length-l.childMeshes.length).forEach(({object:o,childMeshes:l,identity:c})=>{let f=l.filter(p=>!s.has(p));if(f.length<1||!c.hasExplicitIdentity&&f.length<2)return;for(let p of f)s.add(p);let h=new Sr;for(let p of f)p.updateWorldMatrix(!0,!1),h.union(new Sr().setFromObject(p));let d=new Set,u=0,m=0;for(let p of f){u+=eT(p),m+=tT(p);for(let _ of _a(p.material)){let g=iT(_);g&&d.add(g)}}r.push(Ih({name:d3(c,Mh(o,`group-${o.id}`)),triangleCount:u,vertexCount:m,materialName:d.size===0?null:d.size===1?Array.from(d)[0]:`${d.size} materials`,boundingSize:Wr({min:Ht(h.min),max:Ht(h.max)}),center:fn({min:Ht(h.min),max:Ht(h.max)}),source:c.hasExplicitIdentity?"component":"group",meshNames:f.map(p=>Mh(p,`mesh-${p.id}`)),childCount:f.length,componentId:c.componentId,occurrenceId:c.occurrenceId,partNumber:c.partNumber,componentPath:c.componentPath}))}),{parts:r,groupedMeshes:s}}computeSummary(e){let t=this.getRenderableMeshes(e);return kS({rootName:e.name||"__root__",boundingSize:Wr(nf(e)),meshes:t.map(i=>({triangleCount:eT(i),vertexCount:tT(i),materialKeys:_a(i.material).map(r=>r.uuid)})),resourceWarnings:this.resourceWarnings})}}});var lre,lM,cM,ie,di=C(()=>{lre=typeof WeakRef!="undefined",lM=class{constructor(e,t=!1,i,r){this.initialize(e,t,i,r)}initialize(e,t=!1,i,r){return this.mask=e,this.skipNextObservers=t,this.target=i,this.currentTarget=r,this}},cM=class{constructor(e,t,i=null){this.callback=e,this.mask=t,this.scope=i,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1,this._remove=null}remove(e=!1){this._remove&&this._remove(e)}},ie=class n{static FromPromise(e,t){let i=new n;return e.then(r=>{i.notifyObservers(r)}).catch(r=>{if(t)t.notifyObservers(r);else throw r}),i}get observers(){return this._observers}constructor(e,t=!1){this.notifyIfTriggered=t,this._observers=new Array,this._numObserversMarkedAsDeleted=0,this._hasNotified=!1,this._eventState=new lM(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,r=null,s=!1){if(!e)return null;let a=new cM(e,t,r);a.unregisterOnNextCall=s,i?this._observers.unshift(a):this._observers.push(a),this._onObserverAdded&&this._onObserverAdded(a),this._hasNotified&&this.notifyIfTriggered&&this._lastNotifiedValue!==void 0&&this.notifyObserver(a,this._lastNotifiedValue);let o=lre?new WeakRef(this):{deref:()=>this};return a._remove=(l=!1)=>{let c=o.deref();c&&(l?c.remove(a):c._remove(a))},a}addOnce(e){return this.add(e,void 0,void 0,void 0,!0)}remove(e){return e?(e._remove=null,this._observers.indexOf(e)!==-1?(this._deferUnregister(e),!0):!1):!1}removeCallback(e,t){for(let i=0;i{this._remove(e)},0))}_remove(e,t=!0){if(!e)return!1;let i=this._observers.indexOf(e);return i!==-1?(t&&this._numObserversMarkedAsDeleted--,this._observers.splice(i,1),!0):!1}makeObserverTopPriority(e){this._remove(e,!1),this._observers.unshift(e)}makeObserverBottomPriority(e){this._remove(e,!1),this._observers.push(e)}notifyObservers(e,t=-1,i,r,s){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=e),!this._observers.length)return!0;let a=this._eventState;a.mask=t,a.target=i,a.currentTarget=r,a.skipNextObservers=!1,a.lastReturnValue=e,a.userInfo=s;for(let o of this._observers)if(!o._willBeUnregistered&&(o.mask&t&&(o.unregisterOnNextCall&&this._deferUnregister(o),o.scope?a.lastReturnValue=o.callback.apply(o.scope,[e,a]):a.lastReturnValue=o.callback(e,a)),a.skipNextObservers))return!1;return!0}notifyObserver(e,t,i=-1){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=t),e._willBeUnregistered)return;let r=this._eventState;r.mask=i,r.skipNextObservers=!1,e.unregisterOnNextCall&&this._deferUnregister(e),e.callback(t,r)}hasObservers(){return this._observers.length-this._numObserversMarkedAsDeleted>0}clear(){for(;this._observers.length;){let e=this._observers.pop();e&&(e._remove=null)}this._onObserverAdded=null,this._numObserversMarkedAsDeleted=0,this.cleanLastNotifiedState()}cleanLastNotifiedState(){this._hasNotified=!1,this._lastNotifiedValue=void 0}clone(){let e=new n;return e._observers=this._observers.slice(0),e}hasSpecificMask(e=-1){for(let t of this._observers)if(t.mask&e||t.mask===e)return!0;return!1}}});var nT,_3=C(()=>{nT=class{get wrapU(){return this._cachedWrapU}set wrapU(e){this._cachedWrapU=e}get wrapV(){return this._cachedWrapV}set wrapV(e){this._cachedWrapV=e}get wrapR(){return this._cachedWrapR}set wrapR(e){this._cachedWrapR=e}get anisotropicFilteringLevel(){return this._cachedAnisotropicFilteringLevel}set anisotropicFilteringLevel(e){this._cachedAnisotropicFilteringLevel=e}get comparisonFunction(){return this._comparisonFunction}set comparisonFunction(e){this._comparisonFunction=e}get useMipMaps(){return this._useMipMaps}set useMipMaps(e){this._useMipMaps=e}constructor(){this.samplingMode=-1,this._useMipMaps=!0,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this._comparisonFunction=0}setParameters(e=1,t=1,i=1,r=1,s=2,a=0){return this._cachedWrapU=e,this._cachedWrapV=t,this._cachedWrapR=i,this._cachedAnisotropicFilteringLevel=r,this.samplingMode=s,this._comparisonFunction=a,this}compareSampler(e){return this._cachedWrapU===e._cachedWrapU&&this._cachedWrapV===e._cachedWrapV&&this._cachedWrapR===e._cachedWrapR&&this._cachedAnisotropicFilteringLevel===e._cachedAnisotropicFilteringLevel&&this.samplingMode===e.samplingMode&&this._comparisonFunction===e._comparisonFunction&&this._useMipMaps===e._useMipMaps}}});var g3,Pi,vs=C(()=>{di();_3();(function(n){n[n.Unknown=0]="Unknown",n[n.Url=1]="Url",n[n.Temp=2]="Temp",n[n.Raw=3]="Raw",n[n.Dynamic=4]="Dynamic",n[n.RenderTarget=5]="RenderTarget",n[n.MultiRenderTarget=6]="MultiRenderTarget",n[n.Cube=7]="Cube",n[n.CubeRaw=8]="CubeRaw",n[n.CubePrefiltered=9]="CubePrefiltered",n[n.Raw3D=10]="Raw3D",n[n.Raw2DArray=11]="Raw2DArray",n[n.DepthStencil=12]="DepthStencil",n[n.CubeRawRGBD=13]="CubeRawRGBD",n[n.Depth=14]="Depth"})(g3||(g3={}));Pi=class n extends nT{get useMipMaps(){return this._useMipMaps===null?this.generateMipMaps:this._useMipMaps}set useMipMaps(e){this._useMipMaps=e}get uniqueId(){return this._uniqueId}_setUniqueId(e){this._uniqueId=e}getEngine(){return this._engine}get source(){return this._source}constructor(e,t,i=!1){super(),this.isReady=!1,this.isCube=!1,this.is3D=!1,this.is2DArray=!1,this.isMultiview=!1,this.url="",this.generateMipMaps=!1,this._useMipMaps=null,this.mipLevelCount=1,this.samples=0,this.type=-1,this.format=-1,this.onLoadedObservable=new ie,this.onErrorObservable=new ie,this.onRebuildCallback=null,this.width=0,this.height=0,this.depth=0,this.baseWidth=0,this.baseHeight=0,this.baseDepth=0,this.invertY=!1,this._invertVScale=!1,this._associatedChannel=-1,this._source=0,this._buffer=null,this._bufferView=null,this._bufferViewArray=null,this._bufferViewArrayArray=null,this._size=0,this._extension="",this._files=null,this._workingCanvas=null,this._workingContext=null,this._cachedCoordinatesMode=null,this._isDisabled=!1,this._compression=null,this._sphericalPolynomial=null,this._sphericalPolynomialPromise=null,this._sphericalPolynomialComputed=!1,this._lodGenerationScale=0,this._lodGenerationOffset=0,this._useSRGBBuffer=!1,this._creationFlags=0,this._lodTextureHigh=null,this._lodTextureMid=null,this._lodTextureLow=null,this._isRGBD=!1,this._linearSpecularLOD=!1,this._irradianceTexture=null,this._hardwareTexture=null,this._maxLodLevel=null,this._references=1,this._gammaSpace=null,this._premulAlpha=!1,this._dynamicTextureSource=null,this._autoMSAAManagement=!1,this._engine=e,this._source=t,this._uniqueId=n._Counter++,i||(this._hardwareTexture=e._createHardwareTexture())}incrementReferences(){this._references++}updateSize(e,t,i=1){this._engine.updateTextureDimensions(this,e,t,i),this.width=e,this.height=t,this.depth=i,this.baseWidth=e,this.baseHeight=t,this.baseDepth=i,this._size=e*t*i}_rebuild(){var t,i;if(this.isReady=!1,this._cachedCoordinatesMode=null,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this.onRebuildCallback){let r=this.onRebuildCallback(this),s=a=>{a._swapAndDie(this,!1),this.isReady=r.isReady};r.isAsync?r.proxy.then(s):s(r.proxy);return}let e;switch(this.source){case 2:break;case 1:e=this._engine.createTexture((t=this._originalUrl)!=null?t:this.url,!this.generateMipMaps,this.invertY,null,this.samplingMode,r=>{r._swapAndDie(this,!1),this.isReady=!0},null,this._buffer,void 0,this.format,this._extension,void 0,void 0,void 0,this._useSRGBBuffer);return;case 3:if(e=this._engine.createRawTexture(this._bufferView,this.baseWidth,this.baseHeight,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type,this._creationFlags,this._useSRGBBuffer,this.mipLevelCount),e._swapAndDie(this,!1),this._bufferViewArray)for(let r=0;r{e._swapAndDie(this,!1),this.isReady=!0},null,this.format,this._extension,!1,0,0,null,void 0,this._useSRGBBuffer,ArrayBuffer.isView(this._buffer)?this._buffer:null);return;case 8:e=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,(i=this._originalFormat)!=null?i:this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression),e._swapAndDie(this,!1),this.isReady=!0;break;case 13:return;case 9:e=this._engine.createPrefilteredCubeTexture(this.url,null,this._lodGenerationScale,this._lodGenerationOffset,r=>{r&&r._swapAndDie(this,!1),this.isReady=!0},null,this.format,this._extension),e._sphericalPolynomial=this._sphericalPolynomial;return;case 12:case 14:break}}_swapAndDie(e,t=!0){var s;(s=this._hardwareTexture)==null||s.setUsage(e._source,this.generateMipMaps,this.is2DArray,this.isCube,this.is3D,this.width,this.height,this.depth),e._hardwareTexture=this._hardwareTexture,t&&(e._isRGBD=this._isRGBD),this._lodTextureHigh&&(e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureHigh=this._lodTextureHigh),this._lodTextureMid&&(e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureMid=this._lodTextureMid),this._lodTextureLow&&(e._lodTextureLow&&e._lodTextureLow.dispose(),e._lodTextureLow=this._lodTextureLow),this._irradianceTexture&&(e._irradianceTexture&&e._irradianceTexture.dispose(),e._irradianceTexture=this._irradianceTexture);let i=this._engine.getLoadedTexturesCache(),r=i.indexOf(this);r!==-1&&i.splice(r,1),r=i.indexOf(e),r===-1&&i.push(e)}dispose(){this._references--,this._references===0&&(this.onLoadedObservable.clear(),this.onErrorObservable.clear(),this._engine._releaseTexture(this),this._hardwareTexture=null,this._dynamicTextureSource=null)}};Pi._Counter=0});var Oe,Di=C(()=>{di();Oe=class{static get LastCreatedEngine(){return this.Instances.length===0?null:this.Instances[this.Instances.length-1]}static get LastCreatedScene(){return this._LastCreatedScene}};Oe.Instances=[];Oe.OnEnginesDisposedObservable=new ie;Oe._LastCreatedScene=null;Oe.UseFallbackTexture=!0;Oe.FallbackTexture=""});var te,Pt=C(()=>{te=class n{static _CheckLimit(e,t){let i=n._LogLimitOutputs[e];return i?i.current++:(i={limit:t,current:1},n._LogLimitOutputs[e]=i),i.current<=i.limit}static _GenerateLimitMessage(e,t=1){var s;let i=n._LogLimitOutputs[e];if(!i||!n.MessageLimitReached)return;let r=this._Levels[t];i.current===i.limit&&n[r.name](n.MessageLimitReached.replace(/%LIMIT%/g,""+i.limit).replace(/%TYPE%/g,(s=r.name)!=null?s:""))}static _AddLogEntry(e){n._LogCache=e+n._LogCache,n.OnNewCacheEntry&&n.OnNewCacheEntry(e)}static _FormatMessage(e){let t=r=>r<10?"0"+r:""+r,i=new Date;return"["+t(i.getHours())+":"+t(i.getMinutes())+":"+t(i.getSeconds())+"]: "+e}static _LogDisabled(e,t){}static _LogEnabled(e=1,t,i){let r=Array.isArray(t)?t[0]:t;if(i!==void 0&&!n._CheckLimit(r,i))return;let s=n._FormatMessage(r),a=this._Levels[e],o=Array.isArray(t)?t.slice(1):[];a.logFunc&&a.logFunc("BJS - "+s,...o);let l=`
${s}

`;n._AddLogEntry(l),n._GenerateLimitMessage(r,e)}static get LogCache(){return n._LogCache}static ClearLogCache(){n._LogCache="",n._LogLimitOutputs={},n.errorsCount=0}static set LogLevels(e){n.Log=n._LogDisabled,n.Warn=n._LogDisabled,n.Error=n._LogDisabled;let t=[n.MessageLogLevel,n.WarningLogLevel,n.ErrorLogLevel];for(let i of t)if((e&i)===i){let r=this._Levels[i];n[r.name]=n._LogEnabled.bind(n,i)}}};te.NoneLogLevel=0;te.MessageLogLevel=1;te.WarningLogLevel=2;te.ErrorLogLevel=4;te.AllLogLevel=7;te.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.";te._LogCache="";te._LogLimitOutputs={};te._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}];te.errorsCount=0;te.Log=te._LogEnabled.bind(te,te.MessageLogLevel);te.Warn=te._LogEnabled.bind(te,te.WarningLogLevel);te.Error=te._LogEnabled.bind(te,te.ErrorLogLevel)});var T,k=C(()=>{T=class n{static GetShadersRepository(e=0){return e===0?n.ShadersRepository:n.ShadersRepositoryWGSL}static GetShadersStore(e=0){return e===0?n.ShadersStore:n.ShadersStoreWGSL}static GetIncludesShadersStore(e=0){return e===0?n.IncludesShadersStore:n.IncludesShadersStoreWGSL}};T.ShadersRepository="src/Shaders/";T.ShadersStore={};T.IncludesShadersStore={};T.ShadersRepositoryWGSL="src/ShadersWGSL/";T.ShadersStoreWGSL={};T.IncludesShadersStoreWGSL={}});function fr(){return typeof window!="undefined"}function Nl(){return typeof navigator!="undefined"}function sf(){return typeof document!="undefined"}function sT(n){let e="",t=n.firstChild;for(;t;)t.nodeType===3&&(e+=t.textContent),t=t.nextSibling;return e}var ga=C(()=>{});var aT,v3=C(()=>{aT=class{constructor(){this._valueCache={},this.vertexCompilationError=null,this.fragmentCompilationError=null,this.programLinkError=null,this.programValidationError=null,this._isDisposed=!1}get isAsync(){return this.isParallelCompiled}get isReady(){return this.program?this.isParallelCompiled?this.engine._isRenderingStateCompiled(this):!0:!1}_handlesSpectorRebuildCallback(e){e&&this.program&&e(this.program)}setEngine(e){this.engine=e}_fillEffectInformation(e,t,i,r,s,a,o,l){let c=this.engine;if(c.supportsUniformBuffers)for(let d in t)e.bindUniformBlock(d,t[d]);this.engine.getUniforms(this,i).forEach((d,u)=>{r[i[u]]=d}),this._uniforms=r;let h;for(h=0;h{a[d]=u});for(let d of c.getAttributes(this,o))l.push(d)}dispose(){this._uniforms={},this._isDisposed=!0}_cacheMatrix(e,t){let i=this._valueCache[e],r=t.updateFlag;return i!==void 0&&i===r?!1:(this._valueCache[e]=r,!0)}_cacheFloat2(e,t,i){let r=this._valueCache[e];if(!r||r.length!==2)return r=[t,i],this._valueCache[e]=r,!0;let s=!1;return r[0]!==t&&(r[0]=t,s=!0),r[1]!==i&&(r[1]=i,s=!0),s}_cacheFloat3(e,t,i,r){let s=this._valueCache[e];if(!s||s.length!==3)return s=[t,i,r],this._valueCache[e]=s,!0;let a=!1;return s[0]!==t&&(s[0]=t,a=!0),s[1]!==i&&(s[1]=i,a=!0),s[2]!==r&&(s[2]=r,a=!0),a}_cacheFloat4(e,t,i,r,s){let a=this._valueCache[e];if(!a||a.length!==4)return a=[t,i,r,s],this._valueCache[e]=a,!0;let o=!1;return a[0]!==t&&(a[0]=t,o=!0),a[1]!==i&&(a[1]=i,o=!0),a[2]!==r&&(a[2]=r,o=!0),a[3]!==s&&(a[3]=s,o=!0),o}setInt(e,t){let i=this._valueCache[e];i!==void 0&&i===t||this.engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this.engine.setInt3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))}setInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&(this.engine.setInt4(this._uniforms[e],t,i,r,s)||(this._valueCache[e]=null))}setIntArray(e,t){this._valueCache[e]=null,this.engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this.engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this.engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this.engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){let i=this._valueCache[e];i!==void 0&&i===t||this.engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setUInt2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setUInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this.engine.setUInt3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))}setUInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&(this.engine.setUInt4(this._uniforms[e],t,i,r,s)||(this._valueCache[e]=null))}setUIntArray(e,t){this._valueCache[e]=null,this.engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this.engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this.engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this.engine.setUIntArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this.engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this.engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this.engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this.engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this.engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&(this.engine.setMatrices(this._uniforms[e],t.asArray())||(this._valueCache[e]=null))}setMatrix3x3(e,t){this._valueCache[e]=null,this.engine.setMatrix3x3(this._uniforms[e],t)}setMatrix2x2(e,t){this._valueCache[e]=null,this.engine.setMatrix2x2(this._uniforms[e],t)}setFloat(e,t){let i=this._valueCache[e];i!==void 0&&i===t||this.engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&(this.engine.setFloat2(this._uniforms[e],t.x,t.y)||(this._valueCache[e]=null))}setFloat2(e,t,i){this._cacheFloat2(e,t,i)&&(this.engine.setFloat2(this._uniforms[e],t,i)||(this._valueCache[e]=null))}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&(this.engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)||(this._valueCache[e]=null))}setFloat3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&(this.engine.setFloat3(this._uniforms[e],t,i,r)||(this._valueCache[e]=null))}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setFloat4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&(this.engine.setFloat4(this._uniforms[e],t,i,r,s)||(this._valueCache[e]=null))}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this.engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))}setColor4(e,t,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)||(this._valueCache[e]=null))}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))}_getVertexShaderCode(){return this.vertexShader?this.engine._getShaderSource(this.vertexShader):null}_getFragmentShaderCode(){return this.fragmentShader?this.engine._getShaderSource(this.fragmentShader):null}}});function qe(n,e=!1){if(!(e&&E3[n]))return E3[n]=!0,`${n} needs to be imported before as it contains a side-effect required by your code.`}var E3,hn=C(()=>{E3={}});function oT(n,e,t=""){return t+(e?e+` +`:"")+n}function lT(n,e,t,i,r,s,a){let o=a||Bu.loadFile;if(o)return o(n,e,t,i,r,s);throw qe("FileTools")}function cT(n,e,t,i){if(n){e?n.IS_NDC_HALF_ZRANGE="":delete n.IS_NDC_HALF_ZRANGE,t?n.USE_REVERSE_DEPTHBUFFER="":delete n.USE_REVERSE_DEPTHBUFFER,i?n.USE_EXACT_SRGB_CONVERSIONS="":delete n.USE_EXACT_SRGB_CONVERSIONS;return}else{let r="";return e&&(r+="#define IS_NDC_HALF_ZRANGE"),t&&(r&&(r+=` `),r+="#define USE_REVERSE_DEPTHBUFFER"),i&&(r&&(r+=` -`),r+="#define USE_EXACT_SRGB_CONVERSIONS"),r}}function S3(n,e,t=!1,i){switch(n){case 3:{let s=new Int8Array(e);return i&&s.set(new Int8Array(i)),s}case 0:{let s=new Uint8Array(e);return i&&s.set(new Uint8Array(i)),s}case 4:{let s=typeof e!="number"?new Int16Array(e):new Int16Array(t?e/2:e);return i&&s.set(new Int16Array(i)),s}case 5:case 8:case 9:case 10:case 2:{let s=typeof e!="number"?new Uint16Array(e):new Uint16Array(t?e/2:e);return i&&s.set(new Uint16Array(i)),s}case 6:{let s=typeof e!="number"?new Int32Array(e):new Int32Array(t?e/4:e);return i&&s.set(new Int32Array(i)),s}case 7:case 11:case 12:case 13:case 14:case 15:{let s=typeof e!="number"?new Uint32Array(e):new Uint32Array(t?e/4:e);return i&&s.set(new Uint32Array(i)),s}case 1:{let s=typeof e!="number"?new Float32Array(e):new Float32Array(t?e/4:e);return i&&s.set(new Float32Array(i)),s}}let r=new Uint8Array(e);return i&&r.set(new Uint8Array(i)),r}var Uu,of=C(()=>{hn();va();Uu={}});function Pn(n){let e=fM.get(n);if(!e){if(!n)return cre;e={_webGLVersion:n.TEXTURE_BINDING_3D?2:1,_context:n,parallelShaderCompile:n.getExtension("KHR_parallel_shader_compile")||void 0,cachedPipelines:{}},fM.set(n,e)}return e}function cT(n){fM.delete(n)}function dM(n,e,t,i,r,s){var c;let a=Pn(i);s||(s=(c=a._createShaderProgramInjection)!=null?c:fT);let o=hM(e,"vertex",i,a._contextWasLost),l=hM(t,"fragment",i,a._contextWasLost);return s(n,o,l,i,r,a.validateShaderPrograms)}function uM(n,e,t,i,r,s=null,a){var h;let o=Pn(r);a||(a=(h=o._createShaderProgramInjection)!=null?h:fT);let l=o._webGLVersion>1?`#version 300 es +`),r+="#define USE_EXACT_SRGB_CONVERSIONS"),r}}function S3(n,e,t=!1,i){switch(n){case 3:{let s=new Int8Array(e);return i&&s.set(new Int8Array(i)),s}case 0:{let s=new Uint8Array(e);return i&&s.set(new Uint8Array(i)),s}case 4:{let s=typeof e!="number"?new Int16Array(e):new Int16Array(t?e/2:e);return i&&s.set(new Int16Array(i)),s}case 5:case 8:case 9:case 10:case 2:{let s=typeof e!="number"?new Uint16Array(e):new Uint16Array(t?e/2:e);return i&&s.set(new Uint16Array(i)),s}case 6:{let s=typeof e!="number"?new Int32Array(e):new Int32Array(t?e/4:e);return i&&s.set(new Int32Array(i)),s}case 7:case 11:case 12:case 13:case 14:case 15:{let s=typeof e!="number"?new Uint32Array(e):new Uint32Array(t?e/4:e);return i&&s.set(new Uint32Array(i)),s}case 1:{let s=typeof e!="number"?new Float32Array(e):new Float32Array(t?e/4:e);return i&&s.set(new Float32Array(i)),s}}let r=new Uint8Array(e);return i&&r.set(new Uint8Array(i)),r}var Bu,af=C(()=>{hn();ga();Bu={}});function Pn(n){let e=fM.get(n);if(!e){if(!n)return cre;e={_webGLVersion:n.TEXTURE_BINDING_3D?2:1,_context:n,parallelShaderCompile:n.getExtension("KHR_parallel_shader_compile")||void 0,cachedPipelines:{}},fM.set(n,e)}return e}function fT(n){fM.delete(n)}function dM(n,e,t,i,r,s){var c;let a=Pn(i);s||(s=(c=a._createShaderProgramInjection)!=null?c:hT);let o=hM(e,"vertex",i,a._contextWasLost),l=hM(t,"fragment",i,a._contextWasLost);return s(n,o,l,i,r,a.validateShaderPrograms)}function uM(n,e,t,i,r,s=null,a){var h;let o=Pn(r);a||(a=(h=o._createShaderProgramInjection)!=null?h:hT);let l=o._webGLVersion>1?`#version 300 es #define WEBGL2 -`:"",c=T3(e,"vertex",i,l,r,o._contextWasLost),f=T3(t,"fragment",i,l,r,o._contextWasLost);return a(n,c,f,r,s,o.validateShaderPrograms)}function A3(n,e){let t=new sT,i=Pn(n);return i.parallelShaderCompile&&!i.disableParallelShaderCompile&&(t.isParallelCompiled=!0),t.context=i._context,t}function fT(n,e,t,i,r=null,s){let a=i.createProgram();if(n.program=a,!a)throw new Error("Unable to create program");return i.attachShader(a,e),i.attachShader(a,t),i.linkProgram(a),n.context=i,n.vertexShader=e,n.fragmentShader=t,n.isParallelCompiled||hT(n,i,s),a}function x3(n,e,t){let i=n;if(i._isDisposed)return!1;let r=Pn(e);return r&&r.parallelShaderCompile&&r.parallelShaderCompile.COMPLETION_STATUS_KHR&&i.program&&e.getProgramParameter(i.program,r.parallelShaderCompile.COMPLETION_STATUS_KHR)?(hT(i,e,t),!0):!1}function hT(n,e,t){let i=n.context,r=n.vertexShader,s=n.fragmentShader,a=n.program;if(!i.getProgramParameter(a,i.LINK_STATUS)){if(!e.getShaderParameter(r,e.COMPILE_STATUS)){let c=e.getShaderInfoLog(r);if(c)throw n.vertexCompilationError=c,new Error("VERTEX SHADER "+c)}if(!e.getShaderParameter(s,e.COMPILE_STATUS)){let c=e.getShaderInfoLog(s);if(c)throw n.fragmentCompilationError=c,new Error("FRAGMENT SHADER "+c)}let l=i.getProgramInfoLog(a);if(l)throw n.programLinkError=l,new Error(l)}if(t&&(i.validateProgram(a),!i.getProgramParameter(a,i.VALIDATE_STATUS))){let c=i.getProgramInfoLog(a);if(c)throw n.programValidationError=c,new Error(c)}i.deleteShader(r),i.deleteShader(s),n.vertexShader=void 0,n.fragmentShader=void 0,n.onCompiled&&(n.onCompiled(),n.onCompiled=void 0)}function R3(n,e,t,i,r,s,a,o,l,c="",f,h,d){var p,_;let u=Pn(n.context);h||(h=(p=u.createRawShaderProgramInjection)!=null?p:dM),d||(d=(_=u.createShaderProgramInjection)!=null?_:uM);let m=n;i?m.program=h(m,e,t,m.context,l):m.program=d(m,e,t,o,m.context,l),m.program.__SPECTOR_rebuildProgram=a,f()}function T3(n,e,t,i,r,s){return hM(aT(n,t,i),e,r,s)}function hM(n,e,t,i){let r=t.createShader(e==="vertex"?t.VERTEX_SHADER:t.FRAGMENT_SHADER);if(!r){let s=t.NO_ERROR,a;for(;(a=t.getError())!==t.NO_ERROR;)s=a;throw new Error(`Something went wrong while creating a gl ${e} shader object. gl error=${s}, gl isContextLost=${t.isContextLost()}, _contextWasLost=${i}`)}return t.shaderSource(r,n),t.compileShader(r),r}function b3(n,e){e.useProgram(n)}function I3(n,e){let t=n;if(!t.isParallelCompiled){e(n);return}let i=t.onCompiled;t.onCompiled=()=>{i==null||i(),e(n)}}var fM,cre,mM=C(()=>{v3();of();fM=new WeakMap,cre={_webGLVersion:2,cachedPipelines:{}}});var fre,hre,Yo,dT=C(()=>{fre="attribute",hre="varying",Yo=class{constructor(){this.children=[]}isValid(e){return!0}process(e,t,i){var s,a,o,l,c,f,h;let r="";if(this.line){let d=this.line,u=t.processor;if(u){u.lineProcessor&&(d=u.lineProcessor(d,t.isFragment,t.processingContext));let m=(a=(s=t.processor)==null?void 0:s.attributeKeywordName)!=null?a:fre,p=t.isFragment&&((o=t.processor)!=null&&o.varyingFragmentKeywordName)?(l=t.processor)==null?void 0:l.varyingFragmentKeywordName:!t.isFragment&&((c=t.processor)!=null&&c.varyingVertexKeywordName)?(f=t.processor)==null?void 0:f.varyingVertexKeywordName:hre;!t.isFragment&&u.attributeProcessor&&this.line.startsWith(m)?d=u.attributeProcessor(this.line,e,t.processingContext):u.varyingProcessor&&((h=u.varyingCheck)!=null&&h.call(u,this.line,t.isFragment)||!u.varyingCheck&&this.line.startsWith(p))?d=u.varyingProcessor(this.line,t.isFragment,e,t.processingContext):u.uniformProcessor&&u.uniformRegexp&&u.uniformRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(d=u.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):u.uniformBufferProcessor&&u.uniformBufferRegexp&&u.uniformBufferRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(d=u.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0):u.textureProcessor&&u.textureRegexp&&u.textureRegexp.test(this.line)?d=u.textureProcessor(this.line,t.isFragment,e,t.processingContext):(u.uniformProcessor||u.uniformBufferProcessor)&&this.line.startsWith("uniform")&&!t.lookForClosingBracketForUniformBuffer&&(/uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/.test(this.line)?u.uniformProcessor&&(d=u.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):u.uniformBufferProcessor&&(d=u.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0)),t.lookForClosingBracketForUniformBuffer&&this.line.indexOf("}")!==-1&&(t.lookForClosingBracketForUniformBuffer=!1,u.endOfUniformBufferProcessor&&(d=u.endOfUniformBufferProcessor(this.line,t.isFragment,t.processingContext)))}r+=d+` -`}for(let d of this.children)r+=d.process(e,t,i);return this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true",i[this.additionalDefineKey]=e[this.additionalDefineKey]),r}}});var uT,M3=C(()=>{uT=class{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex1&&this._lines.push(i);else{let s=t.split(";");for(let a=0;a{dT();Vu=class extends Yo{process(e,t,i){for(let r=0;r{dT();mT=class extends Yo{isValid(e){return this.testExpression.isTrue(e)}}});var _n,Gu=C(()=>{_n=class n{isTrue(e){return!0}static postfixToInfix(e){let t=[];for(let i of e)if(n._OperatorPriority[i]===void 0)t.push(i);else{let r=t[t.length-1],s=t[t.length-2];t.length-=2,t.push(`(${s}${i}${r})`)}return t[t.length-1]}static infixToPostfix(e){let t=n._InfixToPostfixCache.get(e);if(t)return t.accessTime=Date.now(),t.result;if(!e.includes("&&")&&!e.includes("||")&&!e.includes(")")&&!e.includes("("))return[e];let i=[],r=-1,s=()=>{f=f.trim(),f!==""&&(i.push(f),f="")},a=h=>{rn._Stack[r],l=()=>r===-1?"!!INVALID EXPRESSION!!":n._Stack[r--],c=0,f="";for(;c1){for(s();r!==-1&&n._OperatorPriority[o()]>=n._OperatorPriority[d];)i.push(l());a(d),c++}else f+=h;c++}for(s();r!==-1;)o()==="("?l():i.push(l());return n._InfixToPostfixCache.size>=n.InfixToPostfixCacheLimitSize&&n.ClearCache(),n._InfixToPostfixCache.set(e,{result:i,accessTime:Date.now()}),i}static ClearCache(){let e=Array.from(n._InfixToPostfixCache.entries()).sort((t,i)=>t[1].accessTime-i[1].accessTime);for(let t=0;t{Gu();Ch=class extends _n{constructor(e,t=!1){super(),this.define=e,this.not=t}isTrue(e){let t=e[this.define]!==void 0;return this.not&&(t=!t),t}}});var pT,D3=C(()=>{Gu();pT=class extends _n{isTrue(e){return this.leftOperand.isTrue(e)||this.rightOperand.isTrue(e)}}});var _T,L3=C(()=>{Gu();_T=class extends _n{isTrue(e){return this.leftOperand.isTrue(e)&&this.rightOperand.isTrue(e)}}});var gT,O3=C(()=>{Gu();gT=class extends _n{constructor(e,t,i){super(),this.define=e,this.operand=t,this.testValue=i}toString(){return`${this.define} ${this.operand} ${this.testValue}`}isTrue(e){let t=!1,i=parseInt(e[this.define]!=null?e[this.define]:this.define),r=parseInt(e[this.testValue]!=null?e[this.testValue]:this.testValue);if(isNaN(i)||isNaN(r))return!1;switch(this.operand){case">":t=i>r;break;case"<":t=i=":t=i>=r;break;case"==":t=i===r;break;case"!=":t=i!==r;break}return t}}});function F3(n){n.processor&&n.processor.initializeShaders&&n.processor.initializeShaders(n.processingContext)}function EM(n,e,t,i){var r;(r=e.processor)!=null&&r.preProcessShaderCode&&(n=e.processor.preProcessShaderCode(n,e.isFragment)),D_(n,e,s=>{e.processCodeAfterIncludes&&(s=e.processCodeAfterIncludes(e.isFragment?"fragment":"vertex",s,e.defines));let a=Sre(s,e,i);t(a,s)})}function B3(n,e,t){return!t.processor||!t.processor.finalizeShaders?{vertexCode:n,fragmentCode:e}:t.processor.finalizeShaders(n,e,t.processingContext)}function _re(n,e){var i;if((i=e.processor)!=null&&i.noPrecision)return n;let t=e.shouldUseHighPrecisionShader;return n.indexOf("precision highp float")===-1?t?n=`precision highp float; +`:"",c=T3(e,"vertex",i,l,r,o._contextWasLost),f=T3(t,"fragment",i,l,r,o._contextWasLost);return a(n,c,f,r,s,o.validateShaderPrograms)}function A3(n,e){let t=new aT,i=Pn(n);return i.parallelShaderCompile&&!i.disableParallelShaderCompile&&(t.isParallelCompiled=!0),t.context=i._context,t}function hT(n,e,t,i,r=null,s){let a=i.createProgram();if(n.program=a,!a)throw new Error("Unable to create program");return i.attachShader(a,e),i.attachShader(a,t),i.linkProgram(a),n.context=i,n.vertexShader=e,n.fragmentShader=t,n.isParallelCompiled||dT(n,i,s),a}function x3(n,e,t){let i=n;if(i._isDisposed)return!1;let r=Pn(e);return r&&r.parallelShaderCompile&&r.parallelShaderCompile.COMPLETION_STATUS_KHR&&i.program&&e.getProgramParameter(i.program,r.parallelShaderCompile.COMPLETION_STATUS_KHR)?(dT(i,e,t),!0):!1}function dT(n,e,t){let i=n.context,r=n.vertexShader,s=n.fragmentShader,a=n.program;if(!i.getProgramParameter(a,i.LINK_STATUS)){if(!e.getShaderParameter(r,e.COMPILE_STATUS)){let c=e.getShaderInfoLog(r);if(c)throw n.vertexCompilationError=c,new Error("VERTEX SHADER "+c)}if(!e.getShaderParameter(s,e.COMPILE_STATUS)){let c=e.getShaderInfoLog(s);if(c)throw n.fragmentCompilationError=c,new Error("FRAGMENT SHADER "+c)}let l=i.getProgramInfoLog(a);if(l)throw n.programLinkError=l,new Error(l)}if(t&&(i.validateProgram(a),!i.getProgramParameter(a,i.VALIDATE_STATUS))){let c=i.getProgramInfoLog(a);if(c)throw n.programValidationError=c,new Error(c)}i.deleteShader(r),i.deleteShader(s),n.vertexShader=void 0,n.fragmentShader=void 0,n.onCompiled&&(n.onCompiled(),n.onCompiled=void 0)}function R3(n,e,t,i,r,s,a,o,l,c="",f,h,d){var p,_;let u=Pn(n.context);h||(h=(p=u.createRawShaderProgramInjection)!=null?p:dM),d||(d=(_=u.createShaderProgramInjection)!=null?_:uM);let m=n;i?m.program=h(m,e,t,m.context,l):m.program=d(m,e,t,o,m.context,l),m.program.__SPECTOR_rebuildProgram=a,f()}function T3(n,e,t,i,r,s){return hM(oT(n,t,i),e,r,s)}function hM(n,e,t,i){let r=t.createShader(e==="vertex"?t.VERTEX_SHADER:t.FRAGMENT_SHADER);if(!r){let s=t.NO_ERROR,a;for(;(a=t.getError())!==t.NO_ERROR;)s=a;throw new Error(`Something went wrong while creating a gl ${e} shader object. gl error=${s}, gl isContextLost=${t.isContextLost()}, _contextWasLost=${i}`)}return t.shaderSource(r,n),t.compileShader(r),r}function b3(n,e){e.useProgram(n)}function I3(n,e){let t=n;if(!t.isParallelCompiled){e(n);return}let i=t.onCompiled;t.onCompiled=()=>{i==null||i(),e(n)}}var fM,cre,mM=C(()=>{v3();af();fM=new WeakMap,cre={_webGLVersion:2,cachedPipelines:{}}});var fre,hre,Yo,uT=C(()=>{fre="attribute",hre="varying",Yo=class{constructor(){this.children=[]}isValid(e){return!0}process(e,t,i){var s,a,o,l,c,f,h;let r="";if(this.line){let d=this.line,u=t.processor;if(u){u.lineProcessor&&(d=u.lineProcessor(d,t.isFragment,t.processingContext));let m=(a=(s=t.processor)==null?void 0:s.attributeKeywordName)!=null?a:fre,p=t.isFragment&&((o=t.processor)!=null&&o.varyingFragmentKeywordName)?(l=t.processor)==null?void 0:l.varyingFragmentKeywordName:!t.isFragment&&((c=t.processor)!=null&&c.varyingVertexKeywordName)?(f=t.processor)==null?void 0:f.varyingVertexKeywordName:hre;!t.isFragment&&u.attributeProcessor&&this.line.startsWith(m)?d=u.attributeProcessor(this.line,e,t.processingContext):u.varyingProcessor&&((h=u.varyingCheck)!=null&&h.call(u,this.line,t.isFragment)||!u.varyingCheck&&this.line.startsWith(p))?d=u.varyingProcessor(this.line,t.isFragment,e,t.processingContext):u.uniformProcessor&&u.uniformRegexp&&u.uniformRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(d=u.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):u.uniformBufferProcessor&&u.uniformBufferRegexp&&u.uniformBufferRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(d=u.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0):u.textureProcessor&&u.textureRegexp&&u.textureRegexp.test(this.line)?d=u.textureProcessor(this.line,t.isFragment,e,t.processingContext):(u.uniformProcessor||u.uniformBufferProcessor)&&this.line.startsWith("uniform")&&!t.lookForClosingBracketForUniformBuffer&&(/uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/.test(this.line)?u.uniformProcessor&&(d=u.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):u.uniformBufferProcessor&&(d=u.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0)),t.lookForClosingBracketForUniformBuffer&&this.line.indexOf("}")!==-1&&(t.lookForClosingBracketForUniformBuffer=!1,u.endOfUniformBufferProcessor&&(d=u.endOfUniformBufferProcessor(this.line,t.isFragment,t.processingContext)))}r+=d+` +`}for(let d of this.children)r+=d.process(e,t,i);return this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true",i[this.additionalDefineKey]=e[this.additionalDefineKey]),r}}});var mT,M3=C(()=>{mT=class{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex1&&this._lines.push(i);else{let s=t.split(";");for(let a=0;a{uT();Uu=class extends Yo{process(e,t,i){for(let r=0;r{uT();pT=class extends Yo{isValid(e){return this.testExpression.isTrue(e)}}});var _n,Vu=C(()=>{_n=class n{isTrue(e){return!0}static postfixToInfix(e){let t=[];for(let i of e)if(n._OperatorPriority[i]===void 0)t.push(i);else{let r=t[t.length-1],s=t[t.length-2];t.length-=2,t.push(`(${s}${i}${r})`)}return t[t.length-1]}static infixToPostfix(e){let t=n._InfixToPostfixCache.get(e);if(t)return t.accessTime=Date.now(),t.result;if(!e.includes("&&")&&!e.includes("||")&&!e.includes(")")&&!e.includes("("))return[e];let i=[],r=-1,s=()=>{f=f.trim(),f!==""&&(i.push(f),f="")},a=h=>{rn._Stack[r],l=()=>r===-1?"!!INVALID EXPRESSION!!":n._Stack[r--],c=0,f="";for(;c1){for(s();r!==-1&&n._OperatorPriority[o()]>=n._OperatorPriority[d];)i.push(l());a(d),c++}else f+=h;c++}for(s();r!==-1;)o()==="("?l():i.push(l());return n._InfixToPostfixCache.size>=n.InfixToPostfixCacheLimitSize&&n.ClearCache(),n._InfixToPostfixCache.set(e,{result:i,accessTime:Date.now()}),i}static ClearCache(){let e=Array.from(n._InfixToPostfixCache.entries()).sort((t,i)=>t[1].accessTime-i[1].accessTime);for(let t=0;t{Vu();Ch=class extends _n{constructor(e,t=!1){super(),this.define=e,this.not=t}isTrue(e){let t=e[this.define]!==void 0;return this.not&&(t=!t),t}}});var _T,D3=C(()=>{Vu();_T=class extends _n{isTrue(e){return this.leftOperand.isTrue(e)||this.rightOperand.isTrue(e)}}});var gT,L3=C(()=>{Vu();gT=class extends _n{isTrue(e){return this.leftOperand.isTrue(e)&&this.rightOperand.isTrue(e)}}});var vT,O3=C(()=>{Vu();vT=class extends _n{constructor(e,t,i){super(),this.define=e,this.operand=t,this.testValue=i}toString(){return`${this.define} ${this.operand} ${this.testValue}`}isTrue(e){let t=!1,i=parseInt(e[this.define]!=null?e[this.define]:this.define),r=parseInt(e[this.testValue]!=null?e[this.testValue]:this.testValue);if(isNaN(i)||isNaN(r))return!1;switch(this.operand){case">":t=i>r;break;case"<":t=i=":t=i>=r;break;case"==":t=i===r;break;case"!=":t=i!==r;break}return t}}});function F3(n){n.processor&&n.processor.initializeShaders&&n.processor.initializeShaders(n.processingContext)}function EM(n,e,t,i){var r;(r=e.processor)!=null&&r.preProcessShaderCode&&(n=e.processor.preProcessShaderCode(n,e.isFragment)),D_(n,e,s=>{e.processCodeAfterIncludes&&(s=e.processCodeAfterIncludes(e.isFragment?"fragment":"vertex",s,e.defines));let a=Sre(s,e,i);t(a,s)})}function B3(n,e,t){return!t.processor||!t.processor.finalizeShaders?{vertexCode:n,fragmentCode:e}:t.processor.finalizeShaders(n,e,t.processingContext)}function _re(n,e){var i;if((i=e.processor)!=null&&i.noPrecision)return n;let t=e.shouldUseHighPrecisionShader;return n.indexOf("precision highp float")===-1?t?n=`precision highp float; `+n:n=`precision mediump float; -`+n:t||(n=n.replace("precision highp float","precision mediump float")),n}function _M(n){let t=/defined\((.+)\)/.exec(n);if(t&&t.length)return new Ch(t[1].trim(),n[0]==="!");let i=["==","!=",">=","<=","<",">"],r="",s=0;for(r of i)if(s=n.indexOf(r),s>-1)break;if(s===-1)return new Ch(n);let a=n.substring(0,s).trim(),o=n.substring(s+r.length).trim();return new gT(a,r,o)}function gre(n){n=n.replace(dre,"defined[$1]");let e=_n.infixToPostfix(n),t=[];for(let r of e)if(r!=="||"&&r!=="&&")t.push(r);else if(t.length>=2){let s=t[t.length-1],a=t[t.length-2];t.length-=2;let o=r=="&&"?new _T:new pT;typeof s=="string"&&(s=s.replace(pM,"defined($1)")),typeof a=="string"&&(a=a.replace(pM,"defined($1)")),o.leftOperand=typeof a=="string"?_M(a):a,o.rightOperand=typeof s=="string"?_M(s):s,t.push(o)}let i=t[t.length-1];return typeof i=="string"&&(i=i.replace(pM,"defined($1)")),typeof i=="string"?_M(i):i}function ET(n,e){let t=new mT,i=n.substring(0,e),r=n.substring(e);return r=r.substring(0,(r.indexOf("//")+1||r.length+1)-1).trim(),i==="#ifdef"?t.testExpression=new Ch(r):i==="#ifndef"?t.testExpression=new Ch(r,!0):t.testExpression=gre(r),t}function gM(n,e,t,i){let r;for(;vM(n,t,i);){r=n.currentLine;let s=r.substring(0,5).toLowerCase();if(s==="#else"){let a=new Yo;e.children.push(a),vM(n,a,i);return}else if(s==="#elif"){let a=ET(r,5);e.children.push(a),t=a}}}function vM(n,e,t){for(;n.canRead;){n.lineIndex++;let i=n.currentLine;if(i.indexOf("#")>=0){let s=pre.exec(i);if(s&&s.length){switch(s[0]){case"#ifdef":{let o=new Vu;e.children.push(o);let l=ET(i,6);o.children.push(l),gM(n,o,l,t);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{let o=new Vu;e.children.push(o);let l=ET(i,7);o.children.push(l),gM(n,o,l,t);break}case"#if":{let o=new Vu,l=ET(i,3);e.children.push(o),o.children.push(l),gM(n,o,l,t);break}}continue}}let r=new Yo;if(r.line=i,e.children.push(r),i[0]==="#"&&i[1]==="d"){let s=i.replace(";","").split(" ");r.additionalDefineKey=s[1],s.length===3&&(r.additionalDefineValue=s[2])}}return!1}function vre(n,e,t,i){let r=new Yo,s=new uT;return s.lineIndex=-1,s.lines=n.split(` -`),vM(s,r,i),r.process(e,t,i)}function Ere(n,e){var r;let t=n.defines,i={};for(let s of t){let o=s.replace("#define","").replace(";","").trim().split(" ");i[o[0]]=o.length>1?o[1]:""}return((r=n.processor)==null?void 0:r.shaderLanguage)===0&&(i.GL_ES="true"),i.__VERSION__=n.version,i[n.platformName]="true",lT(i,e==null?void 0:e.isNDCHalfZRange,e==null?void 0:e.useReverseDepthBuffer,e==null?void 0:e.useExactSrgbConversions),i}function Sre(n,e,t){let i=_re(n,e);if(!e.processor||e.processor.shaderLanguage===0&&i.indexOf("#version 3")!==-1&&(i=i.replace("#version 300 es",""),!e.processor.parseGLES3))return i;let r=e.defines,s=Ere(e,t);e.processor.preProcessor&&(i=e.processor.preProcessor(i,r,s,e.isFragment,e.processingContext));let a={};return i=vre(i,s,e,a),e.processor.postProcessor&&(i=e.processor.postProcessor(i,r,e.isFragment,e.processingContext,t?{drawBuffersExtensionDisabled:!t.getCaps().drawBuffersExtension}:{},s,a)),t!=null&&t._features.needShaderCodeInlining&&(i=t.inlineShaderCode(i)),i}function D_(n,e,t){vT.length=0;let i;for(;(i=ure.exec(n))!==null;)vT.push(i);let r=[n],s=!1;for(let o of vT){let l=o[1];if(l.indexOf("__decl__")!==-1&&(l=l.replace(mre,""),e.supportsUniformBuffers&&(l=l.replace("Vertex","Ubo").replace("Fragment","Ubo")),l=l+"Declaration"),e.includesShadersStore[l]){let c=e.includesShadersStore[l];if(o[2]){let h=o[3].split(",");for(let d=0;dv+"{X}")),c+=p.replace(w3,_.toString())+` -`}else e.supportsUniformBuffers||(c=c.replace(N3,(d,u)=>u+"{X}")),c=c.replace(w3,h)}let f=[];for(let h of r){let d=h.split(o[0]);for(let u=0;u=0||c.indexOf("#include <")>=0}else{let c=e.shadersRepository+"ShadersInclude/"+l+".fx";SM.loadFile(c,f=>{e.includesShadersStore[l]=f,D_(r.join(""),e,t)});return}}vT.length=0;let a=r.join("");s?D_(a.toString(),e,t):t(a)}var dre,pM,ure,mre,N3,w3,vT,pre,SM,ST=C(()=>{dT();M3();C3();y3();P3();D3();L3();Gu();O3();hn();of();dre=/defined\s*?\((.+?)\)/g,pM=/defined\s*?\[(.+?)\]/g,ure=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,mre=/__decl__/,N3=/light\{X\}.(\w*)/g,w3=/\{X\}/g,vT=[],pre=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;SM={loadFile:(n,e,t,i,r,s)=>{throw Ze("FileTools")}}});function V3(n,e){return Pn(e).cachedPipelines[n]}function TT(n){let e=n._name,t=n.context;if(e&&t){let i=Pn(t),r=i.cachedPipelines[e];r==null||r.dispose(),delete i.cachedPipelines[e]}}function G3(n,e,t,i,r,s,a){let o,l,c=cr()?s==null?void 0:s.getHostDocument():null;typeof e=="string"?o=e:typeof e.vertexSource=="string"?o="source:"+e.vertexSource:typeof e.vertexElement=="string"?o=(c==null?void 0:c.getElementById(e.vertexElement))||e.vertexElement:o=e.vertex||e,typeof e=="string"?l=e:typeof e.fragmentSource=="string"?l="source:"+e.fragmentSource:typeof e.fragmentElement=="string"?l=(c==null?void 0:c.getElementById(e.fragmentElement))||e.fragmentElement:l=e.fragment||e;let f=[void 0,void 0],h=()=>{if(f[0]&&f[1]){let[d,u]=f;F3(n),EM(d,n,(m,p)=>{a&&(a._vertexSourceCodeBeforeMigration=p),t&&(m=t("vertex",m)),n.isFragment=!0,EM(u,n,(_,g)=>{a&&(a._fragmentSourceCodeBeforeMigration=g),t&&(_=t("fragment",_));let v=B3(m,_,n);n=null;let x=Tre(v.vertexCode,v.fragmentCode,e,r);i==null||i(x.vertexSourceCode,x.fragmentSourceCode)},s)},s)}};U3(o,"Vertex","",d=>{a&&(a._rawVertexSourceCode=d),f[0]=d,h()},r),U3(l,"Fragment","Pixel",d=>{a&&(a._rawFragmentSourceCode=d),f[1]=d,h()},r)}function U3(n,e,t,i,r,s){if(typeof HTMLElement!="undefined"&&n instanceof HTMLElement){let l=nT(n);i(l);return}if(n.substring(0,7)==="source:"){i(n.substring(7));return}if(n.substring(0,7)==="base64:"){let l=window.atob(n.substring(7));i(l);return}let a=T.GetShadersStore(r);if(a[n+e+"Shader"]){i(a[n+e+"Shader"]);return}if(t&&a[n+t+"Shader"]){i(a[n+t+"Shader"]);return}let o;if(n[0]==="."||n[0]==="/"||n.indexOf("http")>-1?o=n:o=T.GetShadersRepository(r)+n,s=s||oT,!s)throw new Error("loadFileInjection is not defined");s(o+"."+e.toLowerCase()+".fx",i)}function Tre(n,e,t,i){if(t){let r=t.vertexElement||t.vertex||t.spectorName||t,s=t.fragmentElement||t.fragment||t.spectorName||t;return{vertexSourceCode:(i===1?"//":"")+"#define SHADER_NAME vertex:"+r+` +`+n:t||(n=n.replace("precision highp float","precision mediump float")),n}function _M(n){let t=/defined\((.+)\)/.exec(n);if(t&&t.length)return new Ch(t[1].trim(),n[0]==="!");let i=["==","!=",">=","<=","<",">"],r="",s=0;for(r of i)if(s=n.indexOf(r),s>-1)break;if(s===-1)return new Ch(n);let a=n.substring(0,s).trim(),o=n.substring(s+r.length).trim();return new vT(a,r,o)}function gre(n){n=n.replace(dre,"defined[$1]");let e=_n.infixToPostfix(n),t=[];for(let r of e)if(r!=="||"&&r!=="&&")t.push(r);else if(t.length>=2){let s=t[t.length-1],a=t[t.length-2];t.length-=2;let o=r=="&&"?new gT:new _T;typeof s=="string"&&(s=s.replace(pM,"defined($1)")),typeof a=="string"&&(a=a.replace(pM,"defined($1)")),o.leftOperand=typeof a=="string"?_M(a):a,o.rightOperand=typeof s=="string"?_M(s):s,t.push(o)}let i=t[t.length-1];return typeof i=="string"&&(i=i.replace(pM,"defined($1)")),typeof i=="string"?_M(i):i}function ST(n,e){let t=new pT,i=n.substring(0,e),r=n.substring(e);return r=r.substring(0,(r.indexOf("//")+1||r.length+1)-1).trim(),i==="#ifdef"?t.testExpression=new Ch(r):i==="#ifndef"?t.testExpression=new Ch(r,!0):t.testExpression=gre(r),t}function gM(n,e,t,i){let r;for(;vM(n,t,i);){r=n.currentLine;let s=r.substring(0,5).toLowerCase();if(s==="#else"){let a=new Yo;e.children.push(a),vM(n,a,i);return}else if(s==="#elif"){let a=ST(r,5);e.children.push(a),t=a}}}function vM(n,e,t){for(;n.canRead;){n.lineIndex++;let i=n.currentLine;if(i.indexOf("#")>=0){let s=pre.exec(i);if(s&&s.length){switch(s[0]){case"#ifdef":{let o=new Uu;e.children.push(o);let l=ST(i,6);o.children.push(l),gM(n,o,l,t);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{let o=new Uu;e.children.push(o);let l=ST(i,7);o.children.push(l),gM(n,o,l,t);break}case"#if":{let o=new Uu,l=ST(i,3);e.children.push(o),o.children.push(l),gM(n,o,l,t);break}}continue}}let r=new Yo;if(r.line=i,e.children.push(r),i[0]==="#"&&i[1]==="d"){let s=i.replace(";","").split(" ");r.additionalDefineKey=s[1],s.length===3&&(r.additionalDefineValue=s[2])}}return!1}function vre(n,e,t,i){let r=new Yo,s=new mT;return s.lineIndex=-1,s.lines=n.split(` +`),vM(s,r,i),r.process(e,t,i)}function Ere(n,e){var r;let t=n.defines,i={};for(let s of t){let o=s.replace("#define","").replace(";","").trim().split(" ");i[o[0]]=o.length>1?o[1]:""}return((r=n.processor)==null?void 0:r.shaderLanguage)===0&&(i.GL_ES="true"),i.__VERSION__=n.version,i[n.platformName]="true",cT(i,e==null?void 0:e.isNDCHalfZRange,e==null?void 0:e.useReverseDepthBuffer,e==null?void 0:e.useExactSrgbConversions),i}function Sre(n,e,t){let i=_re(n,e);if(!e.processor||e.processor.shaderLanguage===0&&i.indexOf("#version 3")!==-1&&(i=i.replace("#version 300 es",""),!e.processor.parseGLES3))return i;let r=e.defines,s=Ere(e,t);e.processor.preProcessor&&(i=e.processor.preProcessor(i,r,s,e.isFragment,e.processingContext));let a={};return i=vre(i,s,e,a),e.processor.postProcessor&&(i=e.processor.postProcessor(i,r,e.isFragment,e.processingContext,t?{drawBuffersExtensionDisabled:!t.getCaps().drawBuffersExtension}:{},s,a)),t!=null&&t._features.needShaderCodeInlining&&(i=t.inlineShaderCode(i)),i}function D_(n,e,t){ET.length=0;let i;for(;(i=ure.exec(n))!==null;)ET.push(i);let r=[n],s=!1;for(let o of ET){let l=o[1];if(l.indexOf("__decl__")!==-1&&(l=l.replace(mre,""),e.supportsUniformBuffers&&(l=l.replace("Vertex","Ubo").replace("Fragment","Ubo")),l=l+"Declaration"),e.includesShadersStore[l]){let c=e.includesShadersStore[l];if(o[2]){let h=o[3].split(",");for(let d=0;dv+"{X}")),c+=p.replace(w3,_.toString())+` +`}else e.supportsUniformBuffers||(c=c.replace(N3,(d,u)=>u+"{X}")),c=c.replace(w3,h)}let f=[];for(let h of r){let d=h.split(o[0]);for(let u=0;u=0||c.indexOf("#include <")>=0}else{let c=e.shadersRepository+"ShadersInclude/"+l+".fx";SM.loadFile(c,f=>{e.includesShadersStore[l]=f,D_(r.join(""),e,t)});return}}ET.length=0;let a=r.join("");s?D_(a.toString(),e,t):t(a)}var dre,pM,ure,mre,N3,w3,ET,pre,SM,TT=C(()=>{uT();M3();C3();y3();P3();D3();L3();Vu();O3();hn();af();dre=/defined\s*?\((.+?)\)/g,pM=/defined\s*?\[(.+?)\]/g,ure=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,mre=/__decl__/,N3=/light\{X\}.(\w*)/g,w3=/\{X\}/g,ET=[],pre=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;SM={loadFile:(n,e,t,i,r,s)=>{throw qe("FileTools")}}});function V3(n,e){return Pn(e).cachedPipelines[n]}function AT(n){let e=n._name,t=n.context;if(e&&t){let i=Pn(t),r=i.cachedPipelines[e];r==null||r.dispose(),delete i.cachedPipelines[e]}}function G3(n,e,t,i,r,s,a){let o,l,c=fr()?s==null?void 0:s.getHostDocument():null;typeof e=="string"?o=e:typeof e.vertexSource=="string"?o="source:"+e.vertexSource:typeof e.vertexElement=="string"?o=(c==null?void 0:c.getElementById(e.vertexElement))||e.vertexElement:o=e.vertex||e,typeof e=="string"?l=e:typeof e.fragmentSource=="string"?l="source:"+e.fragmentSource:typeof e.fragmentElement=="string"?l=(c==null?void 0:c.getElementById(e.fragmentElement))||e.fragmentElement:l=e.fragment||e;let f=[void 0,void 0],h=()=>{if(f[0]&&f[1]){let[d,u]=f;F3(n),EM(d,n,(m,p)=>{a&&(a._vertexSourceCodeBeforeMigration=p),t&&(m=t("vertex",m)),n.isFragment=!0,EM(u,n,(_,g)=>{a&&(a._fragmentSourceCodeBeforeMigration=g),t&&(_=t("fragment",_));let v=B3(m,_,n);n=null;let x=Tre(v.vertexCode,v.fragmentCode,e,r);i==null||i(x.vertexSourceCode,x.fragmentSourceCode)},s)},s)}};U3(o,"Vertex","",d=>{a&&(a._rawVertexSourceCode=d),f[0]=d,h()},r),U3(l,"Fragment","Pixel",d=>{a&&(a._rawFragmentSourceCode=d),f[1]=d,h()},r)}function U3(n,e,t,i,r,s){if(typeof HTMLElement!="undefined"&&n instanceof HTMLElement){let l=sT(n);i(l);return}if(n.substring(0,7)==="source:"){i(n.substring(7));return}if(n.substring(0,7)==="base64:"){let l=window.atob(n.substring(7));i(l);return}let a=T.GetShadersStore(r);if(a[n+e+"Shader"]){i(a[n+e+"Shader"]);return}if(t&&a[n+t+"Shader"]){i(a[n+t+"Shader"]);return}let o;if(n[0]==="."||n[0]==="/"||n.indexOf("http")>-1?o=n:o=T.GetShadersRepository(r)+n,s=s||lT,!s)throw new Error("loadFileInjection is not defined");s(o+"."+e.toLowerCase()+".fx",i)}function Tre(n,e,t,i){if(t){let r=t.vertexElement||t.vertex||t.spectorName||t,s=t.fragmentElement||t.fragment||t.spectorName||t;return{vertexSourceCode:(i===1?"//":"")+"#define SHADER_NAME vertex:"+r+` `+n,fragmentSourceCode:(i===1?"//":"")+"#define SHADER_NAME fragment:"+s+` -`+e}}else return{vertexSourceCode:n,fragmentSourceCode:e}}var k3,TM=C(()=>{va();mM();W();yt();ST();of();k3=(n,e,t,i)=>{try{let r=n.context?Pn(n.context):null;r&&(r.disableParallelShaderCompile=n.disableParallelCompilation);let s=n.existingPipelineContext||e(n.shaderProcessingContext);return s._name=n.name,n.name&&r&&(r.cachedPipelines[n.name]=s),t(s,n.vertex,n.fragment,!!n.createAsRaw,"","",n.rebuildRebind,n.defines,n.transformFeedbackVaryings,"",()=>{i(s,()=>{var a;(a=n.onRenderingStateCompiled)==null||a.call(n,s)})}),s}catch(r){throw te.Error("Error compiling effect"),r}}});function W3(n,e,t){try{if(n())return e(),!0}catch(i){return t==null||t(i),!0}return!1}var AT,Qa,Ko,jo=C(()=>{AT=[],Qa=class{static SetImmediate(e){AT.length===0&&setTimeout(()=>{let t=AT;AT=[];for(let i of t)i()},1),AT.push(e)}};Ko=(n,e,t,i=16,r=3e4,s=!0,a)=>{if(s&&W3(n,e,t))return null;let o=!1,l=null,c=()=>{if(!o&&!W3(n,e,t)){if(r-=i,r<0){t==null||t(new Error("Operation timed out after maximum retries. "+(a||"")),!0);return}l=setTimeout(c,i)}};return l=setTimeout(c,i),()=>{o=!0,l!==null&&clearTimeout(l)}}});var tr,yh=C(()=>{hi();yt();W();TM();jo();tr=class n{static get ShadersRepository(){return T.ShadersRepository}static set ShadersRepository(e){T.ShadersRepository=e}get isDisposed(){return this._isDisposed}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new ie),this._onBindObservable}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i,r=null,s,a=null,o=null,l=null,c=null,f,h="",d=0,u){var _,g,v,x;this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new ie,this.onErrorObservable=new ie,this._onBindObservable=null,this._isDisposed=!1,this._refCount=1,this._bonesComputationForcedToCPU=!1,this._uniformBuffersNames={},this._multiTarget=!1,this._samplers={},this._isReady=!1,this._compilationError="",this._allFallbacksProcessed=!1,this._uniforms={},this._key="",this._fallbacks=null,this._vertexSourceCodeOverride="",this._fragmentSourceCodeOverride="",this._transformFeedbackVaryings=null,this._disableParallelShaderCompilation=!1,this._pipelineContext=null,this._vertexSourceCode="",this._fragmentSourceCode="",this._vertexSourceCodeBeforeMigration="",this._fragmentSourceCodeBeforeMigration="",this._rawVertexSourceCode="",this._rawFragmentSourceCode="",this._processCodeAfterIncludes=void 0,this._processFinalCode=null,this._onReleaseEffectsObserver=null,this.name=e,this._key=h;let m=this._key.replace(/\r/g,"").replace(/\n/g,"|"),p;if(t.attributes){let A=t;if(this._engine=i,this._attributesNames=A.attributes,this._uniformsNames=A.uniformsNames.concat(A.samplers),this._samplerList=A.samplers.slice(),this.defines=A.defines,this.onError=A.onError,this.onCompiled=A.onCompiled,this._fallbacks=A.fallbacks,this._indexParameters=A.indexParameters,this._transformFeedbackVaryings=A.transformFeedbackVaryings||null,this._multiTarget=!!A.multiTarget,this._shaderLanguage=(_=A.shaderLanguage)!=null?_:0,this._disableParallelShaderCompilation=!!A.disableParallelShaderCompilation,A.uniformBuffersNames){this._uniformBuffersNamesList=A.uniformBuffersNames.slice();for(let S=0;S{this._onReleaseEffectsObserver=null,!this.isDisposed&&this.dispose(!0)})}async _processShaderCodeAsync(e=null,t=!1,i=null,r){r&&await r(),this._processingContext=i||this._engine._getShaderProcessingContext(this._shaderLanguage,!1);let s={defines:this.defines.split(` +`+e}}else return{vertexSourceCode:n,fragmentSourceCode:e}}var k3,TM=C(()=>{ga();mM();k();Pt();TT();af();k3=(n,e,t,i)=>{try{let r=n.context?Pn(n.context):null;r&&(r.disableParallelShaderCompile=n.disableParallelCompilation);let s=n.existingPipelineContext||e(n.shaderProcessingContext);return s._name=n.name,n.name&&r&&(r.cachedPipelines[n.name]=s),t(s,n.vertex,n.fragment,!!n.createAsRaw,"","",n.rebuildRebind,n.defines,n.transformFeedbackVaryings,"",()=>{i(s,()=>{var a;(a=n.onRenderingStateCompiled)==null||a.call(n,s)})}),s}catch(r){throw te.Error("Error compiling effect"),r}}});function W3(n,e,t){try{if(n())return e(),!0}catch(i){return t==null||t(i),!0}return!1}var xT,Qa,Ko,jo=C(()=>{xT=[],Qa=class{static SetImmediate(e){xT.length===0&&setTimeout(()=>{let t=xT;xT=[];for(let i of t)i()},1),xT.push(e)}};Ko=(n,e,t,i=16,r=3e4,s=!0,a)=>{if(s&&W3(n,e,t))return null;let o=!1,l=null,c=()=>{if(!o&&!W3(n,e,t)){if(r-=i,r<0){t==null||t(new Error("Operation timed out after maximum retries. "+(a||"")),!0);return}l=setTimeout(c,i)}};return l=setTimeout(c,i),()=>{o=!0,l!==null&&clearTimeout(l)}}});var rr,yh=C(()=>{di();Pt();k();TM();jo();rr=class n{static get ShadersRepository(){return T.ShadersRepository}static set ShadersRepository(e){T.ShadersRepository=e}get isDisposed(){return this._isDisposed}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new ie),this._onBindObservable}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,i,r=null,s,a=null,o=null,l=null,c=null,f,h="",d=0,u){var _,g,v,x;this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new ie,this.onErrorObservable=new ie,this._onBindObservable=null,this._isDisposed=!1,this._refCount=1,this._bonesComputationForcedToCPU=!1,this._uniformBuffersNames={},this._multiTarget=!1,this._samplers={},this._isReady=!1,this._compilationError="",this._allFallbacksProcessed=!1,this._uniforms={},this._key="",this._fallbacks=null,this._vertexSourceCodeOverride="",this._fragmentSourceCodeOverride="",this._transformFeedbackVaryings=null,this._disableParallelShaderCompilation=!1,this._pipelineContext=null,this._vertexSourceCode="",this._fragmentSourceCode="",this._vertexSourceCodeBeforeMigration="",this._fragmentSourceCodeBeforeMigration="",this._rawVertexSourceCode="",this._rawFragmentSourceCode="",this._processCodeAfterIncludes=void 0,this._processFinalCode=null,this._onReleaseEffectsObserver=null,this.name=e,this._key=h;let m=this._key.replace(/\r/g,"").replace(/\n/g,"|"),p;if(t.attributes){let A=t;if(this._engine=i,this._attributesNames=A.attributes,this._uniformsNames=A.uniformsNames.concat(A.samplers),this._samplerList=A.samplers.slice(),this.defines=A.defines,this.onError=A.onError,this.onCompiled=A.onCompiled,this._fallbacks=A.fallbacks,this._indexParameters=A.indexParameters,this._transformFeedbackVaryings=A.transformFeedbackVaryings||null,this._multiTarget=!!A.multiTarget,this._shaderLanguage=(_=A.shaderLanguage)!=null?_:0,this._disableParallelShaderCompilation=!!A.disableParallelShaderCompilation,A.uniformBuffersNames){this._uniformBuffersNamesList=A.uniformBuffersNames.slice();for(let S=0;S{this._onReleaseEffectsObserver=null,!this.isDisposed&&this.dispose(!0)})}async _processShaderCodeAsync(e=null,t=!1,i=null,r){r&&await r(),this._processingContext=i||this._engine._getShaderProcessingContext(this._shaderLanguage,!1);let s={defines:this.defines.split(` `),indexParameters:this._indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:e!=null?e:this._engine._getShaderProcessor(this._shaderLanguage),supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:T.GetShadersRepository(this._shaderLanguage),includesShadersStore:T.GetIncludesShadersStore(this._shaderLanguage),version:(this._engine.version*100).toString(),platformName:this._engine.shaderPlatformName,processingContext:this._processingContext,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:this._processCodeAfterIncludes};G3(s,this.name,this._processFinalCode,(a,o)=>{this._vertexSourceCode=a,this._fragmentSourceCode=o,this._prepareEffect(t)},this._shaderLanguage,this._engine,this)}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch(e){return!1}}_isReadyInternal(){return this._engine.isDisposed||this._isReady?!0:this._pipelineContext?this._pipelineContext.isReady:!1}getEngine(){return this._engine}getPipelineContext(){return this._pipelineContext}getAttributesNames(){return this._attributesNames}getAttributeLocation(e){return this._attributes[e]}getAttributeLocationByName(e){return this._attributeLocationByName[e]}getAttributesCount(){return this._attributes.length}getUniformIndex(e){return this._uniformsNames.indexOf(e)}getUniform(e){return this._uniforms[e]}getSamplers(){return this._samplerList}getUniformNames(){return this._uniformsNames}getUniformBuffersNames(){return this._uniformBuffersNamesList}getIndexParameters(){return this._indexParameters}getCompilationError(){return this._compilationError}allFallbacksProcessed(){return this._allFallbacksProcessed}async whenCompiledAsync(){return await new Promise(e=>{this.executeWhenCompiled(e)})}executeWhenCompiled(e){if(this.isReady()){e(this);return}this.onCompileObservable.add(t=>{e(t)}),(!this._pipelineContext||this._pipelineContext.isAsync)&&this._checkIsReady(null)}_checkIsReady(e){Ko(()=>this._isReadyInternal()||this._isDisposed,()=>{},t=>{this._processCompilationErrors(t,e)},16,12e4,!0,` - Effect: ${typeof this.name=="string"?this.name:this.key}`)}get vertexSourceCode(){var e,t;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._vertexSourceCodeOverride:(t=(e=this._pipelineContext)==null?void 0:e._getVertexShaderCode())!=null?t:this._vertexSourceCode}get fragmentSourceCode(){var e,t;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._fragmentSourceCodeOverride:(t=(e=this._pipelineContext)==null?void 0:e._getFragmentShaderCode())!=null?t:this._fragmentSourceCode}get vertexSourceCodeBeforeMigration(){return this._vertexSourceCodeBeforeMigration}get fragmentSourceCodeBeforeMigration(){return this._fragmentSourceCodeBeforeMigration}get rawVertexSourceCode(){return this._rawVertexSourceCode}get rawFragmentSourceCode(){return this._rawFragmentSourceCode}getPipelineGenerationOptions(){return{platformName:this._engine.shaderPlatformName,shaderLanguage:this._shaderLanguage,shaderNameOrContent:this.name,key:this._key,defines:this.defines.split(` `),addGlobalDefines:!1,extendedProcessingOptions:{indexParameters:this._indexParameters,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,supportsUniformBuffers:this._engine.supportsUniformBuffers},extendedCreatePipelineOptions:{transformFeedbackVaryings:this._transformFeedbackVaryings,createAsRaw:!!(this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride)}}}_rebuildProgram(e,t,i,r){this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=(s,a)=>{r&&r(a)},this.onCompiled=()=>{var a,o;let s=this.getEngine().scenes;if(s)for(let l=0;lthis._rebuildProgram(l,c,f,h),defines:r,transformFeedbackVaryings:this._transformFeedbackVaryings,name:this._key.replace(/\r/g,"").replace(/\n/g,"|"),createAsRaw:i,disableParallelCompilation:this._disableParallelShaderCompilation,shaderProcessingContext:this._processingContext,onRenderingStateCompiled:l=>{t&&!e&&this._engine._deletePipelineContext(t),l&&this._onRenderingStateCompiled(l)}},this._engine.createPipelineContext.bind(this._engine),this._engine._preparePipelineContextAsync.bind(this._engine),this._engine._executeWhenRenderingStateIsCompiled.bind(this._engine)),this._pipelineContext.isAsync&&this._checkIsReady(t)}catch(i){this._processCompilationErrors(i,t)}}_getShaderCodeAndErrorLine(e,t,i){let r=i?/FRAGMENT SHADER ERROR: 0:(\d+?):/:/VERTEX SHADER ERROR: 0:(\d+?):/,s=null;if(t&&e){let a=t.match(r);if(a&&a.length===2){let o=parseInt(a[1]),l=e.split(` `,-1);l.length>=o&&(s=`Offending line [${o}] in ${i?"fragment":"vertex"} code: ${l[o-1]}`)}}return[e,s]}_processCompilationErrors(e,t=null){var a,o,l;this._compilationError=e.message;let i=this._attributesNames,r=this._fallbacks;if(te.Error("Unable to compile effect:"),te.Error(`Uniforms: ${this._uniformsNames.join(" ")}`),te.Error(`Attributes: ${i.join(" ")}`),te.Error(`Defines: -`+this.defines),n.LogShaderCodeOnCompilationError){let c=null,f=null,h;(a=this._pipelineContext)!=null&&a._getVertexShaderCode()&&([h,c]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),h&&(te.Error("Vertex code:"),te.Error(h))),(o=this._pipelineContext)!=null&&o._getFragmentShaderCode()&&([h,f]=this._getShaderCodeAndErrorLine((l=this._pipelineContext)==null?void 0:l._getFragmentShaderCode(),this._compilationError,!0),h&&(te.Error("Fragment code:"),te.Error(h))),c&&te.Error(c),f&&te.Error(f)}te.Error("Error: "+this._compilationError);let s=()=>{this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this),this._engine.onEffectErrorObservable.notifyObservers({effect:this,errors:this._compilationError})};t&&(this._pipelineContext=t,this._isReady=!0,s()),r?(this._pipelineContext=null,r.hasMoreFallbacks?(this._allFallbacksProcessed=!1,te.Error("Trying next fallback."),this.defines=r.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,s(),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):(this._allFallbacksProcessed=!0,t||s())}get isSupported(){return this._compilationError===""}_bindTexture(e,t){this._engine._bindTexture(this._samplers[e],t,e)}setTexture(e,t){this._engine.setTexture(this._samplers[e],this._uniforms[e],t,e)}setTextureArray(e,t){let i=e+"Ex";if(this._samplerList.indexOf(i+"0")===-1){let r=this._samplerList.indexOf(e);for(let a=1;a0||this._isDisposed||(this._onReleaseEffectsObserver&&(this._engine.onReleaseEffectsObservable.remove(this._onReleaseEffectsObserver),this._onReleaseEffectsObserver=null),this._pipelineContext&&TT(this._pipelineContext),this._engine._releaseEffect(this),this.clearCodeCache(),this._isDisposed=!0)}static RegisterShader(e,t,i,r=0){t&&(T.GetShadersStore(r)[`${e}PixelShader`]=t),i&&(T.GetShadersStore(r)[`${e}VertexShader`]=i)}static ResetCache(){n._BaseCache={}}};tr.LogShaderCodeOnCompilationError=!0;tr.PersistentMode=!1;tr.AutomaticallyClearCodeCache=!1;tr._UniqueIdSeed=0;tr._BaseCache={};tr.ShadersStore=T.ShadersStore;tr.IncludesShadersStore=T.IncludesShadersStore});var Zn,AM=C(()=>{Zn=class n{static SetMatrixPrecision(e){if(n.MatrixTrackPrecisionChange=!1,e&&!n.MatrixUse64Bits&&n.MatrixTrackedMatrices)for(let t=0;t{va();mr=class{static get Now(){return cr()&&window.performance&&window.performance.now?window.performance.now():Date.now()}}});var xT,H3=C(()=>{xT=class{constructor(e=!0){this._isDepthTestDirty=!1,this._isDepthMaskDirty=!1,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!1,this._isFrontFaceDirty=!1,e&&this.reset()}get isDirty(){return this._isDepthFuncDirty||this._isDepthTestDirty||this._isDepthMaskDirty||this._isCullFaceDirty||this._isCullDirty||this._isZOffsetDirty||this._isFrontFaceDirty}get zOffset(){return this._zOffset}set zOffset(e){this._zOffset!==e&&(this._zOffset=e,this._isZOffsetDirty=!0)}get zOffsetUnits(){return this._zOffsetUnits}set zOffsetUnits(e){this._zOffsetUnits!==e&&(this._zOffsetUnits=e,this._isZOffsetDirty=!0)}get cullFace(){return this._cullFace}set cullFace(e){this._cullFace!==e&&(this._cullFace=e,this._isCullFaceDirty=!0)}get cull(){return this._cull}set cull(e){this._cull!==e&&(this._cull=e,this._isCullDirty=!0)}get depthFunc(){return this._depthFunc}set depthFunc(e){this._depthFunc!==e&&(this._depthFunc=e,this._isDepthFuncDirty=!0)}get depthMask(){return this._depthMask}set depthMask(e){this._depthMask!==e&&(this._depthMask=e,this._isDepthMaskDirty=!0)}get depthTest(){return this._depthTest}set depthTest(e){this._depthTest!==e&&(this._depthTest=e,this._isDepthTestDirty=!0)}get frontFace(){return this._frontFace}set frontFace(e){this._frontFace!==e&&(this._frontFace=e,this._isFrontFaceDirty=!0)}reset(){this._depthMask=!0,this._depthTest=!0,this._depthFunc=null,this._cullFace=null,this._cull=null,this._zOffset=0,this._zOffsetUnits=0,this._frontFace=null,this._isDepthTestDirty=!0,this._isDepthMaskDirty=!0,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!0,this._isFrontFaceDirty=!1}apply(e){this.isDirty&&(this._isCullDirty&&(this.cull?e.enable(e.CULL_FACE):e.disable(e.CULL_FACE),this._isCullDirty=!1),this._isCullFaceDirty&&(e.cullFace(this.cullFace),this._isCullFaceDirty=!1),this._isDepthMaskDirty&&(e.depthMask(this.depthMask),this._isDepthMaskDirty=!1),this._isDepthTestDirty&&(this.depthTest?e.enable(e.DEPTH_TEST):e.disable(e.DEPTH_TEST),this._isDepthTestDirty=!1),this._isDepthFuncDirty&&(e.depthFunc(this.depthFunc),this._isDepthFuncDirty=!1),this._isZOffsetDirty&&(this.zOffset||this.zOffsetUnits?(e.enable(e.POLYGON_OFFSET_FILL),e.polygonOffset(this.zOffset,this.zOffsetUnits)):e.disable(e.POLYGON_OFFSET_FILL),this._isZOffsetDirty=!1),this._isFrontFaceDirty&&(e.frontFace(this.frontFace),this._isFrontFaceDirty=!1))}}});var RT,z3=C(()=>{RT=class{get isDirty(){return this._isStencilTestDirty||this._isStencilMaskDirty||this._isStencilFuncDirty||this._isStencilOpDirty}get func(){return this._func}set func(e){this._func!==e&&(this._func=e,this._isStencilFuncDirty=!0)}get backFunc(){return this._func}set backFunc(e){this._backFunc!==e&&(this._backFunc=e,this._isStencilFuncDirty=!0)}get funcRef(){return this._funcRef}set funcRef(e){this._funcRef!==e&&(this._funcRef=e,this._isStencilFuncDirty=!0)}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask!==e&&(this._funcMask=e,this._isStencilFuncDirty=!0)}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail!==e&&(this._opStencilFail=e,this._isStencilOpDirty=!0)}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail!==e&&(this._opDepthFail=e,this._isStencilOpDirty=!0)}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass!==e&&(this._opStencilDepthPass=e,this._isStencilOpDirty=!0)}get backOpStencilFail(){return this._backOpStencilFail}set backOpStencilFail(e){this._backOpStencilFail!==e&&(this._backOpStencilFail=e,this._isStencilOpDirty=!0)}get backOpDepthFail(){return this._backOpDepthFail}set backOpDepthFail(e){this._backOpDepthFail!==e&&(this._backOpDepthFail=e,this._isStencilOpDirty=!0)}get backOpStencilDepthPass(){return this._backOpStencilDepthPass}set backOpStencilDepthPass(e){this._backOpStencilDepthPass!==e&&(this._backOpStencilDepthPass=e,this._isStencilOpDirty=!0)}get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this._isStencilMaskDirty=!0)}get enabled(){return this._enabled}set enabled(e){this._enabled!==e&&(this._enabled=e,this._isStencilTestDirty=!0)}constructor(e=!0){this._isStencilTestDirty=!1,this._isStencilMaskDirty=!1,this._isStencilFuncDirty=!1,this._isStencilOpDirty=!1,this.useStencilGlobalOnly=!1,e&&this.reset()}reset(){var e;this.stencilMaterial=void 0,(e=this.stencilGlobal)==null||e.reset(),this._isStencilTestDirty=!0,this._isStencilMaskDirty=!0,this._isStencilFuncDirty=!0,this._isStencilOpDirty=!0}apply(e){var i;if(!e)return;let t=!this.useStencilGlobalOnly&&!!((i=this.stencilMaterial)!=null&&i.enabled);this.enabled=t?this.stencilMaterial.enabled:this.stencilGlobal.enabled,this.func=t?this.stencilMaterial.func:this.stencilGlobal.func,this.backFunc=t?this.stencilMaterial.backFunc:this.stencilGlobal.backFunc,this.funcRef=t?this.stencilMaterial.funcRef:this.stencilGlobal.funcRef,this.funcMask=t?this.stencilMaterial.funcMask:this.stencilGlobal.funcMask,this.opStencilFail=t?this.stencilMaterial.opStencilFail:this.stencilGlobal.opStencilFail,this.opDepthFail=t?this.stencilMaterial.opDepthFail:this.stencilGlobal.opDepthFail,this.opStencilDepthPass=t?this.stencilMaterial.opStencilDepthPass:this.stencilGlobal.opStencilDepthPass,this.backOpStencilFail=t?this.stencilMaterial.backOpStencilFail:this.stencilGlobal.backOpStencilFail,this.backOpDepthFail=t?this.stencilMaterial.backOpDepthFail:this.stencilGlobal.backOpDepthFail,this.backOpStencilDepthPass=t?this.stencilMaterial.backOpStencilDepthPass:this.stencilGlobal.backOpStencilDepthPass,this.mask=t?this.stencilMaterial.mask:this.stencilGlobal.mask,this.isDirty&&(this._isStencilTestDirty&&(this.enabled?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this._isStencilTestDirty=!1),this._isStencilMaskDirty&&(e.stencilMask(this.mask),this._isStencilMaskDirty=!1),this._isStencilFuncDirty&&(e.stencilFuncSeparate(e.FRONT,this.func,this.funcRef,this.funcMask),e.stencilFuncSeparate(e.BACK,this.backFunc,this.funcRef,this.funcMask),this._isStencilFuncDirty=!1),this._isStencilOpDirty&&(e.stencilOpSeparate(e.FRONT,this.opStencilFail,this.opDepthFail,this.opStencilDepthPass),e.stencilOpSeparate(e.BACK,this.backOpStencilFail,this.backOpDepthFail,this.backOpStencilDepthPass),this._isStencilOpDirty=!1))}}});var Ph,X3=C(()=>{Ph=class n{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.funcRef=1,this.funcMask=255,this.func=n.ALWAYS,this.opStencilFail=n.KEEP,this.opDepthFail=n.KEEP,this.opStencilDepthPass=n.REPLACE,this.backFunc=n.ALWAYS,this.backOpStencilFail=n.KEEP,this.backOpDepthFail=n.KEEP,this.backOpStencilDepthPass=n.REPLACE}get stencilFunc(){return this.func}set stencilFunc(e){this.func=e}get stencilBackFunc(){return this.backFunc}set stencilBackFunc(e){this.backFunc=e}get stencilFuncRef(){return this.funcRef}set stencilFuncRef(e){this.funcRef=e}get stencilFuncMask(){return this.funcMask}set stencilFuncMask(e){this.funcMask=e}get stencilOpStencilFail(){return this.opStencilFail}set stencilOpStencilFail(e){this.opStencilFail=e}get stencilOpDepthFail(){return this.opDepthFail}set stencilOpDepthFail(e){this.opDepthFail=e}get stencilOpStencilDepthPass(){return this.opStencilDepthPass}set stencilOpStencilDepthPass(e){this.opStencilDepthPass=e}get stencilBackOpStencilFail(){return this.backOpStencilFail}set stencilBackOpStencilFail(e){this.backOpStencilFail=e}get stencilBackOpDepthFail(){return this.backOpDepthFail}set stencilBackOpDepthFail(e){this.backOpDepthFail=e}get stencilBackOpStencilDepthPass(){return this.backOpStencilDepthPass}set stencilBackOpStencilDepthPass(e){this.backOpStencilDepthPass=e}get stencilMask(){return this.mask}set stencilMask(e){this.mask=e}get stencilTest(){return this.enabled}set stencilTest(e){this.enabled=e}};Ph.ALWAYS=519;Ph.KEEP=7680;Ph.REPLACE=7681});var ku,xM=C(()=>{ku=class{constructor(e){this._supportBlendParametersPerTarget=e,this._blendFunctionParameters=new Array(32),this._blendEquationParameters=new Array(16),this._blendConstants=new Array(4),this._isBlendConstantsDirty=!1,this._alphaBlend=Array(8).fill(!1),this._numTargetEnabled=0,this._isAlphaBlendDirty=!1,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this.reset()}get isDirty(){return this._isAlphaBlendDirty||this._isBlendFunctionParametersDirty||this._isBlendEquationParametersDirty}get alphaBlend(){return this._numTargetEnabled>0}set alphaBlend(e){this.setAlphaBlend(e)}setAlphaBlend(e,t=0){this._alphaBlend[t]!==e&&(e?this._numTargetEnabled++:this._numTargetEnabled--,this._alphaBlend[t]=e,this._isAlphaBlendDirty=!0)}setAlphaBlendConstants(e,t,i,r){this._blendConstants[0]===e&&this._blendConstants[1]===t&&this._blendConstants[2]===i&&this._blendConstants[3]===r||(this._blendConstants[0]=e,this._blendConstants[1]=t,this._blendConstants[2]=i,this._blendConstants[3]=r,this._isBlendConstantsDirty=!0)}setAlphaBlendFunctionParameters(e,t,i,r,s=0){let a=s*4;this._blendFunctionParameters[a+0]===e&&this._blendFunctionParameters[a+1]===t&&this._blendFunctionParameters[a+2]===i&&this._blendFunctionParameters[a+3]===r||(this._blendFunctionParameters[a+0]=e,this._blendFunctionParameters[a+1]=t,this._blendFunctionParameters[a+2]=i,this._blendFunctionParameters[a+3]=r,this._isBlendFunctionParametersDirty=!0)}setAlphaEquationParameters(e,t,i=0){let r=i*2;this._blendEquationParameters[r+0]===e&&this._blendEquationParameters[r+1]===t||(this._blendEquationParameters[r+0]=e,this._blendEquationParameters[r+1]=t,this._isBlendEquationParametersDirty=!0)}reset(){this._alphaBlend.fill(!1),this._numTargetEnabled=0,this._blendFunctionParameters.fill(null),this._blendEquationParameters.fill(null),this._blendConstants[0]=null,this._blendConstants[1]=null,this._blendConstants[2]=null,this._blendConstants[3]=null,this._isAlphaBlendDirty=!0,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this._isBlendConstantsDirty=!1}apply(e,t=1){if(!this.isDirty)return;if(this._isBlendConstantsDirty&&(e.blendColor(this._blendConstants[0],this._blendConstants[1],this._blendConstants[2],this._blendConstants[3]),this._isBlendConstantsDirty=!1),t===1||!this._supportBlendParametersPerTarget){this._isAlphaBlendDirty&&(this._alphaBlend[0]?e.enable(e.BLEND):e.disable(e.BLEND),this._isAlphaBlendDirty=!1),this._isBlendFunctionParametersDirty&&(e.blendFuncSeparate(this._blendFunctionParameters[0],this._blendFunctionParameters[1],this._blendFunctionParameters[2],this._blendFunctionParameters[3]),this._isBlendFunctionParametersDirty=!1),this._isBlendEquationParametersDirty&&(e.blendEquationSeparate(this._blendEquationParameters[0],this._blendEquationParameters[1]),this._isBlendEquationParametersDirty=!1);return}let i=e;if(this._isAlphaBlendDirty){for(let r=0;r{hi();yh();Pi();yt();AM();Fl();H3();z3();X3();xM();hn();Es();va();of();Ie=class n{get frameId(){return this._frameId}get isWebGPU(){return this._isWebGPU}_getShaderProcessor(e){return this._shaderProcessor}_resetAlphaMode(){this._alphaMode.fill(-1),this._alphaEquation.fill(-1)}get shaderPlatformName(){return this._shaderPlatformName}_clearEmptyResources(){this._emptyTexture=null,this._emptyCubeTexture=null,this._emptyTexture3D=null,this._emptyTexture2DArray=null}get useReverseDepthBuffer(){return this._useReverseDepthBuffer}set useReverseDepthBuffer(e){e!==this._useReverseDepthBuffer&&(this._useReverseDepthBuffer=e,e?this._depthCullingState.depthFunc=518:this._depthCullingState.depthFunc=515)}setColorWrite(e){e!==this._colorWrite&&(this._colorWriteChanged=!0,this._colorWrite=e)}getColorWrite(){return this._colorWrite}get depthCullingState(){return this._depthCullingState}get alphaState(){return this._alphaState}get stencilState(){return this._stencilState}get stencilStateComposer(){return this._stencilStateComposer}_getGlobalDefines(e){if(e){this.isNDCHalfZRange?e.IS_NDC_HALF_ZRANGE="":delete e.IS_NDC_HALF_ZRANGE,this.useReverseDepthBuffer?e.USE_REVERSE_DEPTHBUFFER="":delete e.USE_REVERSE_DEPTHBUFFER,this.useExactSrgbConversions?e.USE_EXACT_SRGB_CONVERSIONS="":delete e.USE_EXACT_SRGB_CONVERSIONS;return}else{let t="";return this.isNDCHalfZRange&&(t+="#define IS_NDC_HALF_ZRANGE"),this.useReverseDepthBuffer&&(t&&(t+=` +`+this.defines),n.LogShaderCodeOnCompilationError){let c=null,f=null,h;(a=this._pipelineContext)!=null&&a._getVertexShaderCode()&&([h,c]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),h&&(te.Error("Vertex code:"),te.Error(h))),(o=this._pipelineContext)!=null&&o._getFragmentShaderCode()&&([h,f]=this._getShaderCodeAndErrorLine((l=this._pipelineContext)==null?void 0:l._getFragmentShaderCode(),this._compilationError,!0),h&&(te.Error("Fragment code:"),te.Error(h))),c&&te.Error(c),f&&te.Error(f)}te.Error("Error: "+this._compilationError);let s=()=>{this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this),this._engine.onEffectErrorObservable.notifyObservers({effect:this,errors:this._compilationError})};t&&(this._pipelineContext=t,this._isReady=!0,s()),r?(this._pipelineContext=null,r.hasMoreFallbacks?(this._allFallbacksProcessed=!1,te.Error("Trying next fallback."),this.defines=r.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,s(),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):(this._allFallbacksProcessed=!0,t||s())}get isSupported(){return this._compilationError===""}_bindTexture(e,t){this._engine._bindTexture(this._samplers[e],t,e)}setTexture(e,t){this._engine.setTexture(this._samplers[e],this._uniforms[e],t,e)}setTextureArray(e,t){let i=e+"Ex";if(this._samplerList.indexOf(i+"0")===-1){let r=this._samplerList.indexOf(e);for(let a=1;a0||this._isDisposed||(this._onReleaseEffectsObserver&&(this._engine.onReleaseEffectsObservable.remove(this._onReleaseEffectsObserver),this._onReleaseEffectsObserver=null),this._pipelineContext&&AT(this._pipelineContext),this._engine._releaseEffect(this),this.clearCodeCache(),this._isDisposed=!0)}static RegisterShader(e,t,i,r=0){t&&(T.GetShadersStore(r)[`${e}PixelShader`]=t),i&&(T.GetShadersStore(r)[`${e}VertexShader`]=i)}static ResetCache(){n._BaseCache={}}};rr.LogShaderCodeOnCompilationError=!0;rr.PersistentMode=!1;rr.AutomaticallyClearCodeCache=!1;rr._UniqueIdSeed=0;rr._BaseCache={};rr.ShadersStore=T.ShadersStore;rr.IncludesShadersStore=T.IncludesShadersStore});var qn,AM=C(()=>{qn=class n{static SetMatrixPrecision(e){if(n.MatrixTrackPrecisionChange=!1,e&&!n.MatrixUse64Bits&&n.MatrixTrackedMatrices)for(let t=0;t{ga();pr=class{static get Now(){return fr()&&window.performance&&window.performance.now?window.performance.now():Date.now()}}});var RT,H3=C(()=>{RT=class{constructor(e=!0){this._isDepthTestDirty=!1,this._isDepthMaskDirty=!1,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!1,this._isFrontFaceDirty=!1,e&&this.reset()}get isDirty(){return this._isDepthFuncDirty||this._isDepthTestDirty||this._isDepthMaskDirty||this._isCullFaceDirty||this._isCullDirty||this._isZOffsetDirty||this._isFrontFaceDirty}get zOffset(){return this._zOffset}set zOffset(e){this._zOffset!==e&&(this._zOffset=e,this._isZOffsetDirty=!0)}get zOffsetUnits(){return this._zOffsetUnits}set zOffsetUnits(e){this._zOffsetUnits!==e&&(this._zOffsetUnits=e,this._isZOffsetDirty=!0)}get cullFace(){return this._cullFace}set cullFace(e){this._cullFace!==e&&(this._cullFace=e,this._isCullFaceDirty=!0)}get cull(){return this._cull}set cull(e){this._cull!==e&&(this._cull=e,this._isCullDirty=!0)}get depthFunc(){return this._depthFunc}set depthFunc(e){this._depthFunc!==e&&(this._depthFunc=e,this._isDepthFuncDirty=!0)}get depthMask(){return this._depthMask}set depthMask(e){this._depthMask!==e&&(this._depthMask=e,this._isDepthMaskDirty=!0)}get depthTest(){return this._depthTest}set depthTest(e){this._depthTest!==e&&(this._depthTest=e,this._isDepthTestDirty=!0)}get frontFace(){return this._frontFace}set frontFace(e){this._frontFace!==e&&(this._frontFace=e,this._isFrontFaceDirty=!0)}reset(){this._depthMask=!0,this._depthTest=!0,this._depthFunc=null,this._cullFace=null,this._cull=null,this._zOffset=0,this._zOffsetUnits=0,this._frontFace=null,this._isDepthTestDirty=!0,this._isDepthMaskDirty=!0,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!0,this._isFrontFaceDirty=!1}apply(e){this.isDirty&&(this._isCullDirty&&(this.cull?e.enable(e.CULL_FACE):e.disable(e.CULL_FACE),this._isCullDirty=!1),this._isCullFaceDirty&&(e.cullFace(this.cullFace),this._isCullFaceDirty=!1),this._isDepthMaskDirty&&(e.depthMask(this.depthMask),this._isDepthMaskDirty=!1),this._isDepthTestDirty&&(this.depthTest?e.enable(e.DEPTH_TEST):e.disable(e.DEPTH_TEST),this._isDepthTestDirty=!1),this._isDepthFuncDirty&&(e.depthFunc(this.depthFunc),this._isDepthFuncDirty=!1),this._isZOffsetDirty&&(this.zOffset||this.zOffsetUnits?(e.enable(e.POLYGON_OFFSET_FILL),e.polygonOffset(this.zOffset,this.zOffsetUnits)):e.disable(e.POLYGON_OFFSET_FILL),this._isZOffsetDirty=!1),this._isFrontFaceDirty&&(e.frontFace(this.frontFace),this._isFrontFaceDirty=!1))}}});var bT,z3=C(()=>{bT=class{get isDirty(){return this._isStencilTestDirty||this._isStencilMaskDirty||this._isStencilFuncDirty||this._isStencilOpDirty}get func(){return this._func}set func(e){this._func!==e&&(this._func=e,this._isStencilFuncDirty=!0)}get backFunc(){return this._func}set backFunc(e){this._backFunc!==e&&(this._backFunc=e,this._isStencilFuncDirty=!0)}get funcRef(){return this._funcRef}set funcRef(e){this._funcRef!==e&&(this._funcRef=e,this._isStencilFuncDirty=!0)}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask!==e&&(this._funcMask=e,this._isStencilFuncDirty=!0)}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail!==e&&(this._opStencilFail=e,this._isStencilOpDirty=!0)}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail!==e&&(this._opDepthFail=e,this._isStencilOpDirty=!0)}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass!==e&&(this._opStencilDepthPass=e,this._isStencilOpDirty=!0)}get backOpStencilFail(){return this._backOpStencilFail}set backOpStencilFail(e){this._backOpStencilFail!==e&&(this._backOpStencilFail=e,this._isStencilOpDirty=!0)}get backOpDepthFail(){return this._backOpDepthFail}set backOpDepthFail(e){this._backOpDepthFail!==e&&(this._backOpDepthFail=e,this._isStencilOpDirty=!0)}get backOpStencilDepthPass(){return this._backOpStencilDepthPass}set backOpStencilDepthPass(e){this._backOpStencilDepthPass!==e&&(this._backOpStencilDepthPass=e,this._isStencilOpDirty=!0)}get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this._isStencilMaskDirty=!0)}get enabled(){return this._enabled}set enabled(e){this._enabled!==e&&(this._enabled=e,this._isStencilTestDirty=!0)}constructor(e=!0){this._isStencilTestDirty=!1,this._isStencilMaskDirty=!1,this._isStencilFuncDirty=!1,this._isStencilOpDirty=!1,this.useStencilGlobalOnly=!1,e&&this.reset()}reset(){var e;this.stencilMaterial=void 0,(e=this.stencilGlobal)==null||e.reset(),this._isStencilTestDirty=!0,this._isStencilMaskDirty=!0,this._isStencilFuncDirty=!0,this._isStencilOpDirty=!0}apply(e){var i;if(!e)return;let t=!this.useStencilGlobalOnly&&!!((i=this.stencilMaterial)!=null&&i.enabled);this.enabled=t?this.stencilMaterial.enabled:this.stencilGlobal.enabled,this.func=t?this.stencilMaterial.func:this.stencilGlobal.func,this.backFunc=t?this.stencilMaterial.backFunc:this.stencilGlobal.backFunc,this.funcRef=t?this.stencilMaterial.funcRef:this.stencilGlobal.funcRef,this.funcMask=t?this.stencilMaterial.funcMask:this.stencilGlobal.funcMask,this.opStencilFail=t?this.stencilMaterial.opStencilFail:this.stencilGlobal.opStencilFail,this.opDepthFail=t?this.stencilMaterial.opDepthFail:this.stencilGlobal.opDepthFail,this.opStencilDepthPass=t?this.stencilMaterial.opStencilDepthPass:this.stencilGlobal.opStencilDepthPass,this.backOpStencilFail=t?this.stencilMaterial.backOpStencilFail:this.stencilGlobal.backOpStencilFail,this.backOpDepthFail=t?this.stencilMaterial.backOpDepthFail:this.stencilGlobal.backOpDepthFail,this.backOpStencilDepthPass=t?this.stencilMaterial.backOpStencilDepthPass:this.stencilGlobal.backOpStencilDepthPass,this.mask=t?this.stencilMaterial.mask:this.stencilGlobal.mask,this.isDirty&&(this._isStencilTestDirty&&(this.enabled?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this._isStencilTestDirty=!1),this._isStencilMaskDirty&&(e.stencilMask(this.mask),this._isStencilMaskDirty=!1),this._isStencilFuncDirty&&(e.stencilFuncSeparate(e.FRONT,this.func,this.funcRef,this.funcMask),e.stencilFuncSeparate(e.BACK,this.backFunc,this.funcRef,this.funcMask),this._isStencilFuncDirty=!1),this._isStencilOpDirty&&(e.stencilOpSeparate(e.FRONT,this.opStencilFail,this.opDepthFail,this.opStencilDepthPass),e.stencilOpSeparate(e.BACK,this.backOpStencilFail,this.backOpDepthFail,this.backOpStencilDepthPass),this._isStencilOpDirty=!1))}}});var Ph,X3=C(()=>{Ph=class n{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.funcRef=1,this.funcMask=255,this.func=n.ALWAYS,this.opStencilFail=n.KEEP,this.opDepthFail=n.KEEP,this.opStencilDepthPass=n.REPLACE,this.backFunc=n.ALWAYS,this.backOpStencilFail=n.KEEP,this.backOpDepthFail=n.KEEP,this.backOpStencilDepthPass=n.REPLACE}get stencilFunc(){return this.func}set stencilFunc(e){this.func=e}get stencilBackFunc(){return this.backFunc}set stencilBackFunc(e){this.backFunc=e}get stencilFuncRef(){return this.funcRef}set stencilFuncRef(e){this.funcRef=e}get stencilFuncMask(){return this.funcMask}set stencilFuncMask(e){this.funcMask=e}get stencilOpStencilFail(){return this.opStencilFail}set stencilOpStencilFail(e){this.opStencilFail=e}get stencilOpDepthFail(){return this.opDepthFail}set stencilOpDepthFail(e){this.opDepthFail=e}get stencilOpStencilDepthPass(){return this.opStencilDepthPass}set stencilOpStencilDepthPass(e){this.opStencilDepthPass=e}get stencilBackOpStencilFail(){return this.backOpStencilFail}set stencilBackOpStencilFail(e){this.backOpStencilFail=e}get stencilBackOpDepthFail(){return this.backOpDepthFail}set stencilBackOpDepthFail(e){this.backOpDepthFail=e}get stencilBackOpStencilDepthPass(){return this.backOpStencilDepthPass}set stencilBackOpStencilDepthPass(e){this.backOpStencilDepthPass=e}get stencilMask(){return this.mask}set stencilMask(e){this.mask=e}get stencilTest(){return this.enabled}set stencilTest(e){this.enabled=e}};Ph.ALWAYS=519;Ph.KEEP=7680;Ph.REPLACE=7681});var Gu,xM=C(()=>{Gu=class{constructor(e){this._supportBlendParametersPerTarget=e,this._blendFunctionParameters=new Array(32),this._blendEquationParameters=new Array(16),this._blendConstants=new Array(4),this._isBlendConstantsDirty=!1,this._alphaBlend=Array(8).fill(!1),this._numTargetEnabled=0,this._isAlphaBlendDirty=!1,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this.reset()}get isDirty(){return this._isAlphaBlendDirty||this._isBlendFunctionParametersDirty||this._isBlendEquationParametersDirty}get alphaBlend(){return this._numTargetEnabled>0}set alphaBlend(e){this.setAlphaBlend(e)}setAlphaBlend(e,t=0){this._alphaBlend[t]!==e&&(e?this._numTargetEnabled++:this._numTargetEnabled--,this._alphaBlend[t]=e,this._isAlphaBlendDirty=!0)}setAlphaBlendConstants(e,t,i,r){this._blendConstants[0]===e&&this._blendConstants[1]===t&&this._blendConstants[2]===i&&this._blendConstants[3]===r||(this._blendConstants[0]=e,this._blendConstants[1]=t,this._blendConstants[2]=i,this._blendConstants[3]=r,this._isBlendConstantsDirty=!0)}setAlphaBlendFunctionParameters(e,t,i,r,s=0){let a=s*4;this._blendFunctionParameters[a+0]===e&&this._blendFunctionParameters[a+1]===t&&this._blendFunctionParameters[a+2]===i&&this._blendFunctionParameters[a+3]===r||(this._blendFunctionParameters[a+0]=e,this._blendFunctionParameters[a+1]=t,this._blendFunctionParameters[a+2]=i,this._blendFunctionParameters[a+3]=r,this._isBlendFunctionParametersDirty=!0)}setAlphaEquationParameters(e,t,i=0){let r=i*2;this._blendEquationParameters[r+0]===e&&this._blendEquationParameters[r+1]===t||(this._blendEquationParameters[r+0]=e,this._blendEquationParameters[r+1]=t,this._isBlendEquationParametersDirty=!0)}reset(){this._alphaBlend.fill(!1),this._numTargetEnabled=0,this._blendFunctionParameters.fill(null),this._blendEquationParameters.fill(null),this._blendConstants[0]=null,this._blendConstants[1]=null,this._blendConstants[2]=null,this._blendConstants[3]=null,this._isAlphaBlendDirty=!0,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this._isBlendConstantsDirty=!1}apply(e,t=1){if(!this.isDirty)return;if(this._isBlendConstantsDirty&&(e.blendColor(this._blendConstants[0],this._blendConstants[1],this._blendConstants[2],this._blendConstants[3]),this._isBlendConstantsDirty=!1),t===1||!this._supportBlendParametersPerTarget){this._isAlphaBlendDirty&&(this._alphaBlend[0]?e.enable(e.BLEND):e.disable(e.BLEND),this._isAlphaBlendDirty=!1),this._isBlendFunctionParametersDirty&&(e.blendFuncSeparate(this._blendFunctionParameters[0],this._blendFunctionParameters[1],this._blendFunctionParameters[2],this._blendFunctionParameters[3]),this._isBlendFunctionParametersDirty=!1),this._isBlendEquationParametersDirty&&(e.blendEquationSeparate(this._blendEquationParameters[0],this._blendEquationParameters[1]),this._isBlendEquationParametersDirty=!1);return}let i=e;if(this._isAlphaBlendDirty){for(let r=0;r{di();yh();Di();Pt();AM();wl();H3();z3();X3();xM();hn();vs();ga();af();Me=class n{get frameId(){return this._frameId}get isWebGPU(){return this._isWebGPU}_getShaderProcessor(e){return this._shaderProcessor}_resetAlphaMode(){this._alphaMode.fill(-1),this._alphaEquation.fill(-1)}get shaderPlatformName(){return this._shaderPlatformName}_clearEmptyResources(){this._emptyTexture=null,this._emptyCubeTexture=null,this._emptyTexture3D=null,this._emptyTexture2DArray=null}get useReverseDepthBuffer(){return this._useReverseDepthBuffer}set useReverseDepthBuffer(e){e!==this._useReverseDepthBuffer&&(this._useReverseDepthBuffer=e,e?this._depthCullingState.depthFunc=518:this._depthCullingState.depthFunc=515)}setColorWrite(e){e!==this._colorWrite&&(this._colorWriteChanged=!0,this._colorWrite=e)}getColorWrite(){return this._colorWrite}get depthCullingState(){return this._depthCullingState}get alphaState(){return this._alphaState}get stencilState(){return this._stencilState}get stencilStateComposer(){return this._stencilStateComposer}_getGlobalDefines(e){if(e){this.isNDCHalfZRange?e.IS_NDC_HALF_ZRANGE="":delete e.IS_NDC_HALF_ZRANGE,this.useReverseDepthBuffer?e.USE_REVERSE_DEPTHBUFFER="":delete e.USE_REVERSE_DEPTHBUFFER,this.useExactSrgbConversions?e.USE_EXACT_SRGB_CONVERSIONS="":delete e.USE_EXACT_SRGB_CONVERSIONS;return}else{let t="";return this.isNDCHalfZRange&&(t+="#define IS_NDC_HALF_ZRANGE"),this.useReverseDepthBuffer&&(t&&(t+=` `),t+="#define USE_REVERSE_DEPTHBUFFER"),this.useExactSrgbConversions&&(t&&(t+=` -`),t+="#define USE_EXACT_SRGB_CONVERSIONS"),t}}_rebuildInternalTextures(){let e=this._internalTexturesCache.slice();for(let t of e)t._rebuild()}_rebuildRenderTargetWrappers(){let e=this._renderTargetWrapperCache.slice();for(let t of e)t._rebuild()}_rebuildEffects(){for(let e in this._compiledEffects){let t=this._compiledEffects[e];t._pipelineContext=null,t._prepareEffect()}tr.ResetCache()}_rebuildGraphicsResources(){var e;this.wipeCaches(!0),this._rebuildEffects(),(e=this._rebuildComputeEffects)==null||e.call(this),this._rebuildBuffers(),this._rebuildInternalTextures(),this._rebuildTextures(),this._rebuildRenderTargetWrappers(),this.wipeCaches(!0)}_flagContextRestored(){te.Warn(this.name+" context successfully restored."),this.onContextRestoredObservable.notifyObservers(this),this._contextWasLost=!1}_restoreEngineAfterContextLost(e){setTimeout(()=>{this._clearEmptyResources();let t=this._depthCullingState.depthTest,i=this._depthCullingState.depthFunc,r=this._depthCullingState.depthMask,s=this._stencilState.stencilTest;e(),this._rebuildGraphicsResources(),this._depthCullingState.depthTest=t,this._depthCullingState.depthFunc=i,this._depthCullingState.depthMask=r,this._stencilState.stencilTest=s,this._flagContextRestored()},0)}get isDisposed(){return this._isDisposed}get snapshotRendering(){return!1}set snapshotRendering(e){}get snapshotRenderingMode(){return 0}set snapshotRenderingMode(e){}getClassName(){return"AbstractEngine"}get emptyTexture(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,5,!1,!1,1)),this._emptyTexture}get emptyTexture3D(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture3D}get emptyTexture2DArray(){return this._emptyTexture2DArray||(this._emptyTexture2DArray=this.createRawTexture2DArray(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture2DArray}get emptyCubeTexture(){if(!this._emptyCubeTexture){let e=new Uint8Array(4),t=[e,e,e,e,e,e];this._emptyCubeTexture=this.createRawCubeTexture(t,1,5,0,!1,!1,1)}return this._emptyCubeTexture}get activeRenderLoops(){return this._activeRenderLoops}stopRenderLoop(e){if(!e){this._activeRenderLoops.length=0,this._cancelFrame();return}let t=this._activeRenderLoops.indexOf(e);t>=0&&(this._activeRenderLoops.splice(t,1),this._activeRenderLoops.length==0&&this._cancelFrame())}_cancelFrame(){if(this._frameHandler!==0){let e=this._frameHandler;if(this._frameHandler=0,cr()){let{cancelAnimationFrame:t}=this.getHostWindow()||window;if(typeof t=="function")return t(e)}else if(typeof cancelAnimationFrame=="function")return cancelAnimationFrame(e);return clearTimeout(e)}}beginFrame(){this.onBeginFrameObservable.notifyObservers(this)}endFrame(){this._frameId++,this.onEndFrameObservable.notifyObservers(this)}get maxFPS(){return this._maxFPS}set maxFPS(e){if(this._maxFPS=e,e!==void 0){if(e<=0){this._minFrameTime=Number.MAX_VALUE;return}this._minFrameTime=1e3/e}}_isOverFrameTime(e){if(!e||this._maxFPS===void 0)return!1;let t=e-this._lastFrameTime;return this._lastFrameTime=e,this._renderAccumulator+=t,this._renderAccumulatorthis._minFrameTime&&(this._renderAccumulator=this._minFrameTime),!1)}_processFrame(e){if(this._frameHandler=0,!this._contextWasLost&&!this._isOverFrameTime(e)){let t=!0;(this.isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(t=!1),t&&(this.beginFrame(),!this.skipFrameRender&&!this._renderViews()&&this._renderFrame(),this.endFrame())}}_renderLoop(e){this._processFrame(e),this._activeRenderLoops.length>0&&this._frameHandler===0&&(this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()))}_renderFrame(){for(let e=0;e-1?e.substring(E).toLowerCase():"");R.indexOf("?")>-1&&(R=R.split("?")[0]);let y=n.GetCompatibleTextureLoader(R,m);r&&r.addPendingData(A),A.url=e,A.generateMipMaps=!t,A.samplingMode=s,A.invertY=i,A._useSRGBBuffer=this._getUseSRGBBuffer(!!_,t),this._doNotHandleContextLost||(A._buffer=f);let M=null;a&&!h&&(M=A.onLoadedObservable.add(a)),h||this._internalTexturesCache.push(A);let D=(O,V)=>{r&&r.removePendingData(A),e===S?(M&&A.onLoadedObservable.remove(M),Le.UseFallbackTexture&&e!==Le.FallbackTexture&&this._createTextureBase(Le.FallbackTexture,t,A.invertY,r,s,null,o,l,c,f,A),O=(O||"Unknown error")+(Le.UseFallbackTexture?" - Fallback texture was used":""),A.onErrorObservable.notifyObservers({message:O,exception:V}),o&&o(O,V)):(te.Warn(`Failed to load ${e}, falling back to ${S}`),this._createTextureBase(S,t,A.invertY,r,s,a,o,l,c,f,A,d,u,m,p,_))};if(y){let O=async V=>{(await y).loadData(V,A,(F,U,k,ee,q,Q)=>{Q?D("TextureLoader failed to load data"):l(A,R,r,{width:F,height:U},A.invertY,!k,ee,()=>(q(),!1),s)},p)};if(!f)this._loadFile(e,async V=>{try{await O(new Uint8Array(V))}catch(N){D("Failed to parse texture data",N)}},void 0,r?r.offlineProvider:void 0,!0,(V,N)=>{D("Unable to load "+(V&&V.responseURL,N))});else{let V=async N=>{try{await O(N)}catch(F){D("Failed to parse texture data",F)}};f instanceof ArrayBuffer?V(new Uint8Array(f)):ArrayBuffer.isView(f)?V(f):o&&o("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null)}}else{let O=V=>{v&&!this._doNotHandleContextLost&&(A._buffer=V),l(A,R,r,V,A.invertY,t,!1,c,s)};!g||x?f&&(typeof f.decoding=="string"||f.close)?O(f):n._FileToolsLoadImage(e||"",O,D,r?r.offlineProvider:null,m,A.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0,this):typeof f=="string"||f instanceof ArrayBuffer||ArrayBuffer.isView(f)||f instanceof Blob?n._FileToolsLoadImage(f,O,D,r?r.offlineProvider:null,m,A.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0,this):f&&O(f)}return A}_rebuildBuffers(){for(let e of this._uniformBuffers)e._rebuildAfterContextLost()}get _shouldUseHighPrecisionShader(){return!!(this._caps.highPrecisionShaderSupported&&this._highPrecisionShadersAllowed)}getHostDocument(){return this._renderingCanvas&&this._renderingCanvas.ownerDocument?this._renderingCanvas.ownerDocument:af()?document:null}getLoadedTexturesCache(){return this._internalTexturesCache}clearInternalTexturesCache(){this._internalTexturesCache.length=0}getCaps(){return this._caps}resetTextureCache(){for(let e in this._boundTexturesCache)Object.prototype.hasOwnProperty.call(this._boundTexturesCache,e)&&(this._boundTexturesCache[e]=null);this._currentTextureChannel=-1}get name(){return this._name}set name(e){this._name=e}static get NpmPackage(){return"babylonjs@9.6.0"}static get Version(){return"9.6.0"}getRenderingCanvas(){return this._renderingCanvas}getAudioContext(){return this._audioContext}getAudioDestination(){return this._audioDestination}setHardwareScalingLevel(e){this._hardwareScalingLevel=e,this.resize()}getHardwareScalingLevel(){return this._hardwareScalingLevel}get doNotHandleContextLost(){return this._doNotHandleContextLost}set doNotHandleContextLost(e){this._doNotHandleContextLost=e}get isStencilEnable(){return this._isStencilEnable}getCreationOptions(){return this._creationOptions}constructor(e,t,i){var a,o,l,c,f,h,d,u,m,p;this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new xT,this._stencilStateComposer=new RT,this._stencilState=new Ph,this._alphaState=new ku(!1),this._alphaMode=Array(8).fill(-1),this._alphaEquation=Array(8).fill(-1),this._activeRequests=[],this._badOS=!1,this._badDesktopOS=!1,this._compatibilityMode=!0,this._internalTexturesCache=new Array,this._currentRenderTarget=null,this._boundTexturesCache={},this._activeChannel=0,this._currentTextureChannel=-1,this._viewportCached={x:0,y:0,z:0,w:0},this._isWebGPU=!1,this._enableGPUDebugMarkers=!1,this.onCanvasBlurObservable=new ie,this.onCanvasFocusObservable=new ie,this.onNewSceneAddedObservable=new ie,this.onResizeObservable=new ie,this.onCanvasPointerOutObservable=new ie,this.onEffectErrorObservable=new ie,this.disablePerformanceMonitorInBackground=!1,this.disableVertexArrayObjects=!1,this._frameId=0,this.hostInformation={isMobile:!1},this.isFullscreen=!1,this.enableOfflineSupport=!1,this.disableManifestCheck=!1,this.disableContextMenu=!0,this.currentRenderPassId=0,this.isPointerLock=!1,this.postProcesses=[],this.canvasTabIndex=1,this._contextWasLost=!1,this._useReverseDepthBuffer=!1,this.isNDCHalfZRange=!1,this.hasOriginBottomLeft=!0,this._renderTargetWrapperCache=new Array,this._compiledEffects={},this._isDisposed=!1,this.scenes=[],this._virtualScenes=new Array,this.onBeforeTextureInitObservable=new ie,this.renderEvenInBackground=!0,this.preventCacheWipeBetweenFrames=!1,this._frameHandler=0,this._activeRenderLoops=new Array,this._windowIsBackground=!1,this._boundRenderFunction=_=>this._renderLoop(_),this._lastFrameTime=0,this._renderAccumulator=0,this.skipFrameRender=!1,this.onBeforeShaderCompilationObservable=new ie,this.onAfterShaderCompilationObservable=new ie,this.onBeginFrameObservable=new ie,this.onEndFrameObservable=new ie,this._transformTextureUrl=null,this._uniformBuffers=new Array,this._storageBuffers=new Array,this._highPrecisionShadersAllowed=!0,this.onContextLostObservable=new ie,this.onContextRestoredObservable=new ie,this._name="",this.premultipliedAlpha=!0,this.adaptToDeviceRatio=!1,this._lastDevicePixelRatio=1,this._doNotHandleContextLost=!1,this.cullBackFaces=null,this._renderPassNames=["main"],this._fps=60,this._deltaTime=0,this._deterministicLockstep=!1,this._lockstepMaxSteps=4,this._timeStep=1/60,this.onDisposeObservable=new ie,this.onReleaseEffectsObservable=new ie,Le.Instances.push(this),this.startTime=mr.Now,this._stencilStateComposer.stencilGlobal=this._stencilState,Zn.SetMatrixPrecision(!!t.useLargeWorldRendering||!!t.useHighPrecisionMatrix),wl()&&navigator.userAgent&&(this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent),this._badDesktopOS=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),this.adaptToDeviceRatio=i!=null?i:!1,t.antialias=e!=null?e:t.antialias,t.deterministicLockstep=(a=t.deterministicLockstep)!=null?a:!1,t.lockstepMaxSteps=(o=t.lockstepMaxSteps)!=null?o:4,t.timeStep=(l=t.timeStep)!=null?l:1/60,t.stencil=(c=t.stencil)!=null?c:!0,this._audioContext=(h=(f=t.audioEngineOptions)==null?void 0:f.audioContext)!=null?h:null,this._audioDestination=(u=(d=t.audioEngineOptions)==null?void 0:d.audioDestination)!=null?u:null,this.premultipliedAlpha=(m=t.premultipliedAlpha)!=null?m:!0,this._doNotHandleContextLost=!!t.doNotHandleContextLost,this._isStencilEnable=!!t.stencil,this.useExactSrgbConversions=(p=t.useExactSrgbConversions)!=null?p:!1;let r=cr()&&window.devicePixelRatio||1,s=t.limitDeviceRatio||r;i=i||t.adaptToDeviceRatio||!1,this._hardwareScalingLevel=i?1/Math.min(s,r):1,this._lastDevicePixelRatio=r,this._creationOptions=t}resize(e=!1){var r,s;let t,i;if(this.adaptToDeviceRatio){let a=cr()&&window.devicePixelRatio||1,o=this._lastDevicePixelRatio/a;this._lastDevicePixelRatio=a,this._hardwareScalingLevel*=o}if(cr()&&af())if(this._renderingCanvas){let a=(s=(r=this._renderingCanvas).getBoundingClientRect)==null?void 0:s.call(r);t=this._renderingCanvas.clientWidth||(a==null?void 0:a.width)||this._renderingCanvas.width*this._hardwareScalingLevel||100,i=this._renderingCanvas.clientHeight||(a==null?void 0:a.height)||this._renderingCanvas.height*this._hardwareScalingLevel||100}else t=window.innerWidth,i=window.innerHeight;else t=this._renderingCanvas?this._renderingCanvas.width:100,i=this._renderingCanvas?this._renderingCanvas.height:100;this.setSize(t/this._hardwareScalingLevel,i/this._hardwareScalingLevel,e)}setSize(e,t,i=!1){if(!this._renderingCanvas||(e=e|0,t=t|0,!i&&this._renderingCanvas.width===e&&this._renderingCanvas.height===t))return!1;if(this._renderingCanvas.width=e,this._renderingCanvas.height=t,this.scenes){for(let r=0;r{let e=navigator.userAgent;this.hostInformation.isMobile=e.indexOf("Mobile")!==-1||e.indexOf("Mac")!==-1&&af()&&"ontouchend"in document},this._checkForMobile(),cr()&&window.addEventListener("resize",this._checkForMobile))}createVideoElement(e){return document.createElement("video")}_reportDrawCall(e=1){var t;(t=this._drawCalls)==null||t.addCount(e,!1)}getFps(){return this._fps}getDeltaTime(){return this._deltaTime}isDeterministicLockStep(){return this._deterministicLockstep}getLockstepMaxSteps(){return this._lockstepMaxSteps}getTimeStep(){return this._timeStep*1e3}_createImageBitmapFromSource(e,t){throw new Error("createImageBitmapFromSource is not implemented")}createImageBitmap(e,t){return createImageBitmap(e,t)}resizeImageBitmap(e,t,i){throw new Error("resizeImageBitmap is not implemented")}getFontOffset(e){throw new Error("getFontOffset is not implemented")}static _CreateCanvas(e,t){if(typeof document=="undefined")return new OffscreenCanvas(e,t);let i=document.createElement("canvas");return i.width=e,i.height=t,i}createCanvas(e,t){return n._CreateCanvas(e,t)}static _FileToolsLoadImage(e,t,i,r,s,a,o){throw Ze("FileTools")}_loadFile(e,t,i,r,s,a){let o=oT(e,t,i,r,s,a);return this._activeRequests.push(o),o.onCompleteObservable.add(()=>{let l=this._activeRequests.indexOf(o);l!==-1&&this._activeRequests.splice(l,1)}),o}static _FileToolsLoadFile(e,t,i,r,s,a){if(Uu.loadFile)return Uu.loadFile(e,t,i,r,s,a);throw Ze("FileTools")}dispose(){var t;for(this.releaseEffects(),this._isDisposed=!0,this.stopRenderLoop(),this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this._renderingCanvas=null,this.onBeforeTextureInitObservable&&this.onBeforeTextureInitObservable.clear();this.postProcesses.length;)this.postProcesses[0].dispose();for(;this.scenes.length;)this.scenes[0].dispose();for(;this._virtualScenes.length;)this._virtualScenes[0].dispose();(t=this.releaseComputeEffects)==null||t.call(this),tr.ResetCache();for(let i of this._activeRequests)i.abort();this._boundRenderFunction=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onResizeObservable.clear(),this.onCanvasBlurObservable.clear(),this.onCanvasFocusObservable.clear(),this.onCanvasPointerOutObservable.clear(),this.onNewSceneAddedObservable.clear(),this.onEffectErrorObservable.clear(),cr()&&window.removeEventListener("resize",this._checkForMobile);let e=Le.Instances.indexOf(this);e>=0&&Le.Instances.splice(e,1),Le.Instances.length||(Le.OnEnginesDisposedObservable.notifyObservers(this),Le.OnEnginesDisposedObservable.clear()),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear()}static DefaultLoadingScreenFactory(e){throw Ze("LoadingScreen")}static MarkAllMaterialsAsDirty(e,t){for(let i=0;i{});var IT,K3=C(()=>{IT=class{constructor(){this.shaderLanguage=0}postProcessor(e,t,i,r,s){if(s.drawBuffersExtensionDisabled){let a=/#extension.+GL_EXT_draw_buffers.+(enable|require)/g;e=e.replace(a,"")}return e}}});var Are,MT,j3=C(()=>{Are=/(flat\s)?\s*varying\s*.*/,MT=class{constructor(){this.shaderLanguage=0}attributeProcessor(e){return e.replace("attribute","in")}varyingCheck(e,t){return Are.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){let r=e.search(/#extension.+GL_EXT_draw_buffers.+require/)!==-1,s=/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;if(e=e.replace(s,""),e=e.replace(/texture2D\s*\(/g,"texture("),i){let a=e.search(/layout *\(location *= *0\) *out/g)!==-1,o=t.indexOf("#define DUAL_SOURCE_BLENDING")!==-1,l=o?`layout(location = 0, index = 0) out vec4 glFragColor; +`),t+="#define USE_EXACT_SRGB_CONVERSIONS"),t}}_rebuildInternalTextures(){let e=this._internalTexturesCache.slice();for(let t of e)t._rebuild()}_rebuildRenderTargetWrappers(){let e=this._renderTargetWrapperCache.slice();for(let t of e)t._rebuild()}_rebuildEffects(){for(let e in this._compiledEffects){let t=this._compiledEffects[e];t._pipelineContext=null,t._prepareEffect()}rr.ResetCache()}_rebuildGraphicsResources(){var e;this.wipeCaches(!0),this._rebuildEffects(),(e=this._rebuildComputeEffects)==null||e.call(this),this._rebuildBuffers(),this._rebuildInternalTextures(),this._rebuildTextures(),this._rebuildRenderTargetWrappers(),this.wipeCaches(!0)}_flagContextRestored(){te.Warn(this.name+" context successfully restored."),this.onContextRestoredObservable.notifyObservers(this),this._contextWasLost=!1}_restoreEngineAfterContextLost(e){setTimeout(()=>{this._clearEmptyResources();let t=this._depthCullingState.depthTest,i=this._depthCullingState.depthFunc,r=this._depthCullingState.depthMask,s=this._stencilState.stencilTest;e(),this._rebuildGraphicsResources(),this._depthCullingState.depthTest=t,this._depthCullingState.depthFunc=i,this._depthCullingState.depthMask=r,this._stencilState.stencilTest=s,this._flagContextRestored()},0)}get isDisposed(){return this._isDisposed}get snapshotRendering(){return!1}set snapshotRendering(e){}get snapshotRenderingMode(){return 0}set snapshotRenderingMode(e){}getClassName(){return"AbstractEngine"}get emptyTexture(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,5,!1,!1,1)),this._emptyTexture}get emptyTexture3D(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture3D}get emptyTexture2DArray(){return this._emptyTexture2DArray||(this._emptyTexture2DArray=this.createRawTexture2DArray(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture2DArray}get emptyCubeTexture(){if(!this._emptyCubeTexture){let e=new Uint8Array(4),t=[e,e,e,e,e,e];this._emptyCubeTexture=this.createRawCubeTexture(t,1,5,0,!1,!1,1)}return this._emptyCubeTexture}get activeRenderLoops(){return this._activeRenderLoops}stopRenderLoop(e){if(!e){this._activeRenderLoops.length=0,this._cancelFrame();return}let t=this._activeRenderLoops.indexOf(e);t>=0&&(this._activeRenderLoops.splice(t,1),this._activeRenderLoops.length==0&&this._cancelFrame())}_cancelFrame(){if(this._frameHandler!==0){let e=this._frameHandler;if(this._frameHandler=0,fr()){let{cancelAnimationFrame:t}=this.getHostWindow()||window;if(typeof t=="function")return t(e)}else if(typeof cancelAnimationFrame=="function")return cancelAnimationFrame(e);return clearTimeout(e)}}beginFrame(){this.onBeginFrameObservable.notifyObservers(this)}endFrame(){this._frameId++,this.onEndFrameObservable.notifyObservers(this)}get maxFPS(){return this._maxFPS}set maxFPS(e){if(this._maxFPS=e,e!==void 0){if(e<=0){this._minFrameTime=Number.MAX_VALUE;return}this._minFrameTime=1e3/e}}_isOverFrameTime(e){if(!e||this._maxFPS===void 0)return!1;let t=e-this._lastFrameTime;return this._lastFrameTime=e,this._renderAccumulator+=t,this._renderAccumulatorthis._minFrameTime&&(this._renderAccumulator=this._minFrameTime),!1)}_processFrame(e){if(this._frameHandler=0,!this._contextWasLost&&!this._isOverFrameTime(e)){let t=!0;(this.isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(t=!1),t&&(this.beginFrame(),!this.skipFrameRender&&!this._renderViews()&&this._renderFrame(),this.endFrame())}}_renderLoop(e){this._processFrame(e),this._activeRenderLoops.length>0&&this._frameHandler===0&&(this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()))}_renderFrame(){for(let e=0;e-1?e.substring(E).toLowerCase():"");R.indexOf("?")>-1&&(R=R.split("?")[0]);let y=n.GetCompatibleTextureLoader(R,m);r&&r.addPendingData(A),A.url=e,A.generateMipMaps=!t,A.samplingMode=s,A.invertY=i,A._useSRGBBuffer=this._getUseSRGBBuffer(!!_,t),this._doNotHandleContextLost||(A._buffer=f);let M=null;a&&!h&&(M=A.onLoadedObservable.add(a)),h||this._internalTexturesCache.push(A);let D=(O,V)=>{r&&r.removePendingData(A),e===S?(M&&A.onLoadedObservable.remove(M),Oe.UseFallbackTexture&&e!==Oe.FallbackTexture&&this._createTextureBase(Oe.FallbackTexture,t,A.invertY,r,s,null,o,l,c,f,A),O=(O||"Unknown error")+(Oe.UseFallbackTexture?" - Fallback texture was used":""),A.onErrorObservable.notifyObservers({message:O,exception:V}),o&&o(O,V)):(te.Warn(`Failed to load ${e}, falling back to ${S}`),this._createTextureBase(S,t,A.invertY,r,s,a,o,l,c,f,A,d,u,m,p,_))};if(y){let O=async V=>{(await y).loadData(V,A,(F,U,G,ee,j,Z)=>{Z?D("TextureLoader failed to load data"):l(A,R,r,{width:F,height:U},A.invertY,!G,ee,()=>(j(),!1),s)},p)};if(!f)this._loadFile(e,async V=>{try{await O(new Uint8Array(V))}catch(N){D("Failed to parse texture data",N)}},void 0,r?r.offlineProvider:void 0,!0,(V,N)=>{D("Unable to load "+(V&&V.responseURL,N))});else{let V=async N=>{try{await O(N)}catch(F){D("Failed to parse texture data",F)}};f instanceof ArrayBuffer?V(new Uint8Array(f)):ArrayBuffer.isView(f)?V(f):o&&o("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null)}}else{let O=V=>{v&&!this._doNotHandleContextLost&&(A._buffer=V),l(A,R,r,V,A.invertY,t,!1,c,s)};!g||x?f&&(typeof f.decoding=="string"||f.close)?O(f):n._FileToolsLoadImage(e||"",O,D,r?r.offlineProvider:null,m,A.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0,this):typeof f=="string"||f instanceof ArrayBuffer||ArrayBuffer.isView(f)||f instanceof Blob?n._FileToolsLoadImage(f,O,D,r?r.offlineProvider:null,m,A.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0,this):f&&O(f)}return A}_rebuildBuffers(){for(let e of this._uniformBuffers)e._rebuildAfterContextLost()}get _shouldUseHighPrecisionShader(){return!!(this._caps.highPrecisionShaderSupported&&this._highPrecisionShadersAllowed)}getHostDocument(){return this._renderingCanvas&&this._renderingCanvas.ownerDocument?this._renderingCanvas.ownerDocument:sf()?document:null}getLoadedTexturesCache(){return this._internalTexturesCache}clearInternalTexturesCache(){this._internalTexturesCache.length=0}getCaps(){return this._caps}resetTextureCache(){for(let e in this._boundTexturesCache)Object.prototype.hasOwnProperty.call(this._boundTexturesCache,e)&&(this._boundTexturesCache[e]=null);this._currentTextureChannel=-1}get name(){return this._name}set name(e){this._name=e}static get NpmPackage(){return"babylonjs@9.6.0"}static get Version(){return"9.6.0"}getRenderingCanvas(){return this._renderingCanvas}getAudioContext(){return this._audioContext}getAudioDestination(){return this._audioDestination}setHardwareScalingLevel(e){this._hardwareScalingLevel=e,this.resize()}getHardwareScalingLevel(){return this._hardwareScalingLevel}get doNotHandleContextLost(){return this._doNotHandleContextLost}set doNotHandleContextLost(e){this._doNotHandleContextLost=e}get isStencilEnable(){return this._isStencilEnable}getCreationOptions(){return this._creationOptions}constructor(e,t,i){var a,o,l,c,f,h,d,u,m,p;this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new RT,this._stencilStateComposer=new bT,this._stencilState=new Ph,this._alphaState=new Gu(!1),this._alphaMode=Array(8).fill(-1),this._alphaEquation=Array(8).fill(-1),this._activeRequests=[],this._badOS=!1,this._badDesktopOS=!1,this._compatibilityMode=!0,this._internalTexturesCache=new Array,this._currentRenderTarget=null,this._boundTexturesCache={},this._activeChannel=0,this._currentTextureChannel=-1,this._viewportCached={x:0,y:0,z:0,w:0},this._isWebGPU=!1,this._enableGPUDebugMarkers=!1,this.onCanvasBlurObservable=new ie,this.onCanvasFocusObservable=new ie,this.onNewSceneAddedObservable=new ie,this.onResizeObservable=new ie,this.onCanvasPointerOutObservable=new ie,this.onEffectErrorObservable=new ie,this.disablePerformanceMonitorInBackground=!1,this.disableVertexArrayObjects=!1,this._frameId=0,this.hostInformation={isMobile:!1},this.isFullscreen=!1,this.enableOfflineSupport=!1,this.disableManifestCheck=!1,this.disableContextMenu=!0,this.currentRenderPassId=0,this.isPointerLock=!1,this.postProcesses=[],this.canvasTabIndex=1,this._contextWasLost=!1,this._useReverseDepthBuffer=!1,this.isNDCHalfZRange=!1,this.hasOriginBottomLeft=!0,this._renderTargetWrapperCache=new Array,this._compiledEffects={},this._isDisposed=!1,this.scenes=[],this._virtualScenes=new Array,this.onBeforeTextureInitObservable=new ie,this.renderEvenInBackground=!0,this.preventCacheWipeBetweenFrames=!1,this._frameHandler=0,this._activeRenderLoops=new Array,this._windowIsBackground=!1,this._boundRenderFunction=_=>this._renderLoop(_),this._lastFrameTime=0,this._renderAccumulator=0,this.skipFrameRender=!1,this.onBeforeShaderCompilationObservable=new ie,this.onAfterShaderCompilationObservable=new ie,this.onBeginFrameObservable=new ie,this.onEndFrameObservable=new ie,this._transformTextureUrl=null,this._uniformBuffers=new Array,this._storageBuffers=new Array,this._highPrecisionShadersAllowed=!0,this.onContextLostObservable=new ie,this.onContextRestoredObservable=new ie,this._name="",this.premultipliedAlpha=!0,this.adaptToDeviceRatio=!1,this._lastDevicePixelRatio=1,this._doNotHandleContextLost=!1,this.cullBackFaces=null,this._renderPassNames=["main"],this._fps=60,this._deltaTime=0,this._deterministicLockstep=!1,this._lockstepMaxSteps=4,this._timeStep=1/60,this.onDisposeObservable=new ie,this.onReleaseEffectsObservable=new ie,Oe.Instances.push(this),this.startTime=pr.Now,this._stencilStateComposer.stencilGlobal=this._stencilState,qn.SetMatrixPrecision(!!t.useLargeWorldRendering||!!t.useHighPrecisionMatrix),Nl()&&navigator.userAgent&&(this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent),this._badDesktopOS=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),this.adaptToDeviceRatio=i!=null?i:!1,t.antialias=e!=null?e:t.antialias,t.deterministicLockstep=(a=t.deterministicLockstep)!=null?a:!1,t.lockstepMaxSteps=(o=t.lockstepMaxSteps)!=null?o:4,t.timeStep=(l=t.timeStep)!=null?l:1/60,t.stencil=(c=t.stencil)!=null?c:!0,this._audioContext=(h=(f=t.audioEngineOptions)==null?void 0:f.audioContext)!=null?h:null,this._audioDestination=(u=(d=t.audioEngineOptions)==null?void 0:d.audioDestination)!=null?u:null,this.premultipliedAlpha=(m=t.premultipliedAlpha)!=null?m:!0,this._doNotHandleContextLost=!!t.doNotHandleContextLost,this._isStencilEnable=!!t.stencil,this.useExactSrgbConversions=(p=t.useExactSrgbConversions)!=null?p:!1;let r=fr()&&window.devicePixelRatio||1,s=t.limitDeviceRatio||r;i=i||t.adaptToDeviceRatio||!1,this._hardwareScalingLevel=i?1/Math.min(s,r):1,this._lastDevicePixelRatio=r,this._creationOptions=t}resize(e=!1){var r,s;let t,i;if(this.adaptToDeviceRatio){let a=fr()&&window.devicePixelRatio||1,o=this._lastDevicePixelRatio/a;this._lastDevicePixelRatio=a,this._hardwareScalingLevel*=o}if(fr()&&sf())if(this._renderingCanvas){let a=(s=(r=this._renderingCanvas).getBoundingClientRect)==null?void 0:s.call(r);t=this._renderingCanvas.clientWidth||(a==null?void 0:a.width)||this._renderingCanvas.width*this._hardwareScalingLevel||100,i=this._renderingCanvas.clientHeight||(a==null?void 0:a.height)||this._renderingCanvas.height*this._hardwareScalingLevel||100}else t=window.innerWidth,i=window.innerHeight;else t=this._renderingCanvas?this._renderingCanvas.width:100,i=this._renderingCanvas?this._renderingCanvas.height:100;this.setSize(t/this._hardwareScalingLevel,i/this._hardwareScalingLevel,e)}setSize(e,t,i=!1){if(!this._renderingCanvas||(e=e|0,t=t|0,!i&&this._renderingCanvas.width===e&&this._renderingCanvas.height===t))return!1;if(this._renderingCanvas.width=e,this._renderingCanvas.height=t,this.scenes){for(let r=0;r{let e=navigator.userAgent;this.hostInformation.isMobile=e.indexOf("Mobile")!==-1||e.indexOf("Mac")!==-1&&sf()&&"ontouchend"in document},this._checkForMobile(),fr()&&window.addEventListener("resize",this._checkForMobile))}createVideoElement(e){return document.createElement("video")}_reportDrawCall(e=1){var t;(t=this._drawCalls)==null||t.addCount(e,!1)}getFps(){return this._fps}getDeltaTime(){return this._deltaTime}isDeterministicLockStep(){return this._deterministicLockstep}getLockstepMaxSteps(){return this._lockstepMaxSteps}getTimeStep(){return this._timeStep*1e3}_createImageBitmapFromSource(e,t){throw new Error("createImageBitmapFromSource is not implemented")}createImageBitmap(e,t){return createImageBitmap(e,t)}resizeImageBitmap(e,t,i){throw new Error("resizeImageBitmap is not implemented")}getFontOffset(e){throw new Error("getFontOffset is not implemented")}static _CreateCanvas(e,t){if(typeof document=="undefined")return new OffscreenCanvas(e,t);let i=document.createElement("canvas");return i.width=e,i.height=t,i}createCanvas(e,t){return n._CreateCanvas(e,t)}static _FileToolsLoadImage(e,t,i,r,s,a,o){throw qe("FileTools")}_loadFile(e,t,i,r,s,a){let o=lT(e,t,i,r,s,a);return this._activeRequests.push(o),o.onCompleteObservable.add(()=>{let l=this._activeRequests.indexOf(o);l!==-1&&this._activeRequests.splice(l,1)}),o}static _FileToolsLoadFile(e,t,i,r,s,a){if(Bu.loadFile)return Bu.loadFile(e,t,i,r,s,a);throw qe("FileTools")}dispose(){var t;for(this.releaseEffects(),this._isDisposed=!0,this.stopRenderLoop(),this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this._renderingCanvas=null,this.onBeforeTextureInitObservable&&this.onBeforeTextureInitObservable.clear();this.postProcesses.length;)this.postProcesses[0].dispose();for(;this.scenes.length;)this.scenes[0].dispose();for(;this._virtualScenes.length;)this._virtualScenes[0].dispose();(t=this.releaseComputeEffects)==null||t.call(this),rr.ResetCache();for(let i of this._activeRequests)i.abort();this._boundRenderFunction=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onResizeObservable.clear(),this.onCanvasBlurObservable.clear(),this.onCanvasFocusObservable.clear(),this.onCanvasPointerOutObservable.clear(),this.onNewSceneAddedObservable.clear(),this.onEffectErrorObservable.clear(),fr()&&window.removeEventListener("resize",this._checkForMobile);let e=Oe.Instances.indexOf(this);e>=0&&Oe.Instances.splice(e,1),Oe.Instances.length||(Oe.OnEnginesDisposedObservable.notifyObservers(this),Oe.OnEnginesDisposedObservable.clear()),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear()}static DefaultLoadingScreenFactory(e){throw qe("LoadingScreen")}static MarkAllMaterialsAsDirty(e,t){for(let i=0;i{});var MT,K3=C(()=>{MT=class{constructor(){this.shaderLanguage=0}postProcessor(e,t,i,r,s){if(s.drawBuffersExtensionDisabled){let a=/#extension.+GL_EXT_draw_buffers.+(enable|require)/g;e=e.replace(a,"")}return e}}});var Are,CT,j3=C(()=>{Are=/(flat\s)?\s*varying\s*.*/,CT=class{constructor(){this.shaderLanguage=0}attributeProcessor(e){return e.replace("attribute","in")}varyingCheck(e,t){return Are.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){let r=e.search(/#extension.+GL_EXT_draw_buffers.+require/)!==-1,s=/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;if(e=e.replace(s,""),e=e.replace(/texture2D\s*\(/g,"texture("),i){let a=e.search(/layout *\(location *= *0\) *out/g)!==-1,o=t.indexOf("#define DUAL_SOURCE_BLENDING")!==-1,l=o?`layout(location = 0, index = 0) out vec4 glFragColor; layout(location = 0, index = 1) out vec4 glFragColor2; `:`layout(location = 0) out vec4 glFragColor; `;o&&(e=`#extension GL_EXT_blend_func_extended : require `+e),e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod("),e=e.replace(/textureCubeLodEXT\s*\(/g,"textureLod("),e=e.replace(/textureCube\s*\(/g,"texture("),e=e.replace(/gl_FragDepthEXT/g,"gl_FragDepth"),e=e.replace(/gl_FragColor/g,"glFragColor"),e=e.replace(/gl_FragData/g,"glFragData"),e=e.replace(/void\s+?main\s*\(/g,(r||a?"":l)+"void main(")}else if(t.indexOf("#define VERTEXOUTPUT_INVARIANT")>=0&&(e=`invariant gl_Position; `+e),t.indexOf("#define MULTIVIEW")!==-1)return`#extension GL_OVR_multiview2 : require layout (num_views = 2) in; -`+e;return e}}});var Dh,bM=C(()=>{Dh=class n{get underlyingResource(){return null}constructor(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=n._Counter++}};Dh._Counter=0});var qo,CT=C(()=>{bM();qo=class extends Dh{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}}});function Lh(n){let e=1;do e*=2;while(en-t?t:e}function q3(n){return n--,n|=n>>1,n|=n>>2,n|=n>>4,n|=n>>8,n|=n>>16,n++,n}function yT(n){return n=n|n>>1,n=n|n>>2,n=n|n>>4,n=n|n>>8,n=n|n>>16,n-(n>>1)}function gn(n,e,t=2){let i;switch(t){case 1:i=yT(n);break;case 2:i=IM(n);break;default:i=q3(n);break}return Math.min(i,e)}var $a=C(()=>{});var Wu,MM=C(()=>{Wu=class{get underlyingResource(){return this._webGLTexture}constructor(e=null,t){if(this._MSAARenderBuffers=null,this._context=t,!e&&(e=t.createTexture(),!e))throw new Error("Unable to create webGL texture");this.set(e)}setUsage(){}set(e){this._webGLTexture=e}reset(){this._webGLTexture=null,this._MSAARenderBuffers=null}addMSAARenderBuffer(e){this._MSAARenderBuffers||(this._MSAARenderBuffers=[]),this._MSAARenderBuffers.push(e)}releaseMSAARenderBuffers(){if(this._MSAARenderBuffers){for(let e of this._MSAARenderBuffers)this._context.deleteRenderbuffer(e);this._MSAARenderBuffers=null}}getMSAARenderBuffer(e=0){var t,i;return(i=(t=this._MSAARenderBuffers)==null?void 0:t[e])!=null?i:null}release(){this.releaseMSAARenderBuffers(),this._webGLTexture&&this._context.deleteTexture(this._webGLTexture),this.reset()}}});function CM(n){return n===13||n===14||n===15||n===16||n===17||n===18||n===19}function Bl(n){return n===13||n===17||n===18||n===19}var O_=C(()=>{});var Z3={};tt(Z3,{ThinEngine:()=>Rt});var yM,Rt,Qn=C(()=>{yh();mM();wr();RM();yt();va();K3();j3();CT();$a();MM();Es();of();TM();O_();xM();yM=class{},Rt=class n extends Ie{get name(){return this._name}set name(e){this._name=e}get version(){return this._webGLVersion}static get ShadersRepository(){return tr.ShadersRepository}static set ShadersRepository(e){tr.ShadersRepository=e}get supportsUniformBuffers(){return this.webGLVersion>1&&!this.disableUniformBuffers}get needPOTTextures(){return this._webGLVersion<2||this.forcePOTTextures}get _supportsHardwareTextureRescaling(){return!1}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e}snapshotRenderingReset(){this.snapshotRendering=!1}constructor(e,t,i,r){if(i=i||{},super(t!=null?t:i.antialias,i,r),this._name="WebGL",this.forcePOTTextures=!1,this.validateShaderPrograms=!1,this.disableUniformBuffers=!1,this._webGLVersion=1,this._vertexAttribArraysEnabled=[],this._uintIndicesCurrentlySet=!1,this._currentBoundBuffer=new Array,this._currentFramebuffer=null,this._dummyFramebuffer=null,this._currentBufferPointers=new Array,this._currentInstanceLocations=new Array,this._currentInstanceBuffers=new Array,this._vaoRecordInProgress=!1,this._mustWipeVertexAttributes=!1,this._nextFreeTextureSlots=new Array,this._maxSimultaneousTextures=0,this._maxMSAASamplesOverride=null,this._unpackFlipYCached=null,this.enableUnpackFlipYCached=!0,this._boundUniforms={},!e)return;let s;if(e.getContext){if(s=e,i.preserveDrawingBuffer===void 0&&(i.preserveDrawingBuffer=!1),i.xrCompatible===void 0&&(i.xrCompatible=!1),navigator&&navigator.userAgent){this._setupMobileChecks();let l=navigator.userAgent;for(let c of n.ExceptionList){let f=c.key,h=c.targets;if(new RegExp(f).test(l)){if(c.capture&&c.captureConstraint){let u=c.capture,m=c.captureConstraint,_=new RegExp(u).exec(l);if(_&&_.length>0&&parseInt(_[_.length-1])>=m)continue}for(let u of h)switch(u){case"uniformBuffer":this.disableUniformBuffers=!0;break;case"vao":this.disableVertexArrayObjects=!0;break;case"antialias":i.antialias=!1;break;case"maxMSAASamples":this._maxMSAASamplesOverride=1;break}}}}if(this._doNotHandleContextLost?this._onContextLost=()=>{cT(this._gl)}:(this._onContextLost=l=>{l.preventDefault(),this._contextWasLost=!0,cT(this._gl),te.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost(()=>this._initGLContext())},s.addEventListener("webglcontextrestored",this._onContextRestored,!1),i.powerPreference=i.powerPreference||"high-performance"),s.addEventListener("webglcontextlost",this._onContextLost,!1),this._badDesktopOS&&(i.xrCompatible=!1),!i.disableWebGL2Support)try{this._gl=s.getContext("webgl2",i)||s.getContext("experimental-webgl2",i),this._gl&&(this._webGLVersion=2,this._shaderPlatformName="WEBGL2",this._gl.deleteQuery||(this._webGLVersion=1,this._shaderPlatformName="WEBGL1"))}catch(l){}if(!this._gl){if(!s)throw new Error("The provided canvas is null or undefined.");try{this._gl=s.getContext("webgl",i)||s.getContext("experimental-webgl",i)}catch(l){throw new Error("WebGL not supported",{cause:l})}}if(!this._gl)throw new Error("WebGL not supported")}else{this._gl=e,s=this._gl.canvas,this._gl.renderbufferStorageMultisample?(this._webGLVersion=2,this._shaderPlatformName="WEBGL2"):this._shaderPlatformName="WEBGL1";let l=this._gl.getContextAttributes();l&&(i.stencil=l.stencil)}this._sharedInit(s),this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),i.useHighPrecisionFloats!==void 0&&(this._highPrecisionShadersAllowed=i.useHighPrecisionFloats),this.resize(),this._initGLContext(),this._initFeatures();for(let l=0;l1?new MT:new IT;let a=`Babylon.js v${n.Version}`;te.Log(a+` - ${this.description}`),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",a);let o=Pn(this._gl);o.validateShaderPrograms=this.validateShaderPrograms,o.parallelShaderCompile=this._caps.parallelShaderCompile}_clearEmptyResources(){this._dummyFramebuffer=null,super._clearEmptyResources()}_getShaderProcessingContext(e){return null}areAllEffectsReady(){for(let e in this._compiledEffects)if(!this._compiledEffects[e].isReady())return!1;return!0}_initGLContext(){var i;this._caps={maxTexturesImageUnits:this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS),maxCombinedTexturesImageUnits:this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS),maxVertexTextureImageUnits:this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),maxTextureSize:this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),maxSamples:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_SAMPLES):1,maxCubemapTextureSize:this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE),maxRenderTextureSize:this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE),maxVertexAttribs:this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS),maxVaryingVectors:this._gl.getParameter(this._gl.MAX_VARYING_VECTORS),maxFragmentUniformVectors:this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS),maxVertexUniformVectors:this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS),shaderFloatPrecision:0,parallelShaderCompile:this._gl.getExtension("KHR_parallel_shader_compile")||void 0,standardDerivatives:this._webGLVersion>1||this._gl.getExtension("OES_standard_derivatives")!==null,maxAnisotropy:1,astc:this._gl.getExtension("WEBGL_compressed_texture_astc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_astc"),bptc:this._gl.getExtension("EXT_texture_compression_bptc")||this._gl.getExtension("WEBKIT_EXT_texture_compression_bptc"),s3tc:this._gl.getExtension("WEBGL_compressed_texture_s3tc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"),s3tc_srgb:this._gl.getExtension("WEBGL_compressed_texture_s3tc_srgb")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc_srgb"),pvrtc:this._gl.getExtension("WEBGL_compressed_texture_pvrtc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),etc1:this._gl.getExtension("WEBGL_compressed_texture_etc1")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc1"),etc2:this._gl.getExtension("WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBGL_compressed_texture_es3_0"),textureAnisotropicFilterExtension:this._gl.getExtension("EXT_texture_filter_anisotropic")||this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"),uintIndices:this._webGLVersion>1||this._gl.getExtension("OES_element_index_uint")!==null,fragmentDepthSupported:this._webGLVersion>1||this._gl.getExtension("EXT_frag_depth")!==null,highPrecisionShaderSupported:!1,timerQuery:this._gl.getExtension("EXT_disjoint_timer_query_webgl2")||this._gl.getExtension("EXT_disjoint_timer_query"),supportOcclusionQuery:this._webGLVersion>1,canUseTimestampForTimerQuery:!1,drawBuffersExtension:!1,maxMSAASamples:1,colorBufferFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_float")),blendFloat:this._gl.getExtension("EXT_float_blend")!==null,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,colorBufferHalfFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_half_float")),textureFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_float")),textureHalfFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_half_float")),textureHalfFloatRender:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloatLinearFiltering:!1,vertexArrayObject:!1,instancedArrays:!1,textureLOD:!!(this._webGLVersion>1||this._gl.getExtension("EXT_shader_texture_lod")),texelFetch:this._webGLVersion!==1,blendMinMax:!1,multiview:this._gl.getExtension("OVR_multiview2"),oculusMultiview:this._gl.getExtension("OCULUS_multiview"),depthTextureExtension:!1,canUseGLInstanceID:this._webGLVersion>1,canUseGLVertexID:this._webGLVersion>1,supportComputeShaders:!1,supportSRGBBuffers:!1,supportTransformFeedbacks:this._webGLVersion>1,textureMaxLevel:this._webGLVersion>1,texture2DArrayMaxLayerCount:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_ARRAY_TEXTURE_LAYERS):128,disableMorphTargetTexture:!1,textureNorm16:!!this._gl.getExtension("EXT_texture_norm16"),blendParametersPerTarget:!1,dualSourceBlending:!1,supportReadWriteStorageTextures:!1},this._caps.supportFloatTexturesResolve=this._caps.colorBufferFloat,this._caps.rg11b10ufColorRenderable=this._caps.colorBufferFloat,this._glVersion=this._gl.getParameter(this._gl.VERSION);let e=this._gl.getExtension("WEBGL_debug_renderer_info");e!=null&&(this._glRenderer=this._gl.getParameter(e.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(e.UNMASKED_VENDOR_WEBGL)),this._glVendor||(this._glVendor=this._gl.getParameter(this._gl.VENDOR)||"Unknown vendor"),this._glRenderer||(this._glRenderer=this._gl.getParameter(this._gl.RENDERER)||"Unknown renderer"),this._gl.HALF_FLOAT_OES!==36193&&(this._gl.HALF_FLOAT_OES=36193),this._gl.RGBA16F!==34842&&(this._gl.RGBA16F=34842),this._gl.RGBA32F!==34836&&(this._gl.RGBA32F=34836),this._gl.DEPTH24_STENCIL8!==35056&&(this._gl.DEPTH24_STENCIL8=35056),this._caps.timerQuery&&(this._webGLVersion===1&&(this._gl.getQuery=this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery)),this._caps.canUseTimestampForTimerQuery=((i=this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT))!=null?i:0)>0),this._caps.maxAnisotropy=this._caps.textureAnisotropicFilterExtension?this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0,this._caps.textureFloatLinearFiltering=!!(this._caps.textureFloat&&this._gl.getExtension("OES_texture_float_linear")),this._caps.textureFloatRender=!!(this._caps.textureFloat&&this._canRenderToFloatFramebuffer()),this._caps.textureHalfFloatLinearFiltering=!!(this._webGLVersion>1||this._caps.textureHalfFloat&&this._gl.getExtension("OES_texture_half_float_linear")),this._caps.textureNorm16&&(this._gl.R16_EXT=33322,this._gl.RG16_EXT=33324,this._gl.RGB16_EXT=32852,this._gl.RGBA16_EXT=32859,this._gl.R16_SNORM_EXT=36760,this._gl.RG16_SNORM_EXT=36761,this._gl.RGB16_SNORM_EXT=36762,this._gl.RGBA16_SNORM_EXT=36763);let t=this._gl.getExtension("OES_draw_buffers_indexed");if(this._caps.blendParametersPerTarget=!!t,this._alphaState=new ku(this._caps.blendParametersPerTarget),t&&(this._gl.blendEquationSeparateIndexed=t.blendEquationSeparateiOES.bind(t),this._gl.blendEquationIndexed=t.blendEquationiOES.bind(t),this._gl.blendFuncSeparateIndexed=t.blendFuncSeparateiOES.bind(t),this._gl.blendFuncIndexed=t.blendFunciOES.bind(t),this._gl.colorMaskIndexed=t.colorMaskiOES.bind(t),this._gl.disableIndexed=t.disableiOES.bind(t),this._gl.enableIndexed=t.enableiOES.bind(t)),this._caps.dualSourceBlending=!!this._gl.getExtension("WEBGL_blend_func_extended"),this._caps.astc&&(this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR),this._caps.bptc&&(this._gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT=this._caps.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT),this._caps.s3tc_srgb&&(this._gl.COMPRESSED_SRGB_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT),this._caps.etc2&&(this._gl.COMPRESSED_SRGB8_ETC2=this._caps.etc2.COMPRESSED_SRGB8_ETC2,this._gl.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=this._caps.etc2.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC),this._webGLVersion>1&&this._gl.HALF_FLOAT_OES!==5131&&(this._gl.HALF_FLOAT_OES=5131),this._caps.textureHalfFloatRender=this._caps.textureHalfFloat&&this._canRenderToHalfFloatFramebuffer(),this._webGLVersion>1)this._caps.drawBuffersExtension=!0,this._caps.maxMSAASamples=this._maxMSAASamplesOverride!==null?this._maxMSAASamplesOverride:this._gl.getParameter(this._gl.MAX_SAMPLES),this._caps.maxDrawBuffers=this._gl.getParameter(this._gl.MAX_DRAW_BUFFERS);else{let r=this._gl.getExtension("WEBGL_draw_buffers");if(r!==null){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=r.drawBuffersWEBGL.bind(r),this._caps.maxDrawBuffers=this._gl.getParameter(r.MAX_DRAW_BUFFERS_WEBGL),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(let s=0;s<16;s++)this._gl["COLOR_ATTACHMENT"+s+"_WEBGL"]=r["COLOR_ATTACHMENT"+s+"_WEBGL"]}}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{let r=this._gl.getExtension("WEBGL_depth_texture");r!=null&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=r.UNSIGNED_INT_24_8_WEBGL)}if(this.disableVertexArrayObjects)this._caps.vertexArrayObject=!1;else if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{let r=this._gl.getExtension("OES_vertex_array_object");r!=null&&(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=r.createVertexArrayOES.bind(r),this._gl.bindVertexArray=r.bindVertexArrayOES.bind(r),this._gl.deleteVertexArray=r.deleteVertexArrayOES.bind(r))}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{let r=this._gl.getExtension("ANGLE_instanced_arrays");r!=null?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=r.drawArraysInstancedANGLE.bind(r),this._gl.drawElementsInstanced=r.drawElementsInstancedANGLE.bind(r),this._gl.vertexAttribDivisor=r.vertexAttribDivisorANGLE.bind(r)):this._caps.instancedArrays=!1}if(this._gl.getShaderPrecisionFormat){let r=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.HIGH_FLOAT),s=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);if(r&&s&&(this._caps.highPrecisionShaderSupported=r.precision!==0&&s.precision!==0,this._caps.shaderFloatPrecision=Math.min(r.precision,s.precision)),!this._shouldUseHighPrecisionShader){let a=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.MEDIUM_FLOAT),o=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.MEDIUM_FLOAT);a&&o&&(this._caps.shaderFloatPrecision=Math.min(a.precision,o.precision))}this._caps.shaderFloatPrecision<10&&(this._caps.shaderFloatPrecision=10)}if(this._webGLVersion>1)this._caps.blendMinMax=!0;else{let r=this._gl.getExtension("EXT_blend_minmax");r!=null&&(this._caps.blendMinMax=!0,this._gl.MAX=r.MAX_EXT,this._gl.MIN=r.MIN_EXT)}if(!this._caps.supportSRGBBuffers){if(this._webGLVersion>1)this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:WebGL2RenderingContext.SRGB,SRGB8:WebGL2RenderingContext.SRGB8,SRGB8_ALPHA8:WebGL2RenderingContext.SRGB8_ALPHA8};else{let r=this._gl.getExtension("EXT_sRGB");r!=null&&(this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:r.SRGB_EXT,SRGB8:r.SRGB_ALPHA_EXT,SRGB8_ALPHA8:r.SRGB_ALPHA_EXT})}if(this._creationOptions){let r=this._creationOptions.forceSRGBBufferSupportState;r!==void 0&&(this._caps.supportSRGBBuffers=this._caps.supportSRGBBuffers&&r)}}this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=this._gl.LEQUAL,this._depthCullingState.depthMask=!0,this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(let r=0;r=65535)return new Uint32Array(e);return new Uint16Array(e)}return new Uint16Array(e)}bindArrayBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ARRAY_BUFFER)}bindUniformBlock(e,t,i){let r=e.program,s=this._gl.getUniformBlockIndex(r,t);this._gl.uniformBlockBinding(r,s,i)}bindIndexBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ELEMENT_ARRAY_BUFFER)}_bindBuffer(e,t){(this._vaoRecordInProgress||this._currentBoundBuffer[t]!==e)&&(this._gl.bindBuffer(t,e?e.underlyingResource:null),this._currentBoundBuffer[t]=e)}updateArrayBuffer(e){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)}_vertexAttribPointer(e,t,i,r,s,a,o){let l=this._currentBufferPointers[t];if(!l)return;let c=!1;l.active?(l.buffer!==e&&(l.buffer=e,c=!0),l.size!==i&&(l.size=i,c=!0),l.type!==r&&(l.type=r,c=!0),l.normalized!==s&&(l.normalized=s,c=!0),l.stride!==a&&(l.stride=a,c=!0),l.offset!==o&&(l.offset=o,c=!0)):(c=!0,l.active=!0,l.index=t,l.size=i,l.type=r,l.normalized=s,l.stride=a,l.offset=o,l.buffer=e),(c||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),r===this._gl.UNSIGNED_INT||r===this._gl.INT?this._gl.vertexAttribIPointer(t,i,r,a,o):this._gl.vertexAttribPointer(t,i,r,s,a,o))}_bindIndexBufferWithCache(e){e!=null&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)}_bindVertexBuffersAttributes(e,t,i){let r=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(let s=0;s=0){let o=r[s],l=null;if(i&&(l=i[o]),l||(l=e[o]),!l)continue;this._gl.enableVertexAttribArray(a),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[a]=!0);let c=l.getBuffer();c&&(this._vertexAttribPointer(c,a,l.getSize(),l.type,l.normalized,l.byteStride,l.byteOffset),l.getIsInstanced()&&(this._gl.vertexAttribDivisor(a,l.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(a),this._currentInstanceBuffers.push(c))))}}}recordVertexArrayObject(e,t,i,r){let s=this._gl.createVertexArray();if(!s)throw new Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(s),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i,r),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),s}bindVertexArrayObject(e,t){this._cachedVertexArrayObject!==e&&(this._cachedVertexArrayObject=e,this._gl.bindVertexArray(e),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._uintIndicesCurrentlySet=t!=null&&t.is32Bits,this._mustWipeVertexAttributes=!0)}bindBuffersDirectly(e,t,i,r,s){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==s){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=s;let a=s.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();let o=0;for(let l=0;l=0&&(this._gl.enableVertexAttribArray(c),this._vertexAttribArraysEnabled[c]=!0,this._vertexAttribPointer(e,c,i[l],this._gl.FLOAT,!1,r,o)),o+=i[l]*4}}this._bindIndexBufferWithCache(t)}_unbindVertexArrayObject(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))}bindBuffers(e,t,i,r){(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==i)&&(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i,this._bindVertexBuffersAttributes(e,i,r)),this._bindIndexBufferWithCache(t)}unbindInstanceAttributes(){let e;for(let t=0,i=this._currentInstanceLocations.length;t1||this.isWebGPU)),(o===1&&!this._caps.textureFloatLinearFiltering||o===2&&!this._caps.textureHalfFloatLinearFiltering)&&(l=1),o===1&&!this._caps.textureFloat&&(o=0,te.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));let _=CM(c),g=Bl(c),v=this._gl,x=new yi(this,r),A=e.width||e,S=e.height||e,E=e.depth||0,R=e.layers||0,I=this._getSamplingParameters(l,(s||a)&&!_),y=R!==0?v.TEXTURE_2D_ARRAY:E!==0?v.TEXTURE_3D:p?v.TEXTURE_CUBE_MAP:v.TEXTURE_2D,M=_?this._getInternalFormatFromDepthTextureFormat(c,!0,g):this._getRGBABufferInternalSizedFormat(o,c,f),D=_?g?v.DEPTH_STENCIL:v.DEPTH_COMPONENT:this._getInternalFormat(c),O=_?this._getWebGLTextureTypeFromDepthTextureFormat(c):this._getWebGLTextureType(o);if(this._bindTextureDirectly(y,x),R!==0)x.is2DArray=!0,v.texImage3D(y,0,M,A,S,R,0,D,O,null);else if(E!==0)x.is3D=!0,v.texImage3D(y,0,M,A,S,E,0,D,O,null);else if(p){x.isCube=!0;for(let N=0;N<6;N++)v.texImage2D(v.TEXTURE_CUBE_MAP_POSITIVE_X+N,0,M,A,S,0,D,O,null)}else v.texImage2D(y,0,M,A,S,0,D,O,null);if(v.texParameteri(y,v.TEXTURE_MAG_FILTER,I.mag),v.texParameteri(y,v.TEXTURE_MIN_FILTER,I.min),v.texParameteri(y,v.TEXTURE_WRAP_S,v.CLAMP_TO_EDGE),v.texParameteri(y,v.TEXTURE_WRAP_T,v.CLAMP_TO_EDGE),_&&this.webGLVersion>1&&(m===0?(v.texParameteri(y,v.TEXTURE_COMPARE_FUNC,515),v.texParameteri(y,v.TEXTURE_COMPARE_MODE,v.NONE)):(v.texParameteri(y,v.TEXTURE_COMPARE_FUNC,m),v.texParameteri(y,v.TEXTURE_COMPARE_MODE,v.COMPARE_REF_TO_TEXTURE))),(s||a)&&this._gl.generateMipmap(y),this._bindTextureDirectly(y,null),x._useSRGBBuffer=f,x.baseWidth=A,x.baseHeight=S,x.width=A,x.height=S,x.depth=R||E,x.isReady=!0,x.samples=h,x.generateMipMaps=s,x.samplingMode=l,x.type=o,x.format=c,x.label=d,x.comparisonFunction=m,this._internalTexturesCache.push(x),u){let N;if(CM(x.format)?N=this._setupFramebufferDepthAttachments(Bl(x.format),x.format!==19,x.width,x.height,h,x.format,!0):N=this._createRenderBuffer(x.width,x.height,h,-1,this._getRGBABufferInternalSizedFormat(x.type,x.format,x._useSRGBBuffer),-1),!N)throw new Error("Unable to create render buffer");x._autoMSAAManagement=!0;let F=x._hardwareTexture;F||(F=x._hardwareTexture=this._createHardwareTexture()),F.addMSAARenderBuffer(N)}return x}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||t)}createTexture(e,t,i,r,s=3,a=null,o=null,l=null,c=null,f=null,h=null,d,u,m,p){return this._createTextureBase(e,t,i,r,s,a,o,(..._)=>this._prepareWebGLTexture(..._,f),(_,g,v,x,A,S)=>{let E=this._gl,R=v.width===_&&v.height===g;A._creationFlags=m!=null?m:0;let I=this._getTexImageParametersForCreateTexture(A.format,A._useSRGBBuffer);if(R)return E.texImage2D(E.TEXTURE_2D,0,I.internalFormat,I.format,I.type,v),!1;let y=this._caps.maxTextureSize;if(v.width>y||v.height>y||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!this._workingCanvas||!this._workingContext||(this._workingCanvas.width=_,this._workingCanvas.height=g,this._workingContext.drawImage(v,0,0,v.width,v.height,0,0,_,g),E.texImage2D(E.TEXTURE_2D,0,I.internalFormat,I.format,I.type,this._workingCanvas),A.width=_,A.height=g),!1;{let M=new yi(this,2);this._bindTextureDirectly(E.TEXTURE_2D,M,!0),E.texImage2D(E.TEXTURE_2D,0,I.internalFormat,I.format,I.type,v),this._rescaleTexture(M,A,r,I.format,()=>{this._releaseTexture(M),this._bindTextureDirectly(E.TEXTURE_2D,A,!0),S()})}return!0},l,c,f,h,d,u,p)}_getTexImageParametersForCreateTexture(e,t){let i,r;return this.webGLVersion===1?(i=this._getInternalFormat(e,t),r=i):(i=this._getInternalFormat(e,!1),r=this._getRGBABufferInternalSizedFormat(0,e,t)),{internalFormat:r,format:i,type:this._gl.UNSIGNED_BYTE}}_rescaleTexture(e,t,i,r,s){}_unpackFlipY(e){this._unpackFlipYCached!==e&&(this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,e?1:0),this.enableUnpackFlipYCached&&(this._unpackFlipYCached=e))}_getUnpackAlignement(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)}_getTextureTarget(e){return e.isCube?this._gl.TEXTURE_CUBE_MAP:e.is3D?this._gl.TEXTURE_3D:e.is2DArray||e.isMultiview?this._gl.TEXTURE_2D_ARRAY:this._gl.TEXTURE_2D}updateTextureSamplingMode(e,t,i=!1){let r=this._getTextureTarget(t),s=this._getSamplingParameters(e,t.useMipMaps||i);this._setTextureParameterInteger(r,this._gl.TEXTURE_MAG_FILTER,s.mag,t),this._setTextureParameterInteger(r,this._gl.TEXTURE_MIN_FILTER,s.min),i&&s.hasMipMaps&&(t.generateMipMaps=!0,this._gl.generateMipmap(r)),this._bindTextureDirectly(r,null),t.samplingMode=e}updateTextureDimensions(e,t,i,r=1){}updateTextureWrappingMode(e,t,i=null,r=null){let s=this._getTextureTarget(e);t!==null&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),i!==null&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i),e),e._cachedWrapV=i),(e.is2DArray||e.is3D)&&r!==null&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(r),e),e._cachedWrapR=r),this._bindTextureDirectly(s,null)}_uploadCompressedDataToTextureDirectly(e,t,i,r,s,a=0,o=0){let l=this._gl,c=l.TEXTURE_2D;if(e.isCube&&(c=l.TEXTURE_CUBE_MAP_POSITIVE_X+a),e._useSRGBBuffer)switch(t){case 37492:case 36196:this._caps.etc2?t=l.COMPRESSED_SRGB8_ETC2:e._useSRGBBuffer=!1;break;case 37496:this._caps.etc2?t=l.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:e._useSRGBBuffer=!1;break;case 36492:t=l.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case 37808:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case 37809:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR;break;case 37810:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR;break;case 37811:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR;break;case 37812:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR;break;case 37813:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR;break;case 37814:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR;break;case 37815:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR;break;case 37816:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR;break;case 37817:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR;break;case 37818:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR;break;case 37819:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR;break;case 37820:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR;break;case 37821:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR;break;case 33776:this._caps.s3tc_srgb?t=l.COMPRESSED_SRGB_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33777:this._caps.s3tc_srgb?t=l.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33779:this._caps.s3tc_srgb?t=l.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:e._useSRGBBuffer=!1;break;default:e._useSRGBBuffer=!1;break}if(e.generateMipMaps){let f=e._hardwareTexture;f.memoryAllocated||(l.texStorage2D(e.isCube?l.TEXTURE_CUBE_MAP:l.TEXTURE_2D,Math.floor(Math.log2(Math.max(i,r)))+1,t,e.width,e.height),f.memoryAllocated=!0),this._gl.compressedTexSubImage2D(c,o,0,0,i,r,t,s)}else this._gl.compressedTexImage2D(c,o,t,i,r,0,s)}_uploadDataToTextureDirectly(e,t,i=0,r=0,s,a=!1){let o=this._gl,l=this._getWebGLTextureType(e.type),c=this._getInternalFormat(e.format),f=s===void 0?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(s,e._useSRGBBuffer);this._unpackFlipY(e.invertY);let h=o.TEXTURE_2D;e.isCube&&(h=o.TEXTURE_CUBE_MAP_POSITIVE_X+i);let d=Math.round(Math.log(e.width)*Math.LOG2E),u=Math.round(Math.log(e.height)*Math.LOG2E),m=a?e.width:Math.pow(2,Math.max(d-r,0)),p=a?e.height:Math.pow(2,Math.max(u-r,0));o.texImage2D(h,r,f,m,p,0,c,l,t)}updateTextureData(e,t,i,r,s,a,o=0,l=0,c=!1){let f=this._gl,h=this._getWebGLTextureType(e.type),d=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);let u=f.TEXTURE_2D,m=f.TEXTURE_2D;e.isCube&&(m=f.TEXTURE_CUBE_MAP_POSITIVE_X+o,u=f.TEXTURE_CUBE_MAP),this._bindTextureDirectly(u,e,!0),f.texSubImage2D(m,l,i,r,s,a,d,h,t),c&&this._gl.generateMipmap(m),this._bindTextureDirectly(u,null)}_uploadArrayBufferViewToTexture(e,t,i=0,r=0){let s=this._gl,a=e.isCube?s.TEXTURE_CUBE_MAP:s.TEXTURE_2D;this._bindTextureDirectly(a,e,!0),this._uploadDataToTextureDirectly(e,t,i,r),this._bindTextureDirectly(a,null,!0)}_prepareWebGLTextureContinuation(e,t,i,r,s){let a=this._gl;if(!a)return;let o=this._getSamplingParameters(s,!i);a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,o.mag),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,o.min),!i&&!r&&a.generateMipmap(a.TEXTURE_2D),this._bindTextureDirectly(a.TEXTURE_2D,null),t&&t.removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}_prepareWebGLTexture(e,t,i,r,s,a,o,l,c,f){let h=this.getCaps().maxTextureSize,d=Math.min(h,this.needPOTTextures?gn(r.width,h):r.width),u=Math.min(h,this.needPOTTextures?gn(r.height,h):r.height),m=this._gl;if(m){if(!e._hardwareTexture){i&&i.removePendingData(e);return}this._bindTextureDirectly(m.TEXTURE_2D,e,!0),this._unpackFlipY(s===void 0?!0:!!s),e.baseWidth=r.width,e.baseHeight=r.height,e.width=d,e.height=u,e.isReady=!0,e.type=e.type!==-1?e.type:0,e.format=e.format!==-1?e.format:f!=null?f:t===".jpg"&&!e._useSRGBBuffer?4:5,!l(d,u,r,t,e,()=>{this._prepareWebGLTextureContinuation(e,i,a,o,c)})&&this._prepareWebGLTextureContinuation(e,i,a,o,c)}}_getInternalFormatFromDepthTextureFormat(e,t,i){let r=this._gl;if(!t)return r.STENCIL_INDEX8;let a=i?r.DEPTH_STENCIL:r.DEPTH_COMPONENT;return this.webGLVersion>1?e===15?a=r.DEPTH_COMPONENT16:e===16?a=r.DEPTH_COMPONENT24:e===17||e===13?a=i?r.DEPTH24_STENCIL8:r.DEPTH_COMPONENT24:e===14?a=r.DEPTH_COMPONENT32F:e===18&&(a=i?r.DEPTH32F_STENCIL8:r.DEPTH_COMPONENT32F):a=r.DEPTH_COMPONENT16,a}_getWebGLTextureTypeFromDepthTextureFormat(e){let t=this._gl,i=t.UNSIGNED_INT;return e===15?i=t.UNSIGNED_SHORT:e===17||e===13?i=t.UNSIGNED_INT_24_8:e===14?i=t.FLOAT:e===18?i=t.FLOAT_32_UNSIGNED_INT_24_8_REV:e===19&&(i=t.UNSIGNED_BYTE),i}_setupFramebufferDepthAttachments(e,t,i,r,s=1,a,o=!1){let l=this._gl;a=a!=null?a:e?13:14;let c=this._getInternalFormatFromDepthTextureFormat(a,t,e);return e&&t?this._createRenderBuffer(i,r,s,l.DEPTH_STENCIL,c,o?-1:l.DEPTH_STENCIL_ATTACHMENT):t?this._createRenderBuffer(i,r,s,c,c,o?-1:l.DEPTH_ATTACHMENT):e?this._createRenderBuffer(i,r,s,c,c,o?-1:l.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,i,r,s,a,o=!0){let c=this._gl.createRenderbuffer();return this._updateRenderBuffer(c,e,t,i,r,s,a,o)}_updateRenderBuffer(e,t,i,r,s,a,o,l=!0){let c=this._gl;return c.bindRenderbuffer(c.RENDERBUFFER,e),r>1&&c.renderbufferStorageMultisample?c.renderbufferStorageMultisample(c.RENDERBUFFER,r,a,t,i):c.renderbufferStorage(c.RENDERBUFFER,s,t,i),o!==-1&&c.framebufferRenderbuffer(c.FRAMEBUFFER,o,c.RENDERBUFFER,e),l&&c.bindRenderbuffer(c.RENDERBUFFER,null),e}_releaseTexture(e){this._deleteTexture(e._hardwareTexture),this.unbindAllTextures();let t=this._internalTexturesCache.indexOf(e);t!==-1&&this._internalTexturesCache.splice(t,1),e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureLow&&e._lodTextureLow.dispose(),e._irradianceTexture&&e._irradianceTexture.dispose()}_deleteTexture(e){e==null||e.release()}_setProgram(e){this._currentProgram!==e&&(b3(e,this._gl),this._currentProgram=e)}bindSamplers(e){let t=e.getPipelineContext();this._setProgram(t.program);let i=e.getSamplers();for(let r=0;r-1;if(i&&a&&(this._activeChannel=t._associatedChannel),this._boundTexturesCache[this._activeChannel]!==t||r){if(this._activateCurrentTexture(),t&&t.isMultiview)throw te.Error(["_bindTextureDirectly called with a multiview texture!",e,t]),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(e,(c=(l=t==null?void 0:t._hardwareTexture)==null?void 0:l.underlyingResource)!=null?c:null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)}else i&&(s=!0,this._activateCurrentTexture());return a&&!i&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),s}_bindTexture(e,t,i){if(e===void 0)return;t&&(t._associatedChannel=e),this._activeChannel=e;let r=t?this._getTextureTarget(t):this._gl.TEXTURE_2D;this._bindTextureDirectly(r,t)}unbindAllTextures(){for(let e=0;e1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))}setTexture(e,t,i,r){e!==void 0&&(t&&(this._boundUniforms[e]=t),this._setTexture(e,i))}_bindSamplerUniformToChannel(e,t){let i=this._boundUniforms[e];!i||i._currentState===t||(this._gl.uniform1i(i,t),i._currentState=t)}_getTextureWrapMode(e){switch(e){case 1:return this._gl.REPEAT;case 0:return this._gl.CLAMP_TO_EDGE;case 2:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT}_setTexture(e,t,i=!1,r=!1,s=""){if(!t)return this._boundTexturesCache[e]!=null&&(this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))),!1;if(t.video){this._activeChannel=e;let c=t.getInternalTexture();c&&(c._associatedChannel=e),t.update()}else if(t.delayLoadState===4)return t.delayLoad(),!1;let a;r?a=t.depthStencilTexture:t.isReady()?a=t.getInternalTexture():t.isCube?a=this.emptyCubeTexture:t.is3D?a=this.emptyTexture3D:t.is2DArray?a=this.emptyTexture2DArray:a=this.emptyTexture,!i&&a&&(a._associatedChannel=e);let o=!0;this._boundTexturesCache[e]===a&&(i||this._bindSamplerUniformToChannel(a._associatedChannel,e),o=!1),this._activeChannel=e;let l=this._getTextureTarget(a);if(o&&this._bindTextureDirectly(l,a,i),a&&!a.isMultiview){if(a.isCube&&a._cachedCoordinatesMode!==t.coordinatesMode){a._cachedCoordinatesMode=t.coordinatesMode;let c=t.coordinatesMode!==3&&t.coordinatesMode!==5?1:0;t.wrapU=c,t.wrapV=c}a._cachedWrapU!==t.wrapU&&(a._cachedWrapU=t.wrapU,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),a)),a._cachedWrapV!==t.wrapV&&(a._cachedWrapV=t.wrapV,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),a)),a.is3D&&a._cachedWrapR!==t.wrapR&&(a._cachedWrapR=t.wrapR,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),a)),this._setAnisotropicLevel(l,a,t.anisotropicFilteringLevel)}return!0}setTextureArray(e,t,i,r){if(!(e===void 0||!t)){(!this._textureUnits||this._textureUnits.length!==i.length)&&(this._textureUnits=new Int32Array(i.length));for(let s=0;s=this._caps.maxVertexAttribs||!this._vertexAttribArraysEnabled[e]||this.disableAttributeByIndex(e)}releaseEffects(){this._compiledEffects={},this.onReleaseEffectsObservable.notifyObservers(this)}dispose(){var e;cr()&&this._renderingCanvas&&(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._onContextRestored&&this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored)),super.dispose(),this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.unbindAllAttributes(),this._boundUniforms={},this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers.length=0,this._currentProgram=null,this._creationOptions.loseContextOnDispose&&((e=this._gl.getExtension("WEBGL_lose_context"))==null||e.loseContext()),cT(this._gl)}attachContextLostEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextlost",e,!1)}attachContextRestoredEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextrestored",e,!1)}getError(){return this._gl.getError()}_canRenderToFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(1)}_canRenderToHalfFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(2)}_canRenderToFramebuffer(e){let t=this._gl;for(;t.getError()!==t.NO_ERROR;);let i=!0,r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r),t.texImage2D(t.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(e),1,1,0,t.RGBA,this._getWebGLTextureType(e),null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST);let s=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,s),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,0);let a=t.checkFramebufferStatus(t.FRAMEBUFFER);if(i=i&&a===t.FRAMEBUFFER_COMPLETE,i=i&&t.getError()===t.NO_ERROR,i&&(t.clear(t.COLOR_BUFFER_BIT),i=i&&t.getError()===t.NO_ERROR),i){t.bindFramebuffer(t.FRAMEBUFFER,null);let o=t.RGBA,l=t.UNSIGNED_BYTE,c=new Uint8Array(4);t.readPixels(0,0,1,1,o,l,c),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(r),t.deleteFramebuffer(s),t.bindFramebuffer(t.FRAMEBUFFER,null);!i&&t.getError()!==t.NO_ERROR;);return i}_getWebGLTextureType(e){if(this._webGLVersion===1){switch(e){case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT_OES;case 0:return this._gl.UNSIGNED_BYTE;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5}return this._gl.UNSIGNED_BYTE}switch(e){case 3:return this._gl.BYTE;case 0:return this._gl.UNSIGNED_BYTE;case 4:return this._gl.SHORT;case 5:return this._gl.UNSIGNED_SHORT;case 6:return this._gl.INT;case 7:return this._gl.UNSIGNED_INT;case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5;case 11:return this._gl.UNSIGNED_INT_2_10_10_10_REV;case 12:return this._gl.UNSIGNED_INT_24_8;case 13:return this._gl.UNSIGNED_INT_10F_11F_11F_REV;case 14:return this._gl.UNSIGNED_INT_5_9_9_9_REV;case 15:return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV}return this._gl.UNSIGNED_BYTE}_getInternalFormat(e,t=!1){let i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA;switch(e){case 0:i=this._gl.ALPHA;break;case 1:i=this._gl.LUMINANCE;break;case 2:i=this._gl.LUMINANCE_ALPHA;break;case 6:case 33322:case 36760:i=this._gl.RED;break;case 7:case 33324:case 36761:i=this._gl.RG;break;case 4:case 32852:case 36762:i=t?this._glSRGBExtensionValues.SRGB:this._gl.RGB;break;case 5:case 32859:case 36763:i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA;break}if(this._webGLVersion>1)switch(e){case 8:i=this._gl.RED_INTEGER;break;case 9:i=this._gl.RG_INTEGER;break;case 10:i=this._gl.RGB_INTEGER;break;case 11:i=this._gl.RGBA_INTEGER;break}return i}_getRGBABufferInternalSizedFormat(e,t,i=!1){if(this._webGLVersion===1){if(t!==void 0)switch(t){case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;case 4:return i?this._glSRGBExtensionValues.SRGB:this._gl.RGB}return this._gl.RGBA}switch(e){case 3:switch(t){case 6:return this._gl.R8_SNORM;case 7:return this._gl.RG8_SNORM;case 4:return this._gl.RGB8_SNORM;case 8:return this._gl.R8I;case 9:return this._gl.RG8I;case 10:return this._gl.RGB8I;case 11:return this._gl.RGBA8I;default:return this._gl.RGBA8_SNORM}case 0:switch(t){case 6:return this._gl.R8;case 7:return this._gl.RG8;case 4:return i?this._glSRGBExtensionValues.SRGB8:this._gl.RGB8;case 5:return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8;case 8:return this._gl.R8UI;case 9:return this._gl.RG8UI;case 10:return this._gl.RGB8UI;case 11:return this._gl.RGBA8UI;case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;default:return this._gl.RGBA8}case 4:switch(t){case 8:return this._gl.R16I;case 36760:return this._gl.R16_SNORM_EXT;case 36761:return this._gl.RG16_SNORM_EXT;case 36762:return this._gl.RGB16_SNORM_EXT;case 36763:return this._gl.RGBA16_SNORM_EXT;case 9:return this._gl.RG16I;case 10:return this._gl.RGB16I;case 11:return this._gl.RGBA16I;default:return this._gl.RGBA16I}case 5:switch(t){case 8:return this._gl.R16UI;case 33322:return this._gl.R16_EXT;case 33324:return this._gl.RG16_EXT;case 32852:return this._gl.RGB16_EXT;case 32859:return this._gl.RGBA16_EXT;case 9:return this._gl.RG16UI;case 10:return this._gl.RGB16UI;case 11:return this._gl.RGBA16UI;default:return this._gl.RGBA16UI}case 6:switch(t){case 8:return this._gl.R32I;case 9:return this._gl.RG32I;case 10:return this._gl.RGB32I;case 11:return this._gl.RGBA32I;default:return this._gl.RGBA32I}case 7:switch(t){case 8:return this._gl.R32UI;case 9:return this._gl.RG32UI;case 10:return this._gl.RGB32UI;case 11:return this._gl.RGBA32UI;default:return this._gl.RGBA32UI}case 1:switch(t){case 6:return this._gl.R32F;case 7:return this._gl.RG32F;case 4:return this._gl.RGB32F;case 5:return this._gl.RGBA32F;default:return this._gl.RGBA32F}case 2:switch(t){case 6:return this._gl.R16F;case 7:return this._gl.RG16F;case 4:return this._gl.RGB16F;case 5:return this._gl.RGBA16F;default:return this._gl.RGBA16F}case 10:return this._gl.RGB565;case 13:return this._gl.R11F_G11F_B10F;case 14:return this._gl.RGB9_E5;case 8:return this._gl.RGBA4;case 9:return this._gl.RGB5_A1;case 11:switch(t){case 5:return this._gl.RGB10_A2;case 11:return this._gl.RGB10_A2UI;default:return this._gl.RGB10_A2}}return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8}readPixels(e,t,i,r,s=!0,a=!0,o=null){let l=s?4:3,c=s?this._gl.RGBA:this._gl.RGB,f=i*r*l;if(!o)o=new Uint8Array(f);else if(o.length{Fl();PT=class{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new PM(e)}sampleFrame(e=mr.Now){if(this._enabled){if(this._lastFrameTimeMs!=null){let t=e-this._lastFrameTimeMs;this._rollingFrameTime.add(t)}this._lastFrameTimeMs=e}}get averageFrameTime(){return this._rollingFrameTime.average}get averageFrameTimeVariance(){return this._rollingFrameTime.variance}get instantaneousFrameTime(){return this._rollingFrameTime.history(0)}get averageFPS(){return 1e3/this._rollingFrameTime.average}get instantaneousFPS(){let e=this._rollingFrameTime.history(0);return e===0?0:1e3/e}get isSaturated(){return this._rollingFrameTime.isSaturated()}enable(){this._enabled=!0}disable(){this._enabled=!1,this._lastFrameTimeMs=null}get isEnabled(){return this._enabled}reset(){this._lastFrameTimeMs=null,this._rollingFrameTime.reset()}},PM=class{constructor(e){this._samples=new Array(e),this.reset()}add(e){let t;if(this.isSaturated()){let i=this._samples[this._pos];t=i-this.average,this.average-=t/(this._sampleCount-1),this._m2-=t*(i-this.average)}else this._sampleCount++;t=e-this.average,this.average+=t/this._sampleCount,this._m2+=t*(e-this.average),this.variance=this._m2/(this._sampleCount-1),this._samples[this._pos]=e,this._pos++,this._pos%=this._samples.length}history(e){if(e>=this._sampleCount||e>=this._samples.length)return 0;let t=this._wrapPosition(this._pos-1);return this._samples[this._wrapPosition(t-e)]}isSaturated(){return this._sampleCount>=this._samples.length}reset(){this.average=0,this.variance=0,this._sampleCount=0,this._pos=0,this._m2=0}_wrapPosition(e){let t=this._samples.length;return(e%t+t)%t}}});var $3=C(()=>{Qn();Rt.prototype.setAlphaMode=function(n,e=!1,t=0){if(this._alphaMode[t]===n){if(!e){let r=n===0;this.depthCullingState.depthMask!==r&&(this.depthCullingState.depthMask=r)}return}let i=n===0;this._alphaState.setAlphaBlend(!i,t),this._alphaState.setAlphaMode(n,t),e||(this.depthCullingState.depthMask=i),this._alphaMode[t]=n}});function J3(n,e,t,i){let r,s=1;i===1?r=new Float32Array(e*t*4):i===2?(r=new Uint16Array(e*t*4),s=15360):i===7?r=new Uint32Array(e*t*4):r=new Uint8Array(e*t*4);for(let a=0;a{Es();yt();Qn();$a();Rt.prototype.updateRawTexture=function(n,e,t,i,r=null,s=0,a=!1){if(!n)return;let o=this._getRGBABufferInternalSizedFormat(s,t,a),l=this._getInternalFormat(t),c=this._getWebGLTextureType(s);this._bindTextureDirectly(this._gl.TEXTURE_2D,n,!0),this._unpackFlipY(i===void 0?!0:!!i),this._doNotHandleContextLost||(n._bufferView=e,n.format=t,n.type=s,n.invertY=i,n._compression=r),n.width%4!==0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),r&&e?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[r],n.width,n.height,0,e):this._gl.texImage2D(this._gl.TEXTURE_2D,0,o,n.width,n.height,0,l,c,e),n.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),n.isReady=!0};Rt.prototype.createRawTexture=function(n,e,t,i,r,s,a,o=null,l=0,c=0,f=!1){let h=new yi(this,3);h.baseWidth=e,h.baseHeight=t,h.width=e,h.height=t,h.format=i,h.generateMipMaps=r,h.samplingMode=a,h.invertY=s,h._compression=o,h.type=l,h._useSRGBBuffer=this._getUseSRGBBuffer(f,!r),this._doNotHandleContextLost||(h._bufferView=n),this.updateRawTexture(h,n,i,s,o,l,h._useSRGBBuffer),this._bindTextureDirectly(this._gl.TEXTURE_2D,h,!0);let d=this._getSamplingParameters(a,r);return this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,d.mag),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,d.min),r&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._internalTexturesCache.push(h),h};Rt.prototype.createRawCubeTexture=function(n,e,t,i,r,s,a,o=null){let l=this._gl,c=new yi(this,8);c.isCube=!0,c.format=t,c.type=i,this._doNotHandleContextLost||(c._bufferViewArray=n);let f=this._getWebGLTextureType(i),h=this._getInternalFormat(t);h===l.RGB&&(h=l.RGBA),f===l.FLOAT&&!this._caps.textureFloatLinearFiltering?(r=!1,a=1,te.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):f===this._gl.HALF_FLOAT_OES&&!this._caps.textureHalfFloatLinearFiltering?(r=!1,a=1,te.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):f===l.FLOAT&&!this._caps.textureFloatRender?(r=!1,te.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):f===l.HALF_FLOAT&&!this._caps.colorBufferFloat&&(r=!1,te.Warn("Render to half float textures is not supported. Mipmap generation forced to false."));let d=e,u=d;if(c.width=d,c.height=u,c.invertY=s,c._compression=o,!this.needPOTTextures||Lh(c.width)&&Lh(c.height)||(r=!1),n)this.updateRawCubeTexture(c,n,t,i,s,o);else{let _=this._getRGBABufferInternalSizedFormat(i),g=0;this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,c,!0);for(let v=0;v<6;v++)o?l.compressedTexImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+v,g,this.getCaps().s3tc[o],c.width,c.height,0,void 0):l.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+v,g,_,c.width,c.height,0,h,f,null);this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)}this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,c,!0),n&&r&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);let p=this._getSamplingParameters(a,r);return l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MAG_FILTER,p.mag),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MIN_FILTER,p.min),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_S,l.CLAMP_TO_EDGE),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_T,l.CLAMP_TO_EDGE),this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,null),c.generateMipMaps=r,c.samplingMode=a,c.isReady=!0,c};Rt.prototype.updateRawCubeTexture=function(n,e,t,i,r,s=null,a=0){n._bufferViewArray=e,n.format=t,n.type=i,n.invertY=r,n._compression=s;let o=this._gl,l=this._getWebGLTextureType(i),c=this._getInternalFormat(t),f=this._getRGBABufferInternalSizedFormat(i),h=!1;c===o.RGB&&(c=o.RGBA,h=!0),this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,n,!0),this._unpackFlipY(r===void 0?!0:!!r),n.width%4!==0&&o.pixelStorei(o.UNPACK_ALIGNMENT,1);for(let u=0;u<6;u++){let m=e[u];s?o.compressedTexImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+u,a,this.getCaps().s3tc[s],n.width,n.height,0,m):(h&&(m=J3(m,n.width,n.height,i)),o.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+u,a,f,n.width,n.height,0,c,l,m))}(!this.needPOTTextures||Lh(n.width)&&Lh(n.height))&&n.generateMipMaps&&a===0&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),n.isReady=!0};Rt.prototype.createRawCubeTextureFromUrl=function(n,e,t,i,r,s,a,o,l=null,c=null,f=3,h=!1){let d=this._gl,u=this.createRawCubeTexture(null,t,i,r,!s,h,f,null);e==null||e.addPendingData(u),u.url=n,u.isReady=!1,this._internalTexturesCache.push(u);let m=(_,g)=>{e==null||e.removePendingData(u),c&&c(_?_.status+" "+_.statusText:"Failed to parse texture data",g)},p=async _=>{if(!u._hardwareTexture)return;let g=a(_);if(!g)return;let v=g instanceof Promise?await g:g,x=u.width;if(o){let A=this._getWebGLTextureType(r),S=this._getInternalFormat(i),E=this._getRGBABufferInternalSizedFormat(r),R=!1;S===d.RGB&&(S=d.RGBA,R=!0),this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,u,!0),this._unpackFlipY(!1);let I=o(v);for(let y=0;y>y;for(let D=0;D<6;D++){let O=I[y][D];R&&(O=J3(O,M,M,r)),d.texImage2D(D,y,E,M,M,0,S,A,O)}}this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(u,v,i,r,h);u.isReady=!0,e==null||e.removePendingData(u),u.onLoadedObservable.notifyObservers(u),u.onLoadedObservable.clear(),l&&l()};return this._loadFile(n,_=>{p(_).catch(g=>{m(void 0,g)})},void 0,e==null?void 0:e.offlineProvider,!0,m),u};Rt.prototype.createRawTexture2DArray=e2(!1);Rt.prototype.createRawTexture3D=e2(!0);Rt.prototype.updateRawTexture2DArray=t2(!1);Rt.prototype.updateRawTexture3D=t2(!0)});var r2=C(()=>{Qn();of();Rt.prototype._readTexturePixelsSync=function(n,e,t,i=-1,r=0,s=null,a=!0,o=!1,l=0,c=0){var d,u,m;let f=this._gl;if(!f)throw new Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){let p=f.createFramebuffer();if(!p)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=p}f.bindFramebuffer(f.FRAMEBUFFER,this._dummyFramebuffer),i>-1&&(n.is2DArray||n.is3D)?f.framebufferTextureLayer(f.FRAMEBUFFER,f.COLOR_ATTACHMENT0,(d=n._hardwareTexture)==null?void 0:d.underlyingResource,r,i):i>-1?f.framebufferTexture2D(f.FRAMEBUFFER,f.COLOR_ATTACHMENT0,f.TEXTURE_CUBE_MAP_POSITIVE_X+i,(u=n._hardwareTexture)==null?void 0:u.underlyingResource,r):f.framebufferTexture2D(f.FRAMEBUFFER,f.COLOR_ATTACHMENT0,f.TEXTURE_2D,(m=n._hardwareTexture)==null?void 0:m.underlyingResource,r);let h=n.type!==void 0?this._getWebGLTextureType(n.type):f.UNSIGNED_BYTE;return o?s||(s=S3(n.type,4*e*t)):h===f.UNSIGNED_BYTE?(s||(s=new Uint8Array(4*e*t)),h=f.UNSIGNED_BYTE):(s||(s=new Float32Array(4*e*t)),h=f.FLOAT),a&&this.flushFramebuffer(),f.readPixels(l,c,e,t,f.RGBA,h,s),f.bindFramebuffer(f.FRAMEBUFFER,this._currentFramebuffer),s};Rt.prototype._readTexturePixels=function(n,e,t,i=-1,r=0,s=null,a=!0,o=!1,l=0,c=0){return Promise.resolve(this._readTexturePixelsSync(n,e,t,i,r,s,a,o,l,c))}});var n2=C(()=>{Qn();Rt.prototype.updateDynamicIndexBuffer=function(n,e,t=0){this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(n);let i;n.is32Bits?i=e instanceof Uint32Array?e:new Uint32Array(e):i=e instanceof Uint16Array?e:new Uint16Array(e),this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,i,this._gl.DYNAMIC_DRAW),this._resetIndexBufferBinding()};Rt.prototype.updateDynamicVertexBuffer=function(n,e,t,i){this.bindArrayBuffer(n),t===void 0&&(t=0);let r=e.byteLength||e.length;i===void 0||i>=r&&t===0?e instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,t,new Float32Array(e)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,t,e):e instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,t,new Float32Array(e).subarray(0,i/4)):(ArrayBuffer.isView(e)?e=new Uint8Array(e.buffer,e.byteOffset,i):e=new Uint8Array(e,0,i),this._gl.bufferSubData(this._gl.ARRAY_BUFFER,t,e)),this._resetVertexBufferBinding()}});var s2=C(()=>{Qn();Es();yt();$a();Rt.prototype._createDepthStencilCubeTexture=function(n,e){let t=new yi(this,12);if(t.isCube=!0,this.webGLVersion===1)return te.Error("Depth cube texture is not supported by WebGL 1."),t;let i={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...e},r=this._gl;this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,t,!0),this._setupDepthStencilTexture(t,n,i.bilinearFiltering,i.comparisonFunction);for(let s=0;s<6;s++)i.generateStencil?r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+s,0,r.DEPTH24_STENCIL8,n,n,0,r.DEPTH_STENCIL,r.UNSIGNED_INT_24_8,null):r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+s,0,r.DEPTH_COMPONENT24,n,n,0,r.DEPTH_COMPONENT,r.UNSIGNED_INT,null);return this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),this._internalTexturesCache.push(t),t};Rt.prototype._setCubeMapTextureParams=function(n,e,t){let i=this._gl;i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_MAG_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_MIN_FILTER,e?i.LINEAR_MIPMAP_LINEAR:i.LINEAR),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),n.samplingMode=e?3:2,e&&this.getCaps().textureMaxLevel&&t!==void 0&&t>0&&(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_MAX_LEVEL,t),n._maxLodLevel=t),this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,null)};Rt.prototype.createCubeTexture=function(n,e,t,i,r=null,s=null,a,o=null,l=!1,c=0,f=0,h=null,d,u=!1,m=null){let p=this._gl;return this.createCubeTextureBase(n,e,t,!!i,r,s,a,o,l,c,f,h,_=>this._bindTextureDirectly(p.TEXTURE_CUBE_MAP,_,!0),(_,g)=>{let v=this.needPOTTextures?gn(g[0].width,this._caps.maxCubemapTextureSize):g[0].width,x=v,A=[p.TEXTURE_CUBE_MAP_POSITIVE_X,p.TEXTURE_CUBE_MAP_POSITIVE_Y,p.TEXTURE_CUBE_MAP_POSITIVE_Z,p.TEXTURE_CUBE_MAP_NEGATIVE_X,p.TEXTURE_CUBE_MAP_NEGATIVE_Y,p.TEXTURE_CUBE_MAP_NEGATIVE_Z];this._bindTextureDirectly(p.TEXTURE_CUBE_MAP,_,!0),this._unpackFlipY(!1);let S=a?this._getInternalFormat(a,_._useSRGBBuffer):_._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:p.RGBA,E=a?this._getInternalFormat(a):p.RGBA;_._useSRGBBuffer&&this.webGLVersion===1&&(E=S);for(let R=0;R{O_();DT=class{get depthStencilTexture(){return this._depthStencilTexture}setDepthStencilTexture(e,t=!0){t&&this._depthStencilTexture&&this._depthStencilTexture.dispose(),this._depthStencilTexture=e,this._generateDepthBuffer=this._generateStencilBuffer=this._depthStencilTextureWithStencil=!1,e&&(this._generateDepthBuffer=!0,this._generateStencilBuffer=this._depthStencilTextureWithStencil=Bl(e.format))}get depthStencilTextureWithStencil(){return this._depthStencilTextureWithStencil}get isCube(){return this._isCube}get isMulti(){return this._isMulti}get is2DArray(){return this.layers>0}get is3D(){return this.depth>0}get size(){return this.width}get width(){var e;return(e=this._size.width)!=null?e:this._size}get height(){var e;return(e=this._size.height)!=null?e:this._size}get layers(){return this._size.layers||0}get depth(){return this._size.depth||0}get texture(){var e,t;return(t=(e=this._textures)==null?void 0:e[0])!=null?t:null}get textures(){return this._textures}get faceIndices(){return this._faceIndices}get layerIndices(){return this._layerIndices}getBaseArrayLayer(e){var s,a,o,l;if(!this._textures)return-1;let t=this._textures[e],i=(a=(s=this._layerIndices)==null?void 0:s[e])!=null?a:0,r=(l=(o=this._faceIndices)==null?void 0:o[e])!=null?l:0;return t.isCube?i*6+r:t.is3D?0:i}get samples(){return this._samples}setSamples(e,t=!0,i=!1){if(this.samples===e&&!i)return e;let r=this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,e,t):this._engine.updateRenderTargetTextureSampleCount(this,e);return this._samples=e,r}resolveMSAATextures(){this.isMulti?this._engine.resolveMultiFramebuffer(this):this._engine.resolveFramebuffer(this)}generateMipMaps(){this._engine._currentRenderTarget===this&&(this.isMulti?this._engine.unBindMultiColorAttachmentFramebuffer(this,!0):this._engine.unBindFramebuffer(this,!0)),this.isMulti?this._engine.generateMipMapsMultiFramebuffer(this):this._engine.generateMipMapsFramebuffer(this)}constructor(e,t,i,r,s){this._textures=null,this._faceIndices=null,this._layerIndices=null,this._samples=1,this._attachments=null,this._generateStencilBuffer=!1,this._generateDepthBuffer=!1,this._depthStencilTextureWithStencil=!1,this.disableAutomaticMSAAResolve=!1,this.resolveMSAAColors=!0,this.resolveMSAADepth=!1,this.resolveMSAAStencil=!1,this.depthReadOnly=!1,this.stencilReadOnly=!1,this._isMulti=e,this._isCube=t,this._size=i,this._engine=r,this._depthStencilTexture=null,this.label=s}setTextures(e){Array.isArray(e)?this._textures=e:e?this._textures=[e]:this._textures=null}setTexture(e,t=0,i=!0){this._textures||(this._textures=[]),this._textures[t]!==e&&(this._textures[t]&&i&&this._textures[t].dispose(),this._textures[t]=e)}setLayerAndFaceIndices(e,t){this._layerIndices=e,this._faceIndices=t}setLayerAndFaceIndex(e=0,t,i){this._layerIndices||(this._layerIndices=[]),this._faceIndices||(this._faceIndices=[]),t!==void 0&&t>=0&&(this._layerIndices[e]=t),i!==void 0&&i>=0&&(this._faceIndices[e]=i)}createDepthStencilTexture(e=0,t=!0,i=!1,r=1,s=14,a){var o;return(o=this._depthStencilTexture)==null||o.dispose(),this._depthStencilTextureWithStencil=i,this._depthStencilTextureLabel=a,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:i,isCube:this._isCube,samples:r,depthTextureFormat:s,label:a},this),this._depthStencilTexture}_shareDepth(e){this.shareDepth(e)}shareDepth(e){this._depthStencilTexture&&(e._depthStencilTexture&&e._depthStencilTexture.dispose(),e._depthStencilTexture=this._depthStencilTexture,e._depthStencilTextureWithStencil=this._depthStencilTextureWithStencil,this._depthStencilTexture.incrementReferences())}_swapAndDie(e){this.texture&&this.texture._swapAndDie(e),this._textures=null,this.dispose(!0)}_cloneRenderTargetWrapper(){var t,i,r,s,a,o,l,c;let e=null;if(this._isMulti){let f=this.textures;if(f&&f.length>0){let h=!1,d=f.length,u=-1,m=f[f.length-1]._source;(m===14||m===12)&&(h=!0,u=f[f.length-1].format,d--);let p=[],_=[],g=[],v=[],x=[],A=[],S=[],E={};for(let y=0;y1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}}releaseTextures(){if(this._textures)for(let e=0;e{a2();O_();LT=class extends DT{setDepthStencilTexture(e,t=!0){if(super.setDepthStencilTexture(e,t),!e)return;let i=this._engine,r=this._context,s=e._hardwareTexture;if(s&&e._autoMSAAManagement&&this._MSAAFramebuffer){let a=i._currentFramebuffer;i._bindUnboundFramebuffer(this._MSAAFramebuffer),r.framebufferRenderbuffer(r.FRAMEBUFFER,Bl(e.format)?r.DEPTH_STENCIL_ATTACHMENT:r.DEPTH_ATTACHMENT,r.RENDERBUFFER,s.getMSAARenderBuffer()),i._bindUnboundFramebuffer(a)}}constructor(e,t,i,r,s){super(e,t,i,r),this._framebuffer=null,this._depthStencilBuffer=null,this._MSAAFramebuffer=null,this._colorTextureArray=null,this._depthStencilTextureArray=null,this._disposeOnlyFramebuffers=!1,this._currentLOD=0,this._context=s}_cloneRenderTargetWrapper(){let e;return this._colorTextureArray&&this._depthStencilTextureArray?(e=this._engine.createMultiviewRenderTargetTexture(this.width,this.height),e.texture.isReady=!0):e=super._cloneRenderTargetWrapper(),e}_swapRenderTargetWrapper(e){super._swapRenderTargetWrapper(e),e._framebuffer=this._framebuffer,e._depthStencilBuffer=this._depthStencilBuffer,e._MSAAFramebuffer=this._MSAAFramebuffer,e._colorTextureArray=this._colorTextureArray,e._depthStencilTextureArray=this._depthStencilTextureArray,this._framebuffer=this._depthStencilBuffer=this._MSAAFramebuffer=this._colorTextureArray=this._depthStencilTextureArray=null}createDepthStencilTexture(e=0,t=!0,i=!1,r=1,s=14,a){if(this._depthStencilBuffer){let o=this._engine,l=o._currentFramebuffer,c=this._context;o._bindUnboundFramebuffer(this._framebuffer),c.framebufferRenderbuffer(c.FRAMEBUFFER,c.DEPTH_STENCIL_ATTACHMENT,c.RENDERBUFFER,null),c.framebufferRenderbuffer(c.FRAMEBUFFER,c.DEPTH_ATTACHMENT,c.RENDERBUFFER,null),c.framebufferRenderbuffer(c.FRAMEBUFFER,c.STENCIL_ATTACHMENT,c.RENDERBUFFER,null),o._bindUnboundFramebuffer(l),c.deleteRenderbuffer(this._depthStencilBuffer),this._depthStencilBuffer=null}return super.createDepthStencilTexture(e,t,i,r,s,a)}shareDepth(e){super.shareDepth(e);let t=this._context,i=this._depthStencilBuffer,r=e._MSAAFramebuffer||e._framebuffer,s=this._engine;e._depthStencilBuffer&&e._depthStencilBuffer!==i&&t.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=i;let a=e._generateStencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;s._bindUnboundFramebuffer(r),t.framebufferRenderbuffer(t.FRAMEBUFFER,a,t.RENDERBUFFER,i),s._bindUnboundFramebuffer(null)}_bindTextureRenderTarget(e,t=0,i,r=0){var f,h,d,u;let s=e._hardwareTexture;if(!s)return;let a=this._framebuffer,o=this._engine,l=o._currentFramebuffer;o._bindUnboundFramebuffer(a);let c;if(o.webGLVersion>1){let m=this._context;c=m["COLOR_ATTACHMENT"+t],e.is2DArray||e.is3D?(i=(h=i!=null?i:(f=this.layerIndices)==null?void 0:f[t])!=null?h:0,m.framebufferTextureLayer(m.FRAMEBUFFER,c,s.underlyingResource,r,i)):e.isCube?(i=(u=i!=null?i:(d=this.faceIndices)==null?void 0:d[t])!=null?u:0,m.framebufferTexture2D(m.FRAMEBUFFER,c,m.TEXTURE_CUBE_MAP_POSITIVE_X+i,s.underlyingResource,r)):m.framebufferTexture2D(m.FRAMEBUFFER,c,m.TEXTURE_2D,s.underlyingResource,r)}else{let m=this._context;c=m["COLOR_ATTACHMENT"+t+"_WEBGL"];let p=i!==void 0?m.TEXTURE_CUBE_MAP_POSITIVE_X+i:m.TEXTURE_2D;m.framebufferTexture2D(m.FRAMEBUFFER,c,p,s.underlyingResource,r)}if(e._autoMSAAManagement&&this._MSAAFramebuffer){let m=this._context;o._bindUnboundFramebuffer(this._MSAAFramebuffer),m.framebufferRenderbuffer(m.FRAMEBUFFER,c,m.RENDERBUFFER,s.getMSAARenderBuffer())}o._bindUnboundFramebuffer(l)}setTexture(e,t=0,i=!0){super.setTexture(e,t,i),this._bindTextureRenderTarget(e,t)}setLayerAndFaceIndices(e,t){var r,s;if(super.setLayerAndFaceIndices(e,t),!this.textures||!this.layerIndices||!this.faceIndices)return;let i=(s=(r=this._attachments)==null?void 0:r.length)!=null?s:this.textures.length;for(let a=0;a{wr();Ie.prototype.createDepthStencilTexture=function(n,e,t){if(e.isCube){let i=n.width||n;return this._createDepthStencilCubeTexture(i,e)}else return this._createDepthStencilTexture(n,e,t)}});var l2=C(()=>{Es();yt();Qn();o2();O_();DM();Rt.prototype._createHardwareRenderTargetWrapper=function(n,e,t){let i=new LT(n,e,t,this,this._gl);return this._renderTargetWrapperCache.push(i),i};Rt.prototype.createRenderTargetTexture=function(n,e){var p,_;let t=this._createHardwareRenderTargetWrapper(!1,!1,n),i=!0,r=!1,s=!1,a,o=1,l;e!==void 0&&typeof e=="object"&&(i=(p=e.generateDepthBuffer)!=null?p:!0,r=!!e.generateStencilBuffer,s=!!e.noColorAttachment,a=e.colorAttachment,o=(_=e.samples)!=null?_:1,l=e.label);let c=a||(s?null:this._createInternalTexture(n,e,!0,5)),f=n.width||n,h=n.height||n,d=this._currentFramebuffer,u=this._gl,m=u.createFramebuffer();if(this._bindUnboundFramebuffer(m),t._depthStencilBuffer=this._setupFramebufferDepthAttachments(r,i,f,h),c&&!c.is2DArray&&!c.is3D&&u.framebufferTexture2D(u.FRAMEBUFFER,u.COLOR_ATTACHMENT0,u.TEXTURE_2D,c._hardwareTexture.underlyingResource,0),this._bindUnboundFramebuffer(d),t.label=l!=null?l:"RenderTargetWrapper",t._framebuffer=m,t._generateDepthBuffer=i,t._generateStencilBuffer=r,t.setTextures(c),!a)this.updateRenderTargetTextureSampleCount(t,o);else if(t._samples=a.samples,a.samples>1){let g=a._hardwareTexture.getMSAARenderBuffer(0);t._MSAAFramebuffer=u.createFramebuffer(),this._bindUnboundFramebuffer(t._MSAAFramebuffer),u.framebufferRenderbuffer(u.FRAMEBUFFER,u.COLOR_ATTACHMENT0,u.RENDERBUFFER,g),this._bindUnboundFramebuffer(null)}return t};Rt.prototype._createDepthStencilTexture=function(n,e,t){var u;let i=this._gl,r=n.layers||0,s=n.depth||0,a=i.TEXTURE_2D;r!==0?a=i.TEXTURE_2D_ARRAY:s!==0&&(a=i.TEXTURE_3D);let o=new yi(this,12);if(o.label=e.label,!this._caps.depthTextureExtension)return te.Error("Depth texture is not supported by your browser or hardware."),o;let l={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...e};if(this._bindTextureDirectly(a,o,!0),this._setupDepthStencilTexture(o,n,l.comparisonFunction===0?!1:l.bilinearFiltering,l.comparisonFunction,l.samples),l.depthTextureFormat!==void 0){if(l.depthTextureFormat!==15&&l.depthTextureFormat!==16&&l.depthTextureFormat!==17&&l.depthTextureFormat!==13&&l.depthTextureFormat!==14&&l.depthTextureFormat!==18)return te.Error(`Depth texture ${l.depthTextureFormat} format is not supported.`),o;o.format=l.depthTextureFormat}else o.format=l.generateStencil?13:16;let c=Bl(o.format),f=this._getWebGLTextureTypeFromDepthTextureFormat(o.format),h=c?i.DEPTH_STENCIL:i.DEPTH_COMPONENT,d=this._getInternalFormatFromDepthTextureFormat(o.format,!0,c);return o.is2DArray?i.texImage3D(a,0,d,o.width,o.height,r,0,h,f,null):o.is3D?i.texImage3D(a,0,d,o.width,o.height,s,0,h,f,null):i.texImage2D(a,0,d,o.width,o.height,0,h,f,null),this._bindTextureDirectly(a,null),this._internalTexturesCache.push(o),t._depthStencilBuffer&&(i.deleteRenderbuffer(t._depthStencilBuffer),t._depthStencilBuffer=null),this._bindUnboundFramebuffer((u=t._MSAAFramebuffer)!=null?u:t._framebuffer),t._generateStencilBuffer=c,t._depthStencilTextureWithStencil=c,t._depthStencilBuffer=this._setupFramebufferDepthAttachments(t._generateStencilBuffer,t._generateDepthBuffer,t.width,t.height,t.samples,o.format),this._bindUnboundFramebuffer(null),o};Rt.prototype.updateRenderTargetTextureSampleCount=function(n,e){var s,a;if(this.webGLVersion<2||!n)return 1;if(n.samples===e)return e;let t=this._gl;e=Math.min(e,this.getCaps().maxMSAASamples),n._depthStencilBuffer&&(t.deleteRenderbuffer(n._depthStencilBuffer),n._depthStencilBuffer=null),n._MSAAFramebuffer&&(t.deleteFramebuffer(n._MSAAFramebuffer),n._MSAAFramebuffer=null);let i=(s=n.texture)==null?void 0:s._hardwareTexture;if(i==null||i.releaseMSAARenderBuffers(),n.texture&&e>1&&typeof t.renderbufferStorageMultisample=="function"){let o=t.createFramebuffer();if(!o)throw new Error("Unable to create multi sampled framebuffer");n._MSAAFramebuffer=o,this._bindUnboundFramebuffer(n._MSAAFramebuffer);let l=this._createRenderBuffer(n.texture.width,n.texture.height,e,-1,this._getRGBABufferInternalSizedFormat(n.texture.type,n.texture.format,n.texture._useSRGBBuffer),t.COLOR_ATTACHMENT0,!1);if(!l)throw new Error("Unable to create multi sampled framebuffer");i==null||i.addMSAARenderBuffer(l)}this._bindUnboundFramebuffer((a=n._MSAAFramebuffer)!=null?a:n._framebuffer),n.texture&&(n.texture.samples=e),n._samples=e;let r=n._depthStencilTexture?n._depthStencilTexture.format:void 0;return n._depthStencilBuffer=this._setupFramebufferDepthAttachments(n._generateStencilBuffer,n._generateDepthBuffer,n.width,n.height,e,r),this._bindUnboundFramebuffer(null),e};Rt.prototype._setupDepthStencilTexture=function(n,e,t,i,r=1){var d,u;let s=(d=e.width)!=null?d:e,a=(u=e.height)!=null?u:e,o=e.layers||0,l=e.depth||0;n.baseWidth=s,n.baseHeight=a,n.width=s,n.height=a,n.is2DArray=o>0,n.depth=o||l,n.isReady=!0,n.samples=r,n.generateMipMaps=!1,n.samplingMode=t?2:1,n.type=0,n._comparisonFunction=i;let c=this._gl,f=this._getTextureTarget(n),h=this._getSamplingParameters(n.samplingMode,!1);c.texParameteri(f,c.TEXTURE_MAG_FILTER,h.mag),c.texParameteri(f,c.TEXTURE_MIN_FILTER,h.min),c.texParameteri(f,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(f,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE),this.webGLVersion>1&&(i===0?(c.texParameteri(f,c.TEXTURE_COMPARE_FUNC,515),c.texParameteri(f,c.TEXTURE_COMPARE_MODE,c.NONE)):(c.texParameteri(f,c.TEXTURE_COMPARE_FUNC,i),c.texParameteri(f,c.TEXTURE_COMPARE_MODE,c.COMPARE_REF_TO_TEXTURE)))}});var c2=C(()=>{Qn();Rt.prototype.setDepthStencilTexture=function(n,e,t,i){n!==void 0&&(e&&(this._boundUniforms[n]=e),!t||!t.depthStencilTexture?this._setTexture(n,null,void 0,void 0,i):this._setTexture(n,t,!1,!0,i))}});var f2=C(()=>{Es();yt();Qn();Rt.prototype.createRenderTargetCubeTexture=function(n,e){let t=this._createHardwareRenderTargetWrapper(!1,!0,n),i={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,...e};i.generateStencilBuffer=i.generateDepthBuffer&&i.generateStencilBuffer,(i.type===1&&!this._caps.textureFloatLinearFiltering||i.type===2&&!this._caps.textureHalfFloatLinearFiltering)&&(i.samplingMode=1);let r=this._gl,s=new yi(this,5);this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,s,!0);let a=this._getSamplingParameters(i.samplingMode,i.generateMipMaps);i.type===1&&!this._caps.textureFloat&&(i.type=0,te.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAG_FILTER,a.mag),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MIN_FILTER,a.min),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE);for(let l=0;l<6;l++)r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+l,0,this._getRGBABufferInternalSizedFormat(i.type,i.format),n,n,0,this._getInternalFormat(i.format),this._getWebGLTextureType(i.type),null);let o=r.createFramebuffer();return this._bindUnboundFramebuffer(o),t._depthStencilBuffer=this._setupFramebufferDepthAttachments(i.generateStencilBuffer,i.generateDepthBuffer,n,n),i.generateMipMaps&&r.generateMipmap(r.TEXTURE_CUBE_MAP),this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),t._framebuffer=o,t._generateDepthBuffer=i.generateDepthBuffer,t._generateStencilBuffer=i.generateStencilBuffer,s.width=n,s.height=n,s.isReady=!0,s.isCube=!0,s.samples=1,s.generateMipMaps=i.generateMipMaps,s.samplingMode=i.samplingMode,s.type=i.type,s.format=i.format,this._internalTexturesCache.push(s),t.setTextures(s),t}});var h2,Hu,pr,Ot,Dn=C(()=>{h2=.45454545454545453,Hu=2.2,pr=(1+Math.sqrt(5))/2,Ot=.001});function dn(n,e){let t=[];for(let i=0;i{let s=r.previous;if(!s)return;let a=r.next;a?(s.next=a,a.previous=s):(s.next=void 0,n[e]=s),r.next=void 0,r.previous=void 0}}function OT(n,e){let t=Rre.map(i=>xre(n,i,e));return()=>{for(let i of t)i==null||i()}}var Rre,Zo=C(()=>{Rre=["push","splice","pop","shift","unshift"]});function wt(n,e){d2[n]=e}function vn(n){return d2[n]}var d2,Hi=C(()=>{d2={}});function Si(n,e,t=1401298e-51){return Math.abs(n-e)<=t}function ir(n,e){return n===e?n:Math.random()*(e-n)+n}function Ja(n,e,t){return n+(e-n)*t}function u2(n,e,t,i,r){let s=r*r,a=r*s,o=2*a-3*s+1,l=-2*a+3*s,c=a-2*s+r,f=a-s;return n*o+t*l+e*c+i*f}function Nt(n,e=0,t=1){return Math.min(t,Math.max(e,n))}function m2(n){return n-=Math.PI*2*Math.floor((n+Math.PI)/(Math.PI*2)),n}function eo(n){let e=n.toString(16);return n<=15?("0"+e).toUpperCase():e.toUpperCase()}function p2(n){if(Math.log2)return Math.floor(Math.log2(n));if(n<0)return NaN;if(n===0)return-1/0;let e=0;if(n<1){for(;n<1;)e++,n=n*2;e=-e}else if(n>1)for(;n>1;)e++,n=Math.floor(n/2);return e}function NT(n,e){let t=n%e;return t===0?e:NT(e,t)}var Ln=C(()=>{});function _2(n){n.updateFlag=zu._UpdateFlagSeed++}function LM(n,e,t,i=0){let r=n.asArray(),s=e.asArray(),a=r[0],o=r[1],l=r[2],c=r[3],f=r[4],h=r[5],d=r[6],u=r[7],m=r[8],p=r[9],_=r[10],g=r[11],v=r[12],x=r[13],A=r[14],S=r[15],E=s[0],R=s[1],I=s[2],y=s[3],M=s[4],D=s[5],O=s[6],V=s[7],N=s[8],F=s[9],U=s[10],k=s[11],ee=s[12],q=s[13],Q=s[14],Y=s[15];t[i]=a*E+o*M+l*N+c*ee,t[i+1]=a*R+o*D+l*F+c*q,t[i+2]=a*I+o*O+l*U+c*Q,t[i+3]=a*y+o*V+l*k+c*Y,t[i+4]=f*E+h*M+d*N+u*ee,t[i+5]=f*R+h*D+d*F+u*q,t[i+6]=f*I+h*O+d*U+u*Q,t[i+7]=f*y+h*V+d*k+u*Y,t[i+8]=m*E+p*M+_*N+g*ee,t[i+9]=m*R+p*D+_*F+g*q,t[i+10]=m*I+p*O+_*U+g*Q,t[i+11]=m*y+p*V+_*k+g*Y,t[i+12]=v*E+x*M+A*N+S*ee,t[i+13]=v*R+x*D+A*F+S*q,t[i+14]=v*I+x*O+A*U+S*Q,t[i+15]=v*y+x*V+A*k+S*Y}function Oh(n,e,t,i=0){LM(n,e,t.asArray(),i),_2(t)}function g2(n,e,t=0){let i=n.asArray();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]}function N_(n,e){let t=OM(n,e.asArray());return t&&_2(e),t}function OM(n,e){let t=n.asArray(),i=t[0],r=t[1],s=t[2],a=t[3],o=t[4],l=t[5],c=t[6],f=t[7],h=t[8],d=t[9],u=t[10],m=t[11],p=t[12],_=t[13],g=t[14],v=t[15],x=u*v-g*m,A=d*v-_*m,S=d*g-_*u,E=h*v-p*m,R=h*g-u*p,I=h*_-p*d,y=+(l*x-c*A+f*S),M=-(o*x-c*E+f*R),D=+(o*A-l*E+f*I),O=-(o*S-l*R+c*I),V=i*y+r*M+s*D+a*O;if(V===0)return!1;let N=1/V,F=c*v-g*f,U=l*v-_*f,k=l*g-_*c,ee=o*v-p*f,q=o*g-p*c,Q=o*_-p*l,Y=c*m-u*f,K=l*m-d*f,de=l*u-d*c,Re=o*m-h*f,Fe=o*u-h*c,se=o*d-h*l,ue=-(r*x-s*A+a*S),re=+(i*x-s*E+a*R),he=-(i*A-r*E+a*I),De=+(i*S-r*R+s*I),fe=+(r*F-s*U+a*k),be=-(i*F-s*ee+a*q),Xe=+(i*U-r*ee+a*Q),Et=-(i*k-r*q+s*Q),Ke=-(r*Y-s*K+a*de),qe=+(i*Y-s*Re+a*Fe),Qt=-(i*K-r*Re+a*se),Dt=+(i*de-r*Fe+s*se);return e[0]=y*N,e[1]=ue*N,e[2]=fe*N,e[3]=Ke*N,e[4]=M*N,e[5]=re*N,e[6]=be*N,e[7]=qe*N,e[8]=D*N,e[9]=he*N,e[10]=Xe*N,e[11]=Qt*N,e[12]=O*N,e[13]=De*N,e[14]=Et*N,e[15]=Dt*N,!0}var zu,NM=C(()=>{zu=class{};zu._UpdateFlagSeed=0});var $n,we,b,Ri,Ye,j,ze,$,Nh,Ve=C(()=>{Dn();Zo();Hi();AM();Pi();Ln();NM();$n=n=>parseInt(n.toString().replace(/\W/g,"")),we=class n{constructor(e=0,t=0){this.x=e,this.y=t}toString(){return`{X: ${this.x} Y: ${this.y}}`}getClassName(){return"Vector2"}getHashCode(){let e=$n(this.x),t=$n(this.y),i=e;return i=i*397^t,i}toArray(e,t=0){return e[t]=this.x,e[t+1]=this.y,this}fromArray(e,t=0){return n.FromArrayToRef(e,t,this),this}asArray(){return[this.x,this.y]}copyFrom(e){return this.x=e.x,this.y=e.y,this}copyFromFloats(e,t){return this.x=e,this.y=t,this}set(e,t){return this.copyFromFloats(e,t)}setAll(e){return this.copyFromFloats(e,e)}add(e){return new n(this.x+e.x,this.y+e.y)}addToRef(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,t}addInPlace(e){return this.x+=e.x,this.y+=e.y,this}addInPlaceFromFloats(e,t){return this.x+=e,this.y+=t,this}addVector3(e){return new n(this.x+e.x,this.y+e.y)}subtract(e){return new n(this.x-e.x,this.y-e.y)}subtractToRef(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,t}subtractInPlace(e){return this.x-=e.x,this.y-=e.y,this}multiplyInPlace(e){return this.x*=e.x,this.y*=e.y,this}multiply(e){return new n(this.x*e.x,this.y*e.y)}multiplyToRef(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,t}multiplyByFloats(e,t){return new n(this.x*e,this.y*t)}divide(e){return new n(this.x/e.x,this.y/e.y)}divideToRef(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t}divideInPlace(e){return this.x=this.x/e.x,this.y=this.y/e.y,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e.x,e.y)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e.x,e.y)}minimizeInPlaceFromFloats(e,t){return this.x=Math.min(e,this.x),this.y=Math.min(t,this.y),this}maximizeInPlaceFromFloats(e,t){return this.x=Math.max(e,this.x),this.y=Math.max(t,this.y),this}subtractFromFloats(e,t){return new n(this.x-e,this.y-t)}subtractFromFloatsToRef(e,t,i){return i.x=this.x-e,i.y=this.y-t,i}negate(){return new n(-this.x,-this.y)}negateInPlace(){return this.x*=-1,this.y*=-1,this}negateToRef(e){return e.x=-this.x,e.y=-this.y,e}scaleInPlace(e){return this.x*=e,this.y*=e,this}scale(e){return new n(this.x*e,this.y*e)}scaleToRef(e,t){return t.x=this.x*e,t.y=this.y*e,t}scaleAndAddToRef(e,t){return t.x+=this.x*e,t.y+=this.y*e,t}equals(e){return e&&this.x===e.x&&this.y===e.y}equalsWithEpsilon(e,t=Ot){return e&&Si(this.x,e.x,t)&&Si(this.y,e.y,t)}equalsToFloats(e,t){return this.x===e&&this.y===t}floor(){return new n(Math.floor(this.x),Math.floor(this.y))}floorToRef(e){return e.x=Math.floor(this.x),e.y=Math.floor(this.y),e}fract(){return new n(this.x-Math.floor(this.x),this.y-Math.floor(this.y))}fractToRef(e){return e.x=this.x-Math.floor(this.x),e.y=this.y-Math.floor(this.y),e}rotate(e){return this.rotateToRef(e,new n)}rotateToRef(e,t){let i=Math.cos(e),r=Math.sin(e);return t.x=i*this.x-r*this.y,t.y=r*this.x+i*this.y,t}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}lengthSquared(){return this.x*this.x+this.y*this.y}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){let e=new n;return this.normalizeToRef(e),e}normalizeToRef(e){let t=this.length();return t===0&&(e.x=this.x,e.y=this.y),this.scaleToRef(1/t,e)}clone(){return new n(this.x,this.y)}dot(e){return this.x*e.x+this.y*e.y}static Zero(){return new n(0,0)}static One(){return new n(1,1)}static Random(e=0,t=1){return new n(ir(e,t),ir(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(ir(e,t),ir(e,t))}static get ZeroReadOnly(){return n._ZeroReadOnly}static FromArray(e,t=0){return new n(e[t],e[t+1])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i}static FromFloatsToRef(e,t,i){return i.copyFromFloats(e,t),i}static CatmullRom(e,t,i,r,s){let a=s*s,o=s*a,l=.5*(2*t.x+(-e.x+i.x)*s+(2*e.x-5*t.x+4*i.x-r.x)*a+(-e.x+3*t.x-3*i.x+r.x)*o),c=.5*(2*t.y+(-e.y+i.y)*s+(2*e.y-5*t.y+4*i.y-r.y)*a+(-e.y+3*t.y-3*i.y+r.y)*o);return new n(l,c)}static ClampToRef(e,t,i,r){return r.x=Nt(e.x,t.x,i.x),r.y=Nt(e.y,t.y,i.y),r}static Clamp(e,t,i){let r=Nt(e.x,t.x,i.x),s=Nt(e.y,t.y,i.y);return new n(r,s)}static Hermite(e,t,i,r,s){let a=s*s,o=s*a,l=2*o-3*a+1,c=-2*o+3*a,f=o-2*a+s,h=o-a,d=e.x*l+i.x*c+t.x*f+r.x*h,u=e.y*l+i.y*c+t.y*f+r.y*h;return new n(d,u)}static Hermite1stDerivative(e,t,i,r,s){return this.Hermite1stDerivativeToRef(e,t,i,r,s,new n)}static Hermite1stDerivativeToRef(e,t,i,r,s,a){let o=s*s;return a.x=(o-s)*6*e.x+(3*o-4*s+1)*t.x+(-o+s)*6*i.x+(3*o-2*s)*r.x,a.y=(o-s)*6*e.y+(3*o-4*s+1)*t.y+(-o+s)*6*i.y+(3*o-2*s)*r.y,a}static Lerp(e,t,i){return n.LerpToRef(e,t,i,new n)}static LerpToRef(e,t,i,r){return r.x=e.x+(t.x-e.x)*i,r.y=e.y+(t.y-e.y)*i,r}static Dot(e,t){return e.x*t.x+e.y*t.y}static Normalize(e){return n.NormalizeToRef(e,new n)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){let i=e.xt.x?e.x:t.x,r=e.y>t.y?e.y:t.y;return new n(i,r)}static Transform(e,t){return n.TransformToRef(e,t,new n)}static TransformToRef(e,t,i){let r=t.m,s=e.x*r[0]+e.y*r[4]+r[12],a=e.x*r[1]+e.y*r[5]+r[13];return i.x=s,i.y=a,i}static PointInTriangle(e,t,i,r){let s=.5*(-i.y*r.x+t.y*(-i.x+r.x)+t.x*(i.y-r.y)+i.x*r.y),a=s<0?-1:1,o=(t.y*r.x-t.x*r.y+(r.y-t.y)*e.x+(t.x-r.x)*e.y)*a,l=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*a;return o>0&&l>0&&o+l<2*s*a}static Distance(e,t){return Math.sqrt(n.DistanceSquared(e,t))}static DistanceSquared(e,t){let i=e.x-t.x,r=e.y-t.y;return i*i+r*r}static Center(e,t){return n.CenterToRef(e,t,new n)}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2)}static DistanceOfPointFromSegment(e,t,i){let r=n.DistanceSquared(t,i);if(r===0)return n.Distance(e,t);let s=i.subtract(t),a=Math.max(0,Math.min(1,n.Dot(e.subtract(t),s)/r)),o=t.add(s.multiplyByFloats(a,a));return n.Distance(e,o)}};we._V8PerformanceHack=new we(.5,.5);we._ZeroReadOnly=we.Zero();Object.defineProperties(we.prototype,{dimension:{value:[2]},rank:{value:1}});b=class n{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}constructor(e=0,t=0,i=0){this._isDirty=!0,this._x=e,this._y=t,this._z=i}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z}}`}getClassName(){return"Vector3"}getHashCode(){let e=$n(this._x),t=$n(this._y),i=$n(this._z),r=e;return r=r*397^t,r=r*397^i,r}asArray(){return[this._x,this._y,this._z]}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,this}fromArray(e,t=0){return n.FromArrayToRef(e,t,this),this}toQuaternion(){return Ye.RotationYawPitchRoll(this._y,this._x,this._z)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._isDirty=!0,this}addInPlaceFromFloats(e,t,i){return this._x+=e,this._y+=t,this._z+=i,this._isDirty=!0,this}add(e){return new n(this._x+e._x,this._y+e._y,this._z+e._z)}addToRef(e,t){return t._x=this._x+e._x,t._y=this._y+e._y,t._z=this._z+e._z,t._isDirty=!0,t}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._isDirty=!0,this}subtract(e){return new n(this._x-e._x,this._y-e._y,this._z-e._z)}subtractToRef(e,t){return this.subtractFromFloatsToRef(e._x,e._y,e._z,t)}subtractFromFloats(e,t,i){return new n(this._x-e,this._y-t,this._z-i)}subtractFromFloatsToRef(e,t,i,r){return r._x=this._x-e,r._y=this._y-t,r._z=this._z-i,r._isDirty=!0,r}negate(){return new n(-this._x,-this._y,-this._z)}negateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}negateToRef(e){return e._x=this._x*-1,e._y=this._y*-1,e._z=this._z*-1,e._isDirty=!0,e}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._isDirty=!0,this}scale(e){return new n(this._x*e,this._y*e,this._z*e)}scaleToRef(e,t){return t._x=this._x*e,t._y=this._y*e,t._z=this._z*e,t._isDirty=!0,t}getNormalToRef(e){let t=this.length(),i=Math.acos(this._y/t),r=Math.atan2(this._z,this._x);i>Math.PI/2?i-=Math.PI/2:i+=Math.PI/2;let s=t*Math.sin(i)*Math.cos(r),a=t*Math.cos(i),o=t*Math.sin(i)*Math.sin(r);return e.set(s,a,o),e}applyRotationQuaternionToRef(e,t){let i=this._x,r=this._y,s=this._z,a=e._x,o=e._y,l=e._z,c=e._w,f=2*(o*s-l*r),h=2*(l*i-a*s),d=2*(a*r-o*i);return t._x=i+c*f+o*d-l*h,t._y=r+c*h+l*f-a*d,t._z=s+c*d+a*h-o*f,t._isDirty=!0,t}applyRotationQuaternionInPlace(e){return this.applyRotationQuaternionToRef(e,this)}applyRotationQuaternion(e){return this.applyRotationQuaternionToRef(e,new n)}scaleAndAddToRef(e,t){return t._x+=this._x*e,t._y+=this._y*e,t._z+=this._z*e,t._isDirty=!0,t}projectOnPlane(e,t){return this.projectOnPlaneToRef(e,t,new n)}projectOnPlaneToRef(e,t,i){let r=e.normal,s=e.d,a=ze.Vector3[0];this.subtractToRef(t,a),a.normalize();let o=n.Dot(a,r);if(Math.abs(o)<1e-10)i.setAll(1/0);else{let l=-(n.Dot(t,r)+s)/o,c=a.scaleInPlace(l);t.addToRef(c,i)}return i}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z}equalsWithEpsilon(e,t=Ot){return e&&Si(this._x,e._x,t)&&Si(this._y,e._y,t)&&Si(this._z,e._z,t)}equalsToFloats(e,t,i){return this._x===e&&this._y===t&&this._z===i}multiplyInPlace(e){return this._x*=e._x,this._y*=e._y,this._z*=e._z,this._isDirty=!0,this}multiply(e){return this.multiplyByFloats(e._x,e._y,e._z)}multiplyToRef(e,t){return t._x=this._x*e._x,t._y=this._y*e._y,t._z=this._z*e._z,t._isDirty=!0,t}multiplyByFloats(e,t,i){return new n(this._x*e,this._y*t,this._z*i)}divide(e){return new n(this._x/e._x,this._y/e._y,this._z/e._z)}divideToRef(e,t){return t._x=this._x/e._x,t._y=this._y/e._y,t._z=this._z/e._z,t._isDirty=!0,t}divideInPlace(e){return this._x=this._x/e._x,this._y=this._y/e._y,this._z=this._z/e._z,this._isDirty=!0,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e._x,e._y,e._z)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e._x,e._y,e._z)}minimizeInPlaceFromFloats(e,t,i){return ethis._x&&(this.x=e),t>this._y&&(this.y=t),i>this._z&&(this.z=i),this}isNonUniformWithinEpsilon(e){let t=Math.abs(this._x),i=Math.abs(this._y);if(!Si(t,i,e))return!0;let r=Math.abs(this._z);return!Si(t,r,e)||!Si(i,r,e)}get isNonUniform(){let e=Math.abs(this._x),t=Math.abs(this._y);if(e!==t)return!0;let i=Math.abs(this._z);return e!==i}floorToRef(e){return e._x=Math.floor(this._x),e._y=Math.floor(this._y),e._z=Math.floor(this._z),e._isDirty=!0,e}floor(){return new n(Math.floor(this._x),Math.floor(this._y),Math.floor(this._z))}fractToRef(e){return e._x=this._x-Math.floor(this._x),e._y=this._y-Math.floor(this._y),e._z=this._z-Math.floor(this._z),e._isDirty=!0,e}fract(){return new n(this._x-Math.floor(this._x),this._y-Math.floor(this._y),this._z-Math.floor(this._z))}length(){return Math.sqrt(this.lengthSquared())}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z}get hasAZeroComponent(){return this._x*this._y*this._z===0}normalize(){return this.normalizeFromLength(this.length())}reorderInPlace(e){if(e=e.toLowerCase(),e==="xyz")return this;let t=ze.Vector3[0].copyFrom(this);return this.x=t[e[0]],this.y=t[e[1]],this.z=t[e[2]],this}rotateByQuaternionToRef(e,t){return e.toRotationMatrix(ze.Matrix[0]),n.TransformCoordinatesToRef(this,ze.Matrix[0],t),t}rotateByQuaternionAroundPointToRef(e,t,i){return this.subtractToRef(t,ze.Vector3[0]),ze.Vector3[0].rotateByQuaternionToRef(e,ze.Vector3[0]),t.addToRef(ze.Vector3[0],i),i}cross(e){return n.CrossToRef(this,e,new n)}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new n)}normalizeToRef(e){let t=this.length();return t===0||t===1?(e._x=this._x,e._y=this._y,e._z=this._z,e._isDirty=!0,e):this.scaleToRef(1/t,e)}clone(){return new n(this._x,this._y,this._z)}copyFrom(e){return this.copyFromFloats(e._x,e._y,e._z)}copyFromFloats(e,t,i){return this._x=e,this._y=t,this._z=i,this._isDirty=!0,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this._x=this._y=this._z=e,this._isDirty=!0,this}static GetClipFactor(e,t,i,r){let s=n.Dot(e,i),a=n.Dot(t,i);return(s-r)/(s-a)}static GetAngleBetweenVectors(e,t,i){let r=e.normalizeToRef(ze.Vector3[1]),s=t.normalizeToRef(ze.Vector3[2]),a=n.Dot(r,s);a=Nt(a,-1,1);let o=Math.acos(a),l=ze.Vector3[3];return n.CrossToRef(r,s,l),n.Dot(l,i)>0?isNaN(o)?0:o:isNaN(o)?-Math.PI:-Math.acos(a)}static GetAngleBetweenVectorsOnPlane(e,t,i){ze.Vector3[0].copyFrom(e);let r=ze.Vector3[0];ze.Vector3[1].copyFrom(t);let s=ze.Vector3[1];ze.Vector3[2].copyFrom(i);let a=ze.Vector3[2],o=ze.Vector3[3],l=ze.Vector3[4];r.normalize(),s.normalize(),a.normalize(),n.CrossToRef(a,r,o),n.CrossToRef(o,a,l);let c=Math.atan2(n.Dot(s,o),n.Dot(s,l));return m2(c)}static PitchYawRollToMoveBetweenPointsToRef(e,t,i){let r=$.Vector3[0];return t.subtractToRef(e,r),i._y=Math.atan2(r.x,r.z)||0,i._x=Math.atan2(Math.sqrt(r.x**2+r.z**2),r.y)||0,i._z=0,i._isDirty=!0,i}static PitchYawRollToMoveBetweenPoints(e,t){let i=n.Zero();return n.PitchYawRollToMoveBetweenPointsToRef(e,t,i)}static SlerpToRef(e,t,i,r){i=Nt(i,0,1);let s=ze.Vector3[0],a=ze.Vector3[1];s.copyFrom(e);let o=s.length();s.normalizeFromLength(o),a.copyFrom(t);let l=a.length();a.normalizeFromLength(l);let c=n.Dot(s,a),f,h;if(c<1-Ot){let d=Math.acos(c),u=1/Math.sin(d);f=Math.sin((1-i)*d)*u,h=Math.sin(i*d)*u}else f=1-i,h=i;return s.scaleInPlace(f),a.scaleInPlace(h),r.copyFrom(s).addInPlace(a),r.scaleInPlace(Ja(o,l,i)),r}static SmoothToRef(e,t,i,r,s){return n.SlerpToRef(e,t,r===0?1:i/r,s),s}static FromArray(e,t=0){return new n(e[t],e[t+1],e[t+2])}static FromFloatArray(e,t){return n.FromArray(e,t)}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._isDirty=!0,i}static FromFloatArrayToRef(e,t,i){return n.FromArrayToRef(e,t,i)}static FromFloatsToRef(e,t,i,r){return r.copyFromFloats(e,t,i),r}static Zero(){return new n(0,0,0)}static One(){return new n(1,1,1)}static Up(){return new n(0,1,0)}static get UpReadOnly(){return n._UpReadOnly}static get DownReadOnly(){return n._DownReadOnly}static get RightReadOnly(){return n._RightReadOnly}static get LeftReadOnly(){return n._LeftReadOnly}static get LeftHandedForwardReadOnly(){return n._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return n._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return n._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return n._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return n._ZeroReadOnly}static get OneReadOnly(){return n._OneReadOnly}static Down(){return new n(0,-1,0)}static Forward(e=!1){return new n(0,0,e?-1:1)}static Backward(e=!1){return new n(0,0,e?1:-1)}static Right(){return new n(1,0,0)}static Left(){return new n(-1,0,0)}static Random(e=0,t=1){return new n(ir(e,t),ir(e,t),ir(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(ir(e,t),ir(e,t),ir(e,t))}static TransformCoordinates(e,t){let i=n.Zero();return n.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return n.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,r,s){let a=r.m,o=e*a[0]+t*a[4]+i*a[8]+a[12],l=e*a[1]+t*a[5]+i*a[9]+a[13],c=e*a[2]+t*a[6]+i*a[10]+a[14],f=1/(e*a[3]+t*a[7]+i*a[11]+a[15]);return s._x=o*f,s._y=l*f,s._z=c*f,s._isDirty=!0,s}static TransformNormal(e,t){let i=n.Zero();return n.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){return this.TransformNormalFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformNormalFromFloatsToRef(e,t,i,r,s){let a=r.m;return s._x=e*a[0]+t*a[4]+i*a[8],s._y=e*a[1]+t*a[5]+i*a[9],s._z=e*a[2]+t*a[6]+i*a[10],s._isDirty=!0,s}static CatmullRom(e,t,i,r,s){let a=s*s,o=s*a,l=.5*(2*t._x+(-e._x+i._x)*s+(2*e._x-5*t._x+4*i._x-r._x)*a+(-e._x+3*t._x-3*i._x+r._x)*o),c=.5*(2*t._y+(-e._y+i._y)*s+(2*e._y-5*t._y+4*i._y-r._y)*a+(-e._y+3*t._y-3*i._y+r._y)*o),f=.5*(2*t._z+(-e._z+i._z)*s+(2*e._z-5*t._z+4*i._z-r._z)*a+(-e._z+3*t._z-3*i._z+r._z)*o);return new n(l,c,f)}static Clamp(e,t,i){let r=new n;return n.ClampToRef(e,t,i,r),r}static ClampToRef(e,t,i,r){let s=e._x;s=s>i._x?i._x:s,s=si._y?i._y:a,a=ai._z?i._z:o,o=o0&&M<0?(O.copyFrom(a),V=t,N=i):M>0&&D<0?(O.copyFrom(l),V=i,N=r):(O.copyFrom(o).scaleInPlace(-1),V=r,N=t);let F=ze.Vector3[9],U=ze.Vector3[4];if(V.subtractToRef(v,E),N.subtractToRef(v,F),n.CrossToRef(E,F,U),!(n.Dot(U,c)<0))return s.copyFrom(v),Math.abs(p*_);let ee=ze.Vector3[5];n.CrossToRef(O,U,ee),ee.normalize();let q=ze.Vector3[9];q.copyFrom(V).subtractInPlace(v);let Q=q.length();if(Qthis._x&&(this.x=e.x),e.y>this._y&&(this.y=e.y),e.z>this._z&&(this.z=e.z),e.w>this._w&&(this.w=e.w),this}minimizeInPlaceFromFloats(e,t,i,r){return this.x=Math.min(e,this._x),this.y=Math.min(t,this._y),this.z=Math.min(i,this._z),this.w=Math.min(r,this._w),this}maximizeInPlaceFromFloats(e,t,i,r){return this.x=Math.max(e,this._x),this.y=Math.max(t,this._y),this.z=Math.max(i,this._z),this.w=Math.max(r,this._w),this}floorToRef(e){return e.x=Math.floor(this._x),e.y=Math.floor(this._y),e.z=Math.floor(this._z),e.w=Math.floor(this._w),e}floor(){return new n(Math.floor(this._x),Math.floor(this._y),Math.floor(this._z),Math.floor(this._w))}fractToRef(e){return e.x=this._x-Math.floor(this._x),e.y=this._y-Math.floor(this._y),e.z=this._z-Math.floor(this._z),e.w=this._w-Math.floor(this._w),e}fract(){return new n(this._x-Math.floor(this._x),this._y-Math.floor(this._y),this._z-Math.floor(this._z),this._w-Math.floor(this._w))}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new n)}normalizeToRef(e){let t=this.length();return t===0||t===1?(e.x=this._x,e.y=this._y,e.z=this._z,e.w=this._w,e):this.scaleToRef(1/t,e)}toVector3(){return new b(this._x,this._y,this._z)}clone(){return new n(this._x,this._y,this._z,this._w)}copyFrom(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this}copyFromFloats(e,t,i,r){return this.x=e,this.y=t,this.z=i,this.w=r,this}set(e,t,i,r){return this.copyFromFloats(e,t,i,r)}setAll(e){return this.x=this.y=this.z=this.w=e,this}dot(e){return this._x*e.x+this._y*e.y+this._z*e.z+this._w*e.w}static FromArray(e,t){return t||(t=0),new n(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i.z=e[t+2],i.w=e[t+3],i}static FromFloatArrayToRef(e,t,i){return n.FromArrayToRef(e,t,i),i}static FromFloatsToRef(e,t,i,r,s){return s.x=e,s.y=t,s.z=i,s.w=r,s}static Zero(){return new n(0,0,0,0)}static One(){return new n(1,1,1,1)}static Random(e=0,t=1){return new n(ir(e,t),ir(e,t),ir(e,t),ir(e,t))}static RandomToRef(e=0,t=1,i){return i.x=ir(e,t),i.y=ir(e,t),i.z=ir(e,t),i.w=ir(e,t),i}static Clamp(e,t,i){return n.ClampToRef(e,t,i,new n)}static ClampToRef(e,t,i,r){return r.x=Nt(e.x,t.x,i.x),r.y=Nt(e.y,t.y,i.y),r.z=Nt(e.z,t.z,i.z),r.w=Nt(e.w,t.w,i.w),r}static CheckExtends(e,t,i){t.minimizeInPlace(e),i.maximizeInPlace(e)}static get ZeroReadOnly(){return n._ZeroReadOnly}static Normalize(e){return n.NormalizeToRef(e,new n)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){let i=new n;return i.copyFrom(e),i.minimizeInPlace(t),i}static Maximize(e,t){let i=new n;return i.copyFrom(e),i.maximizeInPlace(t),i}static Distance(e,t){return Math.sqrt(n.DistanceSquared(e,t))}static DistanceSquared(e,t){let i=e.x-t.x,r=e.y-t.y,s=e.z-t.z,a=e.w-t.w;return i*i+r*r+s*s+a*a}static Center(e,t){return n.CenterToRef(e,t,new n)}static CenterToRef(e,t,i){return i.x=(e.x+t.x)/2,i.y=(e.y+t.y)/2,i.z=(e.z+t.z)/2,i.w=(e.w+t.w)/2,i}static TransformCoordinates(e,t){return n.TransformCoordinatesToRef(e,t,new n)}static TransformCoordinatesToRef(e,t,i){return n.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,r,s){let a=r.m,o=e*a[0]+t*a[4]+i*a[8]+a[12],l=e*a[1]+t*a[5]+i*a[9]+a[13],c=e*a[2]+t*a[6]+i*a[10]+a[14],f=e*a[3]+t*a[7]+i*a[11]+a[15];return s.x=o,s.y=l,s.z=c,s.w=f,s}static TransformNormal(e,t){return n.TransformNormalToRef(e,t,new n)}static TransformNormalToRef(e,t,i){let r=t.m,s=e.x*r[0]+e.y*r[4]+e.z*r[8],a=e.x*r[1]+e.y*r[5]+e.z*r[9],o=e.x*r[2]+e.y*r[6]+e.z*r[10];return i.x=s,i.y=a,i.z=o,i.w=e.w,i}static TransformNormalFromFloatsToRef(e,t,i,r,s,a){let o=s.m;return a.x=e*o[0]+t*o[4]+i*o[8],a.y=e*o[1]+t*o[5]+i*o[9],a.z=e*o[2]+t*o[6]+i*o[10],a.w=r,a}static FromVector3(e,t=0){return new n(e._x,e._y,e._z,t)}static Dot(e,t){return e.x*t.x+e.y*t.y+e.z*t.z+e.w*t.w}};Ri._V8PerformanceHack=new Ri(.5,.5,.5,.5);Ri._ZeroReadOnly=Ri.Zero();Object.defineProperties(Ri.prototype,{dimension:{value:[4]},rank:{value:1}});Ye=class n{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}get w(){return this._w}set w(e){this._w=e,this._isDirty=!0}constructor(e=0,t=0,i=0,r=1){this._isDirty=!0,this._x=e,this._y=t,this._z=i,this._w=r}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Quaternion"}getHashCode(){let e=$n(this._x),t=$n(this._y),i=$n(this._z),r=$n(this._w),s=e;return s=s*397^t,s=s*397^i,s=s*397^r,s}asArray(){return[this._x,this._y,this._z,this._w]}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,this}fromArray(e,t=0){return n.FromArrayToRef(e,t,this)}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z&&this._w===e._w}equalsWithEpsilon(e,t=Ot){return e&&Si(this._x,e._x,t)&&Si(this._y,e._y,t)&&Si(this._z,e._z,t)&&Si(this._w,e._w,t)}isApprox(e,t=Ot){return e&&(Si(this._x,e._x,t)&&Si(this._y,e._y,t)&&Si(this._z,e._z,t)&&Si(this._w,e._w,t)||Si(this._x,-e._x,t)&&Si(this._y,-e._y,t)&&Si(this._z,-e._z,t)&&Si(this._w,-e._w,t))}clone(){return new n(this._x,this._y,this._z,this._w)}copyFrom(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._w=e._w,this._isDirty=!0,this}copyFromFloats(e,t,i,r){return this._x=e,this._y=t,this._z=i,this._w=r,this._isDirty=!0,this}set(e,t,i,r){return this.copyFromFloats(e,t,i,r)}setAll(e){return this.copyFromFloats(e,e,e,e)}add(e){return new n(this._x+e._x,this._y+e._y,this._z+e._z,this._w+e._w)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._w+=e._w,this._isDirty=!0,this}addToRef(e,t){return t._x=this._x+e._x,t._y=this._y+e._y,t._z=this._z+e._z,t._w=this._w+e._w,t._isDirty=!0,t}addInPlaceFromFloats(e,t,i,r){return this._x+=e,this._y+=t,this._z+=i,this._w+=r,this._isDirty=!0,this}subtractToRef(e,t){return t._x=this._x-e._x,t._y=this._y-e._y,t._z=this._z-e._z,t._w=this._w-e._w,t._isDirty=!0,t}subtractFromFloats(e,t,i,r){return this.subtractFromFloatsToRef(e,t,i,r,new n)}subtractFromFloatsToRef(e,t,i,r,s){return s._x=this._x-e,s._y=this._y-t,s._z=this._z-i,s._w=this._w-r,s._isDirty=!0,s}subtract(e){return new n(this._x-e._x,this._y-e._y,this._z-e._z,this._w-e._w)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._w-=e._w,this._isDirty=!0,this}scale(e){return new n(this._x*e,this._y*e,this._z*e,this._w*e)}scaleToRef(e,t){return t._x=this._x*e,t._y=this._y*e,t._z=this._z*e,t._w=this._w*e,t._isDirty=!0,t}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._w*=e,this._isDirty=!0,this}scaleAndAddToRef(e,t){return t._x+=this._x*e,t._y+=this._y*e,t._z+=this._z*e,t._w+=this._w*e,t._isDirty=!0,t}multiply(e){let t=new n(0,0,0,1);return this.multiplyToRef(e,t),t}multiplyToRef(e,t){let i=this._x*e._w+this._y*e._z-this._z*e._y+this._w*e._x,r=-this._x*e._z+this._y*e._w+this._z*e._x+this._w*e._y,s=this._x*e._y-this._y*e._x+this._z*e._w+this._w*e._z,a=-this._x*e._x-this._y*e._y-this._z*e._z+this._w*e._w;return t.copyFromFloats(i,r,s,a),t}multiplyInPlace(e){return this.multiplyToRef(e,this)}multiplyByFloats(e,t,i,r){return this._x*=e,this._y*=t,this._z*=i,this._w*=r,this._isDirty=!0,this}divide(e){throw new ReferenceError("Can not divide a quaternion")}divideToRef(e,t){throw new ReferenceError("Can not divide a quaternion")}divideInPlace(e){throw new ReferenceError("Can not divide a quaternion")}minimizeInPlace(){throw new ReferenceError("Can not minimize a quaternion")}minimizeInPlaceFromFloats(){throw new ReferenceError("Can not minimize a quaternion")}maximizeInPlace(){throw new ReferenceError("Can not maximize a quaternion")}maximizeInPlaceFromFloats(){throw new ReferenceError("Can not maximize a quaternion")}negate(){return this.negateToRef(new n)}negateInPlace(){return this._x=-this._x,this._y=-this._y,this._z=-this._z,this._w=-this._w,this._isDirty=!0,this}negateToRef(e){return e._x=-this._x,e._y=-this._y,e._z=-this._z,e._w=-this._w,e._isDirty=!0,e}equalsToFloats(e,t,i,r){return this._x===e&&this._y===t&&this._z===i&&this._w===r}floorToRef(e){throw new ReferenceError("Can not floor a quaternion")}floor(){throw new ReferenceError("Can not floor a quaternion")}fractToRef(e){throw new ReferenceError("Can not fract a quaternion")}fract(){throw new ReferenceError("Can not fract a quaternion")}conjugateToRef(e){return e.copyFromFloats(-this._x,-this._y,-this._z,this._w),e}conjugateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}conjugate(){return new n(-this._x,-this._y,-this._z,this._w)}invert(){let e=this.conjugate(),t=this.lengthSquared();return t==0||t==1||e.scaleInPlace(1/t),e}invertInPlace(){this.conjugateInPlace();let e=this.lengthSquared();return e==0||e==1?this:(this.scaleInPlace(1/e),this)}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this.lengthSquared())}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){let e=new n(0,0,0,1);return this.normalizeToRef(e),e}normalizeToRef(e){let t=this.length();return t===0||t===1?e.copyFromFloats(this._x,this._y,this._z,this._w):this.scaleToRef(1/t,e)}toEulerAngles(){let e=b.Zero();return this.toEulerAnglesToRef(e),e}toEulerAnglesToRef(e){let t=this._z,i=this._x,r=this._y,s=this._w,a=r*t-i*s,o=.4999999;if(a<-o)e._y=2*Math.atan2(r,s),e._x=Math.PI/2,e._z=0,e._isDirty=!0;else if(a>o)e._y=2*Math.atan2(r,s),e._x=-Math.PI/2,e._z=0,e._isDirty=!0;else{let l=s*s,c=t*t,f=i*i,h=r*r;e._z=Math.atan2(2*(i*r+t*s),-c-f+h+l),e._x=Math.asin(-2*a),e._y=Math.atan2(2*(t*i+r*s),c-f-h+l),e._isDirty=!0}return e}toAlphaBetaGammaToRef(e){let t=this._z,i=this._x,r=this._y,s=this._w,a=Math.sqrt(i*i+r*r),o=Math.sqrt(t*t+s*s),l=2*Math.atan2(a,o),c=2*Math.atan2(t,s),f=2*Math.atan2(r,i),h=(c+f)/2,d=(c-f)/2;return e.set(d,l,h),e}toRotationMatrix(e){return j.FromQuaternionToRef(this,e),e}fromRotationMatrix(e){return n.FromRotationMatrixToRef(e,this),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}toAxisAngle(){let e=b.Zero(),t=this.toAxisAngleToRef(e);return{axis:e,angle:t}}toAxisAngleToRef(e){let t,i=Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z),r=this._w;return i>0?(t=2*Math.atan2(i,r),e.set(this._x/i,this._y/i,this._z/i)):(t=0,e.set(1,0,0)),t}static FromRotationMatrix(e){let t=new n;return n.FromRotationMatrixToRef(e,t),t}static FromRotationMatrixToRef(e,t){let i=e.m,r=i[0],s=i[4],a=i[8],o=i[1],l=i[5],c=i[9],f=i[2],h=i[6],d=i[10],u=r+l+d,m;return u>0?(m=.5/Math.sqrt(u+1),t._w=.25/m,t._x=(h-c)*m,t._y=(a-f)*m,t._z=(o-s)*m,t._isDirty=!0):r>l&&r>d?(m=2*Math.sqrt(1+r-l-d),t._w=(h-c)/m,t._x=.25*m,t._y=(s+o)/m,t._z=(a+f)/m,t._isDirty=!0):l>d?(m=2*Math.sqrt(1+l-r-d),t._w=(a-f)/m,t._x=(s+o)/m,t._y=.25*m,t._z=(c+h)/m,t._isDirty=!0):(m=2*Math.sqrt(1+d-r-l),t._w=(o-s)/m,t._x=(a+f)/m,t._y=(c+h)/m,t._z=.25*m,t._isDirty=!0),t}static Dot(e,t){return e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w}static AreClose(e,t,i=.1){let r=n.Dot(e,t);return 1-r*r<=i}static SmoothToRef(e,t,i,r,s){let a=r===0?1:i/r;return a=Nt(a,0,1),n.SlerpToRef(e,t,a,s),s}static Zero(){return new n(0,0,0,0)}static Inverse(e){return new n(-e._x,-e._y,-e._z,e._w)}static InverseToRef(e,t){return t.set(-e._x,-e._y,-e._z,e._w),t}static Identity(){return new n(0,0,0,1)}static IsIdentity(e){return e&&e._x===0&&e._y===0&&e._z===0&&e._w===1}static RotationAxis(e,t){return n.RotationAxisToRef(e,t,new n)}static RotationAxisToRef(e,t,i){i._w=Math.cos(t/2);let r=Math.sin(t/2)/e.length();return i._x=e._x*r,i._y=e._y*r,i._z=e._z*r,i._isDirty=!0,i}static FromArray(e,t){return t||(t=0),new n(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._w=e[t+3],i._isDirty=!0,i}static FromFloatsToRef(e,t,i,r,s){return s.copyFromFloats(e,t,i,r),s}static FromEulerAngles(e,t,i){let r=new n;return n.RotationYawPitchRollToRef(t,e,i,r),r}static FromEulerAnglesToRef(e,t,i,r){return n.RotationYawPitchRollToRef(t,e,i,r),r}static FromEulerVector(e){let t=new n;return n.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromEulerVectorToRef(e,t){return n.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromUnitVectorsToRef(e,t,i,r=Ot){let s=b.Dot(e,t)+1;return sMath.abs(e.z)?i.set(-e.y,e.x,0,0):i.set(0,-e.z,e.y,0):(b.CrossToRef(e,t,$.Vector3[0]),i.set($.Vector3[0].x,$.Vector3[0].y,$.Vector3[0].z,s)),i.normalize()}static RotationYawPitchRoll(e,t,i){let r=new n;return n.RotationYawPitchRollToRef(e,t,i,r),r}static RotationYawPitchRollToRef(e,t,i,r){let s=i*.5,a=t*.5,o=e*.5,l=Math.sin(s),c=Math.cos(s),f=Math.sin(a),h=Math.cos(a),d=Math.sin(o),u=Math.cos(o);return r._x=u*f*c+d*h*l,r._y=d*h*c-u*f*l,r._z=u*h*l-d*f*c,r._w=u*h*c+d*f*l,r._isDirty=!0,r}static RotationAlphaBetaGamma(e,t,i){let r=new n;return n.RotationAlphaBetaGammaToRef(e,t,i,r),r}static RotationAlphaBetaGammaToRef(e,t,i,r){let s=(i+e)*.5,a=(i-e)*.5,o=t*.5;return r._x=Math.cos(a)*Math.sin(o),r._y=Math.sin(a)*Math.sin(o),r._z=Math.sin(s)*Math.cos(o),r._w=Math.cos(s)*Math.cos(o),r._isDirty=!0,r}static RotationQuaternionFromAxis(e,t,i){let r=new n(0,0,0,0);return n.RotationQuaternionFromAxisToRef(e,t,i,r),r}static RotationQuaternionFromAxisToRef(e,t,i,r){let s=ze.Matrix[0];return e=e.normalizeToRef(ze.Vector3[0]),t=t.normalizeToRef(ze.Vector3[1]),i=i.normalizeToRef(ze.Vector3[2]),j.FromXYZAxesToRef(e,t,i,s),n.FromRotationMatrixToRef(s,r),r}static FromLookDirectionLH(e,t){let i=new n;return n.FromLookDirectionLHToRef(e,t,i),i}static FromLookDirectionLHToRef(e,t,i){let r=ze.Matrix[0];return j.LookDirectionLHToRef(e,t,r),n.FromRotationMatrixToRef(r,i),i}static FromLookDirectionRH(e,t){let i=new n;return n.FromLookDirectionRHToRef(e,t,i),i}static FromLookDirectionRHToRef(e,t,i){let r=ze.Matrix[0];return j.LookDirectionRHToRef(e,t,r),n.FromRotationMatrixToRef(r,i)}static Slerp(e,t,i){let r=n.Identity();return n.SlerpToRef(e,t,i,r),r}static SlerpToRef(e,t,i,r){let s,a,o=e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w,l=!1;if(o<0&&(l=!0,o=-o),o>.999999)a=1-i,s=l?-i:i;else{let c=Math.acos(o),f=1/Math.sin(c);a=Math.sin((1-i)*c)*f,s=l?-Math.sin(i*c)*f:Math.sin(i*c)*f}return r._x=a*e._x+s*t._x,r._y=a*e._y+s*t._y,r._z=a*e._z+s*t._z,r._w=a*e._w+s*t._w,r._isDirty=!0,r}static Hermite(e,t,i,r,s){let a=s*s,o=s*a,l=2*o-3*a+1,c=-2*o+3*a,f=o-2*a+s,h=o-a,d=e._x*l+i._x*c+t._x*f+r._x*h,u=e._y*l+i._y*c+t._y*f+r._y*h,m=e._z*l+i._z*c+t._z*f+r._z*h,p=e._w*l+i._w*c+t._w*f+r._w*h;return new n(d,u,m,p)}static Hermite1stDerivative(e,t,i,r,s){let a=new n;return this.Hermite1stDerivativeToRef(e,t,i,r,s,a),a}static Hermite1stDerivativeToRef(e,t,i,r,s,a){let o=s*s;return a._x=(o-s)*6*e._x+(3*o-4*s+1)*t._x+(-o+s)*6*i._x+(3*o-2*s)*r._x,a._y=(o-s)*6*e._y+(3*o-4*s+1)*t._y+(-o+s)*6*i._y+(3*o-2*s)*r._y,a._z=(o-s)*6*e._z+(3*o-4*s+1)*t._z+(-o+s)*6*i._z+(3*o-2*s)*r._z,a._w=(o-s)*6*e._w+(3*o-4*s+1)*t._w+(-o+s)*6*i._w+(3*o-2*s)*r._w,a._isDirty=!0,a}static Normalize(e){let t=n.Zero();return n.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Clamp(e,t,i){let r=new n;return n.ClampToRef(e,t,i,r),r}static ClampToRef(e,t,i,r){return r.copyFromFloats(Nt(e.x,t.x,i.x),Nt(e.y,t.y,i.y),Nt(e.z,t.z,i.z),Nt(e.w,t.w,i.w))}static Random(e=0,t=1){return new n(ir(e,t),ir(e,t),ir(e,t),ir(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(ir(e,t),ir(e,t),ir(e,t),ir(e,t))}static Minimize(){throw new ReferenceError("Quaternion.Minimize does not make sense")}static Maximize(){throw new ReferenceError("Quaternion.Maximize does not make sense")}static Distance(e,t){return Math.sqrt(n.DistanceSquared(e,t))}static DistanceSquared(e,t){let i=e.x-t.x,r=e.y-t.y,s=e.z-t.z,a=e.w-t.w;return i*i+r*r+s*s+a*a}static Center(e,t){return n.CenterToRef(e,t,n.Zero())}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2,(e.z+t.z)/2,(e.w+t.w)/2)}};Ye._V8PerformanceHack=new Ye(.5,.5,.5,.5);Object.defineProperties(Ye.prototype,{dimension:{value:[4]},rank:{value:1}});j=class n{static get Use64Bits(){return Zn.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=zu._UpdateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0}_updateIdentityStatus(e,t=!1,i=!1,r=!0){this._isIdentity=e,this._isIdentity3x2=e||i,this._isIdentityDirty=this._isIdentity?!1:t,this._isIdentity3x2Dirty=this._isIdentity3x2?!1:r}constructor(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,Zn.MatrixTrackPrecisionChange&&Zn.MatrixTrackedMatrices.push(this),this._m=new Zn.MatrixCurrentType(16),this.markAsUpdated()}isIdentity(){if(this._isIdentityDirty){this._isIdentityDirty=!1;let e=this._m;this._isIdentity=e[0]===1&&e[1]===0&&e[2]===0&&e[3]===0&&e[4]===0&&e[5]===1&&e[6]===0&&e[7]===0&&e[8]===0&&e[9]===0&&e[10]===1&&e[11]===0&&e[12]===0&&e[13]===0&&e[14]===0&&e[15]===1}return this._isIdentity}isIdentityAs3x2(){return this._isIdentity3x2Dirty&&(this._isIdentity3x2Dirty=!1,this._m[0]!==1||this._m[5]!==1||this._m[15]!==1?this._isIdentity3x2=!1:this._m[1]!==0||this._m[2]!==0||this._m[3]!==0||this._m[4]!==0||this._m[6]!==0||this._m[7]!==0||this._m[8]!==0||this._m[9]!==0||this._m[10]!==0||this._m[11]!==0||this._m[12]!==0||this._m[13]!==0||this._m[14]!==0?this._isIdentity3x2=!1:this._isIdentity3x2=!0),this._isIdentity3x2}determinant(){if(this._isIdentity===!0)return 1;let e=this._m,t=e[0],i=e[1],r=e[2],s=e[3],a=e[4],o=e[5],l=e[6],c=e[7],f=e[8],h=e[9],d=e[10],u=e[11],m=e[12],p=e[13],_=e[14],g=e[15],v=d*g-_*u,x=h*g-p*u,A=h*_-p*d,S=f*g-m*u,E=f*_-d*m,R=f*p-m*h,I=+(o*v-l*x+c*A),y=-(a*v-l*S+c*E),M=+(a*x-o*S+c*R),D=-(a*A-o*E+l*R);return t*I+i*y+r*M+s*D}toString(){return`{${this.m[0]}, ${this.m[1]}, ${this.m[2]}, ${this.m[3]} +`+e;return e}}});var Dh,bM=C(()=>{Dh=class n{get underlyingResource(){return null}constructor(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=n._Counter++}};Dh._Counter=0});var qo,yT=C(()=>{bM();qo=class extends Dh{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}}});function Lh(n){let e=1;do e*=2;while(en-t?t:e}function q3(n){return n--,n|=n>>1,n|=n>>2,n|=n>>4,n|=n>>8,n|=n>>16,n++,n}function PT(n){return n=n|n>>1,n=n|n>>2,n=n|n>>4,n=n|n>>8,n=n|n>>16,n-(n>>1)}function gn(n,e,t=2){let i;switch(t){case 1:i=PT(n);break;case 2:i=IM(n);break;default:i=q3(n);break}return Math.min(i,e)}var $a=C(()=>{});var ku,MM=C(()=>{ku=class{get underlyingResource(){return this._webGLTexture}constructor(e=null,t){if(this._MSAARenderBuffers=null,this._context=t,!e&&(e=t.createTexture(),!e))throw new Error("Unable to create webGL texture");this.set(e)}setUsage(){}set(e){this._webGLTexture=e}reset(){this._webGLTexture=null,this._MSAARenderBuffers=null}addMSAARenderBuffer(e){this._MSAARenderBuffers||(this._MSAARenderBuffers=[]),this._MSAARenderBuffers.push(e)}releaseMSAARenderBuffers(){if(this._MSAARenderBuffers){for(let e of this._MSAARenderBuffers)this._context.deleteRenderbuffer(e);this._MSAARenderBuffers=null}}getMSAARenderBuffer(e=0){var t,i;return(i=(t=this._MSAARenderBuffers)==null?void 0:t[e])!=null?i:null}release(){this.releaseMSAARenderBuffers(),this._webGLTexture&&this._context.deleteTexture(this._webGLTexture),this.reset()}}});function CM(n){return n===13||n===14||n===15||n===16||n===17||n===18||n===19}function Fl(n){return n===13||n===17||n===18||n===19}var O_=C(()=>{});var Z3={};tt(Z3,{ThinEngine:()=>bt});var yM,bt,Zn=C(()=>{yh();mM();wr();RM();Pt();ga();K3();j3();yT();$a();MM();vs();af();TM();O_();xM();yM=class{},bt=class n extends Me{get name(){return this._name}set name(e){this._name=e}get version(){return this._webGLVersion}static get ShadersRepository(){return rr.ShadersRepository}static set ShadersRepository(e){rr.ShadersRepository=e}get supportsUniformBuffers(){return this.webGLVersion>1&&!this.disableUniformBuffers}get needPOTTextures(){return this._webGLVersion<2||this.forcePOTTextures}get _supportsHardwareTextureRescaling(){return!1}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e}snapshotRenderingReset(){this.snapshotRendering=!1}constructor(e,t,i,r){if(i=i||{},super(t!=null?t:i.antialias,i,r),this._name="WebGL",this.forcePOTTextures=!1,this.validateShaderPrograms=!1,this.disableUniformBuffers=!1,this._webGLVersion=1,this._vertexAttribArraysEnabled=[],this._uintIndicesCurrentlySet=!1,this._currentBoundBuffer=new Array,this._currentFramebuffer=null,this._dummyFramebuffer=null,this._currentBufferPointers=new Array,this._currentInstanceLocations=new Array,this._currentInstanceBuffers=new Array,this._vaoRecordInProgress=!1,this._mustWipeVertexAttributes=!1,this._nextFreeTextureSlots=new Array,this._maxSimultaneousTextures=0,this._maxMSAASamplesOverride=null,this._unpackFlipYCached=null,this.enableUnpackFlipYCached=!0,this._boundUniforms={},!e)return;let s;if(e.getContext){if(s=e,i.preserveDrawingBuffer===void 0&&(i.preserveDrawingBuffer=!1),i.xrCompatible===void 0&&(i.xrCompatible=!1),navigator&&navigator.userAgent){this._setupMobileChecks();let l=navigator.userAgent;for(let c of n.ExceptionList){let f=c.key,h=c.targets;if(new RegExp(f).test(l)){if(c.capture&&c.captureConstraint){let u=c.capture,m=c.captureConstraint,_=new RegExp(u).exec(l);if(_&&_.length>0&&parseInt(_[_.length-1])>=m)continue}for(let u of h)switch(u){case"uniformBuffer":this.disableUniformBuffers=!0;break;case"vao":this.disableVertexArrayObjects=!0;break;case"antialias":i.antialias=!1;break;case"maxMSAASamples":this._maxMSAASamplesOverride=1;break}}}}if(this._doNotHandleContextLost?this._onContextLost=()=>{fT(this._gl)}:(this._onContextLost=l=>{l.preventDefault(),this._contextWasLost=!0,fT(this._gl),te.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost(()=>this._initGLContext())},s.addEventListener("webglcontextrestored",this._onContextRestored,!1),i.powerPreference=i.powerPreference||"high-performance"),s.addEventListener("webglcontextlost",this._onContextLost,!1),this._badDesktopOS&&(i.xrCompatible=!1),!i.disableWebGL2Support)try{this._gl=s.getContext("webgl2",i)||s.getContext("experimental-webgl2",i),this._gl&&(this._webGLVersion=2,this._shaderPlatformName="WEBGL2",this._gl.deleteQuery||(this._webGLVersion=1,this._shaderPlatformName="WEBGL1"))}catch(l){}if(!this._gl){if(!s)throw new Error("The provided canvas is null or undefined.");try{this._gl=s.getContext("webgl",i)||s.getContext("experimental-webgl",i)}catch(l){throw new Error("WebGL not supported",{cause:l})}}if(!this._gl)throw new Error("WebGL not supported")}else{this._gl=e,s=this._gl.canvas,this._gl.renderbufferStorageMultisample?(this._webGLVersion=2,this._shaderPlatformName="WEBGL2"):this._shaderPlatformName="WEBGL1";let l=this._gl.getContextAttributes();l&&(i.stencil=l.stencil)}this._sharedInit(s),this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),i.useHighPrecisionFloats!==void 0&&(this._highPrecisionShadersAllowed=i.useHighPrecisionFloats),this.resize(),this._initGLContext(),this._initFeatures();for(let l=0;l1?new CT:new MT;let a=`Babylon.js v${n.Version}`;te.Log(a+` - ${this.description}`),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",a);let o=Pn(this._gl);o.validateShaderPrograms=this.validateShaderPrograms,o.parallelShaderCompile=this._caps.parallelShaderCompile}_clearEmptyResources(){this._dummyFramebuffer=null,super._clearEmptyResources()}_getShaderProcessingContext(e){return null}areAllEffectsReady(){for(let e in this._compiledEffects)if(!this._compiledEffects[e].isReady())return!1;return!0}_initGLContext(){var i;this._caps={maxTexturesImageUnits:this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS),maxCombinedTexturesImageUnits:this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS),maxVertexTextureImageUnits:this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),maxTextureSize:this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),maxSamples:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_SAMPLES):1,maxCubemapTextureSize:this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE),maxRenderTextureSize:this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE),maxVertexAttribs:this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS),maxVaryingVectors:this._gl.getParameter(this._gl.MAX_VARYING_VECTORS),maxFragmentUniformVectors:this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS),maxVertexUniformVectors:this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS),shaderFloatPrecision:0,parallelShaderCompile:this._gl.getExtension("KHR_parallel_shader_compile")||void 0,standardDerivatives:this._webGLVersion>1||this._gl.getExtension("OES_standard_derivatives")!==null,maxAnisotropy:1,astc:this._gl.getExtension("WEBGL_compressed_texture_astc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_astc"),bptc:this._gl.getExtension("EXT_texture_compression_bptc")||this._gl.getExtension("WEBKIT_EXT_texture_compression_bptc"),s3tc:this._gl.getExtension("WEBGL_compressed_texture_s3tc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"),s3tc_srgb:this._gl.getExtension("WEBGL_compressed_texture_s3tc_srgb")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc_srgb"),pvrtc:this._gl.getExtension("WEBGL_compressed_texture_pvrtc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),etc1:this._gl.getExtension("WEBGL_compressed_texture_etc1")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc1"),etc2:this._gl.getExtension("WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBGL_compressed_texture_es3_0"),textureAnisotropicFilterExtension:this._gl.getExtension("EXT_texture_filter_anisotropic")||this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"),uintIndices:this._webGLVersion>1||this._gl.getExtension("OES_element_index_uint")!==null,fragmentDepthSupported:this._webGLVersion>1||this._gl.getExtension("EXT_frag_depth")!==null,highPrecisionShaderSupported:!1,timerQuery:this._gl.getExtension("EXT_disjoint_timer_query_webgl2")||this._gl.getExtension("EXT_disjoint_timer_query"),supportOcclusionQuery:this._webGLVersion>1,canUseTimestampForTimerQuery:!1,drawBuffersExtension:!1,maxMSAASamples:1,colorBufferFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_float")),blendFloat:this._gl.getExtension("EXT_float_blend")!==null,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,colorBufferHalfFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_half_float")),textureFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_float")),textureHalfFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_half_float")),textureHalfFloatRender:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloatLinearFiltering:!1,vertexArrayObject:!1,instancedArrays:!1,textureLOD:!!(this._webGLVersion>1||this._gl.getExtension("EXT_shader_texture_lod")),texelFetch:this._webGLVersion!==1,blendMinMax:!1,multiview:this._gl.getExtension("OVR_multiview2"),oculusMultiview:this._gl.getExtension("OCULUS_multiview"),depthTextureExtension:!1,canUseGLInstanceID:this._webGLVersion>1,canUseGLVertexID:this._webGLVersion>1,supportComputeShaders:!1,supportSRGBBuffers:!1,supportTransformFeedbacks:this._webGLVersion>1,textureMaxLevel:this._webGLVersion>1,texture2DArrayMaxLayerCount:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_ARRAY_TEXTURE_LAYERS):128,disableMorphTargetTexture:!1,textureNorm16:!!this._gl.getExtension("EXT_texture_norm16"),blendParametersPerTarget:!1,dualSourceBlending:!1,supportReadWriteStorageTextures:!1},this._caps.supportFloatTexturesResolve=this._caps.colorBufferFloat,this._caps.rg11b10ufColorRenderable=this._caps.colorBufferFloat,this._glVersion=this._gl.getParameter(this._gl.VERSION);let e=this._gl.getExtension("WEBGL_debug_renderer_info");e!=null&&(this._glRenderer=this._gl.getParameter(e.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(e.UNMASKED_VENDOR_WEBGL)),this._glVendor||(this._glVendor=this._gl.getParameter(this._gl.VENDOR)||"Unknown vendor"),this._glRenderer||(this._glRenderer=this._gl.getParameter(this._gl.RENDERER)||"Unknown renderer"),this._gl.HALF_FLOAT_OES!==36193&&(this._gl.HALF_FLOAT_OES=36193),this._gl.RGBA16F!==34842&&(this._gl.RGBA16F=34842),this._gl.RGBA32F!==34836&&(this._gl.RGBA32F=34836),this._gl.DEPTH24_STENCIL8!==35056&&(this._gl.DEPTH24_STENCIL8=35056),this._caps.timerQuery&&(this._webGLVersion===1&&(this._gl.getQuery=this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery)),this._caps.canUseTimestampForTimerQuery=((i=this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT))!=null?i:0)>0),this._caps.maxAnisotropy=this._caps.textureAnisotropicFilterExtension?this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0,this._caps.textureFloatLinearFiltering=!!(this._caps.textureFloat&&this._gl.getExtension("OES_texture_float_linear")),this._caps.textureFloatRender=!!(this._caps.textureFloat&&this._canRenderToFloatFramebuffer()),this._caps.textureHalfFloatLinearFiltering=!!(this._webGLVersion>1||this._caps.textureHalfFloat&&this._gl.getExtension("OES_texture_half_float_linear")),this._caps.textureNorm16&&(this._gl.R16_EXT=33322,this._gl.RG16_EXT=33324,this._gl.RGB16_EXT=32852,this._gl.RGBA16_EXT=32859,this._gl.R16_SNORM_EXT=36760,this._gl.RG16_SNORM_EXT=36761,this._gl.RGB16_SNORM_EXT=36762,this._gl.RGBA16_SNORM_EXT=36763);let t=this._gl.getExtension("OES_draw_buffers_indexed");if(this._caps.blendParametersPerTarget=!!t,this._alphaState=new Gu(this._caps.blendParametersPerTarget),t&&(this._gl.blendEquationSeparateIndexed=t.blendEquationSeparateiOES.bind(t),this._gl.blendEquationIndexed=t.blendEquationiOES.bind(t),this._gl.blendFuncSeparateIndexed=t.blendFuncSeparateiOES.bind(t),this._gl.blendFuncIndexed=t.blendFunciOES.bind(t),this._gl.colorMaskIndexed=t.colorMaskiOES.bind(t),this._gl.disableIndexed=t.disableiOES.bind(t),this._gl.enableIndexed=t.enableiOES.bind(t)),this._caps.dualSourceBlending=!!this._gl.getExtension("WEBGL_blend_func_extended"),this._caps.astc&&(this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR,this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR),this._caps.bptc&&(this._gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT=this._caps.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT),this._caps.s3tc_srgb&&(this._gl.COMPRESSED_SRGB_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT),this._caps.etc2&&(this._gl.COMPRESSED_SRGB8_ETC2=this._caps.etc2.COMPRESSED_SRGB8_ETC2,this._gl.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=this._caps.etc2.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC),this._webGLVersion>1&&this._gl.HALF_FLOAT_OES!==5131&&(this._gl.HALF_FLOAT_OES=5131),this._caps.textureHalfFloatRender=this._caps.textureHalfFloat&&this._canRenderToHalfFloatFramebuffer(),this._webGLVersion>1)this._caps.drawBuffersExtension=!0,this._caps.maxMSAASamples=this._maxMSAASamplesOverride!==null?this._maxMSAASamplesOverride:this._gl.getParameter(this._gl.MAX_SAMPLES),this._caps.maxDrawBuffers=this._gl.getParameter(this._gl.MAX_DRAW_BUFFERS);else{let r=this._gl.getExtension("WEBGL_draw_buffers");if(r!==null){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=r.drawBuffersWEBGL.bind(r),this._caps.maxDrawBuffers=this._gl.getParameter(r.MAX_DRAW_BUFFERS_WEBGL),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(let s=0;s<16;s++)this._gl["COLOR_ATTACHMENT"+s+"_WEBGL"]=r["COLOR_ATTACHMENT"+s+"_WEBGL"]}}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{let r=this._gl.getExtension("WEBGL_depth_texture");r!=null&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=r.UNSIGNED_INT_24_8_WEBGL)}if(this.disableVertexArrayObjects)this._caps.vertexArrayObject=!1;else if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{let r=this._gl.getExtension("OES_vertex_array_object");r!=null&&(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=r.createVertexArrayOES.bind(r),this._gl.bindVertexArray=r.bindVertexArrayOES.bind(r),this._gl.deleteVertexArray=r.deleteVertexArrayOES.bind(r))}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{let r=this._gl.getExtension("ANGLE_instanced_arrays");r!=null?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=r.drawArraysInstancedANGLE.bind(r),this._gl.drawElementsInstanced=r.drawElementsInstancedANGLE.bind(r),this._gl.vertexAttribDivisor=r.vertexAttribDivisorANGLE.bind(r)):this._caps.instancedArrays=!1}if(this._gl.getShaderPrecisionFormat){let r=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.HIGH_FLOAT),s=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);if(r&&s&&(this._caps.highPrecisionShaderSupported=r.precision!==0&&s.precision!==0,this._caps.shaderFloatPrecision=Math.min(r.precision,s.precision)),!this._shouldUseHighPrecisionShader){let a=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.MEDIUM_FLOAT),o=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.MEDIUM_FLOAT);a&&o&&(this._caps.shaderFloatPrecision=Math.min(a.precision,o.precision))}this._caps.shaderFloatPrecision<10&&(this._caps.shaderFloatPrecision=10)}if(this._webGLVersion>1)this._caps.blendMinMax=!0;else{let r=this._gl.getExtension("EXT_blend_minmax");r!=null&&(this._caps.blendMinMax=!0,this._gl.MAX=r.MAX_EXT,this._gl.MIN=r.MIN_EXT)}if(!this._caps.supportSRGBBuffers){if(this._webGLVersion>1)this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:WebGL2RenderingContext.SRGB,SRGB8:WebGL2RenderingContext.SRGB8,SRGB8_ALPHA8:WebGL2RenderingContext.SRGB8_ALPHA8};else{let r=this._gl.getExtension("EXT_sRGB");r!=null&&(this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:r.SRGB_EXT,SRGB8:r.SRGB_ALPHA_EXT,SRGB8_ALPHA8:r.SRGB_ALPHA_EXT})}if(this._creationOptions){let r=this._creationOptions.forceSRGBBufferSupportState;r!==void 0&&(this._caps.supportSRGBBuffers=this._caps.supportSRGBBuffers&&r)}}this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=this._gl.LEQUAL,this._depthCullingState.depthMask=!0,this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(let r=0;r=65535)return new Uint32Array(e);return new Uint16Array(e)}return new Uint16Array(e)}bindArrayBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ARRAY_BUFFER)}bindUniformBlock(e,t,i){let r=e.program,s=this._gl.getUniformBlockIndex(r,t);this._gl.uniformBlockBinding(r,s,i)}bindIndexBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ELEMENT_ARRAY_BUFFER)}_bindBuffer(e,t){(this._vaoRecordInProgress||this._currentBoundBuffer[t]!==e)&&(this._gl.bindBuffer(t,e?e.underlyingResource:null),this._currentBoundBuffer[t]=e)}updateArrayBuffer(e){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)}_vertexAttribPointer(e,t,i,r,s,a,o){let l=this._currentBufferPointers[t];if(!l)return;let c=!1;l.active?(l.buffer!==e&&(l.buffer=e,c=!0),l.size!==i&&(l.size=i,c=!0),l.type!==r&&(l.type=r,c=!0),l.normalized!==s&&(l.normalized=s,c=!0),l.stride!==a&&(l.stride=a,c=!0),l.offset!==o&&(l.offset=o,c=!0)):(c=!0,l.active=!0,l.index=t,l.size=i,l.type=r,l.normalized=s,l.stride=a,l.offset=o,l.buffer=e),(c||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),r===this._gl.UNSIGNED_INT||r===this._gl.INT?this._gl.vertexAttribIPointer(t,i,r,a,o):this._gl.vertexAttribPointer(t,i,r,s,a,o))}_bindIndexBufferWithCache(e){e!=null&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)}_bindVertexBuffersAttributes(e,t,i){let r=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(let s=0;s=0){let o=r[s],l=null;if(i&&(l=i[o]),l||(l=e[o]),!l)continue;this._gl.enableVertexAttribArray(a),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[a]=!0);let c=l.getBuffer();c&&(this._vertexAttribPointer(c,a,l.getSize(),l.type,l.normalized,l.byteStride,l.byteOffset),l.getIsInstanced()&&(this._gl.vertexAttribDivisor(a,l.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(a),this._currentInstanceBuffers.push(c))))}}}recordVertexArrayObject(e,t,i,r){let s=this._gl.createVertexArray();if(!s)throw new Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(s),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i,r),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),s}bindVertexArrayObject(e,t){this._cachedVertexArrayObject!==e&&(this._cachedVertexArrayObject=e,this._gl.bindVertexArray(e),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._uintIndicesCurrentlySet=t!=null&&t.is32Bits,this._mustWipeVertexAttributes=!0)}bindBuffersDirectly(e,t,i,r,s){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==s){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=s;let a=s.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();let o=0;for(let l=0;l=0&&(this._gl.enableVertexAttribArray(c),this._vertexAttribArraysEnabled[c]=!0,this._vertexAttribPointer(e,c,i[l],this._gl.FLOAT,!1,r,o)),o+=i[l]*4}}this._bindIndexBufferWithCache(t)}_unbindVertexArrayObject(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))}bindBuffers(e,t,i,r){(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==i)&&(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i,this._bindVertexBuffersAttributes(e,i,r)),this._bindIndexBufferWithCache(t)}unbindInstanceAttributes(){let e;for(let t=0,i=this._currentInstanceLocations.length;t1||this.isWebGPU)),(o===1&&!this._caps.textureFloatLinearFiltering||o===2&&!this._caps.textureHalfFloatLinearFiltering)&&(l=1),o===1&&!this._caps.textureFloat&&(o=0,te.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));let _=CM(c),g=Fl(c),v=this._gl,x=new Pi(this,r),A=e.width||e,S=e.height||e,E=e.depth||0,R=e.layers||0,I=this._getSamplingParameters(l,(s||a)&&!_),y=R!==0?v.TEXTURE_2D_ARRAY:E!==0?v.TEXTURE_3D:p?v.TEXTURE_CUBE_MAP:v.TEXTURE_2D,M=_?this._getInternalFormatFromDepthTextureFormat(c,!0,g):this._getRGBABufferInternalSizedFormat(o,c,f),D=_?g?v.DEPTH_STENCIL:v.DEPTH_COMPONENT:this._getInternalFormat(c),O=_?this._getWebGLTextureTypeFromDepthTextureFormat(c):this._getWebGLTextureType(o);if(this._bindTextureDirectly(y,x),R!==0)x.is2DArray=!0,v.texImage3D(y,0,M,A,S,R,0,D,O,null);else if(E!==0)x.is3D=!0,v.texImage3D(y,0,M,A,S,E,0,D,O,null);else if(p){x.isCube=!0;for(let N=0;N<6;N++)v.texImage2D(v.TEXTURE_CUBE_MAP_POSITIVE_X+N,0,M,A,S,0,D,O,null)}else v.texImage2D(y,0,M,A,S,0,D,O,null);if(v.texParameteri(y,v.TEXTURE_MAG_FILTER,I.mag),v.texParameteri(y,v.TEXTURE_MIN_FILTER,I.min),v.texParameteri(y,v.TEXTURE_WRAP_S,v.CLAMP_TO_EDGE),v.texParameteri(y,v.TEXTURE_WRAP_T,v.CLAMP_TO_EDGE),_&&this.webGLVersion>1&&(m===0?(v.texParameteri(y,v.TEXTURE_COMPARE_FUNC,515),v.texParameteri(y,v.TEXTURE_COMPARE_MODE,v.NONE)):(v.texParameteri(y,v.TEXTURE_COMPARE_FUNC,m),v.texParameteri(y,v.TEXTURE_COMPARE_MODE,v.COMPARE_REF_TO_TEXTURE))),(s||a)&&this._gl.generateMipmap(y),this._bindTextureDirectly(y,null),x._useSRGBBuffer=f,x.baseWidth=A,x.baseHeight=S,x.width=A,x.height=S,x.depth=R||E,x.isReady=!0,x.samples=h,x.generateMipMaps=s,x.samplingMode=l,x.type=o,x.format=c,x.label=d,x.comparisonFunction=m,this._internalTexturesCache.push(x),u){let N;if(CM(x.format)?N=this._setupFramebufferDepthAttachments(Fl(x.format),x.format!==19,x.width,x.height,h,x.format,!0):N=this._createRenderBuffer(x.width,x.height,h,-1,this._getRGBABufferInternalSizedFormat(x.type,x.format,x._useSRGBBuffer),-1),!N)throw new Error("Unable to create render buffer");x._autoMSAAManagement=!0;let F=x._hardwareTexture;F||(F=x._hardwareTexture=this._createHardwareTexture()),F.addMSAARenderBuffer(N)}return x}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||t)}createTexture(e,t,i,r,s=3,a=null,o=null,l=null,c=null,f=null,h=null,d,u,m,p){return this._createTextureBase(e,t,i,r,s,a,o,(..._)=>this._prepareWebGLTexture(..._,f),(_,g,v,x,A,S)=>{let E=this._gl,R=v.width===_&&v.height===g;A._creationFlags=m!=null?m:0;let I=this._getTexImageParametersForCreateTexture(A.format,A._useSRGBBuffer);if(R)return E.texImage2D(E.TEXTURE_2D,0,I.internalFormat,I.format,I.type,v),!1;let y=this._caps.maxTextureSize;if(v.width>y||v.height>y||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!this._workingCanvas||!this._workingContext||(this._workingCanvas.width=_,this._workingCanvas.height=g,this._workingContext.drawImage(v,0,0,v.width,v.height,0,0,_,g),E.texImage2D(E.TEXTURE_2D,0,I.internalFormat,I.format,I.type,this._workingCanvas),A.width=_,A.height=g),!1;{let M=new Pi(this,2);this._bindTextureDirectly(E.TEXTURE_2D,M,!0),E.texImage2D(E.TEXTURE_2D,0,I.internalFormat,I.format,I.type,v),this._rescaleTexture(M,A,r,I.format,()=>{this._releaseTexture(M),this._bindTextureDirectly(E.TEXTURE_2D,A,!0),S()})}return!0},l,c,f,h,d,u,p)}_getTexImageParametersForCreateTexture(e,t){let i,r;return this.webGLVersion===1?(i=this._getInternalFormat(e,t),r=i):(i=this._getInternalFormat(e,!1),r=this._getRGBABufferInternalSizedFormat(0,e,t)),{internalFormat:r,format:i,type:this._gl.UNSIGNED_BYTE}}_rescaleTexture(e,t,i,r,s){}_unpackFlipY(e){this._unpackFlipYCached!==e&&(this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,e?1:0),this.enableUnpackFlipYCached&&(this._unpackFlipYCached=e))}_getUnpackAlignement(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)}_getTextureTarget(e){return e.isCube?this._gl.TEXTURE_CUBE_MAP:e.is3D?this._gl.TEXTURE_3D:e.is2DArray||e.isMultiview?this._gl.TEXTURE_2D_ARRAY:this._gl.TEXTURE_2D}updateTextureSamplingMode(e,t,i=!1){let r=this._getTextureTarget(t),s=this._getSamplingParameters(e,t.useMipMaps||i);this._setTextureParameterInteger(r,this._gl.TEXTURE_MAG_FILTER,s.mag,t),this._setTextureParameterInteger(r,this._gl.TEXTURE_MIN_FILTER,s.min),i&&s.hasMipMaps&&(t.generateMipMaps=!0,this._gl.generateMipmap(r)),this._bindTextureDirectly(r,null),t.samplingMode=e}updateTextureDimensions(e,t,i,r=1){}updateTextureWrappingMode(e,t,i=null,r=null){let s=this._getTextureTarget(e);t!==null&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),i!==null&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i),e),e._cachedWrapV=i),(e.is2DArray||e.is3D)&&r!==null&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(r),e),e._cachedWrapR=r),this._bindTextureDirectly(s,null)}_uploadCompressedDataToTextureDirectly(e,t,i,r,s,a=0,o=0){let l=this._gl,c=l.TEXTURE_2D;if(e.isCube&&(c=l.TEXTURE_CUBE_MAP_POSITIVE_X+a),e._useSRGBBuffer)switch(t){case 37492:case 36196:this._caps.etc2?t=l.COMPRESSED_SRGB8_ETC2:e._useSRGBBuffer=!1;break;case 37496:this._caps.etc2?t=l.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:e._useSRGBBuffer=!1;break;case 36492:t=l.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case 37808:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case 37809:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR;break;case 37810:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR;break;case 37811:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR;break;case 37812:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR;break;case 37813:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR;break;case 37814:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR;break;case 37815:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR;break;case 37816:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR;break;case 37817:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR;break;case 37818:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR;break;case 37819:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR;break;case 37820:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR;break;case 37821:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR;break;case 33776:this._caps.s3tc_srgb?t=l.COMPRESSED_SRGB_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33777:this._caps.s3tc_srgb?t=l.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33779:this._caps.s3tc_srgb?t=l.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:e._useSRGBBuffer=!1;break;default:e._useSRGBBuffer=!1;break}if(e.generateMipMaps){let f=e._hardwareTexture;f.memoryAllocated||(l.texStorage2D(e.isCube?l.TEXTURE_CUBE_MAP:l.TEXTURE_2D,Math.floor(Math.log2(Math.max(i,r)))+1,t,e.width,e.height),f.memoryAllocated=!0),this._gl.compressedTexSubImage2D(c,o,0,0,i,r,t,s)}else this._gl.compressedTexImage2D(c,o,t,i,r,0,s)}_uploadDataToTextureDirectly(e,t,i=0,r=0,s,a=!1){let o=this._gl,l=this._getWebGLTextureType(e.type),c=this._getInternalFormat(e.format),f=s===void 0?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(s,e._useSRGBBuffer);this._unpackFlipY(e.invertY);let h=o.TEXTURE_2D;e.isCube&&(h=o.TEXTURE_CUBE_MAP_POSITIVE_X+i);let d=Math.round(Math.log(e.width)*Math.LOG2E),u=Math.round(Math.log(e.height)*Math.LOG2E),m=a?e.width:Math.pow(2,Math.max(d-r,0)),p=a?e.height:Math.pow(2,Math.max(u-r,0));o.texImage2D(h,r,f,m,p,0,c,l,t)}updateTextureData(e,t,i,r,s,a,o=0,l=0,c=!1){let f=this._gl,h=this._getWebGLTextureType(e.type),d=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);let u=f.TEXTURE_2D,m=f.TEXTURE_2D;e.isCube&&(m=f.TEXTURE_CUBE_MAP_POSITIVE_X+o,u=f.TEXTURE_CUBE_MAP),this._bindTextureDirectly(u,e,!0),f.texSubImage2D(m,l,i,r,s,a,d,h,t),c&&this._gl.generateMipmap(m),this._bindTextureDirectly(u,null)}_uploadArrayBufferViewToTexture(e,t,i=0,r=0){let s=this._gl,a=e.isCube?s.TEXTURE_CUBE_MAP:s.TEXTURE_2D;this._bindTextureDirectly(a,e,!0),this._uploadDataToTextureDirectly(e,t,i,r),this._bindTextureDirectly(a,null,!0)}_prepareWebGLTextureContinuation(e,t,i,r,s){let a=this._gl;if(!a)return;let o=this._getSamplingParameters(s,!i);a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,o.mag),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,o.min),!i&&!r&&a.generateMipmap(a.TEXTURE_2D),this._bindTextureDirectly(a.TEXTURE_2D,null),t&&t.removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}_prepareWebGLTexture(e,t,i,r,s,a,o,l,c,f){let h=this.getCaps().maxTextureSize,d=Math.min(h,this.needPOTTextures?gn(r.width,h):r.width),u=Math.min(h,this.needPOTTextures?gn(r.height,h):r.height),m=this._gl;if(m){if(!e._hardwareTexture){i&&i.removePendingData(e);return}this._bindTextureDirectly(m.TEXTURE_2D,e,!0),this._unpackFlipY(s===void 0?!0:!!s),e.baseWidth=r.width,e.baseHeight=r.height,e.width=d,e.height=u,e.isReady=!0,e.type=e.type!==-1?e.type:0,e.format=e.format!==-1?e.format:f!=null?f:t===".jpg"&&!e._useSRGBBuffer?4:5,!l(d,u,r,t,e,()=>{this._prepareWebGLTextureContinuation(e,i,a,o,c)})&&this._prepareWebGLTextureContinuation(e,i,a,o,c)}}_getInternalFormatFromDepthTextureFormat(e,t,i){let r=this._gl;if(!t)return r.STENCIL_INDEX8;let a=i?r.DEPTH_STENCIL:r.DEPTH_COMPONENT;return this.webGLVersion>1?e===15?a=r.DEPTH_COMPONENT16:e===16?a=r.DEPTH_COMPONENT24:e===17||e===13?a=i?r.DEPTH24_STENCIL8:r.DEPTH_COMPONENT24:e===14?a=r.DEPTH_COMPONENT32F:e===18&&(a=i?r.DEPTH32F_STENCIL8:r.DEPTH_COMPONENT32F):a=r.DEPTH_COMPONENT16,a}_getWebGLTextureTypeFromDepthTextureFormat(e){let t=this._gl,i=t.UNSIGNED_INT;return e===15?i=t.UNSIGNED_SHORT:e===17||e===13?i=t.UNSIGNED_INT_24_8:e===14?i=t.FLOAT:e===18?i=t.FLOAT_32_UNSIGNED_INT_24_8_REV:e===19&&(i=t.UNSIGNED_BYTE),i}_setupFramebufferDepthAttachments(e,t,i,r,s=1,a,o=!1){let l=this._gl;a=a!=null?a:e?13:14;let c=this._getInternalFormatFromDepthTextureFormat(a,t,e);return e&&t?this._createRenderBuffer(i,r,s,l.DEPTH_STENCIL,c,o?-1:l.DEPTH_STENCIL_ATTACHMENT):t?this._createRenderBuffer(i,r,s,c,c,o?-1:l.DEPTH_ATTACHMENT):e?this._createRenderBuffer(i,r,s,c,c,o?-1:l.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,i,r,s,a,o=!0){let c=this._gl.createRenderbuffer();return this._updateRenderBuffer(c,e,t,i,r,s,a,o)}_updateRenderBuffer(e,t,i,r,s,a,o,l=!0){let c=this._gl;return c.bindRenderbuffer(c.RENDERBUFFER,e),r>1&&c.renderbufferStorageMultisample?c.renderbufferStorageMultisample(c.RENDERBUFFER,r,a,t,i):c.renderbufferStorage(c.RENDERBUFFER,s,t,i),o!==-1&&c.framebufferRenderbuffer(c.FRAMEBUFFER,o,c.RENDERBUFFER,e),l&&c.bindRenderbuffer(c.RENDERBUFFER,null),e}_releaseTexture(e){this._deleteTexture(e._hardwareTexture),this.unbindAllTextures();let t=this._internalTexturesCache.indexOf(e);t!==-1&&this._internalTexturesCache.splice(t,1),e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureLow&&e._lodTextureLow.dispose(),e._irradianceTexture&&e._irradianceTexture.dispose()}_deleteTexture(e){e==null||e.release()}_setProgram(e){this._currentProgram!==e&&(b3(e,this._gl),this._currentProgram=e)}bindSamplers(e){let t=e.getPipelineContext();this._setProgram(t.program);let i=e.getSamplers();for(let r=0;r-1;if(i&&a&&(this._activeChannel=t._associatedChannel),this._boundTexturesCache[this._activeChannel]!==t||r){if(this._activateCurrentTexture(),t&&t.isMultiview)throw te.Error(["_bindTextureDirectly called with a multiview texture!",e,t]),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(e,(c=(l=t==null?void 0:t._hardwareTexture)==null?void 0:l.underlyingResource)!=null?c:null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)}else i&&(s=!0,this._activateCurrentTexture());return a&&!i&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),s}_bindTexture(e,t,i){if(e===void 0)return;t&&(t._associatedChannel=e),this._activeChannel=e;let r=t?this._getTextureTarget(t):this._gl.TEXTURE_2D;this._bindTextureDirectly(r,t)}unbindAllTextures(){for(let e=0;e1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))}setTexture(e,t,i,r){e!==void 0&&(t&&(this._boundUniforms[e]=t),this._setTexture(e,i))}_bindSamplerUniformToChannel(e,t){let i=this._boundUniforms[e];!i||i._currentState===t||(this._gl.uniform1i(i,t),i._currentState=t)}_getTextureWrapMode(e){switch(e){case 1:return this._gl.REPEAT;case 0:return this._gl.CLAMP_TO_EDGE;case 2:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT}_setTexture(e,t,i=!1,r=!1,s=""){if(!t)return this._boundTexturesCache[e]!=null&&(this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))),!1;if(t.video){this._activeChannel=e;let c=t.getInternalTexture();c&&(c._associatedChannel=e),t.update()}else if(t.delayLoadState===4)return t.delayLoad(),!1;let a;r?a=t.depthStencilTexture:t.isReady()?a=t.getInternalTexture():t.isCube?a=this.emptyCubeTexture:t.is3D?a=this.emptyTexture3D:t.is2DArray?a=this.emptyTexture2DArray:a=this.emptyTexture,!i&&a&&(a._associatedChannel=e);let o=!0;this._boundTexturesCache[e]===a&&(i||this._bindSamplerUniformToChannel(a._associatedChannel,e),o=!1),this._activeChannel=e;let l=this._getTextureTarget(a);if(o&&this._bindTextureDirectly(l,a,i),a&&!a.isMultiview){if(a.isCube&&a._cachedCoordinatesMode!==t.coordinatesMode){a._cachedCoordinatesMode=t.coordinatesMode;let c=t.coordinatesMode!==3&&t.coordinatesMode!==5?1:0;t.wrapU=c,t.wrapV=c}a._cachedWrapU!==t.wrapU&&(a._cachedWrapU=t.wrapU,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),a)),a._cachedWrapV!==t.wrapV&&(a._cachedWrapV=t.wrapV,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),a)),a.is3D&&a._cachedWrapR!==t.wrapR&&(a._cachedWrapR=t.wrapR,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),a)),this._setAnisotropicLevel(l,a,t.anisotropicFilteringLevel)}return!0}setTextureArray(e,t,i,r){if(!(e===void 0||!t)){(!this._textureUnits||this._textureUnits.length!==i.length)&&(this._textureUnits=new Int32Array(i.length));for(let s=0;s=this._caps.maxVertexAttribs||!this._vertexAttribArraysEnabled[e]||this.disableAttributeByIndex(e)}releaseEffects(){this._compiledEffects={},this.onReleaseEffectsObservable.notifyObservers(this)}dispose(){var e;fr()&&this._renderingCanvas&&(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._onContextRestored&&this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored)),super.dispose(),this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.unbindAllAttributes(),this._boundUniforms={},this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers.length=0,this._currentProgram=null,this._creationOptions.loseContextOnDispose&&((e=this._gl.getExtension("WEBGL_lose_context"))==null||e.loseContext()),fT(this._gl)}attachContextLostEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextlost",e,!1)}attachContextRestoredEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextrestored",e,!1)}getError(){return this._gl.getError()}_canRenderToFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(1)}_canRenderToHalfFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(2)}_canRenderToFramebuffer(e){let t=this._gl;for(;t.getError()!==t.NO_ERROR;);let i=!0,r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r),t.texImage2D(t.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(e),1,1,0,t.RGBA,this._getWebGLTextureType(e),null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST);let s=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,s),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,0);let a=t.checkFramebufferStatus(t.FRAMEBUFFER);if(i=i&&a===t.FRAMEBUFFER_COMPLETE,i=i&&t.getError()===t.NO_ERROR,i&&(t.clear(t.COLOR_BUFFER_BIT),i=i&&t.getError()===t.NO_ERROR),i){t.bindFramebuffer(t.FRAMEBUFFER,null);let o=t.RGBA,l=t.UNSIGNED_BYTE,c=new Uint8Array(4);t.readPixels(0,0,1,1,o,l,c),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(r),t.deleteFramebuffer(s),t.bindFramebuffer(t.FRAMEBUFFER,null);!i&&t.getError()!==t.NO_ERROR;);return i}_getWebGLTextureType(e){if(this._webGLVersion===1){switch(e){case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT_OES;case 0:return this._gl.UNSIGNED_BYTE;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5}return this._gl.UNSIGNED_BYTE}switch(e){case 3:return this._gl.BYTE;case 0:return this._gl.UNSIGNED_BYTE;case 4:return this._gl.SHORT;case 5:return this._gl.UNSIGNED_SHORT;case 6:return this._gl.INT;case 7:return this._gl.UNSIGNED_INT;case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5;case 11:return this._gl.UNSIGNED_INT_2_10_10_10_REV;case 12:return this._gl.UNSIGNED_INT_24_8;case 13:return this._gl.UNSIGNED_INT_10F_11F_11F_REV;case 14:return this._gl.UNSIGNED_INT_5_9_9_9_REV;case 15:return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV}return this._gl.UNSIGNED_BYTE}_getInternalFormat(e,t=!1){let i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA;switch(e){case 0:i=this._gl.ALPHA;break;case 1:i=this._gl.LUMINANCE;break;case 2:i=this._gl.LUMINANCE_ALPHA;break;case 6:case 33322:case 36760:i=this._gl.RED;break;case 7:case 33324:case 36761:i=this._gl.RG;break;case 4:case 32852:case 36762:i=t?this._glSRGBExtensionValues.SRGB:this._gl.RGB;break;case 5:case 32859:case 36763:i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA;break}if(this._webGLVersion>1)switch(e){case 8:i=this._gl.RED_INTEGER;break;case 9:i=this._gl.RG_INTEGER;break;case 10:i=this._gl.RGB_INTEGER;break;case 11:i=this._gl.RGBA_INTEGER;break}return i}_getRGBABufferInternalSizedFormat(e,t,i=!1){if(this._webGLVersion===1){if(t!==void 0)switch(t){case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;case 4:return i?this._glSRGBExtensionValues.SRGB:this._gl.RGB}return this._gl.RGBA}switch(e){case 3:switch(t){case 6:return this._gl.R8_SNORM;case 7:return this._gl.RG8_SNORM;case 4:return this._gl.RGB8_SNORM;case 8:return this._gl.R8I;case 9:return this._gl.RG8I;case 10:return this._gl.RGB8I;case 11:return this._gl.RGBA8I;default:return this._gl.RGBA8_SNORM}case 0:switch(t){case 6:return this._gl.R8;case 7:return this._gl.RG8;case 4:return i?this._glSRGBExtensionValues.SRGB8:this._gl.RGB8;case 5:return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8;case 8:return this._gl.R8UI;case 9:return this._gl.RG8UI;case 10:return this._gl.RGB8UI;case 11:return this._gl.RGBA8UI;case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;default:return this._gl.RGBA8}case 4:switch(t){case 8:return this._gl.R16I;case 36760:return this._gl.R16_SNORM_EXT;case 36761:return this._gl.RG16_SNORM_EXT;case 36762:return this._gl.RGB16_SNORM_EXT;case 36763:return this._gl.RGBA16_SNORM_EXT;case 9:return this._gl.RG16I;case 10:return this._gl.RGB16I;case 11:return this._gl.RGBA16I;default:return this._gl.RGBA16I}case 5:switch(t){case 8:return this._gl.R16UI;case 33322:return this._gl.R16_EXT;case 33324:return this._gl.RG16_EXT;case 32852:return this._gl.RGB16_EXT;case 32859:return this._gl.RGBA16_EXT;case 9:return this._gl.RG16UI;case 10:return this._gl.RGB16UI;case 11:return this._gl.RGBA16UI;default:return this._gl.RGBA16UI}case 6:switch(t){case 8:return this._gl.R32I;case 9:return this._gl.RG32I;case 10:return this._gl.RGB32I;case 11:return this._gl.RGBA32I;default:return this._gl.RGBA32I}case 7:switch(t){case 8:return this._gl.R32UI;case 9:return this._gl.RG32UI;case 10:return this._gl.RGB32UI;case 11:return this._gl.RGBA32UI;default:return this._gl.RGBA32UI}case 1:switch(t){case 6:return this._gl.R32F;case 7:return this._gl.RG32F;case 4:return this._gl.RGB32F;case 5:return this._gl.RGBA32F;default:return this._gl.RGBA32F}case 2:switch(t){case 6:return this._gl.R16F;case 7:return this._gl.RG16F;case 4:return this._gl.RGB16F;case 5:return this._gl.RGBA16F;default:return this._gl.RGBA16F}case 10:return this._gl.RGB565;case 13:return this._gl.R11F_G11F_B10F;case 14:return this._gl.RGB9_E5;case 8:return this._gl.RGBA4;case 9:return this._gl.RGB5_A1;case 11:switch(t){case 5:return this._gl.RGB10_A2;case 11:return this._gl.RGB10_A2UI;default:return this._gl.RGB10_A2}}return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8}readPixels(e,t,i,r,s=!0,a=!0,o=null){let l=s?4:3,c=s?this._gl.RGBA:this._gl.RGB,f=i*r*l;if(!o)o=new Uint8Array(f);else if(o.length{wl();DT=class{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new PM(e)}sampleFrame(e=pr.Now){if(this._enabled){if(this._lastFrameTimeMs!=null){let t=e-this._lastFrameTimeMs;this._rollingFrameTime.add(t)}this._lastFrameTimeMs=e}}get averageFrameTime(){return this._rollingFrameTime.average}get averageFrameTimeVariance(){return this._rollingFrameTime.variance}get instantaneousFrameTime(){return this._rollingFrameTime.history(0)}get averageFPS(){return 1e3/this._rollingFrameTime.average}get instantaneousFPS(){let e=this._rollingFrameTime.history(0);return e===0?0:1e3/e}get isSaturated(){return this._rollingFrameTime.isSaturated()}enable(){this._enabled=!0}disable(){this._enabled=!1,this._lastFrameTimeMs=null}get isEnabled(){return this._enabled}reset(){this._lastFrameTimeMs=null,this._rollingFrameTime.reset()}},PM=class{constructor(e){this._samples=new Array(e),this.reset()}add(e){let t;if(this.isSaturated()){let i=this._samples[this._pos];t=i-this.average,this.average-=t/(this._sampleCount-1),this._m2-=t*(i-this.average)}else this._sampleCount++;t=e-this.average,this.average+=t/this._sampleCount,this._m2+=t*(e-this.average),this.variance=this._m2/(this._sampleCount-1),this._samples[this._pos]=e,this._pos++,this._pos%=this._samples.length}history(e){if(e>=this._sampleCount||e>=this._samples.length)return 0;let t=this._wrapPosition(this._pos-1);return this._samples[this._wrapPosition(t-e)]}isSaturated(){return this._sampleCount>=this._samples.length}reset(){this.average=0,this.variance=0,this._sampleCount=0,this._pos=0,this._m2=0}_wrapPosition(e){let t=this._samples.length;return(e%t+t)%t}}});var $3=C(()=>{Zn();bt.prototype.setAlphaMode=function(n,e=!1,t=0){if(this._alphaMode[t]===n){if(!e){let r=n===0;this.depthCullingState.depthMask!==r&&(this.depthCullingState.depthMask=r)}return}let i=n===0;this._alphaState.setAlphaBlend(!i,t),this._alphaState.setAlphaMode(n,t),e||(this.depthCullingState.depthMask=i),this._alphaMode[t]=n}});function J3(n,e,t,i){let r,s=1;i===1?r=new Float32Array(e*t*4):i===2?(r=new Uint16Array(e*t*4),s=15360):i===7?r=new Uint32Array(e*t*4):r=new Uint8Array(e*t*4);for(let a=0;a{vs();Pt();Zn();$a();bt.prototype.updateRawTexture=function(n,e,t,i,r=null,s=0,a=!1){if(!n)return;let o=this._getRGBABufferInternalSizedFormat(s,t,a),l=this._getInternalFormat(t),c=this._getWebGLTextureType(s);this._bindTextureDirectly(this._gl.TEXTURE_2D,n,!0),this._unpackFlipY(i===void 0?!0:!!i),this._doNotHandleContextLost||(n._bufferView=e,n.format=t,n.type=s,n.invertY=i,n._compression=r),n.width%4!==0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),r&&e?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[r],n.width,n.height,0,e):this._gl.texImage2D(this._gl.TEXTURE_2D,0,o,n.width,n.height,0,l,c,e),n.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),n.isReady=!0};bt.prototype.createRawTexture=function(n,e,t,i,r,s,a,o=null,l=0,c=0,f=!1){let h=new Pi(this,3);h.baseWidth=e,h.baseHeight=t,h.width=e,h.height=t,h.format=i,h.generateMipMaps=r,h.samplingMode=a,h.invertY=s,h._compression=o,h.type=l,h._useSRGBBuffer=this._getUseSRGBBuffer(f,!r),this._doNotHandleContextLost||(h._bufferView=n),this.updateRawTexture(h,n,i,s,o,l,h._useSRGBBuffer),this._bindTextureDirectly(this._gl.TEXTURE_2D,h,!0);let d=this._getSamplingParameters(a,r);return this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,d.mag),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,d.min),r&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._internalTexturesCache.push(h),h};bt.prototype.createRawCubeTexture=function(n,e,t,i,r,s,a,o=null){let l=this._gl,c=new Pi(this,8);c.isCube=!0,c.format=t,c.type=i,this._doNotHandleContextLost||(c._bufferViewArray=n);let f=this._getWebGLTextureType(i),h=this._getInternalFormat(t);h===l.RGB&&(h=l.RGBA),f===l.FLOAT&&!this._caps.textureFloatLinearFiltering?(r=!1,a=1,te.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):f===this._gl.HALF_FLOAT_OES&&!this._caps.textureHalfFloatLinearFiltering?(r=!1,a=1,te.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):f===l.FLOAT&&!this._caps.textureFloatRender?(r=!1,te.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):f===l.HALF_FLOAT&&!this._caps.colorBufferFloat&&(r=!1,te.Warn("Render to half float textures is not supported. Mipmap generation forced to false."));let d=e,u=d;if(c.width=d,c.height=u,c.invertY=s,c._compression=o,!this.needPOTTextures||Lh(c.width)&&Lh(c.height)||(r=!1),n)this.updateRawCubeTexture(c,n,t,i,s,o);else{let _=this._getRGBABufferInternalSizedFormat(i),g=0;this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,c,!0);for(let v=0;v<6;v++)o?l.compressedTexImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+v,g,this.getCaps().s3tc[o],c.width,c.height,0,void 0):l.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+v,g,_,c.width,c.height,0,h,f,null);this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)}this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,c,!0),n&&r&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);let p=this._getSamplingParameters(a,r);return l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MAG_FILTER,p.mag),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MIN_FILTER,p.min),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_S,l.CLAMP_TO_EDGE),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_T,l.CLAMP_TO_EDGE),this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,null),c.generateMipMaps=r,c.samplingMode=a,c.isReady=!0,c};bt.prototype.updateRawCubeTexture=function(n,e,t,i,r,s=null,a=0){n._bufferViewArray=e,n.format=t,n.type=i,n.invertY=r,n._compression=s;let o=this._gl,l=this._getWebGLTextureType(i),c=this._getInternalFormat(t),f=this._getRGBABufferInternalSizedFormat(i),h=!1;c===o.RGB&&(c=o.RGBA,h=!0),this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,n,!0),this._unpackFlipY(r===void 0?!0:!!r),n.width%4!==0&&o.pixelStorei(o.UNPACK_ALIGNMENT,1);for(let u=0;u<6;u++){let m=e[u];s?o.compressedTexImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+u,a,this.getCaps().s3tc[s],n.width,n.height,0,m):(h&&(m=J3(m,n.width,n.height,i)),o.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+u,a,f,n.width,n.height,0,c,l,m))}(!this.needPOTTextures||Lh(n.width)&&Lh(n.height))&&n.generateMipMaps&&a===0&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),n.isReady=!0};bt.prototype.createRawCubeTextureFromUrl=function(n,e,t,i,r,s,a,o,l=null,c=null,f=3,h=!1){let d=this._gl,u=this.createRawCubeTexture(null,t,i,r,!s,h,f,null);e==null||e.addPendingData(u),u.url=n,u.isReady=!1,this._internalTexturesCache.push(u);let m=(_,g)=>{e==null||e.removePendingData(u),c&&c(_?_.status+" "+_.statusText:"Failed to parse texture data",g)},p=async _=>{if(!u._hardwareTexture)return;let g=a(_);if(!g)return;let v=g instanceof Promise?await g:g,x=u.width;if(o){let A=this._getWebGLTextureType(r),S=this._getInternalFormat(i),E=this._getRGBABufferInternalSizedFormat(r),R=!1;S===d.RGB&&(S=d.RGBA,R=!0),this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,u,!0),this._unpackFlipY(!1);let I=o(v);for(let y=0;y>y;for(let D=0;D<6;D++){let O=I[y][D];R&&(O=J3(O,M,M,r)),d.texImage2D(D,y,E,M,M,0,S,A,O)}}this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(u,v,i,r,h);u.isReady=!0,e==null||e.removePendingData(u),u.onLoadedObservable.notifyObservers(u),u.onLoadedObservable.clear(),l&&l()};return this._loadFile(n,_=>{p(_).catch(g=>{m(void 0,g)})},void 0,e==null?void 0:e.offlineProvider,!0,m),u};bt.prototype.createRawTexture2DArray=e2(!1);bt.prototype.createRawTexture3D=e2(!0);bt.prototype.updateRawTexture2DArray=t2(!1);bt.prototype.updateRawTexture3D=t2(!0)});var r2=C(()=>{Zn();af();bt.prototype._readTexturePixelsSync=function(n,e,t,i=-1,r=0,s=null,a=!0,o=!1,l=0,c=0){var d,u,m;let f=this._gl;if(!f)throw new Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){let p=f.createFramebuffer();if(!p)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=p}f.bindFramebuffer(f.FRAMEBUFFER,this._dummyFramebuffer),i>-1&&(n.is2DArray||n.is3D)?f.framebufferTextureLayer(f.FRAMEBUFFER,f.COLOR_ATTACHMENT0,(d=n._hardwareTexture)==null?void 0:d.underlyingResource,r,i):i>-1?f.framebufferTexture2D(f.FRAMEBUFFER,f.COLOR_ATTACHMENT0,f.TEXTURE_CUBE_MAP_POSITIVE_X+i,(u=n._hardwareTexture)==null?void 0:u.underlyingResource,r):f.framebufferTexture2D(f.FRAMEBUFFER,f.COLOR_ATTACHMENT0,f.TEXTURE_2D,(m=n._hardwareTexture)==null?void 0:m.underlyingResource,r);let h=n.type!==void 0?this._getWebGLTextureType(n.type):f.UNSIGNED_BYTE;return o?s||(s=S3(n.type,4*e*t)):h===f.UNSIGNED_BYTE?(s||(s=new Uint8Array(4*e*t)),h=f.UNSIGNED_BYTE):(s||(s=new Float32Array(4*e*t)),h=f.FLOAT),a&&this.flushFramebuffer(),f.readPixels(l,c,e,t,f.RGBA,h,s),f.bindFramebuffer(f.FRAMEBUFFER,this._currentFramebuffer),s};bt.prototype._readTexturePixels=function(n,e,t,i=-1,r=0,s=null,a=!0,o=!1,l=0,c=0){return Promise.resolve(this._readTexturePixelsSync(n,e,t,i,r,s,a,o,l,c))}});var n2=C(()=>{Zn();bt.prototype.updateDynamicIndexBuffer=function(n,e,t=0){this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(n);let i;n.is32Bits?i=e instanceof Uint32Array?e:new Uint32Array(e):i=e instanceof Uint16Array?e:new Uint16Array(e),this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,i,this._gl.DYNAMIC_DRAW),this._resetIndexBufferBinding()};bt.prototype.updateDynamicVertexBuffer=function(n,e,t,i){this.bindArrayBuffer(n),t===void 0&&(t=0);let r=e.byteLength||e.length;i===void 0||i>=r&&t===0?e instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,t,new Float32Array(e)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,t,e):e instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,t,new Float32Array(e).subarray(0,i/4)):(ArrayBuffer.isView(e)?e=new Uint8Array(e.buffer,e.byteOffset,i):e=new Uint8Array(e,0,i),this._gl.bufferSubData(this._gl.ARRAY_BUFFER,t,e)),this._resetVertexBufferBinding()}});var s2=C(()=>{Zn();vs();Pt();$a();bt.prototype._createDepthStencilCubeTexture=function(n,e){let t=new Pi(this,12);if(t.isCube=!0,this.webGLVersion===1)return te.Error("Depth cube texture is not supported by WebGL 1."),t;let i={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...e},r=this._gl;this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,t,!0),this._setupDepthStencilTexture(t,n,i.bilinearFiltering,i.comparisonFunction);for(let s=0;s<6;s++)i.generateStencil?r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+s,0,r.DEPTH24_STENCIL8,n,n,0,r.DEPTH_STENCIL,r.UNSIGNED_INT_24_8,null):r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+s,0,r.DEPTH_COMPONENT24,n,n,0,r.DEPTH_COMPONENT,r.UNSIGNED_INT,null);return this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),this._internalTexturesCache.push(t),t};bt.prototype._setCubeMapTextureParams=function(n,e,t){let i=this._gl;i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_MAG_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_MIN_FILTER,e?i.LINEAR_MIPMAP_LINEAR:i.LINEAR),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),n.samplingMode=e?3:2,e&&this.getCaps().textureMaxLevel&&t!==void 0&&t>0&&(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_MAX_LEVEL,t),n._maxLodLevel=t),this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,null)};bt.prototype.createCubeTexture=function(n,e,t,i,r=null,s=null,a,o=null,l=!1,c=0,f=0,h=null,d,u=!1,m=null){let p=this._gl;return this.createCubeTextureBase(n,e,t,!!i,r,s,a,o,l,c,f,h,_=>this._bindTextureDirectly(p.TEXTURE_CUBE_MAP,_,!0),(_,g)=>{let v=this.needPOTTextures?gn(g[0].width,this._caps.maxCubemapTextureSize):g[0].width,x=v,A=[p.TEXTURE_CUBE_MAP_POSITIVE_X,p.TEXTURE_CUBE_MAP_POSITIVE_Y,p.TEXTURE_CUBE_MAP_POSITIVE_Z,p.TEXTURE_CUBE_MAP_NEGATIVE_X,p.TEXTURE_CUBE_MAP_NEGATIVE_Y,p.TEXTURE_CUBE_MAP_NEGATIVE_Z];this._bindTextureDirectly(p.TEXTURE_CUBE_MAP,_,!0),this._unpackFlipY(!1);let S=a?this._getInternalFormat(a,_._useSRGBBuffer):_._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:p.RGBA,E=a?this._getInternalFormat(a):p.RGBA;_._useSRGBBuffer&&this.webGLVersion===1&&(E=S);for(let R=0;R{O_();LT=class{get depthStencilTexture(){return this._depthStencilTexture}setDepthStencilTexture(e,t=!0){t&&this._depthStencilTexture&&this._depthStencilTexture.dispose(),this._depthStencilTexture=e,this._generateDepthBuffer=this._generateStencilBuffer=this._depthStencilTextureWithStencil=!1,e&&(this._generateDepthBuffer=!0,this._generateStencilBuffer=this._depthStencilTextureWithStencil=Fl(e.format))}get depthStencilTextureWithStencil(){return this._depthStencilTextureWithStencil}get isCube(){return this._isCube}get isMulti(){return this._isMulti}get is2DArray(){return this.layers>0}get is3D(){return this.depth>0}get size(){return this.width}get width(){var e;return(e=this._size.width)!=null?e:this._size}get height(){var e;return(e=this._size.height)!=null?e:this._size}get layers(){return this._size.layers||0}get depth(){return this._size.depth||0}get texture(){var e,t;return(t=(e=this._textures)==null?void 0:e[0])!=null?t:null}get textures(){return this._textures}get faceIndices(){return this._faceIndices}get layerIndices(){return this._layerIndices}getBaseArrayLayer(e){var s,a,o,l;if(!this._textures)return-1;let t=this._textures[e],i=(a=(s=this._layerIndices)==null?void 0:s[e])!=null?a:0,r=(l=(o=this._faceIndices)==null?void 0:o[e])!=null?l:0;return t.isCube?i*6+r:t.is3D?0:i}get samples(){return this._samples}setSamples(e,t=!0,i=!1){if(this.samples===e&&!i)return e;let r=this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,e,t):this._engine.updateRenderTargetTextureSampleCount(this,e);return this._samples=e,r}resolveMSAATextures(){this.isMulti?this._engine.resolveMultiFramebuffer(this):this._engine.resolveFramebuffer(this)}generateMipMaps(){this._engine._currentRenderTarget===this&&(this.isMulti?this._engine.unBindMultiColorAttachmentFramebuffer(this,!0):this._engine.unBindFramebuffer(this,!0)),this.isMulti?this._engine.generateMipMapsMultiFramebuffer(this):this._engine.generateMipMapsFramebuffer(this)}constructor(e,t,i,r,s){this._textures=null,this._faceIndices=null,this._layerIndices=null,this._samples=1,this._attachments=null,this._generateStencilBuffer=!1,this._generateDepthBuffer=!1,this._depthStencilTextureWithStencil=!1,this.disableAutomaticMSAAResolve=!1,this.resolveMSAAColors=!0,this.resolveMSAADepth=!1,this.resolveMSAAStencil=!1,this.depthReadOnly=!1,this.stencilReadOnly=!1,this._isMulti=e,this._isCube=t,this._size=i,this._engine=r,this._depthStencilTexture=null,this.label=s}setTextures(e){Array.isArray(e)?this._textures=e:e?this._textures=[e]:this._textures=null}setTexture(e,t=0,i=!0){this._textures||(this._textures=[]),this._textures[t]!==e&&(this._textures[t]&&i&&this._textures[t].dispose(),this._textures[t]=e)}setLayerAndFaceIndices(e,t){this._layerIndices=e,this._faceIndices=t}setLayerAndFaceIndex(e=0,t,i){this._layerIndices||(this._layerIndices=[]),this._faceIndices||(this._faceIndices=[]),t!==void 0&&t>=0&&(this._layerIndices[e]=t),i!==void 0&&i>=0&&(this._faceIndices[e]=i)}createDepthStencilTexture(e=0,t=!0,i=!1,r=1,s=14,a){var o;return(o=this._depthStencilTexture)==null||o.dispose(),this._depthStencilTextureWithStencil=i,this._depthStencilTextureLabel=a,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:i,isCube:this._isCube,samples:r,depthTextureFormat:s,label:a},this),this._depthStencilTexture}_shareDepth(e){this.shareDepth(e)}shareDepth(e){this._depthStencilTexture&&(e._depthStencilTexture&&e._depthStencilTexture.dispose(),e._depthStencilTexture=this._depthStencilTexture,e._depthStencilTextureWithStencil=this._depthStencilTextureWithStencil,this._depthStencilTexture.incrementReferences())}_swapAndDie(e){this.texture&&this.texture._swapAndDie(e),this._textures=null,this.dispose(!0)}_cloneRenderTargetWrapper(){var t,i,r,s,a,o,l,c;let e=null;if(this._isMulti){let f=this.textures;if(f&&f.length>0){let h=!1,d=f.length,u=-1,m=f[f.length-1]._source;(m===14||m===12)&&(h=!0,u=f[f.length-1].format,d--);let p=[],_=[],g=[],v=[],x=[],A=[],S=[],E={};for(let y=0;y1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}}releaseTextures(){if(this._textures)for(let e=0;e{a2();O_();OT=class extends LT{setDepthStencilTexture(e,t=!0){if(super.setDepthStencilTexture(e,t),!e)return;let i=this._engine,r=this._context,s=e._hardwareTexture;if(s&&e._autoMSAAManagement&&this._MSAAFramebuffer){let a=i._currentFramebuffer;i._bindUnboundFramebuffer(this._MSAAFramebuffer),r.framebufferRenderbuffer(r.FRAMEBUFFER,Fl(e.format)?r.DEPTH_STENCIL_ATTACHMENT:r.DEPTH_ATTACHMENT,r.RENDERBUFFER,s.getMSAARenderBuffer()),i._bindUnboundFramebuffer(a)}}constructor(e,t,i,r,s){super(e,t,i,r),this._framebuffer=null,this._depthStencilBuffer=null,this._MSAAFramebuffer=null,this._colorTextureArray=null,this._depthStencilTextureArray=null,this._disposeOnlyFramebuffers=!1,this._currentLOD=0,this._context=s}_cloneRenderTargetWrapper(){let e;return this._colorTextureArray&&this._depthStencilTextureArray?(e=this._engine.createMultiviewRenderTargetTexture(this.width,this.height),e.texture.isReady=!0):e=super._cloneRenderTargetWrapper(),e}_swapRenderTargetWrapper(e){super._swapRenderTargetWrapper(e),e._framebuffer=this._framebuffer,e._depthStencilBuffer=this._depthStencilBuffer,e._MSAAFramebuffer=this._MSAAFramebuffer,e._colorTextureArray=this._colorTextureArray,e._depthStencilTextureArray=this._depthStencilTextureArray,this._framebuffer=this._depthStencilBuffer=this._MSAAFramebuffer=this._colorTextureArray=this._depthStencilTextureArray=null}createDepthStencilTexture(e=0,t=!0,i=!1,r=1,s=14,a){if(this._depthStencilBuffer){let o=this._engine,l=o._currentFramebuffer,c=this._context;o._bindUnboundFramebuffer(this._framebuffer),c.framebufferRenderbuffer(c.FRAMEBUFFER,c.DEPTH_STENCIL_ATTACHMENT,c.RENDERBUFFER,null),c.framebufferRenderbuffer(c.FRAMEBUFFER,c.DEPTH_ATTACHMENT,c.RENDERBUFFER,null),c.framebufferRenderbuffer(c.FRAMEBUFFER,c.STENCIL_ATTACHMENT,c.RENDERBUFFER,null),o._bindUnboundFramebuffer(l),c.deleteRenderbuffer(this._depthStencilBuffer),this._depthStencilBuffer=null}return super.createDepthStencilTexture(e,t,i,r,s,a)}shareDepth(e){super.shareDepth(e);let t=this._context,i=this._depthStencilBuffer,r=e._MSAAFramebuffer||e._framebuffer,s=this._engine;e._depthStencilBuffer&&e._depthStencilBuffer!==i&&t.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=i;let a=e._generateStencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;s._bindUnboundFramebuffer(r),t.framebufferRenderbuffer(t.FRAMEBUFFER,a,t.RENDERBUFFER,i),s._bindUnboundFramebuffer(null)}_bindTextureRenderTarget(e,t=0,i,r=0){var f,h,d,u;let s=e._hardwareTexture;if(!s)return;let a=this._framebuffer,o=this._engine,l=o._currentFramebuffer;o._bindUnboundFramebuffer(a);let c;if(o.webGLVersion>1){let m=this._context;c=m["COLOR_ATTACHMENT"+t],e.is2DArray||e.is3D?(i=(h=i!=null?i:(f=this.layerIndices)==null?void 0:f[t])!=null?h:0,m.framebufferTextureLayer(m.FRAMEBUFFER,c,s.underlyingResource,r,i)):e.isCube?(i=(u=i!=null?i:(d=this.faceIndices)==null?void 0:d[t])!=null?u:0,m.framebufferTexture2D(m.FRAMEBUFFER,c,m.TEXTURE_CUBE_MAP_POSITIVE_X+i,s.underlyingResource,r)):m.framebufferTexture2D(m.FRAMEBUFFER,c,m.TEXTURE_2D,s.underlyingResource,r)}else{let m=this._context;c=m["COLOR_ATTACHMENT"+t+"_WEBGL"];let p=i!==void 0?m.TEXTURE_CUBE_MAP_POSITIVE_X+i:m.TEXTURE_2D;m.framebufferTexture2D(m.FRAMEBUFFER,c,p,s.underlyingResource,r)}if(e._autoMSAAManagement&&this._MSAAFramebuffer){let m=this._context;o._bindUnboundFramebuffer(this._MSAAFramebuffer),m.framebufferRenderbuffer(m.FRAMEBUFFER,c,m.RENDERBUFFER,s.getMSAARenderBuffer())}o._bindUnboundFramebuffer(l)}setTexture(e,t=0,i=!0){super.setTexture(e,t,i),this._bindTextureRenderTarget(e,t)}setLayerAndFaceIndices(e,t){var r,s;if(super.setLayerAndFaceIndices(e,t),!this.textures||!this.layerIndices||!this.faceIndices)return;let i=(s=(r=this._attachments)==null?void 0:r.length)!=null?s:this.textures.length;for(let a=0;a{wr();Me.prototype.createDepthStencilTexture=function(n,e,t){if(e.isCube){let i=n.width||n;return this._createDepthStencilCubeTexture(i,e)}else return this._createDepthStencilTexture(n,e,t)}});var l2=C(()=>{vs();Pt();Zn();o2();O_();DM();bt.prototype._createHardwareRenderTargetWrapper=function(n,e,t){let i=new OT(n,e,t,this,this._gl);return this._renderTargetWrapperCache.push(i),i};bt.prototype.createRenderTargetTexture=function(n,e){var p,_;let t=this._createHardwareRenderTargetWrapper(!1,!1,n),i=!0,r=!1,s=!1,a,o=1,l;e!==void 0&&typeof e=="object"&&(i=(p=e.generateDepthBuffer)!=null?p:!0,r=!!e.generateStencilBuffer,s=!!e.noColorAttachment,a=e.colorAttachment,o=(_=e.samples)!=null?_:1,l=e.label);let c=a||(s?null:this._createInternalTexture(n,e,!0,5)),f=n.width||n,h=n.height||n,d=this._currentFramebuffer,u=this._gl,m=u.createFramebuffer();if(this._bindUnboundFramebuffer(m),t._depthStencilBuffer=this._setupFramebufferDepthAttachments(r,i,f,h),c&&!c.is2DArray&&!c.is3D&&u.framebufferTexture2D(u.FRAMEBUFFER,u.COLOR_ATTACHMENT0,u.TEXTURE_2D,c._hardwareTexture.underlyingResource,0),this._bindUnboundFramebuffer(d),t.label=l!=null?l:"RenderTargetWrapper",t._framebuffer=m,t._generateDepthBuffer=i,t._generateStencilBuffer=r,t.setTextures(c),!a)this.updateRenderTargetTextureSampleCount(t,o);else if(t._samples=a.samples,a.samples>1){let g=a._hardwareTexture.getMSAARenderBuffer(0);t._MSAAFramebuffer=u.createFramebuffer(),this._bindUnboundFramebuffer(t._MSAAFramebuffer),u.framebufferRenderbuffer(u.FRAMEBUFFER,u.COLOR_ATTACHMENT0,u.RENDERBUFFER,g),this._bindUnboundFramebuffer(null)}return t};bt.prototype._createDepthStencilTexture=function(n,e,t){var u;let i=this._gl,r=n.layers||0,s=n.depth||0,a=i.TEXTURE_2D;r!==0?a=i.TEXTURE_2D_ARRAY:s!==0&&(a=i.TEXTURE_3D);let o=new Pi(this,12);if(o.label=e.label,!this._caps.depthTextureExtension)return te.Error("Depth texture is not supported by your browser or hardware."),o;let l={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...e};if(this._bindTextureDirectly(a,o,!0),this._setupDepthStencilTexture(o,n,l.comparisonFunction===0?!1:l.bilinearFiltering,l.comparisonFunction,l.samples),l.depthTextureFormat!==void 0){if(l.depthTextureFormat!==15&&l.depthTextureFormat!==16&&l.depthTextureFormat!==17&&l.depthTextureFormat!==13&&l.depthTextureFormat!==14&&l.depthTextureFormat!==18)return te.Error(`Depth texture ${l.depthTextureFormat} format is not supported.`),o;o.format=l.depthTextureFormat}else o.format=l.generateStencil?13:16;let c=Fl(o.format),f=this._getWebGLTextureTypeFromDepthTextureFormat(o.format),h=c?i.DEPTH_STENCIL:i.DEPTH_COMPONENT,d=this._getInternalFormatFromDepthTextureFormat(o.format,!0,c);return o.is2DArray?i.texImage3D(a,0,d,o.width,o.height,r,0,h,f,null):o.is3D?i.texImage3D(a,0,d,o.width,o.height,s,0,h,f,null):i.texImage2D(a,0,d,o.width,o.height,0,h,f,null),this._bindTextureDirectly(a,null),this._internalTexturesCache.push(o),t._depthStencilBuffer&&(i.deleteRenderbuffer(t._depthStencilBuffer),t._depthStencilBuffer=null),this._bindUnboundFramebuffer((u=t._MSAAFramebuffer)!=null?u:t._framebuffer),t._generateStencilBuffer=c,t._depthStencilTextureWithStencil=c,t._depthStencilBuffer=this._setupFramebufferDepthAttachments(t._generateStencilBuffer,t._generateDepthBuffer,t.width,t.height,t.samples,o.format),this._bindUnboundFramebuffer(null),o};bt.prototype.updateRenderTargetTextureSampleCount=function(n,e){var s,a;if(this.webGLVersion<2||!n)return 1;if(n.samples===e)return e;let t=this._gl;e=Math.min(e,this.getCaps().maxMSAASamples),n._depthStencilBuffer&&(t.deleteRenderbuffer(n._depthStencilBuffer),n._depthStencilBuffer=null),n._MSAAFramebuffer&&(t.deleteFramebuffer(n._MSAAFramebuffer),n._MSAAFramebuffer=null);let i=(s=n.texture)==null?void 0:s._hardwareTexture;if(i==null||i.releaseMSAARenderBuffers(),n.texture&&e>1&&typeof t.renderbufferStorageMultisample=="function"){let o=t.createFramebuffer();if(!o)throw new Error("Unable to create multi sampled framebuffer");n._MSAAFramebuffer=o,this._bindUnboundFramebuffer(n._MSAAFramebuffer);let l=this._createRenderBuffer(n.texture.width,n.texture.height,e,-1,this._getRGBABufferInternalSizedFormat(n.texture.type,n.texture.format,n.texture._useSRGBBuffer),t.COLOR_ATTACHMENT0,!1);if(!l)throw new Error("Unable to create multi sampled framebuffer");i==null||i.addMSAARenderBuffer(l)}this._bindUnboundFramebuffer((a=n._MSAAFramebuffer)!=null?a:n._framebuffer),n.texture&&(n.texture.samples=e),n._samples=e;let r=n._depthStencilTexture?n._depthStencilTexture.format:void 0;return n._depthStencilBuffer=this._setupFramebufferDepthAttachments(n._generateStencilBuffer,n._generateDepthBuffer,n.width,n.height,e,r),this._bindUnboundFramebuffer(null),e};bt.prototype._setupDepthStencilTexture=function(n,e,t,i,r=1){var d,u;let s=(d=e.width)!=null?d:e,a=(u=e.height)!=null?u:e,o=e.layers||0,l=e.depth||0;n.baseWidth=s,n.baseHeight=a,n.width=s,n.height=a,n.is2DArray=o>0,n.depth=o||l,n.isReady=!0,n.samples=r,n.generateMipMaps=!1,n.samplingMode=t?2:1,n.type=0,n._comparisonFunction=i;let c=this._gl,f=this._getTextureTarget(n),h=this._getSamplingParameters(n.samplingMode,!1);c.texParameteri(f,c.TEXTURE_MAG_FILTER,h.mag),c.texParameteri(f,c.TEXTURE_MIN_FILTER,h.min),c.texParameteri(f,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(f,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE),this.webGLVersion>1&&(i===0?(c.texParameteri(f,c.TEXTURE_COMPARE_FUNC,515),c.texParameteri(f,c.TEXTURE_COMPARE_MODE,c.NONE)):(c.texParameteri(f,c.TEXTURE_COMPARE_FUNC,i),c.texParameteri(f,c.TEXTURE_COMPARE_MODE,c.COMPARE_REF_TO_TEXTURE)))}});var c2=C(()=>{Zn();bt.prototype.setDepthStencilTexture=function(n,e,t,i){n!==void 0&&(e&&(this._boundUniforms[n]=e),!t||!t.depthStencilTexture?this._setTexture(n,null,void 0,void 0,i):this._setTexture(n,t,!1,!0,i))}});var f2=C(()=>{vs();Pt();Zn();bt.prototype.createRenderTargetCubeTexture=function(n,e){let t=this._createHardwareRenderTargetWrapper(!1,!0,n),i={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,...e};i.generateStencilBuffer=i.generateDepthBuffer&&i.generateStencilBuffer,(i.type===1&&!this._caps.textureFloatLinearFiltering||i.type===2&&!this._caps.textureHalfFloatLinearFiltering)&&(i.samplingMode=1);let r=this._gl,s=new Pi(this,5);this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,s,!0);let a=this._getSamplingParameters(i.samplingMode,i.generateMipMaps);i.type===1&&!this._caps.textureFloat&&(i.type=0,te.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAG_FILTER,a.mag),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MIN_FILTER,a.min),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE);for(let l=0;l<6;l++)r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+l,0,this._getRGBABufferInternalSizedFormat(i.type,i.format),n,n,0,this._getInternalFormat(i.format),this._getWebGLTextureType(i.type),null);let o=r.createFramebuffer();return this._bindUnboundFramebuffer(o),t._depthStencilBuffer=this._setupFramebufferDepthAttachments(i.generateStencilBuffer,i.generateDepthBuffer,n,n),i.generateMipMaps&&r.generateMipmap(r.TEXTURE_CUBE_MAP),this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),t._framebuffer=o,t._generateDepthBuffer=i.generateDepthBuffer,t._generateStencilBuffer=i.generateStencilBuffer,s.width=n,s.height=n,s.isReady=!0,s.isCube=!0,s.samples=1,s.generateMipMaps=i.generateMipMaps,s.samplingMode=i.samplingMode,s.type=i.type,s.format=i.format,this._internalTexturesCache.push(s),t.setTextures(s),t}});var h2,Wu,_r,Nt,Dn=C(()=>{h2=.45454545454545453,Wu=2.2,_r=(1+Math.sqrt(5))/2,Nt=.001});function dn(n,e){let t=[];for(let i=0;i{let s=r.previous;if(!s)return;let a=r.next;a?(s.next=a,a.previous=s):(s.next=void 0,n[e]=s),r.next=void 0,r.previous=void 0}}function NT(n,e){let t=Rre.map(i=>xre(n,i,e));return()=>{for(let i of t)i==null||i()}}var Rre,Zo=C(()=>{Rre=["push","splice","pop","shift","unshift"]});function Ft(n,e){d2[n]=e}function vn(n){return d2[n]}var d2,Hi=C(()=>{d2={}});function Si(n,e,t=1401298e-51){return Math.abs(n-e)<=t}function nr(n,e){return n===e?n:Math.random()*(e-n)+n}function Ja(n,e,t){return n+(e-n)*t}function u2(n,e,t,i,r){let s=r*r,a=r*s,o=2*a-3*s+1,l=-2*a+3*s,c=a-2*s+r,f=a-s;return n*o+t*l+e*c+i*f}function wt(n,e=0,t=1){return Math.min(t,Math.max(e,n))}function m2(n){return n-=Math.PI*2*Math.floor((n+Math.PI)/(Math.PI*2)),n}function eo(n){let e=n.toString(16);return n<=15?("0"+e).toUpperCase():e.toUpperCase()}function p2(n){if(Math.log2)return Math.floor(Math.log2(n));if(n<0)return NaN;if(n===0)return-1/0;let e=0;if(n<1){for(;n<1;)e++,n=n*2;e=-e}else if(n>1)for(;n>1;)e++,n=Math.floor(n/2);return e}function wT(n,e){let t=n%e;return t===0?e:wT(e,t)}var Ln=C(()=>{});function _2(n){n.updateFlag=Hu._UpdateFlagSeed++}function LM(n,e,t,i=0){let r=n.asArray(),s=e.asArray(),a=r[0],o=r[1],l=r[2],c=r[3],f=r[4],h=r[5],d=r[6],u=r[7],m=r[8],p=r[9],_=r[10],g=r[11],v=r[12],x=r[13],A=r[14],S=r[15],E=s[0],R=s[1],I=s[2],y=s[3],M=s[4],D=s[5],O=s[6],V=s[7],N=s[8],F=s[9],U=s[10],G=s[11],ee=s[12],j=s[13],Z=s[14],X=s[15];t[i]=a*E+o*M+l*N+c*ee,t[i+1]=a*R+o*D+l*F+c*j,t[i+2]=a*I+o*O+l*U+c*Z,t[i+3]=a*y+o*V+l*G+c*X,t[i+4]=f*E+h*M+d*N+u*ee,t[i+5]=f*R+h*D+d*F+u*j,t[i+6]=f*I+h*O+d*U+u*Z,t[i+7]=f*y+h*V+d*G+u*X,t[i+8]=m*E+p*M+_*N+g*ee,t[i+9]=m*R+p*D+_*F+g*j,t[i+10]=m*I+p*O+_*U+g*Z,t[i+11]=m*y+p*V+_*G+g*X,t[i+12]=v*E+x*M+A*N+S*ee,t[i+13]=v*R+x*D+A*F+S*j,t[i+14]=v*I+x*O+A*U+S*Z,t[i+15]=v*y+x*V+A*G+S*X}function Oh(n,e,t,i=0){LM(n,e,t.asArray(),i),_2(t)}function g2(n,e,t=0){let i=n.asArray();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]}function N_(n,e){let t=OM(n,e.asArray());return t&&_2(e),t}function OM(n,e){let t=n.asArray(),i=t[0],r=t[1],s=t[2],a=t[3],o=t[4],l=t[5],c=t[6],f=t[7],h=t[8],d=t[9],u=t[10],m=t[11],p=t[12],_=t[13],g=t[14],v=t[15],x=u*v-g*m,A=d*v-_*m,S=d*g-_*u,E=h*v-p*m,R=h*g-u*p,I=h*_-p*d,y=+(l*x-c*A+f*S),M=-(o*x-c*E+f*R),D=+(o*A-l*E+f*I),O=-(o*S-l*R+c*I),V=i*y+r*M+s*D+a*O;if(V===0)return!1;let N=1/V,F=c*v-g*f,U=l*v-_*f,G=l*g-_*c,ee=o*v-p*f,j=o*g-p*c,Z=o*_-p*l,X=c*m-u*f,Y=l*m-d*f,ue=l*u-d*c,Re=o*m-h*f,Be=o*u-h*c,ae=o*d-h*l,me=-(r*x-s*A+a*S),re=+(i*x-s*E+a*R),de=-(i*A-r*E+a*I),De=+(i*S-r*R+s*I),he=+(r*F-s*U+a*G),Ie=-(i*F-s*ee+a*j),ze=+(i*U-r*ee+a*Z),St=-(i*G-r*j+s*Z),Ye=-(r*X-s*Y+a*ue),je=+(i*X-s*Re+a*Be),$t=-(i*Y-r*Re+a*ae),Lt=+(i*ue-r*Be+s*ae);return e[0]=y*N,e[1]=me*N,e[2]=he*N,e[3]=Ye*N,e[4]=M*N,e[5]=re*N,e[6]=Ie*N,e[7]=je*N,e[8]=D*N,e[9]=de*N,e[10]=ze*N,e[11]=$t*N,e[12]=O*N,e[13]=De*N,e[14]=St*N,e[15]=Lt*N,!0}var Hu,NM=C(()=>{Hu=class{};Hu._UpdateFlagSeed=0});var Qn,we,b,bi,Xe,K,He,$,Nh,Ge=C(()=>{Dn();Zo();Hi();AM();Di();Ln();NM();Qn=n=>parseInt(n.toString().replace(/\W/g,"")),we=class n{constructor(e=0,t=0){this.x=e,this.y=t}toString(){return`{X: ${this.x} Y: ${this.y}}`}getClassName(){return"Vector2"}getHashCode(){let e=Qn(this.x),t=Qn(this.y),i=e;return i=i*397^t,i}toArray(e,t=0){return e[t]=this.x,e[t+1]=this.y,this}fromArray(e,t=0){return n.FromArrayToRef(e,t,this),this}asArray(){return[this.x,this.y]}copyFrom(e){return this.x=e.x,this.y=e.y,this}copyFromFloats(e,t){return this.x=e,this.y=t,this}set(e,t){return this.copyFromFloats(e,t)}setAll(e){return this.copyFromFloats(e,e)}add(e){return new n(this.x+e.x,this.y+e.y)}addToRef(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,t}addInPlace(e){return this.x+=e.x,this.y+=e.y,this}addInPlaceFromFloats(e,t){return this.x+=e,this.y+=t,this}addVector3(e){return new n(this.x+e.x,this.y+e.y)}subtract(e){return new n(this.x-e.x,this.y-e.y)}subtractToRef(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,t}subtractInPlace(e){return this.x-=e.x,this.y-=e.y,this}multiplyInPlace(e){return this.x*=e.x,this.y*=e.y,this}multiply(e){return new n(this.x*e.x,this.y*e.y)}multiplyToRef(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,t}multiplyByFloats(e,t){return new n(this.x*e,this.y*t)}divide(e){return new n(this.x/e.x,this.y/e.y)}divideToRef(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t}divideInPlace(e){return this.x=this.x/e.x,this.y=this.y/e.y,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e.x,e.y)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e.x,e.y)}minimizeInPlaceFromFloats(e,t){return this.x=Math.min(e,this.x),this.y=Math.min(t,this.y),this}maximizeInPlaceFromFloats(e,t){return this.x=Math.max(e,this.x),this.y=Math.max(t,this.y),this}subtractFromFloats(e,t){return new n(this.x-e,this.y-t)}subtractFromFloatsToRef(e,t,i){return i.x=this.x-e,i.y=this.y-t,i}negate(){return new n(-this.x,-this.y)}negateInPlace(){return this.x*=-1,this.y*=-1,this}negateToRef(e){return e.x=-this.x,e.y=-this.y,e}scaleInPlace(e){return this.x*=e,this.y*=e,this}scale(e){return new n(this.x*e,this.y*e)}scaleToRef(e,t){return t.x=this.x*e,t.y=this.y*e,t}scaleAndAddToRef(e,t){return t.x+=this.x*e,t.y+=this.y*e,t}equals(e){return e&&this.x===e.x&&this.y===e.y}equalsWithEpsilon(e,t=Nt){return e&&Si(this.x,e.x,t)&&Si(this.y,e.y,t)}equalsToFloats(e,t){return this.x===e&&this.y===t}floor(){return new n(Math.floor(this.x),Math.floor(this.y))}floorToRef(e){return e.x=Math.floor(this.x),e.y=Math.floor(this.y),e}fract(){return new n(this.x-Math.floor(this.x),this.y-Math.floor(this.y))}fractToRef(e){return e.x=this.x-Math.floor(this.x),e.y=this.y-Math.floor(this.y),e}rotate(e){return this.rotateToRef(e,new n)}rotateToRef(e,t){let i=Math.cos(e),r=Math.sin(e);return t.x=i*this.x-r*this.y,t.y=r*this.x+i*this.y,t}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}lengthSquared(){return this.x*this.x+this.y*this.y}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){let e=new n;return this.normalizeToRef(e),e}normalizeToRef(e){let t=this.length();return t===0&&(e.x=this.x,e.y=this.y),this.scaleToRef(1/t,e)}clone(){return new n(this.x,this.y)}dot(e){return this.x*e.x+this.y*e.y}static Zero(){return new n(0,0)}static One(){return new n(1,1)}static Random(e=0,t=1){return new n(nr(e,t),nr(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(nr(e,t),nr(e,t))}static get ZeroReadOnly(){return n._ZeroReadOnly}static FromArray(e,t=0){return new n(e[t],e[t+1])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i}static FromFloatsToRef(e,t,i){return i.copyFromFloats(e,t),i}static CatmullRom(e,t,i,r,s){let a=s*s,o=s*a,l=.5*(2*t.x+(-e.x+i.x)*s+(2*e.x-5*t.x+4*i.x-r.x)*a+(-e.x+3*t.x-3*i.x+r.x)*o),c=.5*(2*t.y+(-e.y+i.y)*s+(2*e.y-5*t.y+4*i.y-r.y)*a+(-e.y+3*t.y-3*i.y+r.y)*o);return new n(l,c)}static ClampToRef(e,t,i,r){return r.x=wt(e.x,t.x,i.x),r.y=wt(e.y,t.y,i.y),r}static Clamp(e,t,i){let r=wt(e.x,t.x,i.x),s=wt(e.y,t.y,i.y);return new n(r,s)}static Hermite(e,t,i,r,s){let a=s*s,o=s*a,l=2*o-3*a+1,c=-2*o+3*a,f=o-2*a+s,h=o-a,d=e.x*l+i.x*c+t.x*f+r.x*h,u=e.y*l+i.y*c+t.y*f+r.y*h;return new n(d,u)}static Hermite1stDerivative(e,t,i,r,s){return this.Hermite1stDerivativeToRef(e,t,i,r,s,new n)}static Hermite1stDerivativeToRef(e,t,i,r,s,a){let o=s*s;return a.x=(o-s)*6*e.x+(3*o-4*s+1)*t.x+(-o+s)*6*i.x+(3*o-2*s)*r.x,a.y=(o-s)*6*e.y+(3*o-4*s+1)*t.y+(-o+s)*6*i.y+(3*o-2*s)*r.y,a}static Lerp(e,t,i){return n.LerpToRef(e,t,i,new n)}static LerpToRef(e,t,i,r){return r.x=e.x+(t.x-e.x)*i,r.y=e.y+(t.y-e.y)*i,r}static Dot(e,t){return e.x*t.x+e.y*t.y}static Normalize(e){return n.NormalizeToRef(e,new n)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){let i=e.xt.x?e.x:t.x,r=e.y>t.y?e.y:t.y;return new n(i,r)}static Transform(e,t){return n.TransformToRef(e,t,new n)}static TransformToRef(e,t,i){let r=t.m,s=e.x*r[0]+e.y*r[4]+r[12],a=e.x*r[1]+e.y*r[5]+r[13];return i.x=s,i.y=a,i}static PointInTriangle(e,t,i,r){let s=.5*(-i.y*r.x+t.y*(-i.x+r.x)+t.x*(i.y-r.y)+i.x*r.y),a=s<0?-1:1,o=(t.y*r.x-t.x*r.y+(r.y-t.y)*e.x+(t.x-r.x)*e.y)*a,l=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*a;return o>0&&l>0&&o+l<2*s*a}static Distance(e,t){return Math.sqrt(n.DistanceSquared(e,t))}static DistanceSquared(e,t){let i=e.x-t.x,r=e.y-t.y;return i*i+r*r}static Center(e,t){return n.CenterToRef(e,t,new n)}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2)}static DistanceOfPointFromSegment(e,t,i){let r=n.DistanceSquared(t,i);if(r===0)return n.Distance(e,t);let s=i.subtract(t),a=Math.max(0,Math.min(1,n.Dot(e.subtract(t),s)/r)),o=t.add(s.multiplyByFloats(a,a));return n.Distance(e,o)}};we._V8PerformanceHack=new we(.5,.5);we._ZeroReadOnly=we.Zero();Object.defineProperties(we.prototype,{dimension:{value:[2]},rank:{value:1}});b=class n{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}constructor(e=0,t=0,i=0){this._isDirty=!0,this._x=e,this._y=t,this._z=i}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z}}`}getClassName(){return"Vector3"}getHashCode(){let e=Qn(this._x),t=Qn(this._y),i=Qn(this._z),r=e;return r=r*397^t,r=r*397^i,r}asArray(){return[this._x,this._y,this._z]}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,this}fromArray(e,t=0){return n.FromArrayToRef(e,t,this),this}toQuaternion(){return Xe.RotationYawPitchRoll(this._y,this._x,this._z)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._isDirty=!0,this}addInPlaceFromFloats(e,t,i){return this._x+=e,this._y+=t,this._z+=i,this._isDirty=!0,this}add(e){return new n(this._x+e._x,this._y+e._y,this._z+e._z)}addToRef(e,t){return t._x=this._x+e._x,t._y=this._y+e._y,t._z=this._z+e._z,t._isDirty=!0,t}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._isDirty=!0,this}subtract(e){return new n(this._x-e._x,this._y-e._y,this._z-e._z)}subtractToRef(e,t){return this.subtractFromFloatsToRef(e._x,e._y,e._z,t)}subtractFromFloats(e,t,i){return new n(this._x-e,this._y-t,this._z-i)}subtractFromFloatsToRef(e,t,i,r){return r._x=this._x-e,r._y=this._y-t,r._z=this._z-i,r._isDirty=!0,r}negate(){return new n(-this._x,-this._y,-this._z)}negateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}negateToRef(e){return e._x=this._x*-1,e._y=this._y*-1,e._z=this._z*-1,e._isDirty=!0,e}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._isDirty=!0,this}scale(e){return new n(this._x*e,this._y*e,this._z*e)}scaleToRef(e,t){return t._x=this._x*e,t._y=this._y*e,t._z=this._z*e,t._isDirty=!0,t}getNormalToRef(e){let t=this.length(),i=Math.acos(this._y/t),r=Math.atan2(this._z,this._x);i>Math.PI/2?i-=Math.PI/2:i+=Math.PI/2;let s=t*Math.sin(i)*Math.cos(r),a=t*Math.cos(i),o=t*Math.sin(i)*Math.sin(r);return e.set(s,a,o),e}applyRotationQuaternionToRef(e,t){let i=this._x,r=this._y,s=this._z,a=e._x,o=e._y,l=e._z,c=e._w,f=2*(o*s-l*r),h=2*(l*i-a*s),d=2*(a*r-o*i);return t._x=i+c*f+o*d-l*h,t._y=r+c*h+l*f-a*d,t._z=s+c*d+a*h-o*f,t._isDirty=!0,t}applyRotationQuaternionInPlace(e){return this.applyRotationQuaternionToRef(e,this)}applyRotationQuaternion(e){return this.applyRotationQuaternionToRef(e,new n)}scaleAndAddToRef(e,t){return t._x+=this._x*e,t._y+=this._y*e,t._z+=this._z*e,t._isDirty=!0,t}projectOnPlane(e,t){return this.projectOnPlaneToRef(e,t,new n)}projectOnPlaneToRef(e,t,i){let r=e.normal,s=e.d,a=He.Vector3[0];this.subtractToRef(t,a),a.normalize();let o=n.Dot(a,r);if(Math.abs(o)<1e-10)i.setAll(1/0);else{let l=-(n.Dot(t,r)+s)/o,c=a.scaleInPlace(l);t.addToRef(c,i)}return i}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z}equalsWithEpsilon(e,t=Nt){return e&&Si(this._x,e._x,t)&&Si(this._y,e._y,t)&&Si(this._z,e._z,t)}equalsToFloats(e,t,i){return this._x===e&&this._y===t&&this._z===i}multiplyInPlace(e){return this._x*=e._x,this._y*=e._y,this._z*=e._z,this._isDirty=!0,this}multiply(e){return this.multiplyByFloats(e._x,e._y,e._z)}multiplyToRef(e,t){return t._x=this._x*e._x,t._y=this._y*e._y,t._z=this._z*e._z,t._isDirty=!0,t}multiplyByFloats(e,t,i){return new n(this._x*e,this._y*t,this._z*i)}divide(e){return new n(this._x/e._x,this._y/e._y,this._z/e._z)}divideToRef(e,t){return t._x=this._x/e._x,t._y=this._y/e._y,t._z=this._z/e._z,t._isDirty=!0,t}divideInPlace(e){return this._x=this._x/e._x,this._y=this._y/e._y,this._z=this._z/e._z,this._isDirty=!0,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e._x,e._y,e._z)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e._x,e._y,e._z)}minimizeInPlaceFromFloats(e,t,i){return ethis._x&&(this.x=e),t>this._y&&(this.y=t),i>this._z&&(this.z=i),this}isNonUniformWithinEpsilon(e){let t=Math.abs(this._x),i=Math.abs(this._y);if(!Si(t,i,e))return!0;let r=Math.abs(this._z);return!Si(t,r,e)||!Si(i,r,e)}get isNonUniform(){let e=Math.abs(this._x),t=Math.abs(this._y);if(e!==t)return!0;let i=Math.abs(this._z);return e!==i}floorToRef(e){return e._x=Math.floor(this._x),e._y=Math.floor(this._y),e._z=Math.floor(this._z),e._isDirty=!0,e}floor(){return new n(Math.floor(this._x),Math.floor(this._y),Math.floor(this._z))}fractToRef(e){return e._x=this._x-Math.floor(this._x),e._y=this._y-Math.floor(this._y),e._z=this._z-Math.floor(this._z),e._isDirty=!0,e}fract(){return new n(this._x-Math.floor(this._x),this._y-Math.floor(this._y),this._z-Math.floor(this._z))}length(){return Math.sqrt(this.lengthSquared())}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z}get hasAZeroComponent(){return this._x*this._y*this._z===0}normalize(){return this.normalizeFromLength(this.length())}reorderInPlace(e){if(e=e.toLowerCase(),e==="xyz")return this;let t=He.Vector3[0].copyFrom(this);return this.x=t[e[0]],this.y=t[e[1]],this.z=t[e[2]],this}rotateByQuaternionToRef(e,t){return e.toRotationMatrix(He.Matrix[0]),n.TransformCoordinatesToRef(this,He.Matrix[0],t),t}rotateByQuaternionAroundPointToRef(e,t,i){return this.subtractToRef(t,He.Vector3[0]),He.Vector3[0].rotateByQuaternionToRef(e,He.Vector3[0]),t.addToRef(He.Vector3[0],i),i}cross(e){return n.CrossToRef(this,e,new n)}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new n)}normalizeToRef(e){let t=this.length();return t===0||t===1?(e._x=this._x,e._y=this._y,e._z=this._z,e._isDirty=!0,e):this.scaleToRef(1/t,e)}clone(){return new n(this._x,this._y,this._z)}copyFrom(e){return this.copyFromFloats(e._x,e._y,e._z)}copyFromFloats(e,t,i){return this._x=e,this._y=t,this._z=i,this._isDirty=!0,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this._x=this._y=this._z=e,this._isDirty=!0,this}static GetClipFactor(e,t,i,r){let s=n.Dot(e,i),a=n.Dot(t,i);return(s-r)/(s-a)}static GetAngleBetweenVectors(e,t,i){let r=e.normalizeToRef(He.Vector3[1]),s=t.normalizeToRef(He.Vector3[2]),a=n.Dot(r,s);a=wt(a,-1,1);let o=Math.acos(a),l=He.Vector3[3];return n.CrossToRef(r,s,l),n.Dot(l,i)>0?isNaN(o)?0:o:isNaN(o)?-Math.PI:-Math.acos(a)}static GetAngleBetweenVectorsOnPlane(e,t,i){He.Vector3[0].copyFrom(e);let r=He.Vector3[0];He.Vector3[1].copyFrom(t);let s=He.Vector3[1];He.Vector3[2].copyFrom(i);let a=He.Vector3[2],o=He.Vector3[3],l=He.Vector3[4];r.normalize(),s.normalize(),a.normalize(),n.CrossToRef(a,r,o),n.CrossToRef(o,a,l);let c=Math.atan2(n.Dot(s,o),n.Dot(s,l));return m2(c)}static PitchYawRollToMoveBetweenPointsToRef(e,t,i){let r=$.Vector3[0];return t.subtractToRef(e,r),i._y=Math.atan2(r.x,r.z)||0,i._x=Math.atan2(Math.sqrt(r.x**2+r.z**2),r.y)||0,i._z=0,i._isDirty=!0,i}static PitchYawRollToMoveBetweenPoints(e,t){let i=n.Zero();return n.PitchYawRollToMoveBetweenPointsToRef(e,t,i)}static SlerpToRef(e,t,i,r){i=wt(i,0,1);let s=He.Vector3[0],a=He.Vector3[1];s.copyFrom(e);let o=s.length();s.normalizeFromLength(o),a.copyFrom(t);let l=a.length();a.normalizeFromLength(l);let c=n.Dot(s,a),f,h;if(c<1-Nt){let d=Math.acos(c),u=1/Math.sin(d);f=Math.sin((1-i)*d)*u,h=Math.sin(i*d)*u}else f=1-i,h=i;return s.scaleInPlace(f),a.scaleInPlace(h),r.copyFrom(s).addInPlace(a),r.scaleInPlace(Ja(o,l,i)),r}static SmoothToRef(e,t,i,r,s){return n.SlerpToRef(e,t,r===0?1:i/r,s),s}static FromArray(e,t=0){return new n(e[t],e[t+1],e[t+2])}static FromFloatArray(e,t){return n.FromArray(e,t)}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._isDirty=!0,i}static FromFloatArrayToRef(e,t,i){return n.FromArrayToRef(e,t,i)}static FromFloatsToRef(e,t,i,r){return r.copyFromFloats(e,t,i),r}static Zero(){return new n(0,0,0)}static One(){return new n(1,1,1)}static Up(){return new n(0,1,0)}static get UpReadOnly(){return n._UpReadOnly}static get DownReadOnly(){return n._DownReadOnly}static get RightReadOnly(){return n._RightReadOnly}static get LeftReadOnly(){return n._LeftReadOnly}static get LeftHandedForwardReadOnly(){return n._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return n._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return n._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return n._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return n._ZeroReadOnly}static get OneReadOnly(){return n._OneReadOnly}static Down(){return new n(0,-1,0)}static Forward(e=!1){return new n(0,0,e?-1:1)}static Backward(e=!1){return new n(0,0,e?1:-1)}static Right(){return new n(1,0,0)}static Left(){return new n(-1,0,0)}static Random(e=0,t=1){return new n(nr(e,t),nr(e,t),nr(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(nr(e,t),nr(e,t),nr(e,t))}static TransformCoordinates(e,t){let i=n.Zero();return n.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return n.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,r,s){let a=r.m,o=e*a[0]+t*a[4]+i*a[8]+a[12],l=e*a[1]+t*a[5]+i*a[9]+a[13],c=e*a[2]+t*a[6]+i*a[10]+a[14],f=1/(e*a[3]+t*a[7]+i*a[11]+a[15]);return s._x=o*f,s._y=l*f,s._z=c*f,s._isDirty=!0,s}static TransformNormal(e,t){let i=n.Zero();return n.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){return this.TransformNormalFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformNormalFromFloatsToRef(e,t,i,r,s){let a=r.m;return s._x=e*a[0]+t*a[4]+i*a[8],s._y=e*a[1]+t*a[5]+i*a[9],s._z=e*a[2]+t*a[6]+i*a[10],s._isDirty=!0,s}static CatmullRom(e,t,i,r,s){let a=s*s,o=s*a,l=.5*(2*t._x+(-e._x+i._x)*s+(2*e._x-5*t._x+4*i._x-r._x)*a+(-e._x+3*t._x-3*i._x+r._x)*o),c=.5*(2*t._y+(-e._y+i._y)*s+(2*e._y-5*t._y+4*i._y-r._y)*a+(-e._y+3*t._y-3*i._y+r._y)*o),f=.5*(2*t._z+(-e._z+i._z)*s+(2*e._z-5*t._z+4*i._z-r._z)*a+(-e._z+3*t._z-3*i._z+r._z)*o);return new n(l,c,f)}static Clamp(e,t,i){let r=new n;return n.ClampToRef(e,t,i,r),r}static ClampToRef(e,t,i,r){let s=e._x;s=s>i._x?i._x:s,s=si._y?i._y:a,a=ai._z?i._z:o,o=o0&&M<0?(O.copyFrom(a),V=t,N=i):M>0&&D<0?(O.copyFrom(l),V=i,N=r):(O.copyFrom(o).scaleInPlace(-1),V=r,N=t);let F=He.Vector3[9],U=He.Vector3[4];if(V.subtractToRef(v,E),N.subtractToRef(v,F),n.CrossToRef(E,F,U),!(n.Dot(U,c)<0))return s.copyFrom(v),Math.abs(p*_);let ee=He.Vector3[5];n.CrossToRef(O,U,ee),ee.normalize();let j=He.Vector3[9];j.copyFrom(V).subtractInPlace(v);let Z=j.length();if(Zthis._x&&(this.x=e.x),e.y>this._y&&(this.y=e.y),e.z>this._z&&(this.z=e.z),e.w>this._w&&(this.w=e.w),this}minimizeInPlaceFromFloats(e,t,i,r){return this.x=Math.min(e,this._x),this.y=Math.min(t,this._y),this.z=Math.min(i,this._z),this.w=Math.min(r,this._w),this}maximizeInPlaceFromFloats(e,t,i,r){return this.x=Math.max(e,this._x),this.y=Math.max(t,this._y),this.z=Math.max(i,this._z),this.w=Math.max(r,this._w),this}floorToRef(e){return e.x=Math.floor(this._x),e.y=Math.floor(this._y),e.z=Math.floor(this._z),e.w=Math.floor(this._w),e}floor(){return new n(Math.floor(this._x),Math.floor(this._y),Math.floor(this._z),Math.floor(this._w))}fractToRef(e){return e.x=this._x-Math.floor(this._x),e.y=this._y-Math.floor(this._y),e.z=this._z-Math.floor(this._z),e.w=this._w-Math.floor(this._w),e}fract(){return new n(this._x-Math.floor(this._x),this._y-Math.floor(this._y),this._z-Math.floor(this._z),this._w-Math.floor(this._w))}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new n)}normalizeToRef(e){let t=this.length();return t===0||t===1?(e.x=this._x,e.y=this._y,e.z=this._z,e.w=this._w,e):this.scaleToRef(1/t,e)}toVector3(){return new b(this._x,this._y,this._z)}clone(){return new n(this._x,this._y,this._z,this._w)}copyFrom(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this}copyFromFloats(e,t,i,r){return this.x=e,this.y=t,this.z=i,this.w=r,this}set(e,t,i,r){return this.copyFromFloats(e,t,i,r)}setAll(e){return this.x=this.y=this.z=this.w=e,this}dot(e){return this._x*e.x+this._y*e.y+this._z*e.z+this._w*e.w}static FromArray(e,t){return t||(t=0),new n(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i.z=e[t+2],i.w=e[t+3],i}static FromFloatArrayToRef(e,t,i){return n.FromArrayToRef(e,t,i),i}static FromFloatsToRef(e,t,i,r,s){return s.x=e,s.y=t,s.z=i,s.w=r,s}static Zero(){return new n(0,0,0,0)}static One(){return new n(1,1,1,1)}static Random(e=0,t=1){return new n(nr(e,t),nr(e,t),nr(e,t),nr(e,t))}static RandomToRef(e=0,t=1,i){return i.x=nr(e,t),i.y=nr(e,t),i.z=nr(e,t),i.w=nr(e,t),i}static Clamp(e,t,i){return n.ClampToRef(e,t,i,new n)}static ClampToRef(e,t,i,r){return r.x=wt(e.x,t.x,i.x),r.y=wt(e.y,t.y,i.y),r.z=wt(e.z,t.z,i.z),r.w=wt(e.w,t.w,i.w),r}static CheckExtends(e,t,i){t.minimizeInPlace(e),i.maximizeInPlace(e)}static get ZeroReadOnly(){return n._ZeroReadOnly}static Normalize(e){return n.NormalizeToRef(e,new n)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){let i=new n;return i.copyFrom(e),i.minimizeInPlace(t),i}static Maximize(e,t){let i=new n;return i.copyFrom(e),i.maximizeInPlace(t),i}static Distance(e,t){return Math.sqrt(n.DistanceSquared(e,t))}static DistanceSquared(e,t){let i=e.x-t.x,r=e.y-t.y,s=e.z-t.z,a=e.w-t.w;return i*i+r*r+s*s+a*a}static Center(e,t){return n.CenterToRef(e,t,new n)}static CenterToRef(e,t,i){return i.x=(e.x+t.x)/2,i.y=(e.y+t.y)/2,i.z=(e.z+t.z)/2,i.w=(e.w+t.w)/2,i}static TransformCoordinates(e,t){return n.TransformCoordinatesToRef(e,t,new n)}static TransformCoordinatesToRef(e,t,i){return n.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,r,s){let a=r.m,o=e*a[0]+t*a[4]+i*a[8]+a[12],l=e*a[1]+t*a[5]+i*a[9]+a[13],c=e*a[2]+t*a[6]+i*a[10]+a[14],f=e*a[3]+t*a[7]+i*a[11]+a[15];return s.x=o,s.y=l,s.z=c,s.w=f,s}static TransformNormal(e,t){return n.TransformNormalToRef(e,t,new n)}static TransformNormalToRef(e,t,i){let r=t.m,s=e.x*r[0]+e.y*r[4]+e.z*r[8],a=e.x*r[1]+e.y*r[5]+e.z*r[9],o=e.x*r[2]+e.y*r[6]+e.z*r[10];return i.x=s,i.y=a,i.z=o,i.w=e.w,i}static TransformNormalFromFloatsToRef(e,t,i,r,s,a){let o=s.m;return a.x=e*o[0]+t*o[4]+i*o[8],a.y=e*o[1]+t*o[5]+i*o[9],a.z=e*o[2]+t*o[6]+i*o[10],a.w=r,a}static FromVector3(e,t=0){return new n(e._x,e._y,e._z,t)}static Dot(e,t){return e.x*t.x+e.y*t.y+e.z*t.z+e.w*t.w}};bi._V8PerformanceHack=new bi(.5,.5,.5,.5);bi._ZeroReadOnly=bi.Zero();Object.defineProperties(bi.prototype,{dimension:{value:[4]},rank:{value:1}});Xe=class n{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}get w(){return this._w}set w(e){this._w=e,this._isDirty=!0}constructor(e=0,t=0,i=0,r=1){this._isDirty=!0,this._x=e,this._y=t,this._z=i,this._w=r}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Quaternion"}getHashCode(){let e=Qn(this._x),t=Qn(this._y),i=Qn(this._z),r=Qn(this._w),s=e;return s=s*397^t,s=s*397^i,s=s*397^r,s}asArray(){return[this._x,this._y,this._z,this._w]}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,this}fromArray(e,t=0){return n.FromArrayToRef(e,t,this)}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z&&this._w===e._w}equalsWithEpsilon(e,t=Nt){return e&&Si(this._x,e._x,t)&&Si(this._y,e._y,t)&&Si(this._z,e._z,t)&&Si(this._w,e._w,t)}isApprox(e,t=Nt){return e&&(Si(this._x,e._x,t)&&Si(this._y,e._y,t)&&Si(this._z,e._z,t)&&Si(this._w,e._w,t)||Si(this._x,-e._x,t)&&Si(this._y,-e._y,t)&&Si(this._z,-e._z,t)&&Si(this._w,-e._w,t))}clone(){return new n(this._x,this._y,this._z,this._w)}copyFrom(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._w=e._w,this._isDirty=!0,this}copyFromFloats(e,t,i,r){return this._x=e,this._y=t,this._z=i,this._w=r,this._isDirty=!0,this}set(e,t,i,r){return this.copyFromFloats(e,t,i,r)}setAll(e){return this.copyFromFloats(e,e,e,e)}add(e){return new n(this._x+e._x,this._y+e._y,this._z+e._z,this._w+e._w)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._w+=e._w,this._isDirty=!0,this}addToRef(e,t){return t._x=this._x+e._x,t._y=this._y+e._y,t._z=this._z+e._z,t._w=this._w+e._w,t._isDirty=!0,t}addInPlaceFromFloats(e,t,i,r){return this._x+=e,this._y+=t,this._z+=i,this._w+=r,this._isDirty=!0,this}subtractToRef(e,t){return t._x=this._x-e._x,t._y=this._y-e._y,t._z=this._z-e._z,t._w=this._w-e._w,t._isDirty=!0,t}subtractFromFloats(e,t,i,r){return this.subtractFromFloatsToRef(e,t,i,r,new n)}subtractFromFloatsToRef(e,t,i,r,s){return s._x=this._x-e,s._y=this._y-t,s._z=this._z-i,s._w=this._w-r,s._isDirty=!0,s}subtract(e){return new n(this._x-e._x,this._y-e._y,this._z-e._z,this._w-e._w)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._w-=e._w,this._isDirty=!0,this}scale(e){return new n(this._x*e,this._y*e,this._z*e,this._w*e)}scaleToRef(e,t){return t._x=this._x*e,t._y=this._y*e,t._z=this._z*e,t._w=this._w*e,t._isDirty=!0,t}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._w*=e,this._isDirty=!0,this}scaleAndAddToRef(e,t){return t._x+=this._x*e,t._y+=this._y*e,t._z+=this._z*e,t._w+=this._w*e,t._isDirty=!0,t}multiply(e){let t=new n(0,0,0,1);return this.multiplyToRef(e,t),t}multiplyToRef(e,t){let i=this._x*e._w+this._y*e._z-this._z*e._y+this._w*e._x,r=-this._x*e._z+this._y*e._w+this._z*e._x+this._w*e._y,s=this._x*e._y-this._y*e._x+this._z*e._w+this._w*e._z,a=-this._x*e._x-this._y*e._y-this._z*e._z+this._w*e._w;return t.copyFromFloats(i,r,s,a),t}multiplyInPlace(e){return this.multiplyToRef(e,this)}multiplyByFloats(e,t,i,r){return this._x*=e,this._y*=t,this._z*=i,this._w*=r,this._isDirty=!0,this}divide(e){throw new ReferenceError("Can not divide a quaternion")}divideToRef(e,t){throw new ReferenceError("Can not divide a quaternion")}divideInPlace(e){throw new ReferenceError("Can not divide a quaternion")}minimizeInPlace(){throw new ReferenceError("Can not minimize a quaternion")}minimizeInPlaceFromFloats(){throw new ReferenceError("Can not minimize a quaternion")}maximizeInPlace(){throw new ReferenceError("Can not maximize a quaternion")}maximizeInPlaceFromFloats(){throw new ReferenceError("Can not maximize a quaternion")}negate(){return this.negateToRef(new n)}negateInPlace(){return this._x=-this._x,this._y=-this._y,this._z=-this._z,this._w=-this._w,this._isDirty=!0,this}negateToRef(e){return e._x=-this._x,e._y=-this._y,e._z=-this._z,e._w=-this._w,e._isDirty=!0,e}equalsToFloats(e,t,i,r){return this._x===e&&this._y===t&&this._z===i&&this._w===r}floorToRef(e){throw new ReferenceError("Can not floor a quaternion")}floor(){throw new ReferenceError("Can not floor a quaternion")}fractToRef(e){throw new ReferenceError("Can not fract a quaternion")}fract(){throw new ReferenceError("Can not fract a quaternion")}conjugateToRef(e){return e.copyFromFloats(-this._x,-this._y,-this._z,this._w),e}conjugateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}conjugate(){return new n(-this._x,-this._y,-this._z,this._w)}invert(){let e=this.conjugate(),t=this.lengthSquared();return t==0||t==1||e.scaleInPlace(1/t),e}invertInPlace(){this.conjugateInPlace();let e=this.lengthSquared();return e==0||e==1?this:(this.scaleInPlace(1/e),this)}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this.lengthSquared())}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return e===0||e===1?this:this.scaleInPlace(1/e)}normalizeToNew(){let e=new n(0,0,0,1);return this.normalizeToRef(e),e}normalizeToRef(e){let t=this.length();return t===0||t===1?e.copyFromFloats(this._x,this._y,this._z,this._w):this.scaleToRef(1/t,e)}toEulerAngles(){let e=b.Zero();return this.toEulerAnglesToRef(e),e}toEulerAnglesToRef(e){let t=this._z,i=this._x,r=this._y,s=this._w,a=r*t-i*s,o=.4999999;if(a<-o)e._y=2*Math.atan2(r,s),e._x=Math.PI/2,e._z=0,e._isDirty=!0;else if(a>o)e._y=2*Math.atan2(r,s),e._x=-Math.PI/2,e._z=0,e._isDirty=!0;else{let l=s*s,c=t*t,f=i*i,h=r*r;e._z=Math.atan2(2*(i*r+t*s),-c-f+h+l),e._x=Math.asin(-2*a),e._y=Math.atan2(2*(t*i+r*s),c-f-h+l),e._isDirty=!0}return e}toAlphaBetaGammaToRef(e){let t=this._z,i=this._x,r=this._y,s=this._w,a=Math.sqrt(i*i+r*r),o=Math.sqrt(t*t+s*s),l=2*Math.atan2(a,o),c=2*Math.atan2(t,s),f=2*Math.atan2(r,i),h=(c+f)/2,d=(c-f)/2;return e.set(d,l,h),e}toRotationMatrix(e){return K.FromQuaternionToRef(this,e),e}fromRotationMatrix(e){return n.FromRotationMatrixToRef(e,this),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}toAxisAngle(){let e=b.Zero(),t=this.toAxisAngleToRef(e);return{axis:e,angle:t}}toAxisAngleToRef(e){let t,i=Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z),r=this._w;return i>0?(t=2*Math.atan2(i,r),e.set(this._x/i,this._y/i,this._z/i)):(t=0,e.set(1,0,0)),t}static FromRotationMatrix(e){let t=new n;return n.FromRotationMatrixToRef(e,t),t}static FromRotationMatrixToRef(e,t){let i=e.m,r=i[0],s=i[4],a=i[8],o=i[1],l=i[5],c=i[9],f=i[2],h=i[6],d=i[10],u=r+l+d,m;return u>0?(m=.5/Math.sqrt(u+1),t._w=.25/m,t._x=(h-c)*m,t._y=(a-f)*m,t._z=(o-s)*m,t._isDirty=!0):r>l&&r>d?(m=2*Math.sqrt(1+r-l-d),t._w=(h-c)/m,t._x=.25*m,t._y=(s+o)/m,t._z=(a+f)/m,t._isDirty=!0):l>d?(m=2*Math.sqrt(1+l-r-d),t._w=(a-f)/m,t._x=(s+o)/m,t._y=.25*m,t._z=(c+h)/m,t._isDirty=!0):(m=2*Math.sqrt(1+d-r-l),t._w=(o-s)/m,t._x=(a+f)/m,t._y=(c+h)/m,t._z=.25*m,t._isDirty=!0),t}static Dot(e,t){return e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w}static AreClose(e,t,i=.1){let r=n.Dot(e,t);return 1-r*r<=i}static SmoothToRef(e,t,i,r,s){let a=r===0?1:i/r;return a=wt(a,0,1),n.SlerpToRef(e,t,a,s),s}static Zero(){return new n(0,0,0,0)}static Inverse(e){return new n(-e._x,-e._y,-e._z,e._w)}static InverseToRef(e,t){return t.set(-e._x,-e._y,-e._z,e._w),t}static Identity(){return new n(0,0,0,1)}static IsIdentity(e){return e&&e._x===0&&e._y===0&&e._z===0&&e._w===1}static RotationAxis(e,t){return n.RotationAxisToRef(e,t,new n)}static RotationAxisToRef(e,t,i){i._w=Math.cos(t/2);let r=Math.sin(t/2)/e.length();return i._x=e._x*r,i._y=e._y*r,i._z=e._z*r,i._isDirty=!0,i}static FromArray(e,t){return t||(t=0),new n(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._w=e[t+3],i._isDirty=!0,i}static FromFloatsToRef(e,t,i,r,s){return s.copyFromFloats(e,t,i,r),s}static FromEulerAngles(e,t,i){let r=new n;return n.RotationYawPitchRollToRef(t,e,i,r),r}static FromEulerAnglesToRef(e,t,i,r){return n.RotationYawPitchRollToRef(t,e,i,r),r}static FromEulerVector(e){let t=new n;return n.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromEulerVectorToRef(e,t){return n.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromUnitVectorsToRef(e,t,i,r=Nt){let s=b.Dot(e,t)+1;return sMath.abs(e.z)?i.set(-e.y,e.x,0,0):i.set(0,-e.z,e.y,0):(b.CrossToRef(e,t,$.Vector3[0]),i.set($.Vector3[0].x,$.Vector3[0].y,$.Vector3[0].z,s)),i.normalize()}static RotationYawPitchRoll(e,t,i){let r=new n;return n.RotationYawPitchRollToRef(e,t,i,r),r}static RotationYawPitchRollToRef(e,t,i,r){let s=i*.5,a=t*.5,o=e*.5,l=Math.sin(s),c=Math.cos(s),f=Math.sin(a),h=Math.cos(a),d=Math.sin(o),u=Math.cos(o);return r._x=u*f*c+d*h*l,r._y=d*h*c-u*f*l,r._z=u*h*l-d*f*c,r._w=u*h*c+d*f*l,r._isDirty=!0,r}static RotationAlphaBetaGamma(e,t,i){let r=new n;return n.RotationAlphaBetaGammaToRef(e,t,i,r),r}static RotationAlphaBetaGammaToRef(e,t,i,r){let s=(i+e)*.5,a=(i-e)*.5,o=t*.5;return r._x=Math.cos(a)*Math.sin(o),r._y=Math.sin(a)*Math.sin(o),r._z=Math.sin(s)*Math.cos(o),r._w=Math.cos(s)*Math.cos(o),r._isDirty=!0,r}static RotationQuaternionFromAxis(e,t,i){let r=new n(0,0,0,0);return n.RotationQuaternionFromAxisToRef(e,t,i,r),r}static RotationQuaternionFromAxisToRef(e,t,i,r){let s=He.Matrix[0];return e=e.normalizeToRef(He.Vector3[0]),t=t.normalizeToRef(He.Vector3[1]),i=i.normalizeToRef(He.Vector3[2]),K.FromXYZAxesToRef(e,t,i,s),n.FromRotationMatrixToRef(s,r),r}static FromLookDirectionLH(e,t){let i=new n;return n.FromLookDirectionLHToRef(e,t,i),i}static FromLookDirectionLHToRef(e,t,i){let r=He.Matrix[0];return K.LookDirectionLHToRef(e,t,r),n.FromRotationMatrixToRef(r,i),i}static FromLookDirectionRH(e,t){let i=new n;return n.FromLookDirectionRHToRef(e,t,i),i}static FromLookDirectionRHToRef(e,t,i){let r=He.Matrix[0];return K.LookDirectionRHToRef(e,t,r),n.FromRotationMatrixToRef(r,i)}static Slerp(e,t,i){let r=n.Identity();return n.SlerpToRef(e,t,i,r),r}static SlerpToRef(e,t,i,r){let s,a,o=e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w,l=!1;if(o<0&&(l=!0,o=-o),o>.999999)a=1-i,s=l?-i:i;else{let c=Math.acos(o),f=1/Math.sin(c);a=Math.sin((1-i)*c)*f,s=l?-Math.sin(i*c)*f:Math.sin(i*c)*f}return r._x=a*e._x+s*t._x,r._y=a*e._y+s*t._y,r._z=a*e._z+s*t._z,r._w=a*e._w+s*t._w,r._isDirty=!0,r}static Hermite(e,t,i,r,s){let a=s*s,o=s*a,l=2*o-3*a+1,c=-2*o+3*a,f=o-2*a+s,h=o-a,d=e._x*l+i._x*c+t._x*f+r._x*h,u=e._y*l+i._y*c+t._y*f+r._y*h,m=e._z*l+i._z*c+t._z*f+r._z*h,p=e._w*l+i._w*c+t._w*f+r._w*h;return new n(d,u,m,p)}static Hermite1stDerivative(e,t,i,r,s){let a=new n;return this.Hermite1stDerivativeToRef(e,t,i,r,s,a),a}static Hermite1stDerivativeToRef(e,t,i,r,s,a){let o=s*s;return a._x=(o-s)*6*e._x+(3*o-4*s+1)*t._x+(-o+s)*6*i._x+(3*o-2*s)*r._x,a._y=(o-s)*6*e._y+(3*o-4*s+1)*t._y+(-o+s)*6*i._y+(3*o-2*s)*r._y,a._z=(o-s)*6*e._z+(3*o-4*s+1)*t._z+(-o+s)*6*i._z+(3*o-2*s)*r._z,a._w=(o-s)*6*e._w+(3*o-4*s+1)*t._w+(-o+s)*6*i._w+(3*o-2*s)*r._w,a._isDirty=!0,a}static Normalize(e){let t=n.Zero();return n.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Clamp(e,t,i){let r=new n;return n.ClampToRef(e,t,i,r),r}static ClampToRef(e,t,i,r){return r.copyFromFloats(wt(e.x,t.x,i.x),wt(e.y,t.y,i.y),wt(e.z,t.z,i.z),wt(e.w,t.w,i.w))}static Random(e=0,t=1){return new n(nr(e,t),nr(e,t),nr(e,t),nr(e,t))}static RandomToRef(e=0,t=1,i){return i.copyFromFloats(nr(e,t),nr(e,t),nr(e,t),nr(e,t))}static Minimize(){throw new ReferenceError("Quaternion.Minimize does not make sense")}static Maximize(){throw new ReferenceError("Quaternion.Maximize does not make sense")}static Distance(e,t){return Math.sqrt(n.DistanceSquared(e,t))}static DistanceSquared(e,t){let i=e.x-t.x,r=e.y-t.y,s=e.z-t.z,a=e.w-t.w;return i*i+r*r+s*s+a*a}static Center(e,t){return n.CenterToRef(e,t,n.Zero())}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2,(e.z+t.z)/2,(e.w+t.w)/2)}};Xe._V8PerformanceHack=new Xe(.5,.5,.5,.5);Object.defineProperties(Xe.prototype,{dimension:{value:[4]},rank:{value:1}});K=class n{static get Use64Bits(){return qn.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=Hu._UpdateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0}_updateIdentityStatus(e,t=!1,i=!1,r=!0){this._isIdentity=e,this._isIdentity3x2=e||i,this._isIdentityDirty=this._isIdentity?!1:t,this._isIdentity3x2Dirty=this._isIdentity3x2?!1:r}constructor(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,qn.MatrixTrackPrecisionChange&&qn.MatrixTrackedMatrices.push(this),this._m=new qn.MatrixCurrentType(16),this.markAsUpdated()}isIdentity(){if(this._isIdentityDirty){this._isIdentityDirty=!1;let e=this._m;this._isIdentity=e[0]===1&&e[1]===0&&e[2]===0&&e[3]===0&&e[4]===0&&e[5]===1&&e[6]===0&&e[7]===0&&e[8]===0&&e[9]===0&&e[10]===1&&e[11]===0&&e[12]===0&&e[13]===0&&e[14]===0&&e[15]===1}return this._isIdentity}isIdentityAs3x2(){return this._isIdentity3x2Dirty&&(this._isIdentity3x2Dirty=!1,this._m[0]!==1||this._m[5]!==1||this._m[15]!==1?this._isIdentity3x2=!1:this._m[1]!==0||this._m[2]!==0||this._m[3]!==0||this._m[4]!==0||this._m[6]!==0||this._m[7]!==0||this._m[8]!==0||this._m[9]!==0||this._m[10]!==0||this._m[11]!==0||this._m[12]!==0||this._m[13]!==0||this._m[14]!==0?this._isIdentity3x2=!1:this._isIdentity3x2=!0),this._isIdentity3x2}determinant(){if(this._isIdentity===!0)return 1;let e=this._m,t=e[0],i=e[1],r=e[2],s=e[3],a=e[4],o=e[5],l=e[6],c=e[7],f=e[8],h=e[9],d=e[10],u=e[11],m=e[12],p=e[13],_=e[14],g=e[15],v=d*g-_*u,x=h*g-p*u,A=h*_-p*d,S=f*g-m*u,E=f*_-d*m,R=f*p-m*h,I=+(o*v-l*x+c*A),y=-(a*v-l*S+c*E),M=+(a*x-o*S+c*R),D=-(a*A-o*E+l*R);return t*I+i*y+r*M+s*D}toString(){return`{${this.m[0]}, ${this.m[1]}, ${this.m[2]}, ${this.m[3]} ${this.m[4]}, ${this.m[5]}, ${this.m[6]}, ${this.m[7]} ${this.m[8]}, ${this.m[9]}, ${this.m[10]}, ${this.m[11]} -${this.m[12]}, ${this.m[13]}, ${this.m[14]}, ${this.m[15]}}`}toArray(e=null,t=0){if(!e)return this._m;let i=this._m;for(let r=0;r<16;r++)e[t+r]=i[r];return this}asArray(){return this._m}fromArray(e,t=0){return n.FromArrayToRef(e,t,this)}copyFromFloats(...e){return n.FromArrayToRef(e,0,this)}set(...e){let t=this._m;for(let i=0;i<16;i++)t[i]=e[i];return this.markAsUpdated(),this}setAll(e){let t=this._m;for(let i=0;i<16;i++)t[i]=e;return this.markAsUpdated(),this}invert(){return this.invertToRef(this),this}reset(){return n.FromValuesToRef(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,this),this._updateIdentityStatus(!1),this}add(e){let t=new n;return this.addToRef(e,t),t}addToRef(e,t){let i=this._m,r=t._m,s=e.m;for(let a=0;a<16;a++)r[a]=i[a]+s[a];return t.markAsUpdated(),t}addToSelf(e){let t=this._m,i=e.m;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.markAsUpdated(),this}addInPlace(e){let t=this._m,i=e.m;for(let r=0;r<16;r++)t[r]+=i[r];return this.markAsUpdated(),this}addInPlaceFromFloats(...e){let t=this._m;for(let i=0;i<16;i++)t[i]+=e[i];return this.markAsUpdated(),this}subtract(e){let t=this._m,i=e.m;for(let r=0;r<16;r++)t[r]-=i[r];return this.markAsUpdated(),this}subtractToRef(e,t){let i=this._m,r=e.m,s=t._m;for(let a=0;a<16;a++)s[a]=i[a]-r[a];return t.markAsUpdated(),t}subtractInPlace(e){let t=this._m,i=e.m;for(let r=0;r<16;r++)t[r]-=i[r];return this.markAsUpdated(),this}subtractFromFloats(...e){return this.subtractFromFloatsToRef(...e,new n)}subtractFromFloatsToRef(...e){let t=e.pop(),i=this._m,r=t._m,s=e;for(let a=0;a<16;a++)r[a]=i[a]-s[a];return t.markAsUpdated(),t}invertToRef(e){return this._isIdentity===!0?(n.IdentityToRef(e),e):(OM(this,e.asArray())?e.markAsUpdated():e.copyFrom(this),e)}addAtIndex(e,t){return this._m[e]+=t,this.markAsUpdated(),this}multiplyAtIndex(e,t){return this._m[e]*=t,this.markAsUpdated(),this}setTranslationFromFloats(e,t,i){return this._m[12]=e,this._m[13]=t,this._m[14]=i,this.markAsUpdated(),this}addTranslationFromFloats(e,t,i){return this._m[12]+=e,this._m[13]+=t,this._m[14]+=i,this.markAsUpdated(),this}setTranslation(e){return this.setTranslationFromFloats(e._x,e._y,e._z)}getTranslation(){return new b(this._m[12],this._m[13],this._m[14])}getTranslationToRef(e){return e.x=this._m[12],e.y=this._m[13],e.z=this._m[14],e}removeRotationAndScaling(){let e=this.m;return n.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e[12],e[13],e[14],e[15],this),this._updateIdentityStatus(e[12]===0&&e[13]===0&&e[14]===0&&e[15]===1),this}copyFrom(e){e.copyToArray(this._m);let t=e;return this.updateFlag=t.updateFlag,this._updateIdentityStatus(t._isIdentity,t._isIdentityDirty,t._isIdentity3x2,t._isIdentity3x2Dirty),this}copyToArray(e,t=0){return g2(this,e,t),this}multiply(e){let t=new n;return this.multiplyToRef(e,t),t}multiplyInPlace(e){let t=this._m,i=e.m;for(let r=0;r<16;r++)t[r]*=i[r];return this.markAsUpdated(),this}multiplyByFloats(...e){let t=this._m;for(let i=0;i<16;i++)t[i]*=e[i];return this.markAsUpdated(),this}multiplyByFloatsToRef(...e){let t=e.pop(),i=this._m,r=t._m,s=e;for(let a=0;a<16;a++)r[a]=i[a]*s[a];return t.markAsUpdated(),t}multiplyToRef(e,t){return this._isIdentity?(t.copyFrom(e),t):e._isIdentity?(t.copyFrom(this),t):(this.multiplyToArray(e,t._m,0),t.markAsUpdated(),t)}multiplyToArray(e,t,i){return LM(this,e,t,i),this}divide(e){return this.divideToRef(e,new n)}divideToRef(e,t){let i=this._m,r=e.m,s=t._m;for(let a=0;a<16;a++)s[a]=i[a]/r[a];return t.markAsUpdated(),t}divideInPlace(e){let t=this._m,i=e.m;for(let r=0;r<16;r++)t[r]/=i[r];return this.markAsUpdated(),this}minimizeInPlace(e){let t=this._m,i=e.m;for(let r=0;r<16;r++)t[r]=Math.min(t[r],i[r]);return this.markAsUpdated(),this}minimizeInPlaceFromFloats(...e){let t=this._m;for(let i=0;i<16;i++)t[i]=Math.min(t[i],e[i]);return this.markAsUpdated(),this}maximizeInPlace(e){let t=this._m,i=e.m;for(let r=0;r<16;r++)t[r]=Math.min(t[r],i[r]);return this.markAsUpdated(),this}maximizeInPlaceFromFloats(...e){let t=this._m;for(let i=0;i<16;i++)t[i]=Math.min(t[i],e[i]);return this.markAsUpdated(),this}negate(){return this.negateToRef(new n)}negateInPlace(){let e=this._m;for(let t=0;t<16;t++)e[t]=-e[t];return this.markAsUpdated(),this}negateToRef(e){let t=this._m,i=e._m;for(let r=0;r<16;r++)i[r]=-t[r];return e.markAsUpdated(),e}equals(e){let t=e;if(!t)return!1;if((this._isIdentity||t._isIdentity)&&!this._isIdentityDirty&&!t._isIdentityDirty)return this._isIdentity&&t._isIdentity;let i=this.m,r=t.m;return i[0]===r[0]&&i[1]===r[1]&&i[2]===r[2]&&i[3]===r[3]&&i[4]===r[4]&&i[5]===r[5]&&i[6]===r[6]&&i[7]===r[7]&&i[8]===r[8]&&i[9]===r[9]&&i[10]===r[10]&&i[11]===r[11]&&i[12]===r[12]&&i[13]===r[13]&&i[14]===r[14]&&i[15]===r[15]}equalsWithEpsilon(e,t=0){let i=this._m,r=e.m;for(let s=0;s<16;s++)if(!Si(i[s],r[s],t))return!1;return!0}equalsToFloats(...e){let t=this._m;for(let i=0;i<16;i++)if(t[i]!=e[i])return!1;return!0}floor(){return this.floorToRef(new n)}floorToRef(e){let t=this._m,i=e._m;for(let r=0;r<16;r++)i[r]=Math.floor(t[r]);return e.markAsUpdated(),e}fract(){return this.fractToRef(new n)}fractToRef(e){let t=this._m,i=e._m;for(let r=0;r<16;r++)i[r]=t[r]-Math.floor(t[r]);return e.markAsUpdated(),e}clone(){let e=new n;return e.copyFrom(this),e}getClassName(){return"Matrix"}getHashCode(){let e=$n(this._m[0]);for(let t=1;t<16;t++)e=e*397^$n(this._m[t]);return e}decomposeToTransformNode(e){return e.rotationQuaternion=e.rotationQuaternion||new Ye,this.decompose(e.scaling,e.rotationQuaternion,e.position)}decompose(e,t,i,r,s=!0){if(this._isIdentity)return i&&i.setAll(0),e&&e.setAll(1),t&&t.copyFromFloats(0,0,0,1),!0;let a=this._m;if(i&&i.copyFromFloats(a[12],a[13],a[14]),e=e||ze.Vector3[0],e.x=Math.sqrt(a[0]*a[0]+a[1]*a[1]+a[2]*a[2]),e.y=Math.sqrt(a[4]*a[4]+a[5]*a[5]+a[6]*a[6]),e.z=Math.sqrt(a[8]*a[8]+a[9]*a[9]+a[10]*a[10]),r){let o=(s?r.absoluteScaling.x:r.scaling.x)<0?-1:1,l=(s?r.absoluteScaling.y:r.scaling.y)<0?-1:1,c=(s?r.absoluteScaling.z:r.scaling.z)<0?-1:1;e.x*=o,e.y*=l,e.z*=c}else this.determinant()<=0&&(e.y*=-1);if(e._x===0||e._y===0||e._z===0)return t&&t.copyFromFloats(0,0,0,1),!1;if(t){let o=1/e._x,l=1/e._y,c=1/e._z;n.FromValuesToRef(a[0]*o,a[1]*o,a[2]*o,0,a[4]*l,a[5]*l,a[6]*l,0,a[8]*c,a[9]*c,a[10]*c,0,0,0,0,1,ze.Matrix[0]),Ye.FromRotationMatrixToRef(ze.Matrix[0],t)}return!0}getRow(e){if(e<0||e>3)return null;let t=e*4;return new Ri(this._m[t+0],this._m[t+1],this._m[t+2],this._m[t+3])}getRowToRef(e,t){if(e>=0&&e<=3){let i=e*4;t.x=this._m[i+0],t.y=this._m[i+1],t.z=this._m[i+2],t.w=this._m[i+3]}return t}setRow(e,t){return this.setRowFromFloats(e,t.x,t.y,t.z,t.w)}transpose(){let e=new n;return n.TransposeToRef(this,e),e}transposeToRef(e){return n.TransposeToRef(this,e),e}setRowFromFloats(e,t,i,r,s){if(e<0||e>3)return this;let a=e*4;return this._m[a+0]=t,this._m[a+1]=i,this._m[a+2]=r,this._m[a+3]=s,this.markAsUpdated(),this}scale(e){let t=new n;return this.scaleToRef(e,t),t}scaleToRef(e,t){for(let i=0;i<16;i++)t._m[i]=this._m[i]*e;return t.markAsUpdated(),t}scaleAndAddToRef(e,t){for(let i=0;i<16;i++)t._m[i]+=this._m[i]*e;return t.markAsUpdated(),t}scaleInPlace(e){let t=this._m;for(let i=0;i<16;i++)t[i]*=e;return this.markAsUpdated(),this}toNormalMatrix(e){let t=ze.Matrix[0];this.invertToRef(t),t.transposeToRef(e);let i=e._m;return n.FromValuesToRef(i[0],i[1],i[2],0,i[4],i[5],i[6],0,i[8],i[9],i[10],0,0,0,0,1,e),e}getRotationMatrix(){let e=new n;return this.getRotationMatrixToRef(e),e}getRotationMatrixToRef(e){let t=ze.Vector3[0];if(!this.decompose(t))return n.IdentityToRef(e),e;let i=this._m,r=1/t._x,s=1/t._y,a=1/t._z;return n.FromValuesToRef(i[0]*r,i[1]*r,i[2]*r,0,i[4]*s,i[5]*s,i[6]*s,0,i[8]*a,i[9]*a,i[10]*a,0,0,0,0,1,e),e}toggleModelMatrixHandInPlace(){let e=this._m;return e[2]*=-1,e[6]*=-1,e[8]*=-1,e[9]*=-1,e[14]*=-1,this.markAsUpdated(),this}toggleProjectionMatrixHandInPlace(){let e=this._m;return e[8]*=-1,e[9]*=-1,e[10]*=-1,e[11]*=-1,this.markAsUpdated(),this}static FromArray(e,t=0){let i=new n;return n.FromArrayToRef(e,t,i),i}static FromArrayToRef(e,t,i){for(let r=0;r<16;r++)i._m[r]=e[r+t];return i.markAsUpdated(),i}static FromFloat32ArrayToRefScaled(e,t,i,r){return r._m[0]=e[0+t]*i,r._m[1]=e[1+t]*i,r._m[2]=e[2+t]*i,r._m[3]=e[3+t]*i,r._m[4]=e[4+t]*i,r._m[5]=e[5+t]*i,r._m[6]=e[6+t]*i,r._m[7]=e[7+t]*i,r._m[8]=e[8+t]*i,r._m[9]=e[9+t]*i,r._m[10]=e[10+t]*i,r._m[11]=e[11+t]*i,r._m[12]=e[12+t]*i,r._m[13]=e[13+t]*i,r._m[14]=e[14+t]*i,r._m[15]=e[15+t]*i,r.markAsUpdated(),r}static get IdentityReadOnly(){return n._IdentityReadOnly}static FromValuesToRef(e,t,i,r,s,a,o,l,c,f,h,d,u,m,p,_,g){let v=g._m;v[0]=e,v[1]=t,v[2]=i,v[3]=r,v[4]=s,v[5]=a,v[6]=o,v[7]=l,v[8]=c,v[9]=f,v[10]=h,v[11]=d,v[12]=u,v[13]=m,v[14]=p,v[15]=_,g.markAsUpdated()}static FromValues(e,t,i,r,s,a,o,l,c,f,h,d,u,m,p,_){let g=new n,v=g._m;return v[0]=e,v[1]=t,v[2]=i,v[3]=r,v[4]=s,v[5]=a,v[6]=o,v[7]=l,v[8]=c,v[9]=f,v[10]=h,v[11]=d,v[12]=u,v[13]=m,v[14]=p,v[15]=_,g.markAsUpdated(),g}static Compose(e,t,i){let r=new n;return n.ComposeToRef(e,t,i,r),r}static ComposeToRef(e,t,i,r){let s=r._m,a=t._x,o=t._y,l=t._z,c=t._w,f=a+a,h=o+o,d=l+l,u=a*f,m=a*h,p=a*d,_=o*h,g=o*d,v=l*d,x=c*f,A=c*h,S=c*d,E=e._x,R=e._y,I=e._z;return s[0]=(1-(_+v))*E,s[1]=(m+S)*E,s[2]=(p-A)*E,s[3]=0,s[4]=(m-S)*R,s[5]=(1-(u+v))*R,s[6]=(g+x)*R,s[7]=0,s[8]=(p+A)*I,s[9]=(g-x)*I,s[10]=(1-(u+_))*I,s[11]=0,s[12]=i._x,s[13]=i._y,s[14]=i._z,s[15]=1,r.markAsUpdated(),r}static Identity(){let e=n.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return e._updateIdentityStatus(!0),e}static IdentityToRef(e){return n.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,e),e._updateIdentityStatus(!0),e}static Zero(){let e=n.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return e._updateIdentityStatus(!1),e}static RotationX(e){let t=new n;return n.RotationXToRef(e,t),t}static Invert(e){let t=new n;return e.invertToRef(t),t}static RotationXToRef(e,t){let i=Math.sin(e),r=Math.cos(e);return n.FromValuesToRef(1,0,0,0,0,r,i,0,0,-i,r,0,0,0,0,1,t),t._updateIdentityStatus(r===1&&i===0),t}static RotationY(e){let t=new n;return n.RotationYToRef(e,t),t}static RotationYToRef(e,t){let i=Math.sin(e),r=Math.cos(e);return n.FromValuesToRef(r,0,-i,0,0,1,0,0,i,0,r,0,0,0,0,1,t),t._updateIdentityStatus(r===1&&i===0),t}static RotationZ(e){let t=new n;return n.RotationZToRef(e,t),t}static RotationZToRef(e,t){let i=Math.sin(e),r=Math.cos(e);return n.FromValuesToRef(r,i,0,0,-i,r,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(r===1&&i===0),t}static RotationAxis(e,t){let i=new n;return n.RotationAxisToRef(e,t,i),i}static RotationAxisToRef(e,t,i){let r=Math.sin(-t),s=Math.cos(-t),a=1-s;e=e.normalizeToRef(ze.Vector3[0]);let o=i._m;return o[0]=e._x*e._x*a+s,o[1]=e._x*e._y*a-e._z*r,o[2]=e._x*e._z*a+e._y*r,o[3]=0,o[4]=e._y*e._x*a+e._z*r,o[5]=e._y*e._y*a+s,o[6]=e._y*e._z*a-e._x*r,o[7]=0,o[8]=e._z*e._x*a-e._y*r,o[9]=e._z*e._y*a+e._x*r,o[10]=e._z*e._z*a+s,o[11]=0,o[12]=0,o[13]=0,o[14]=0,o[15]=1,i.markAsUpdated(),i}static RotationAlignToRef(e,t,i,r=!1){let s=b.Dot(t,e),a=i._m;if(s<-1+Ot)a[0]=-1,a[1]=0,a[2]=0,a[3]=0,a[4]=0,a[5]=r?1:-1,a[6]=0,a[7]=0,a[8]=0,a[9]=0,a[10]=r?-1:1,a[11]=0;else{let o=b.Cross(t,e),l=1/(1+s);a[0]=o._x*o._x*l+s,a[1]=o._y*o._x*l-o._z,a[2]=o._z*o._x*l+o._y,a[3]=0,a[4]=o._x*o._y*l+o._z,a[5]=o._y*o._y*l+s,a[6]=o._z*o._y*l-o._x,a[7]=0,a[8]=o._x*o._z*l-o._y,a[9]=o._y*o._z*l+o._x,a[10]=o._z*o._z*l+s,a[11]=0}return a[12]=0,a[13]=0,a[14]=0,a[15]=1,i.markAsUpdated(),i}static RotationYawPitchRoll(e,t,i){let r=new n;return n.RotationYawPitchRollToRef(e,t,i,r),r}static RotationYawPitchRollToRef(e,t,i,r){return Ye.RotationYawPitchRollToRef(e,t,i,ze.Quaternion[0]),ze.Quaternion[0].toRotationMatrix(r),r}static Scaling(e,t,i){let r=new n;return n.ScalingToRef(e,t,i,r),r}static ScalingToRef(e,t,i,r){return n.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1,r),r._updateIdentityStatus(e===1&&t===1&&i===1),r}static Translation(e,t,i){let r=new n;return n.TranslationToRef(e,t,i,r),r}static TranslationToRef(e,t,i,r){return n.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1,r),r._updateIdentityStatus(e===0&&t===0&&i===0),r}static Lerp(e,t,i){let r=new n;return n.LerpToRef(e,t,i,r),r}static LerpToRef(e,t,i,r){let s=r._m,a=e.m,o=t.m;for(let l=0;l<16;l++)s[l]=a[l]*(1-i)+o[l]*i;return r.markAsUpdated(),r}static DecomposeLerp(e,t,i){let r=new n;return n.DecomposeLerpToRef(e,t,i,r),r}static DecomposeLerpToRef(e,t,i,r){let s=ze.Vector3[0],a=ze.Quaternion[0],o=ze.Vector3[1];e.decompose(s,a,o);let l=ze.Vector3[2],c=ze.Quaternion[1],f=ze.Vector3[3];t.decompose(l,c,f);let h=ze.Vector3[4];b.LerpToRef(s,l,i,h);let d=ze.Quaternion[2];Ye.SlerpToRef(a,c,i,d);let u=ze.Vector3[5];return b.LerpToRef(o,f,i,u),n.ComposeToRef(h,d,u,r),r}static LookAtLH(e,t,i){let r=new n;return n.LookAtLHToRef(e,t,i,r),r}static LookAtLHToRef(e,t,i,r){let s=ze.Vector3[0],a=ze.Vector3[1],o=ze.Vector3[2];t.subtractToRef(e,o),o.normalize(),b.CrossToRef(i,o,s);let l=s.lengthSquared();l===0?s.x=1:s.normalizeFromLength(Math.sqrt(l)),b.CrossToRef(o,s,a),a.normalize();let c=-b.Dot(s,e),f=-b.Dot(a,e),h=-b.Dot(o,e);return n.FromValuesToRef(s._x,a._x,o._x,0,s._y,a._y,o._y,0,s._z,a._z,o._z,0,c,f,h,1,r),r}static LookAtRH(e,t,i){let r=new n;return n.LookAtRHToRef(e,t,i,r),r}static LookAtRHToRef(e,t,i,r){let s=ze.Vector3[0],a=ze.Vector3[1],o=ze.Vector3[2];e.subtractToRef(t,o),o.normalize(),b.CrossToRef(i,o,s);let l=s.lengthSquared();l===0?s.x=1:s.normalizeFromLength(Math.sqrt(l)),b.CrossToRef(o,s,a),a.normalize();let c=-b.Dot(s,e),f=-b.Dot(a,e),h=-b.Dot(o,e);return n.FromValuesToRef(s._x,a._x,o._x,0,s._y,a._y,o._y,0,s._z,a._z,o._z,0,c,f,h,1,r),r}static LookDirectionLH(e,t){let i=new n;return n.LookDirectionLHToRef(e,t,i),i}static LookDirectionLHToRef(e,t,i){let r=ze.Vector3[0];r.copyFrom(e),r.scaleInPlace(-1);let s=ze.Vector3[1];return b.CrossToRef(t,r,s),n.FromValuesToRef(s._x,s._y,s._z,0,t._x,t._y,t._z,0,r._x,r._y,r._z,0,0,0,0,1,i),i}static LookDirectionRH(e,t){let i=new n;return n.LookDirectionRHToRef(e,t,i),i}static LookDirectionRHToRef(e,t,i){let r=ze.Vector3[2];return b.CrossToRef(t,e,r),n.FromValuesToRef(r._x,r._y,r._z,0,t._x,t._y,t._z,0,e._x,e._y,e._z,0,0,0,0,1,i),i}static OrthoLH(e,t,i,r,s){let a=new n;return n.OrthoLHToRef(e,t,i,r,a,s),a}static OrthoLHToRef(e,t,i,r,s,a){let o=i,l=r,c=2/e,f=2/t,h=2/(l-o),d=-(l+o)/(l-o);return n.FromValuesToRef(c,0,0,0,0,f,0,0,0,0,h,0,0,0,d,1,s),a&&s.multiplyToRef(Nh,s),s._updateIdentityStatus(c===1&&f===1&&h===1&&d===0),s}static OrthoOffCenterLH(e,t,i,r,s,a,o){let l=new n;return n.OrthoOffCenterLHToRef(e,t,i,r,s,a,l,o),l}static OrthoOffCenterLHToRef(e,t,i,r,s,a,o,l){let c=s,f=a,h=2/(t-e),d=2/(r-i),u=2/(f-c),m=-(f+c)/(f-c),p=(e+t)/(e-t),_=(r+i)/(i-r);return n.FromValuesToRef(h,0,0,0,0,d,0,0,0,0,u,0,p,_,m,1,o),l&&o.multiplyToRef(Nh,o),o.markAsUpdated(),o}static ObliqueOffCenterLHToRef(e,t,i,r,s,a,o,l,c,f,h){let d=-o*Math.cos(l),u=-o*Math.sin(l);return n.TranslationToRef(0,0,-c,ze.Matrix[1]),n.FromValuesToRef(1,0,0,0,0,1,0,0,d,u,1,0,0,0,0,1,ze.Matrix[0]),ze.Matrix[1].multiplyToRef(ze.Matrix[0],ze.Matrix[0]),n.TranslationToRef(0,0,c,ze.Matrix[1]),ze.Matrix[0].multiplyToRef(ze.Matrix[1],ze.Matrix[0]),n.OrthoOffCenterLHToRef(e,t,i,r,s,a,f,h),ze.Matrix[0].multiplyToRef(f,f),f}static OrthoOffCenterRH(e,t,i,r,s,a,o){let l=new n;return n.OrthoOffCenterRHToRef(e,t,i,r,s,a,l,o),l}static OrthoOffCenterRHToRef(e,t,i,r,s,a,o,l){return n.OrthoOffCenterLHToRef(e,t,i,r,s,a,o,l),o._m[10]*=-1,o}static ObliqueOffCenterRHToRef(e,t,i,r,s,a,o,l,c,f,h){let d=o*Math.cos(l),u=o*Math.sin(l);return n.TranslationToRef(0,0,c,ze.Matrix[1]),n.FromValuesToRef(1,0,0,0,0,1,0,0,d,u,1,0,0,0,0,1,ze.Matrix[0]),ze.Matrix[1].multiplyToRef(ze.Matrix[0],ze.Matrix[0]),n.TranslationToRef(0,0,-c,ze.Matrix[1]),ze.Matrix[0].multiplyToRef(ze.Matrix[1],ze.Matrix[0]),n.OrthoOffCenterRHToRef(e,t,i,r,s,a,f,h),ze.Matrix[0].multiplyToRef(f,f),f}static PerspectiveLH(e,t,i,r,s,a=0){let o=new n,l=i,c=r,f=2*l/e,h=2*l/t,d=(c+l)/(c-l),u=-2*c*l/(c-l),m=Math.tan(a);return n.FromValuesToRef(f,0,0,0,0,h,0,m,0,0,d,1,0,0,u,0,o),s&&o.multiplyToRef(Nh,o),o._updateIdentityStatus(!1),o}static PerspectiveFovLH(e,t,i,r,s,a=0,o=!1){let l=new n;return n.PerspectiveFovLHToRef(e,t,i,r,l,!0,s,a,o),l}static PerspectiveFovLHToRef(e,t,i,r,s,a=!0,o,l=0,c=!1){let f=i,h=r,d=1/Math.tan(e*.5),u=a?d/t:d,m=a?d:d*t,p=c&&f===0?-1:h!==0?(h+f)/(h-f):1,_=c&&f===0?2*h:h!==0?-2*h*f/(h-f):-2*f,g=Math.tan(l);return n.FromValuesToRef(u,0,0,0,0,m,0,g,0,0,p,1,0,0,_,0,s),o&&s.multiplyToRef(Nh,s),s._updateIdentityStatus(!1),s}static PerspectiveFovReverseLHToRef(e,t,i,r,s,a=!0,o,l=0){let c=1/Math.tan(e*.5),f=a?c/t:c,h=a?c:c*t,d=Math.tan(l);return n.FromValuesToRef(f,0,0,0,0,h,0,d,0,0,-i,1,0,0,1,0,s),o&&s.multiplyToRef(Nh,s),s._updateIdentityStatus(!1),s}static PerspectiveFovRH(e,t,i,r,s,a=0,o=!1){let l=new n;return n.PerspectiveFovRHToRef(e,t,i,r,l,!0,s,a,o),l}static PerspectiveFovRHToRef(e,t,i,r,s,a=!0,o,l=0,c=!1){let f=i,h=r,d=1/Math.tan(e*.5),u=a?d/t:d,m=a?d:d*t,p=c&&f===0?1:h!==0?-(h+f)/(h-f):-1,_=c&&f===0?2*h:h!==0?-2*h*f/(h-f):-2*f,g=Math.tan(l);return n.FromValuesToRef(u,0,0,0,0,m,0,g,0,0,p,-1,0,0,_,0,s),o&&s.multiplyToRef(Nh,s),s._updateIdentityStatus(!1),s}static PerspectiveFovReverseRHToRef(e,t,i,r,s,a=!0,o,l=0){let c=1/Math.tan(e*.5),f=a?c/t:c,h=a?c:c*t,d=Math.tan(l);return n.FromValuesToRef(f,0,0,0,0,h,0,d,0,0,-i,-1,0,0,-1,0,s),o&&s.multiplyToRef(Nh,s),s._updateIdentityStatus(!1),s}static GetFinalMatrix(e,t,i,r,s,a){let o=e.width,l=e.height,c=e.x,f=e.y,h=n.FromValues(o/2,0,0,0,0,-l/2,0,0,0,0,a-s,0,c+o/2,l/2+f,s,1),d=new n;return t.multiplyToRef(i,d),d.multiplyToRef(r,d),d.multiplyToRef(h,d)}static GetAsMatrix2x2(e){let t=e.m,i=[t[0],t[1],t[4],t[5]];return Zn.MatrixUse64Bits?i:new Float32Array(i)}static GetAsMatrix3x3(e){let t=e.m,i=[t[0],t[1],t[2],t[4],t[5],t[6],t[8],t[9],t[10]];return Zn.MatrixUse64Bits?i:new Float32Array(i)}static Transpose(e){let t=new n;return n.TransposeToRef(e,t),t}static TransposeToRef(e,t){let i=e.m,r=i[0],s=i[4],a=i[8],o=i[12],l=i[1],c=i[5],f=i[9],h=i[13],d=i[2],u=i[6],m=i[10],p=i[14],_=i[3],g=i[7],v=i[11],x=i[15],A=t._m;return A[0]=r,A[1]=s,A[2]=a,A[3]=o,A[4]=l,A[5]=c,A[6]=f,A[7]=h,A[8]=d,A[9]=u,A[10]=m,A[11]=p,A[12]=_,A[13]=g,A[14]=v,A[15]=x,t.markAsUpdated(),t._updateIdentityStatus(e._isIdentity,e._isIdentityDirty),t}static Reflection(e){let t=new n;return n.ReflectionToRef(e,t),t}static ReflectionToRef(e,t){e.normalize();let i=e.normal.x,r=e.normal.y,s=e.normal.z,a=-2*i,o=-2*r,l=-2*s;return n.FromValuesToRef(a*i+1,o*i,l*i,0,a*r,o*r+1,l*r,0,a*s,o*s,l*s+1,0,a*e.d,o*e.d,l*e.d,1,t),t}static FromXYZAxesToRef(e,t,i,r){return n.FromValuesToRef(e._x,e._y,e._z,0,t._x,t._y,t._z,0,i._x,i._y,i._z,0,0,0,0,1,r),r}static FromQuaternionToRef(e,t){let i=e._x*e._x,r=e._y*e._y,s=e._z*e._z,a=e._x*e._y,o=e._z*e._w,l=e._z*e._x,c=e._y*e._w,f=e._y*e._z,h=e._x*e._w;return t._m[0]=1-2*(r+s),t._m[1]=2*(a+o),t._m[2]=2*(l-c),t._m[3]=0,t._m[4]=2*(a-o),t._m[5]=1-2*(s+i),t._m[6]=2*(f+h),t._m[7]=0,t._m[8]=2*(l+c),t._m[9]=2*(f-h),t._m[10]=1-2*(r+i),t._m[11]=0,t._m[12]=0,t._m[13]=0,t._m[14]=0,t._m[15]=1,t.markAsUpdated(),t}};j._IdentityReadOnly=j.Identity();Object.defineProperties(j.prototype,{dimension:{value:[4,4]},rank:{value:2}});ze=class{};ze.Vector3=Ul(11,b.Zero);ze.Matrix=Ul(2,j.Identity);ze.Quaternion=Ul(3,Ye.Zero);$=class{};$.Vector2=Ul(3,we.Zero);$.Vector3=Ul(13,b.Zero);$.Vector4=Ul(3,Ri.Zero);$.Quaternion=Ul(3,Ye.Zero);$.Matrix=Ul(8,j.Identity);wt("BABYLON.Vector2",we);wt("BABYLON.Vector3",b);wt("BABYLON.Vector4",Ri);wt("BABYLON.Matrix",j);Nh=j.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1)});var v2,Ss,E2,Xu=C(()=>{Ve();(function(n){n[n.LOCAL=0]="LOCAL",n[n.WORLD=1]="WORLD",n[n.BONE=2]="BONE"})(v2||(v2={}));Ss=class{};Ss.X=new b(1,0,0);Ss.Y=new b(0,1,0);Ss.Z=new b(0,0,1);(function(n){n[n.X=0]="X",n[n.Y=1]="Y",n[n.Z=2]="Z"})(E2||(E2={}))});function Yu(n){return Math.pow(n,Hu)}function Ku(n){return n<=.04045?.0773993808*n:Math.pow(.947867299*(n+.055),2.4)}function ju(n){return Math.pow(n,h2)}function qu(n){return n<=.0031308?12.92*n:1.055*Math.pow(n,.41666)-.055}var ge,lt,En,zt=C(()=>{Zo();Hi();Dn();Ln();ge=class n{constructor(e=0,t=0,i=0){this.r=e,this.g=t,this.b=i}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+"}"}getClassName(){return"Color3"}getHashCode(){let e=this.r*255|0;return e=e*397^(this.g*255|0),e=e*397^(this.b*255|0),e}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,this}fromArray(e,t=0){return n.FromArrayToRef(e,t,this),this}toColor4(e=1){return new lt(this.r,this.g,this.b,e)}asArray(){return[this.r,this.g,this.b]}toLuminance(){return this.r*.3+this.g*.59+this.b*.11}multiply(e){return new n(this.r*e.r,this.g*e.g,this.b*e.b)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyByFloats(e,t,i){return new n(this.r*e,this.g*t,this.b*i)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e.r,e.g,e.b)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e.r,e.g,e.b)}minimizeInPlaceFromFloats(e,t,i){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this}maximizeInPlaceFromFloats(e,t,i){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,this.b),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b}equalsFloats(e,t,i){return this.equalsToFloats(e,t,i)}equalsToFloats(e,t,i){return this.r===e&&this.g===t&&this.b===i}equalsWithEpsilon(e,t=Ot){return Si(this.r,e.r,t)&&Si(this.g,e.g,t)&&Si(this.b,e.b,t)}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}scale(e){return new n(this.r*e,this.g*e,this.b*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t}clampToRef(e=0,t=1,i){return i.r=Nt(this.r,e,t),i.g=Nt(this.g,e,t),i.b=Nt(this.b,e,t),i}add(e){return new n(this.r+e.r,this.g+e.g,this.b+e.b)}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addInPlaceFromFloats(e,t,i){return this.r+=e,this.g+=t,this.b+=i,this}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t}subtract(e){return new n(this.r-e.r,this.g-e.g,this.b-e.b)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this}subtractFromFloats(e,t,i){return new n(this.r-e,this.g-t,this.b-i)}subtractFromFloatsToRef(e,t,i,r){return r.r=this.r-e,r.g=this.g-t,r.b=this.b-i,r}clone(){return new n(this.r,this.g,this.b)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copyFromFloats(e,t,i){return this.r=e,this.g=t,this.b=i,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this.r=this.g=this.b=e,this}toHexString(){let e=Math.round(this.r*255),t=Math.round(this.g*255),i=Math.round(this.b*255);return"#"+eo(e)+eo(t)+eo(i)}fromHexString(e){return e.substring(0,1)!=="#"||e.length!==7?this:(this.r=parseInt(e.substring(1,3),16)/255,this.g=parseInt(e.substring(3,5),16)/255,this.b=parseInt(e.substring(5,7),16)/255,this)}toHSV(){return this.toHSVToRef(new n)}toHSVToRef(e){let t=this.r,i=this.g,r=this.b,s=Math.max(t,i,r),a=Math.min(t,i,r),o=0,l=0,c=s,f=s-a;return s!==0&&(l=f/s),s!=a&&(s==t?(o=(i-r)/f,i=0&&a<=1?(l=s,c=o):a>=1&&a<=2?(l=o,c=s):a>=2&&a<=3?(c=s,f=o):a>=3&&a<=4?(c=o,f=s):a>=4&&a<=5?(l=o,f=s):a>=5&&a<=6&&(l=s,f=o);let h=i-s;return r.r=l+h,r.g=c+h,r.b=f+h,r}static FromHSV(e,t,i){let r=new n(0,0,0);return n.HSVtoRGBToRef(e,t,i,r),r}static FromHexString(e){return new n(0,0,0).fromHexString(e)}static FromArray(e,t=0){return new n(e[t],e[t+1],e[t+2])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2]}static FromInts(e,t,i){return new n(e/255,t/255,i/255)}static Lerp(e,t,i){let r=new n(0,0,0);return n.LerpToRef(e,t,i,r),r}static LerpToRef(e,t,i,r){r.r=e.r+(t.r-e.r)*i,r.g=e.g+(t.g-e.g)*i,r.b=e.b+(t.b-e.b)*i}static Hermite(e,t,i,r,s){let a=s*s,o=s*a,l=2*o-3*a+1,c=-2*o+3*a,f=o-2*a+s,h=o-a,d=e.r*l+i.r*c+t.r*f+r.r*h,u=e.g*l+i.g*c+t.g*f+r.g*h,m=e.b*l+i.b*c+t.b*f+r.b*h;return new n(d,u,m)}static Hermite1stDerivative(e,t,i,r,s){let a=n.Black();return this.Hermite1stDerivativeToRef(e,t,i,r,s,a),a}static Hermite1stDerivativeToRef(e,t,i,r,s,a){let o=s*s;a.r=(o-s)*6*e.r+(3*o-4*s+1)*t.r+(-o+s)*6*i.r+(3*o-2*s)*r.r,a.g=(o-s)*6*e.g+(3*o-4*s+1)*t.g+(-o+s)*6*i.g+(3*o-2*s)*r.g,a.b=(o-s)*6*e.b+(3*o-4*s+1)*t.b+(-o+s)*6*i.b+(3*o-2*s)*r.b}static Red(){return new n(1,0,0)}static Green(){return new n(0,1,0)}static Blue(){return new n(0,0,1)}static Black(){return new n(0,0,0)}static get BlackReadOnly(){return n._BlackReadOnly}static White(){return new n(1,1,1)}static Purple(){return new n(.5,0,.5)}static Magenta(){return new n(1,0,1)}static Yellow(){return new n(1,1,0)}static Gray(){return new n(.5,.5,.5)}static Teal(){return new n(0,1,1)}static Random(){return new n(Math.random(),Math.random(),Math.random())}};ge._V8PerformanceHack=new ge(.5,.5,.5);ge._BlackReadOnly=ge.Black();Object.defineProperties(ge.prototype,{dimension:{value:[3]},rank:{value:1}});lt=class n{constructor(e=0,t=0,i=0,r=1){this.r=e,this.g=t,this.b=i,this.a=r}asArray(){return[this.r,this.g,this.b,this.a]}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e[t+3]=this.a,this}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this.a=e[t+3],this}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b&&this.a===e.a}add(e){return new n(this.r+e.r,this.g+e.g,this.b+e.b,this.a+e.a)}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t.a=this.a+e.a,t}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this}addInPlaceFromFloats(e,t,i,r){return this.r+=e,this.g+=t,this.b+=i,this.a+=r,this}subtract(e){return new n(this.r-e.r,this.g-e.g,this.b-e.b,this.a-e.a)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t.a=this.a-e.a,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this.a-=e.a,this}subtractFromFloats(e,t,i,r){return new n(this.r-e,this.g-t,this.b-i,this.a-r)}subtractFromFloatsToRef(e,t,i,r,s){return s.r=this.r-e,s.g=this.g-t,s.b=this.b-i,s.a=this.a-r,s}scale(e){return new n(this.r*e,this.g*e,this.b*e,this.a*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this.a*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t.a=this.a*e,t}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t.a+=this.a*e,t}clampToRef(e=0,t=1,i){return i.r=Nt(this.r,e,t),i.g=Nt(this.g,e,t),i.b=Nt(this.b,e,t),i.a=Nt(this.a,e,t),i}multiply(e){return new n(this.r*e.r,this.g*e.g,this.b*e.b,this.a*e.a)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t.a=this.a*e.a,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this.a*=e.a,this}multiplyByFloats(e,t,i,r){return new n(this.r*e,this.g*t,this.b*i,this.a*r)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.r=Math.min(this.r,e.r),this.g=Math.min(this.g,e.g),this.b=Math.min(this.b,e.b),this.a=Math.min(this.a,e.a),this}maximizeInPlace(e){return this.r=Math.max(this.r,e.r),this.g=Math.max(this.g,e.g),this.b=Math.max(this.b,e.b),this.a=Math.max(this.a,e.a),this}minimizeInPlaceFromFloats(e,t,i,r){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this.a=Math.min(r,this.a),this}maximizeInPlaceFromFloats(e,t,i,r){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,this.b),this.a=Math.max(r,this.a),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}equalsWithEpsilon(e,t=Ot){return Si(this.r,e.r,t)&&Si(this.g,e.g,t)&&Si(this.b,e.b,t)&&Si(this.a,e.a,t)}equalsToFloats(e,t,i,r){return this.r===e&&this.g===t&&this.b===i&&this.a===r}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+" A:"+this.a+"}"}getClassName(){return"Color4"}getHashCode(){let e=this.r*255|0;return e=e*397^(this.g*255|0),e=e*397^(this.b*255|0),e=e*397^(this.a*255|0),e}clone(){return new n().copyFrom(this)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this}copyFromFloats(e,t,i,r){return this.r=e,this.g=t,this.b=i,this.a=r,this}set(e,t,i,r){return this.copyFromFloats(e,t,i,r)}setAll(e){return this.r=this.g=this.b=this.a=e,this}toHexString(e=!1){let t=Math.round(this.r*255),i=Math.round(this.g*255),r=Math.round(this.b*255);if(e)return"#"+eo(t)+eo(i)+eo(r);let s=Math.round(this.a*255);return"#"+eo(t)+eo(i)+eo(r)+eo(s)}fromHexString(e){return e.substring(0,1)!=="#"||e.length!==9&&e.length!==7?this:(this.r=parseInt(e.substring(1,3),16)/255,this.g=parseInt(e.substring(3,5),16)/255,this.b=parseInt(e.substring(5,7),16)/255,e.length===9&&(this.a=parseInt(e.substring(7,9),16)/255),this)}toLinearSpace(e=!1){let t=new n;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=Ku(this.r),e.g=Ku(this.g),e.b=Ku(this.b)):(e.r=Yu(this.r),e.g=Yu(this.g),e.b=Yu(this.b)),e.a=this.a,this}toGammaSpace(e=!1){let t=new n;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=qu(this.r),e.g=qu(this.g),e.b=qu(this.b)):(e.r=ju(this.r),e.g=ju(this.g),e.b=ju(this.b)),e.a=this.a,this}static FromHexString(e){return e.substring(0,1)!=="#"||e.length!==9&&e.length!==7?new n(0,0,0,0):new n(0,0,0,1).fromHexString(e)}static Lerp(e,t,i){return n.LerpToRef(e,t,i,new n)}static LerpToRef(e,t,i,r){return r.r=e.r+(t.r-e.r)*i,r.g=e.g+(t.g-e.g)*i,r.b=e.b+(t.b-e.b)*i,r.a=e.a+(t.a-e.a)*i,r}static Hermite(e,t,i,r,s){let a=s*s,o=s*a,l=2*o-3*a+1,c=-2*o+3*a,f=o-2*a+s,h=o-a,d=e.r*l+i.r*c+t.r*f+r.r*h,u=e.g*l+i.g*c+t.g*f+r.g*h,m=e.b*l+i.b*c+t.b*f+r.b*h,p=e.a*l+i.a*c+t.a*f+r.a*h;return new n(d,u,m,p)}static Hermite1stDerivative(e,t,i,r,s){let a=new n;return this.Hermite1stDerivativeToRef(e,t,i,r,s,a),a}static Hermite1stDerivativeToRef(e,t,i,r,s,a){let o=s*s;a.r=(o-s)*6*e.r+(3*o-4*s+1)*t.r+(-o+s)*6*i.r+(3*o-2*s)*r.r,a.g=(o-s)*6*e.g+(3*o-4*s+1)*t.g+(-o+s)*6*i.g+(3*o-2*s)*r.g,a.b=(o-s)*6*e.b+(3*o-4*s+1)*t.b+(-o+s)*6*i.b+(3*o-2*s)*r.b,a.a=(o-s)*6*e.a+(3*o-4*s+1)*t.a+(-o+s)*6*i.a+(3*o-2*s)*r.a}static FromColor3(e,t=1){return new n(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new n(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2],i.a=e[t+3]}static FromInts(e,t,i,r){return new n(e/255,t/255,i/255,r/255)}static CheckColors4(e,t){if(e.length===t*3){let i=[];for(let r=0;rnew lt(0,0,0,0));wt("BABYLON.Color3",ge);wt("BABYLON.Color4",lt)});var to,Zu=C(()=>{Ve();to=class n{constructor(e,t,i,r){this.normal=new b(e,t,i),this.d=r}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new n(this.normal.x,this.normal.y,this.normal.z,this.d)}getClassName(){return"Plane"}getHashCode(){let e=this.normal.getHashCode();return e=e*397^(this.d|0),e}normalize(){let e=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),t=0;return e!==0&&(t=1/e),this.normal.x*=t,this.normal.y*=t,this.normal.z*=t,this.d*=t,this}transform(e){let t=n._TmpMatrix;e.invertToRef(t);let i=t.m,r=this.normal.x,s=this.normal.y,a=this.normal.z,o=this.d,l=r*i[0]+s*i[1]+a*i[2]+o*i[3],c=r*i[4]+s*i[5]+a*i[6]+o*i[7],f=r*i[8]+s*i[9]+a*i[10]+o*i[11],h=r*i[12]+s*i[13]+a*i[14]+o*i[15];return new n(l,c,f,h)}dotCoordinate(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d}copyFromPoints(e,t,i){let r=t.x-e.x,s=t.y-e.y,a=t.z-e.z,o=i.x-e.x,l=i.y-e.y,c=i.z-e.z,f=s*c-a*l,h=a*o-r*c,d=r*l-s*o,u=Math.sqrt(f*f+h*h+d*d),m;return u!==0?m=1/u:m=0,this.normal.x=f*m,this.normal.y=h*m,this.normal.z=d*m,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){return b.Dot(this.normal,e)<=t}signedDistanceTo(e){return b.Dot(e,this.normal)+this.d}static FromArray(e){return new n(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){let r=new n(0,0,0,0);return r.copyFromPoints(e,t,i),r}static FromPositionAndNormal(e,t){let i=new n(0,0,0,0);return this.FromPositionAndNormalToRef(e,t,i)}static FromPositionAndNormalToRef(e,t,i){return i.normal.copyFrom(t),i.normal.normalize(),i.d=-e.dot(i.normal),i}static SignedDistanceToPlaneFromPositionAndNormal(e,t,i){let r=-(t.x*e.x+t.y*e.y+t.z*e.z);return b.Dot(i,t)+r}};to._TmpMatrix=j.Identity()});var lf,wT=C(()=>{Zu();lf=class n{static GetPlanes(e){let t=[];for(let i=0;i<6;i++)t.push(new to(0,0,0,0));return n.GetPlanesToRef(e,t),t}static GetNearPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]+i[2],t.normal.y=i[7]+i[6],t.normal.z=i[11]+i[10],t.d=i[15]+i[14],t.normalize()}static GetFarPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]-i[2],t.normal.y=i[7]-i[6],t.normal.z=i[11]-i[10],t.d=i[15]-i[14],t.normalize()}static GetLeftPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]+i[0],t.normal.y=i[7]+i[4],t.normal.z=i[11]+i[8],t.d=i[15]+i[12],t.normalize()}static GetRightPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]-i[0],t.normal.y=i[7]-i[4],t.normal.z=i[11]-i[8],t.d=i[15]-i[12],t.normalize()}static GetTopPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]-i[1],t.normal.y=i[7]-i[5],t.normal.z=i[11]-i[9],t.d=i[15]-i[13],t.normalize()}static GetBottomPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]+i[1],t.normal.y=i[7]+i[5],t.normal.z=i[11]+i[9],t.d=i[15]+i[13],t.normalize()}static GetPlanesToRef(e,t){n.GetNearPlaneToRef(e,t[0]),n.GetFarPlaneToRef(e,t[1]),n.GetLeftPlaneToRef(e,t[2]),n.GetRightPlaneToRef(e,t[3]),n.GetTopPlaneToRef(e,t[4]),n.GetBottomPlaneToRef(e,t[5])}static IsPointInFrustum(e,t){for(let i=0;i<6;i++)if(t[i].dotCoordinate(e)<0)return!1;return!0}}});var S2,Qu,wM,$u,wh,Fh=C(()=>{Ln();Ve();Dn();(function(n){n[n.CW=0]="CW",n[n.CCW=1]="CCW"})(S2||(S2={}));Qu=class n{constructor(e){this._radians=e,this._radians<0&&(this._radians+=2*Math.PI)}degrees(){return this._radians*180/Math.PI}radians(){return this._radians}static BetweenTwoPoints(e,t){let i=t.subtract(e),r=Math.atan2(i.y,i.x);return new n(r)}static BetweenTwoVectors(e,t){let i=e.lengthSquared()*t.lengthSquared();if(i===0)return new n(Math.PI/2);i=Math.sqrt(i);let r=e.dot(t)/i;r=Nt(r,-1,1);let s=Math.acos(r);return new n(s)}static FromRadians(e){return new n(e)}static FromDegrees(e){return new n(e*Math.PI/180)}},wM=class{constructor(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;let r=Math.pow(t.x,2)+Math.pow(t.y,2),s=(Math.pow(e.x,2)+Math.pow(e.y,2)-r)/2,a=(r-Math.pow(i.x,2)-Math.pow(i.y,2))/2,o=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new we((s*(t.y-i.y)-a*(e.y-t.y))/o,((e.x-t.x)*a-(t.x-i.x)*s)/o),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=Qu.BetweenTwoPoints(this.centerPoint,this.startPoint);let l=this.startAngle.degrees(),c=Qu.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),f=Qu.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();c-l>180&&(c-=360),c-l<-180&&(c+=360),f-c>180&&(f-=360),f-c<-180&&(f+=360),this.orientation=c-l<0?0:1,this.angle=Qu.FromDegrees(this.orientation===0?l-f:f-l)}},$u=class n{constructor(e,t){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new we(e,t))}addLineTo(e,t){if(this.closed)return this;let i=new we(e,t),r=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(r).length(),this}addArcTo(e,t,i,r,s=36){if(this.closed)return this;let a=this._points[this._points.length-1],o=new we(e,t),l=new we(i,r),c=new wM(a,o,l),f=c.angle.radians()/s;c.orientation===0&&(f*=-1);let h=c.startAngle.radians()+f;for(let d=0;d(1-l)*(1-l)*c+2*l*(1-l)*f+l*l*h,o=this._points[this._points.length-1];for(let l=0;l<=s;l++){let c=l/s,f=a(c,o.x,e,i),h=a(c,o.y,t,r);this.addLineTo(f,h)}return this}addBezierCurveTo(e,t,i,r,s,a,o=36){if(this.closed)return this;let l=(f,h,d,u,m)=>(1-f)*(1-f)*(1-f)*h+3*f*(1-f)*(1-f)*d+3*f*f*(1-f)*u+f*f*f*m,c=this._points[this._points.length-1];for(let f=0;f<=o;f++){let h=f/o,d=l(h,c.x,e,i,s),u=l(h,c.y,t,r,a);this.addLineTo(d,u)}return this}isPointInside(e){let t=!1,i=this._points.length;for(let r=i-1,s=0;sNumber.EPSILON){if(c<0&&(a=this._points[s],l=-l,o=this._points[r],c=-c),e.yo.y)continue;if(e.y===a.y&&e.x===a.x)return!0;{let f=c*(e.x-a.x)-l*(e.y-a.y);if(f===0)return!0;if(f<0)continue;t=!t}}else{if(e.y!==a.y)continue;if(o.x<=e.x&&e.x<=a.x||a.x<=e.x&&e.x<=o.x)return!0}}return t}close(){return this.closed=!0,this}length(){let e=this._length;if(this.closed){let t=this._points[this._points.length-1],i=this._points[0];e+=i.subtract(t).length()}return e}area(){let e=this._points.length,t=0;for(let i=e-1,r=0;r1)return we.Zero();let t=e*this.length(),i=0;for(let r=0;r=i&&t<=c){let f=l.normalize(),h=t-i;return new we(a.x+f.x*h,a.y+f.y*h)}i=c}return we.Zero()}static StartingAt(e,t){return new n(e,t)}},wh=class n{constructor(e,t=null,i,r=!1){this.path=e,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array,this._pointAtData={id:0,point:b.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:j.Identity()};for(let s=0;st){let c=e;e=t,t=c}let i=this.getCurve(),r=this.getPointAt(e),s=this.getPreviousPointIndexAt(e),a=this.getPointAt(t),o=this.getPreviousPointIndexAt(t)+1,l=[];return e!==0&&(s++,l.push(r)),l.push(...i.slice(s,o)),(t!==1||e===1)&&l.push(a),new n(l,this.getNormalAt(e),this._raw,this._alignTangentsWithPath)}update(e,t=null,i=!1){for(let r=0;rt+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i}_normalVector(e,t){let i,r=e.length();if(r===0&&(r=1),t==null){let s;Si(Math.abs(e.y)/r,1,Ot)?Si(Math.abs(e.x)/r,1,Ot)?Si(Math.abs(e.z)/r,1,Ot)?s=b.Zero():s=new b(0,0,1):s=new b(1,0,0):s=new b(0,-1,0),i=b.Cross(e,s)}else i=b.Cross(e,t),b.CrossToRef(i,e,i);return i.normalize(),i}_updatePointAtData(e,t=!1){if(this._pointAtData.id===e)return this._pointAtData.interpolateReady||this._updateInterpolationMatrix(),this._pointAtData;this._pointAtData.id=e;let i=this.getPoints();if(e<=0)return this._setPointAtData(0,0,i[0],0,t);if(e>=1)return this._setPointAtData(1,1,i[i.length-1],i.length-1,t);let r=i[0],s,a=0,o=e*this.length();for(let l=1;lo){let h=(a-o)/c,d=r.subtract(s),u=s.add(d.scaleInPlace(h));return this._setPointAtData(e,1-h,u,l-1,t)}r=s}return this._pointAtData}_setPointAtData(e,t,i,r,s){return this._pointAtData.point=i,this._pointAtData.position=e,this._pointAtData.subPosition=t,this._pointAtData.previousPointArrayIndex=r,this._pointAtData.interpolateReady=s,s&&this._updateInterpolationMatrix(),this._pointAtData}_updateInterpolationMatrix(){this._pointAtData.interpolationMatrix=j.Identity();let e=this._pointAtData.previousPointArrayIndex;if(e!==this._tangents.length-1){let t=e+1,i=this._tangents[e].clone(),r=this._normals[e].clone(),s=this._binormals[e].clone(),a=this._tangents[t].clone(),o=this._normals[t].clone(),l=this._binormals[t].clone(),c=Ye.RotationQuaternionFromAxis(r,s,i),f=Ye.RotationQuaternionFromAxis(o,l,a);Ye.Slerp(c,f,this._pointAtData.subPosition).toRotationMatrix(this._pointAtData.interpolationMatrix)}}}});var Vl,FT=C(()=>{Vl=class n{constructor(e,t){this.width=e,this.height=t}toString(){return`{W: ${this.width}, H: ${this.height}}`}getClassName(){return"Size"}getHashCode(){let e=this.width|0;return e=e*397^(this.height|0),e}copyFrom(e){this.width=e.width,this.height=e.height}copyFromFloats(e,t){return this.width=e,this.height=t,this}set(e,t){return this.copyFromFloats(e,t)}multiplyByFloats(e,t){return new n(this.width*e,this.height*t)}clone(){return new n(this.width,this.height)}equals(e){return e?this.width===e.width&&this.height===e.height:!1}get surface(){return this.width*this.height}static Zero(){return new n(0,0)}add(e){return new n(this.width+e.width,this.height+e.height)}subtract(e){return new n(this.width-e.width,this.height-e.height)}scale(e){return new n(this.width*e,this.height*e)}static Lerp(e,t,i){let r=e.width+(t.width-e.width)*i,s=e.height+(t.height-e.height)*i;return new n(r,s)}}});var T2=C(()=>{Ve()});var io,Ju=C(()=>{io=class n{constructor(e,t,i,r){this.x=e,this.y=t,this.width=i,this.height=r}toGlobal(e,t){return new n(this.x*e,this.y*t,this.width*e,this.height*t)}toGlobalToRef(e,t,i){return i.x=this.x*e,i.y=this.y*t,i.width=this.width*e,i.height=this.height*t,this}clone(){return new n(this.x,this.y,this.width,this.height)}}});var A2=C(()=>{Xu();zt();Dn();wT();Fh();Zu();FT();Ve();T2();Ju()});var Qo,bre,Gl,kl,w_,$o,F_=C(()=>{Ve();A2();Qo=[Math.sqrt(1/(4*Math.PI)),-Math.sqrt(3/(4*Math.PI)),Math.sqrt(3/(4*Math.PI)),-Math.sqrt(3/(4*Math.PI)),Math.sqrt(15/(4*Math.PI)),-Math.sqrt(15/(4*Math.PI)),Math.sqrt(5/(16*Math.PI)),-Math.sqrt(15/(4*Math.PI)),Math.sqrt(15/(16*Math.PI))],bre=[()=>1,n=>n.y,n=>n.z,n=>n.x,n=>n.x*n.y,n=>n.y*n.z,n=>3*n.z*n.z-1,n=>n.x*n.z,n=>n.x*n.x-n.y*n.y],Gl=(n,e)=>Qo[n]*bre[n](e),kl=[Math.PI,2*Math.PI/3,2*Math.PI/3,2*Math.PI/3,Math.PI/4,Math.PI/4,Math.PI/4,Math.PI/4,Math.PI/4],w_=class n{constructor(){this.preScaled=!1,this.l00=b.Zero(),this.l1_1=b.Zero(),this.l10=b.Zero(),this.l11=b.Zero(),this.l2_2=b.Zero(),this.l2_1=b.Zero(),this.l20=b.Zero(),this.l21=b.Zero(),this.l22=b.Zero()}addLight(e,t,i){$.Vector3[0].set(t.r,t.g,t.b);let r=$.Vector3[0],s=$.Vector3[1];r.scaleToRef(i,s),s.scaleToRef(Gl(0,e),$.Vector3[2]),this.l00.addInPlace($.Vector3[2]),s.scaleToRef(Gl(1,e),$.Vector3[2]),this.l1_1.addInPlace($.Vector3[2]),s.scaleToRef(Gl(2,e),$.Vector3[2]),this.l10.addInPlace($.Vector3[2]),s.scaleToRef(Gl(3,e),$.Vector3[2]),this.l11.addInPlace($.Vector3[2]),s.scaleToRef(Gl(4,e),$.Vector3[2]),this.l2_2.addInPlace($.Vector3[2]),s.scaleToRef(Gl(5,e),$.Vector3[2]),this.l2_1.addInPlace($.Vector3[2]),s.scaleToRef(Gl(6,e),$.Vector3[2]),this.l20.addInPlace($.Vector3[2]),s.scaleToRef(Gl(7,e),$.Vector3[2]),this.l21.addInPlace($.Vector3[2]),s.scaleToRef(Gl(8,e),$.Vector3[2]),this.l22.addInPlace($.Vector3[2])}scaleInPlace(e){this.l00.scaleInPlace(e),this.l1_1.scaleInPlace(e),this.l10.scaleInPlace(e),this.l11.scaleInPlace(e),this.l2_2.scaleInPlace(e),this.l2_1.scaleInPlace(e),this.l20.scaleInPlace(e),this.l21.scaleInPlace(e),this.l22.scaleInPlace(e)}convertIncidentRadianceToIrradiance(){this.l00.scaleInPlace(kl[0]),this.l1_1.scaleInPlace(kl[1]),this.l10.scaleInPlace(kl[2]),this.l11.scaleInPlace(kl[3]),this.l2_2.scaleInPlace(kl[4]),this.l2_1.scaleInPlace(kl[5]),this.l20.scaleInPlace(kl[6]),this.l21.scaleInPlace(kl[7]),this.l22.scaleInPlace(kl[8])}convertIrradianceToLambertianRadiance(){this.scaleInPlace(1/Math.PI)}preScaleForRendering(){this.preScaled=!0,this.l00.scaleInPlace(Qo[0]),this.l1_1.scaleInPlace(Qo[1]),this.l10.scaleInPlace(Qo[2]),this.l11.scaleInPlace(Qo[3]),this.l2_2.scaleInPlace(Qo[4]),this.l2_1.scaleInPlace(Qo[5]),this.l20.scaleInPlace(Qo[6]),this.l21.scaleInPlace(Qo[7]),this.l22.scaleInPlace(Qo[8])}updateFromArray(e){return b.FromArrayToRef(e[0],0,this.l00),b.FromArrayToRef(e[1],0,this.l1_1),b.FromArrayToRef(e[2],0,this.l10),b.FromArrayToRef(e[3],0,this.l11),b.FromArrayToRef(e[4],0,this.l2_2),b.FromArrayToRef(e[5],0,this.l2_1),b.FromArrayToRef(e[6],0,this.l20),b.FromArrayToRef(e[7],0,this.l21),b.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return b.FromFloatsToRef(e[0],e[1],e[2],this.l00),b.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),b.FromFloatsToRef(e[6],e[7],e[8],this.l10),b.FromFloatsToRef(e[9],e[10],e[11],this.l11),b.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),b.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),b.FromFloatsToRef(e[18],e[19],e[20],this.l20),b.FromFloatsToRef(e[21],e[22],e[23],this.l21),b.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){return new n().updateFromArray(e)}static FromPolynomial(e){let t=new n;return t.l00=e.xx.scale(.376127).add(e.yy.scale(.376127)).add(e.zz.scale(.376126)),t.l1_1=e.y.scale(.977204),t.l10=e.z.scale(.977204),t.l11=e.x.scale(.977204),t.l2_2=e.xy.scale(1.16538),t.l2_1=e.yz.scale(1.16538),t.l20=e.zz.scale(1.34567).subtract(e.xx.scale(.672834)).subtract(e.yy.scale(.672834)),t.l21=e.zx.scale(1.16538),t.l22=e.xx.scale(1.16538).subtract(e.yy.scale(1.16538)),t.l1_1.scaleInPlace(-1),t.l11.scaleInPlace(-1),t.l2_1.scaleInPlace(-1),t.l21.scaleInPlace(-1),t.scaleInPlace(Math.PI),t}},$o=class n{constructor(){this.x=b.Zero(),this.y=b.Zero(),this.z=b.Zero(),this.xx=b.Zero(),this.yy=b.Zero(),this.zz=b.Zero(),this.xy=b.Zero(),this.yz=b.Zero(),this.zx=b.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=w_.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){$.Vector3[0].copyFromFloats(e.r,e.g,e.b);let t=$.Vector3[0];this.xx.addInPlace(t),this.yy.addInPlace(t),this.zz.addInPlace(t)}scaleInPlace(e){this.x.scaleInPlace(e),this.y.scaleInPlace(e),this.z.scaleInPlace(e),this.xx.scaleInPlace(e),this.yy.scaleInPlace(e),this.zz.scaleInPlace(e),this.yz.scaleInPlace(e),this.zx.scaleInPlace(e),this.xy.scaleInPlace(e)}updateFromHarmonics(e){return this._harmonics=e,this.x.copyFrom(e.l11),this.x.scaleInPlace(1.02333).scaleInPlace(-1),this.y.copyFrom(e.l1_1),this.y.scaleInPlace(1.02333).scaleInPlace(-1),this.z.copyFrom(e.l10),this.z.scaleInPlace(1.02333),this.xx.copyFrom(e.l00),$.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),$.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace($.Vector3[0]).addInPlace($.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace($.Vector3[0]).subtractInPlace($.Vector3[1]),this.zz.copyFrom(e.l00),$.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace($.Vector3[0]),this.yz.copyFrom(e.l2_1),this.yz.scaleInPlace(.858086).scaleInPlace(-1),this.zx.copyFrom(e.l21),this.zx.scaleInPlace(.858086).scaleInPlace(-1),this.xy.copyFrom(e.l2_2),this.xy.scaleInPlace(.858086),this.scaleInPlace(1/Math.PI),this}static FromHarmonics(e){return new n().updateFromHarmonics(e)}static FromArray(e){let t=new n;return b.FromArrayToRef(e[0],0,t.x),b.FromArrayToRef(e[1],0,t.y),b.FromArrayToRef(e[2],0,t.z),b.FromArrayToRef(e[3],0,t.xx),b.FromArrayToRef(e[4],0,t.yy),b.FromArrayToRef(e[5],0,t.zz),b.FromArrayToRef(e[6],0,t.yz),b.FromArrayToRef(e[7],0,t.zx),b.FromArrayToRef(e[8],0,t.xy),t}}});function P(n,e,t,i){var r=arguments.length,s=r<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(n,e,t,i);else for(var o=n.length-1;o>=0;o--)(a=n[o])&&(s=(r<3?a(s):r>3?a(e,t,s):a(e,t))||s);return r>3&&s&&Object.defineProperty(e,t,s),s}var Gt=C(()=>{});function x2(n){let e=n.getClassName();return UT[e]||(UT[e]={}),UT[e]}function VT(n){let e=n.getClassName();if(BT[e])return BT[e];BT[e]={};let t=BT[e],i=n,r=e;for(;r;){let s=UT[r];for(let l in s)t[l]=s[l];let a,o=!1;do{if(a=Object.getPrototypeOf(i),!a.getClassName){o=!0;break}if(a.getClassName()!==r)break;i=a}while(a);if(o)break;r=a.getClassName(),i=a}return t}var BT,UT,FM=C(()=>{BT={},UT={}});function Ea(n,e){return(t,i)=>{let r=x2(t);r[i]||(r[i]={type:n,sourceName:e})}}function Ire(n,e=null){return(t,i)=>{let r=e||"_"+i;Object.defineProperty(t,i,{get:function(){return this[r]},set:function(s){var a;typeof((a=this[r])==null?void 0:a.equals)=="function"&&this[r].equals(s)||this[r]!==s&&(this[r]=s,t[n].apply(this))},enumerable:!0,configurable:!0})}}function oe(n,e=null){return Ire(n,e)}function w(n){return Ea(0,n)}function Bt(n){return Ea(1,n)}function _r(n){return Ea(2,n)}function em(n){return Ea(3,n)}function tm(n){return Ea(4,n)}function Hr(n){return Ea(5,n)}function GT(n){return Ea(6,n)}function R2(n){return Ea(7,n)}function im(n){return Ea(8,n)}function b2(n){return Ea(9,n)}function I2(n){return Ea(10,n)}function M2(n){return Ea(11,n)}function Ts(n,e,t,i){let r=t.value;t.value=(...s)=>{let a=r;if(typeof _native!="undefined"&&_native[e]){let o=_native[e];i?a=(...l)=>i(...l)?o(...l):r(...l):a=o}return n[e]=a,a(...s)}}function dt(n,e=null){return(t,i)=>{let r=i;Object.defineProperty(t,e||"",{get:function(){return this[r].value},set:function(a){var o,l;typeof((l=(o=this[r])==null?void 0:o.value)==null?void 0:l.equals)=="function"&&this[r].value.equals(a)||this[r].value!==a&&(this[r].value=a,t[n].apply(this))},enumerable:!0,configurable:!0})}}var Ut=C(()=>{FM();Ts.filter=function(n){return(e,t,i)=>Ts(e,t,i,n)}});function cf(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{let e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}var B_=C(()=>{});function Mre(){return typeof _native!="undefined"&&_native.XMLHttpRequest?new _native.XMLHttpRequest:new XMLHttpRequest}var Ir,Bh=C(()=>{Ir=class n{constructor(){this._xhr=Mre(),this._requestURL=""}static get IsCustomRequestAvailable(){return Object.keys(n.CustomRequestHeaders).length>0||n.CustomRequestModifiers.length>0}static _CleanUrl(e){return e=e.replace("file:http:","http:"),e=e.replace("file:https:","https:"),e}static _ShouldSkipRequestModifications(e){return n.SkipRequestModificationForBabylonCDN&&(e.includes("preview.babylonjs.com")||e.includes("cdn.babylonjs.com"))}static _CollectCustomizations(e,t={}){let i={...t};if(n._ShouldSkipRequestModifications(e))return{url:e,headers:i};for(let s in n.CustomRequestHeaders){let a=n.CustomRequestHeaders[s];a&&(i[s]=a)}let r={setRequestHeader:(s,a)=>{i[s]=a}};for(let s of n.CustomRequestModifiers){if(n._ShouldSkipRequestModifications(e))break;let a=s(r,e);typeof a=="string"&&(e=a)}return{url:e,headers:i}}static async FetchAsync(e,t={}){var r,s,a;let i=(r=t.method)!=null?r:"GET";if(typeof fetch!="undefined"){let{url:o,headers:l}=n._CollectCustomizations(n._CleanUrl(e),(s=t.headers)!=null?s:{});return await fetch(o,{method:i,headers:l,body:(a=t.body)!=null?a:void 0})}return await new Promise((o,l)=>{var f;let c=new n;c.responseType="arraybuffer",c.addEventListener("readystatechange",()=>{if(c.readyState===4)if(c.status>=200&&c.status<300){let h=typeof Headers!="undefined"?new Headers:void 0,d=c.getResponseHeader("Content-Type");d&&h&&h.set("Content-Type",d),o(typeof Response!="undefined"?new Response(c.response,{status:c.status,statusText:c.statusText,headers:h}):{ok:!0,status:c.status,statusText:c.statusText,headers:{get:u=>c.getResponseHeader(u)},arrayBuffer:async()=>await Promise.resolve(c.response)})}else l(new Error(`HTTP ${c.status} loading '${c.requestURL}': ${c.statusText}`))}),c.open(i,e,t.headers),c.send((f=t.body)!=null?f:null)})}get requestURL(){return this._requestURL}get onprogress(){return this._xhr.onprogress}set onprogress(e){this._xhr.onprogress=e}get readyState(){return this._xhr.readyState}get status(){return this._xhr.status}get statusText(){return this._xhr.statusText}get response(){return this._xhr.response}get responseURL(){return this._xhr.responseURL}get responseText(){return this._xhr.responseText}get responseType(){return this._xhr.responseType}set responseType(e){this._xhr.responseType=e}get timeout(){return this._xhr.timeout}set timeout(e){this._xhr.timeout=e}addEventListener(e,t,i){this._xhr.addEventListener(e,t,i)}removeEventListener(e,t,i){this._xhr.removeEventListener(e,t,i)}abort(){this._xhr.abort()}send(e){this._xhr.send(e)}open(e,t,i){let{url:r,headers:s}=n._CollectCustomizations(t,i);this._requestURL=n._CleanUrl(r),this._xhr.open(e,this._requestURL,!0);for(let a in s)this._xhr.setRequestHeader(a,s[a])}setRequestHeader(e,t){this._xhr.setRequestHeader(e,t)}getResponseHeader(e){return this._xhr.getResponseHeader(e)}};Ir.CustomRequestHeaders={};Ir.CustomRequestModifiers=new Array;Ir.SkipRequestModificationForBabylonCDN=!0});var ff,C2=C(()=>{ff=class{};ff.FilesToLoad={}});var kT,y2=C(()=>{kT=class{static ExponentialBackoff(e=3,t=500){return(i,r,s)=>r.status!==0||s>=e||i.indexOf("file:")!==-1?-1:Math.pow(2,s)*t}}});var Wl,Sa,As,U_=C(()=>{Wl=class extends Error{};Wl._setPrototypeOf=Object.setPrototypeOf||((n,e)=>(n.__proto__=e,n));Sa={MeshInvalidPositionsError:0,UnsupportedTextureError:1e3,GLTFLoaderUnexpectedMagicError:2e3,SceneLoaderError:3e3,LoadFileError:4e3,RequestFileError:4001,ReadFileError:4002},As=class n extends Wl{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",Wl._setPrototypeOf(this,n.prototype)}}});function Cre(n){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",i,r,s,a,o,l,c,f=0;for(;f>2,o=(i&3)<<4|r>>4,l=(r&15)<<2|s>>6,c=s&63,isNaN(r)?l=c=64:isNaN(s)&&(c=64),t+=e.charAt(a)+e.charAt(o)+e.charAt(l)+e.charAt(c);return t}function yre(n){let e=BM(n),t=e.length,i=new Uint8Array(new ArrayBuffer(t));for(let r=0;r{P2=n=>{if(typeof TextDecoder!="undefined")return new TextDecoder().decode(n);let e="";for(let t=0;t{let e=ArrayBuffer.isView(n)?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n);return typeof e.toBase64=="function"?e.toBase64():Cre(e)},BM=n=>atob(n),D2=n=>typeof Uint8Array.fromBase64=="function"?Uint8Array.fromBase64(n).buffer:yre(n)});function Pre(n,e,t,i){switch(e){case 5120:{let r=n.getInt8(t);return i&&(r=Math.max(r/127,-1)),r}case 5121:{let r=n.getUint8(t);return i&&(r=r/255),r}case 5122:{let r=n.getInt16(t,!0);return i&&(r=Math.max(r/32767,-1)),r}case 5123:{let r=n.getUint16(t,!0);return i&&(r=r/65535),r}case 5124:return n.getInt32(t,!0);case 5125:return n.getUint32(t,!0);case 5126:return n.getFloat32(t,!0);default:throw new Error(`Invalid component type ${e}`)}}function Dre(n,e,t,i,r){switch(e){case 5120:{i&&(r=Math.round(r*127)),n.setInt8(t,r);break}case 5121:{i&&(r=Math.round(r*255)),n.setUint8(t,r);break}case 5122:{i&&(r=Math.round(r*32767)),n.setInt16(t,r,!0);break}case 5123:{i&&(r=Math.round(r*65535)),n.setUint16(t,r,!0);break}case 5124:{n.setInt32(t,r,!0);break}case 5125:{n.setUint32(t,r,!0);break}case 5126:{n.setFloat32(t,r,!0);break}default:throw new Error(`Invalid component type ${e}`)}}function Jo(n){switch(n){case 5120:case 5121:return 1;case 5122:case 5123:return 2;case 5124:case 5125:case 5126:return 4;default:throw new Error(`Invalid type '${n}'`)}}function UM(n){switch(n){case 5120:return Int8Array;case 5121:return Uint8Array;case 5122:return Int16Array;case 5123:return Uint16Array;case 5124:return Int32Array;case 5125:return Uint32Array;case 5126:return Float32Array;default:throw new Error(`Invalid component type '${n}'`)}}function Uh(n,e,t,i,r,s,a,o){let l=new Array(i),c=new Array(i);if(n instanceof Array){let f=e/4,h=t/4;for(let d=0;d{for(let u=0;un.length)throw new Error("Last accessed index is out of bounds.");if(p{for(let A=0;Af.byteLength)throw new Error("Last accessed byte is out of bounds.");let u=e*o;if(r{for(let g=0;g{for(let d=0;d{yt()});function df(n){return D2(n.split(",")[1])}var w2,sm,HT,GM,Lre,Vi,zT,N2,am,Vh,el,XT,F2,B2,hf,U2,V2,Ore,G_,Nre,Hl=C(()=>{Bh();va();hi();C2();y2();U_();V_();ST();Pi();yt();jo();of();wr();nm();w2=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i),sm=class n extends As{constructor(e,t){super(e,Sa.LoadFileError),this.name="LoadFileError",Wl._setPrototypeOf(this,n.prototype),t instanceof Ir?this.request=t:this.file=t}},HT=class n extends As{constructor(e,t){super(e,Sa.RequestFileError),this.request=t,this.name="RequestFileError",Wl._setPrototypeOf(this,n.prototype)}},GM=class n extends As{constructor(e,t){super(e,Sa.ReadFileError),this.file=t,this.name="ReadFileError",Wl._setPrototypeOf(this,n.prototype)}},Lre=n=>(n=n.replace(/#/gm,"%23"),n),Vi={DefaultRetryStrategy:kT.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:n=>n,ScriptBaseUrl:"",ScriptPreprocessUrl:n=>n,CleanUrl:Lre},zT=(n,e)=>{if(!(n&&n.indexOf("data:")===0)&&Vi.CorsBehavior)if(typeof Vi.CorsBehavior=="string"||Vi.CorsBehavior instanceof String)e.crossOrigin=Vi.CorsBehavior;else{let t=Vi.CorsBehavior(n);t&&(e.crossOrigin=t)}},N2={getRequiredSize:null},am=(n,e,t,i,r="",s,a=Le.LastCreatedEngine)=>{if(typeof HTMLImageElement=="undefined"&&!(a!=null&&a._features.forceBitmapOverHTMLImageElement))return t("LoadImage is only supported in web or BabylonNative environments."),null;let o,l=!1;if(n instanceof ArrayBuffer||ArrayBuffer.isView(n))if(typeof Blob!="undefined"&&typeof URL!="undefined"){let S;n instanceof ArrayBuffer?S=n:S=WT(n),o=URL.createObjectURL(new Blob([S],{type:r})),l=!0}else o=`data:${r};base64,`+rm(n);else n instanceof Blob?(o=URL.createObjectURL(n),l=!0):(o=Vi.CleanUrl(n),o=Vi.PreprocessUrl(o));let c=S=>{if(t){let E=o||n.toString();t(`Error while trying to load image: ${E.indexOf("http")===0||E.length<=128?E:E.slice(0,128)+"..."}`,S)}};if(a!=null&&a._features.forceBitmapOverHTMLImageElement)return el(o,S=>{a.createImageBitmap(new Blob([S],{type:r}),{premultiplyAlpha:"none",colorSpaceConversion:"none",...s}).then(E=>{e(E),l&&URL.revokeObjectURL(o)}).catch(E=>{t&&t("Error while trying to load image: "+n,E)})},void 0,i||void 0,!0,(S,E)=>{c(E)}),null;let f=new Image;if(N2.getRequiredSize){let S=N2.getRequiredSize(n);S.width&&(f.width=S.width),S.height&&(f.height=S.height)}zT(o,f);let h=[],d=()=>{for(let S of h)S.target.addEventListener(S.name,S.handler)},u=()=>{for(let S of h)S.target.removeEventListener(S.name,S.handler);h.length=0},m=()=>{u(),e(f),l&&f.src&&URL.revokeObjectURL(f.src)},p=S=>{u(),c(S),l&&f.src&&URL.revokeObjectURL(f.src)},_=S=>{if(S.blockedURI!==f.src||S.disposition==="report")return;u();let E=new Error(`CSP violation of policy ${S.effectiveDirective} ${S.blockedURI}. Current policy is ${S.originalPolicy}`);Le.UseFallbackTexture=!1,c(E),l&&f.src&&URL.revokeObjectURL(f.src),f.src=""};h.push({target:f,name:"load",handler:m}),h.push({target:f,name:"error",handler:p}),h.push({target:document,name:"securitypolicyviolation",handler:_}),d();let g=o.substring(0,5)==="blob:",v=o.substring(0,5)==="data:",x=()=>{g||v||!Ir.IsCustomRequestAvailable?f.src=o:el(o,(S,E,R)=>{let I=!r&&R?R:r,y=new Blob([S],{type:I}),M=URL.createObjectURL(y);l=!0,f.src=M},void 0,i||void 0,!0,(S,E)=>{c(E)})},A=()=>{i&&i.loadImage(o,f)};if(!g&&!v&&i&&i.enableTexturesOffline)i.open(A,x);else{if(o.indexOf("file:")!==-1){let S=decodeURIComponent(o.substring(5).toLowerCase());if(ff.FilesToLoad[S]&&typeof URL!="undefined"){try{let E;try{E=URL.createObjectURL(ff.FilesToLoad[S])}catch(R){E=URL.createObjectURL(ff.FilesToLoad[S])}f.src=E,l=!0}catch(E){f.src=""}return f}}x()}return f},Vh=(n,e,t,i,r)=>{let s=new FileReader,a={onCompleteObservable:new ie,abort:()=>s.abort()};return s.onloadend=()=>a.onCompleteObservable.notifyObservers(a),r&&(s.onerror=()=>{r(new GM(`Unable to read ${n.name}`,n))}),s.onload=o=>{e(o.target.result)},t&&(s.onprogress=t),i?s.readAsArrayBuffer(n):s.readAsText(n),a},el=(n,e,t,i,r,s,a)=>{if(n.name)return Vh(n,e,t,r,s?f=>{s(void 0,f)}:void 0);let o=n;if(o.indexOf("file:")!==-1){let f=decodeURIComponent(o.substring(5).toLowerCase());f.indexOf("./")===0&&(f=f.substring(2));let h=ff.FilesToLoad[f];if(h)return Vh(h,e,t,r,s?d=>s(void 0,new sm(d.message,d.file)):void 0)}let{match:l,type:c}=U2(o);if(l){let f={onCompleteObservable:new ie,abort:()=>()=>{}};try{let h=r?df(o):V2(o);e(h,void 0,c)}catch(h){s?s(void 0,h):te.Error(h.message||"Failed to parse the Data URL")}return Qa.SetImmediate(()=>{f.onCompleteObservable.notifyObservers(f)}),f}return XT(o,(f,h)=>{e(f,h==null?void 0:h.responseURL,h==null?void 0:h.getResponseHeader("content-type"))},t,i,r,s?f=>{s(f.request,new sm(f.message,f.request))}:void 0,a)},XT=(n,e,t,i,r,s,a)=>{var h;i!==null&&(i!=null||(i=(h=Le.LastCreatedScene)==null?void 0:h.offlineProvider)),n=Vi.CleanUrl(n),n=Vi.PreprocessUrl(n);let o=Vi.BaseUrl+n,l=!1,c={onCompleteObservable:new ie,abort:()=>l=!0},f=()=>{let d=new Ir,u=null,m,p=()=>{d&&(t&&d.removeEventListener("progress",t),m&&d.removeEventListener("readystatechange",m),d.removeEventListener("loadend",_))},_=()=>{p(),c.onCompleteObservable.notifyObservers(c),c.onCompleteObservable.clear(),t=void 0,m=null,_=null,s=void 0,a=void 0,e=void 0};c.abort=()=>{l=!0,_&&_(),d&&d.readyState!==(XMLHttpRequest.DONE||4)&&d.abort(),u!==null&&(clearTimeout(u),u=null),d=null};let g=x=>{let A=x.message||"Unknown error";s&&d?s(new HT(A,d)):te.Error(A)},v=x=>{if(d){if(d.open("GET",o),a)try{a(d)}catch(A){g(A);return}r&&(d.responseType="arraybuffer"),t&&d.addEventListener("progress",t),_&&d.addEventListener("loadend",_),m=()=>{if(!(l||!d)&&d.readyState===(XMLHttpRequest.DONE||4)){if(m&&d.removeEventListener("readystatechange",m),d.status>=200&&d.status<300||d.status===0&&(!cr()||B2())){let E=r?d.response:d.responseText;if(E!==null){try{e&&e(E,d)}catch(R){g(R)}return}}let A=Vi.DefaultRetryStrategy;if(A){let E=A(o,d,x);if(E!==-1){p(),d=new Ir,u=setTimeout(()=>v(x+1),E);return}}let S=new HT("Error status: "+d.status+" "+d.statusText+" - Unable to load "+o,d);s&&s(S)}},d.addEventListener("readystatechange",m),d.send()}};v(0)};if(i&&i.enableSceneOffline&&!n.startsWith("blob:")){let d=m=>{m&&m.status>400?s&&s(m):f()},u=()=>{i&&i.loadFile(Vi.BaseUrl+n,m=>{!l&&e&&e(m),c.onCompleteObservable.notifyObservers(c)},t?m=>{!l&&t&&t(m)}:void 0,d,r)};i.open(u,d)}else f();return c},F2=n=>{let{match:e,type:t}=U2(n);if(e)return t||void 0;let i=n.lastIndexOf(".");switch(n.substring(i+1).toLowerCase()){case"glb":return"model/gltf-binary";case"bin":return"application/octet-stream";case"gltf":return"model/gltf+json";case"jpg":case"jpeg":return"image/jpeg";case"png":return"image/png";case"webp":return"image/webp";case"ktx":return"image/ktx";case"ktx2":return"image/ktx2";case"avif":return"image/avif";default:return}},B2=()=>typeof location!="undefined"&&location.protocol==="file:",hf=n=>w2.test(n),U2=n=>{let e=w2.exec(n);return e===null||e.length===0?{match:!1,type:""}:{match:!0,type:e[0].replace("data:","").replace(";base64,","")}};V2=n=>BM(n.split(",")[1]),Ore=()=>{Ie._FileToolsLoadImage=am,Uu.loadFile=el,SM.loadFile=el};Ore();Nre=(n,e,t,i,r,s,a,o,l,c)=>{G_={DecodeBase64UrlToBinary:n,DecodeBase64UrlToString:e,DefaultRetryStrategy:t.DefaultRetryStrategy,BaseUrl:t.BaseUrl,CorsBehavior:t.CorsBehavior,PreprocessUrl:t.PreprocessUrl,IsBase64DataUrl:i,IsFileURL:r,LoadFile:s,LoadImage:a,ReadFile:o,RequestFile:l,SetCorsBehavior:c},Object.defineProperty(G_,"DefaultRetryStrategy",{get:function(){return t.DefaultRetryStrategy},set:function(f){t.DefaultRetryStrategy=f}}),Object.defineProperty(G_,"BaseUrl",{get:function(){return t.BaseUrl},set:function(f){t.BaseUrl=f}}),Object.defineProperty(G_,"PreprocessUrl",{get:function(){return t.PreprocessUrl},set:function(f){t.PreprocessUrl=f}}),Object.defineProperty(G_,"CorsBehavior",{get:function(){return t.CorsBehavior},set:function(f){t.CorsBehavior=f}})};Nre(df,V2,Vi,hf,B2,el,am,Vh,XT,zT)});var YT,G2=C(()=>{FT();YT=class n{get wrapU(){return this._wrapU}set wrapU(e){this._wrapU=e}get wrapV(){return this._wrapV}set wrapV(e){this._wrapV=e}get coordinatesMode(){return 0}get isCube(){return this._texture?this._texture.isCube:!1}set isCube(e){this._texture&&(this._texture.isCube=e)}get is3D(){return this._texture?this._texture.is3D:!1}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return this._texture?this._texture.is2DArray:!1}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}getClassName(){return"ThinTexture"}static _IsRenderTargetWrapper(e){return(e==null?void 0:e.shareDepth)!==void 0}constructor(e){var t,i,r;this._wrapU=1,this._wrapV=1,this.wrapR=1,this.anisotropicFilteringLevel=4,this.delayLoadState=0,this._texture=null,this._engine=null,this._cachedSize=Vl.Zero(),this._cachedBaseSize=Vl.Zero(),this._initialSamplingMode=2,this._texture=n._IsRenderTargetWrapper(e)?e.texture:e,this._texture&&(this._engine=this._texture.getEngine(),this.wrapU=(t=this._texture._cachedWrapU)!=null?t:this.wrapU,this.wrapV=(i=this._texture._cachedWrapV)!=null?i:this.wrapV,this.wrapR=(r=this._texture._cachedWrapR)!=null?r:this.wrapR)}isReady(){return this.delayLoadState===4?(this.delayLoad(),!1):this._texture?this._texture.isReady:!1}delayLoad(){}getInternalTexture(){return this._texture}getSize(){if(this._texture){if(this._texture.width)return this._cachedSize.width=this._texture.width,this._cachedSize.height=this._texture.height,this._cachedSize;if(this._texture._size)return this._cachedSize.width=this._texture._size,this._cachedSize.height=this._texture._size,this._cachedSize}return this._cachedSize}getBaseSize(){return!this.isReady()||!this._texture?(this._cachedBaseSize.width=0,this._cachedBaseSize.height=0,this._cachedBaseSize):this._texture._size?(this._cachedBaseSize.width=this._texture._size,this._cachedBaseSize.height=this._texture._size,this._cachedBaseSize):(this._cachedBaseSize.width=this._texture.baseWidth,this._cachedBaseSize.height=this._texture.baseHeight,this._cachedBaseSize)}get samplingMode(){return this._texture?this._texture.samplingMode:this._initialSamplingMode}updateSamplingMode(e,t=!1){this._texture&&this._engine&&this._engine.updateTextureSamplingMode(e,this._texture,this._texture.generateMipMaps&&t)}releaseInternalTexture(){this._texture&&(this._texture.dispose(),this._texture=null)}dispose(){this._texture&&(this.releaseInternalTexture(),this._engine=null)}}});var KT,k2=C(()=>{KT=class n{static Eval(e,t){return e.match(/\([^()]*\)/g)?e=e.replace(/\([^()]*\)/g,i=>(i=i.slice(1,i.length-1),n._HandleParenthesisContent(i,t))):e=n._HandleParenthesisContent(e,t),e==="true"?!0:e==="false"?!1:n.Eval(e,t)}static _HandleParenthesisContent(e,t){t=t||(s=>s==="true");let i,r=e.split("||");for(let s in r)if(Object.prototype.hasOwnProperty.call(r,s)){let a=n._SimplifyNegation(r[s].trim()),o=a.split("&&");if(o.length>1)for(let l=0;l(t=t.replace(/[\s]/g,()=>""),t.length%2?"!":"")),e=e.trim(),e==="!true"?e="false":e==="!false"&&(e="true"),e}}});var qt,uf=C(()=>{k2();qt=class n{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>n.HasTags(e),e.addTags=t=>n.AddTagsTo(e,t),e.removeTags=t=>n.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>n.MatchesQuery(e,t)}static DisableFor(e){delete e._tags,delete e.hasTags,delete e.addTags,delete e.removeTags,delete e.matchesTagsQuery}static HasTags(e){if(!e._tags)return!1;let t=e._tags;for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i))return!0;return!1}static GetTags(e,t=!0){if(!e._tags)return null;if(t){let i=[];for(let r in e._tags)Object.prototype.hasOwnProperty.call(e._tags,r)&&e._tags[r]===!0&&i.push(r);return i.join(" ")}else return e._tags}static AddTagsTo(e,t){if(!t||typeof t!="string")return;let i=t.split(" ");for(let r of i)n._AddTagTo(e,r)}static _AddTagTo(e,t){t=t.trim(),!(t===""||t==="true"||t==="false")&&(t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(n.EnableFor(e),e._tags[t]=!0))}static RemoveTagsFrom(e,t){if(!n.HasTags(e))return;let i=t.split(" ");for(let r in i)n._RemoveTagFrom(e,i[r])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return t===void 0?!0:t===""?n.HasTags(e):KT.Eval(t,i=>n.HasTags(e)&&e._tags[i])}}});var W2,it,Tr=C(()=>{hn();uf();zt();Ve();FM();W2=function(n,e,t,i={}){let r=n();qt&&qt.HasTags(e)&&qt.AddTagsTo(r,qt.GetTags(e,!0));let s=VT(r),a={};for(let o in s){let l=s[o],c=e[o],f=l.type;if(c!=null&&(o!=="uniqueId"||it.AllowLoadingUniqueId))switch(f){case 0:case 6:case 9:case 11:typeof c.slice=="function"?r[o]=c.slice():r[o]=c;break;case 1:i.cloneTexturesOnlyOnce&&a[c.uniqueId]?r[o]=a[c.uniqueId]:(r[o]=t||c.isRenderTarget?c:c.clone(),a[c.uniqueId]=r[o]);break;case 2:case 3:case 4:case 5:case 7:case 8:case 10:case 12:r[o]=t?c:c.clone();break}}return r},it=class n{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i{throw Ze("ImageProcessingConfiguration")};it._FresnelParametersParser=n=>{throw Ze("FresnelParameters")};it._ColorCurvesParser=n=>{throw Ze("ColorCurves")};it._TextureParser=(n,e,t)=>{throw Ze("Texture")}});var pi,k_=C(()=>{Gt();Ut();hi();Ve();Pi();B_();Hl();G2();Tr();pi=class n extends YT{set hasAlpha(e){this._hasAlpha!==e&&(this._hasAlpha=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,t=>t.hasTexture(this)))}get hasAlpha(){return this._hasAlpha}set getAlphaFromRGB(e){this._getAlphaFromRGB!==e&&(this._getAlphaFromRGB=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,t=>t.hasTexture(this)))}get getAlphaFromRGB(){return this._getAlphaFromRGB}set coordinatesIndex(e){this._coordinatesIndex!==e&&(this._coordinatesIndex=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,t=>t.hasTexture(this)))}get coordinatesIndex(){return this._coordinatesIndex}set coordinatesMode(e){this._coordinatesMode!==e&&(this._coordinatesMode=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,t=>t.hasTexture(this)))}get coordinatesMode(){return this._coordinatesMode}get wrapU(){return this._wrapU}set wrapU(e){this._wrapU=e}get wrapV(){return this._wrapV}set wrapV(e){this._wrapV=e}get isCube(){return this._texture?this._texture.isCube:this._isCube}set isCube(e){this._texture?this._texture.isCube=e:this._isCube=e}get is3D(){return this._texture?this._texture.is3D:!1}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return this._texture?this._texture.is2DArray:!1}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}get gammaSpace(){if(this._texture)this._texture._gammaSpace===null&&(this._texture._gammaSpace=this._gammaSpace);else return this._gammaSpace;return this._texture._gammaSpace&&!this._texture._useSRGBBuffer}set gammaSpace(e){var t;if(this._texture){if(this._texture._gammaSpace===e)return;this._texture._gammaSpace=e}else{if(this._gammaSpace===e)return;this._gammaSpace=e}(t=this.getScene())==null||t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this))}get isRGBD(){return this._texture!=null&&this._texture._isRGBD}set isRGBD(e){var t;e!==this.isRGBD&&(this._texture&&(this._texture._isRGBD=e),(t=this.getScene())==null||t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this)))}get noMipmap(){return!1}get lodGenerationOffset(){return this._texture?this._texture._lodGenerationOffset:0}set lodGenerationOffset(e){this._texture&&(this._texture._lodGenerationOffset=e)}get lodGenerationScale(){return this._texture?this._texture._lodGenerationScale:0}set lodGenerationScale(e){this._texture&&(this._texture._lodGenerationScale=e)}get linearSpecularLOD(){return this._texture?this._texture._linearSpecularLOD:!1}set linearSpecularLOD(e){this._texture&&(this._texture._linearSpecularLOD=e)}get irradianceTexture(){return this._texture?this._texture._irradianceTexture:null}set irradianceTexture(e){this._texture&&(this._texture._irradianceTexture=e)}get uid(){return this._uid||(this._uid=cf()),this._uid}toString(){return this.name}getClassName(){return"BaseTexture"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get isBlocking(){return!0}get loadingError(){return this._loadingError}get errorObject(){return this._errorObject}constructor(e,t=null){super(null),this.metadata=null,this.reservedDataStore=null,this._hasAlpha=!1,this._getAlphaFromRGB=!1,this.level=1,this._coordinatesIndex=0,this.optimizeUVAllocation=!0,this._coordinatesMode=0,this.wrapR=1,this.anisotropicFilteringLevel=n.DEFAULT_ANISOTROPIC_FILTERING_LEVEL,this._isCube=!1,this._gammaSpace=!0,this.invertZ=!1,this.lodLevelInAlpha=!1,this._dominantDirection=null,this.isRenderTarget=!1,this._prefiltered=!1,this._forceSerialize=!1,this.animations=[],this.onDisposeObservable=new ie,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?n._IsScene(e)?this._scene=e:this._engine=e:this._scene=Le.LastCreatedScene,this._scene&&(this.uniqueId=this._scene.getUniqueId(),this._scene.addTexture(this),this._engine=this._scene.getEngine()),this._texture=t,this._uid=null}getScene(){return this._scene}_getEngine(){return this._engine}getTextureMatrix(){return j.IdentityReadOnly}getReflectionTextureMatrix(){return j.IdentityReadOnly}getRefractionTextureMatrix(){return this.getReflectionTextureMatrix()}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,i,r,s,a){let o=this._getEngine();if(!o)return null;let l=o._getUseSRGBBuffer(!!s,t),c=o.getLoadedTexturesCache();for(let f=0;f=0&&this._scene.textures.splice(e,1),this._scene.onTextureRemovedObservable.notifyObservers(this),this._scene=null,this._parentContainer){let t=this._parentContainer.textures.indexOf(this);t>-1&&this._parentContainer.textures.splice(t,1),this._parentContainer=null}}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.metadata=null,super.dispose()}serialize(e=!1){if(!this.name&&!e)return null;let t=it.Serialize(this);return it.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let i=e.length;if(i===0){t();return}for(let r=0;r{--i===0&&t()}):--i===0&&t()}}}static _IsScene(e){return e.getClassName()==="Scene"}};pi.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4;P([w()],pi.prototype,"uniqueId",void 0);P([w()],pi.prototype,"name",void 0);P([w()],pi.prototype,"displayName",void 0);P([w()],pi.prototype,"metadata",void 0);P([w("hasAlpha")],pi.prototype,"_hasAlpha",void 0);P([w("getAlphaFromRGB")],pi.prototype,"_getAlphaFromRGB",void 0);P([w()],pi.prototype,"level",void 0);P([w("coordinatesIndex")],pi.prototype,"_coordinatesIndex",void 0);P([w()],pi.prototype,"optimizeUVAllocation",void 0);P([w("coordinatesMode")],pi.prototype,"_coordinatesMode",void 0);P([w()],pi.prototype,"wrapU",null);P([w()],pi.prototype,"wrapV",null);P([w()],pi.prototype,"wrapR",void 0);P([w()],pi.prototype,"anisotropicFilteringLevel",void 0);P([w()],pi.prototype,"isCube",null);P([w()],pi.prototype,"is3D",null);P([w()],pi.prototype,"is2DArray",null);P([w()],pi.prototype,"gammaSpace",null);P([w()],pi.prototype,"invertZ",void 0);P([w()],pi.prototype,"lodLevelInAlpha",void 0);P([w()],pi.prototype,"lodGenerationOffset",null);P([w()],pi.prototype,"lodGenerationScale",null);P([w()],pi.prototype,"linearSpecularLOD",null);P([Bt()],pi.prototype,"irradianceTexture",null);P([w()],pi.prototype,"isRenderTarget",void 0)});var mf,zl,kM=C(()=>{Ve();Ln();F_();Dn();zt();mf=class{constructor(e,t,i,r){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=r}},zl=class{static _NearestPow2Floor(e){return e<=1?1:1<0?this._NearestPow2Floor(i):0,s=!e.noMipmap&&((x=e._texture)==null?void 0:x.generateMipMaps)===!0,a=r>0&&r0&&r{Promise.all([f,c,h,d,u,m]).then(([S,E,R,I,y,M])=>{let D=l;g&&(S=this._DownsampleFace(S,t,r,4),E=this._DownsampleFace(E,t,r,4),R=this._DownsampleFace(R,t,r,4),I=this._DownsampleFace(I,t,r,4),y=this._DownsampleFace(y,t,r,4),M=this._DownsampleFace(M,t,r,4),D=r);let O={size:D,right:E,left:S,up:R,down:I,front:y,back:M,format:_,type:S instanceof Float32Array?1:0,gammaSpace:p};A(this.ConvertCubeMapToSphericalPolynomial(O))})})}static _AreaElement(e,t){return Math.atan2(e*t,Math.sqrt(e*e+t*t+1))}static _DownsampleFace(e,t,i,r){let s=e instanceof Float32Array?e:Float32Array.from(e),a=i*i*r,o=new Float32Array(a),l=t/i,c=1/(l*l);for(let d=0;d0?this._NearestPow2Floor(t):0;if(i>0&&e.size>i){let m=e.format===5?4:3,p=["right","left","up","down","front","back"],_={};for(let g of p)_[g]=this._DownsampleFace(e[g],e.size,i,m);e={...e,..._,size:i}}let r=new w_,s=0,a=2/e.size,o=a,l=.5*a,c=l-1;for(let m=0;m<6;m++){let p=this._FileFaces[m],_=e[p.name],g=c,v=e.format===5?4:3;for(let x=0;xD){let N=D/V;I*=N,y*=N,M*=N}}else I=Nt(I,0,D),y=Nt(y,0,D),M=Nt(M,0,D);let O=new ge(I,y,M);r.addLight(E,O,R),s+=R,A+=a}g+=o}}let u=4*Math.PI*6/6/s;return r.scaleInPlace(u),r.convertIncidentRadianceToIrradiance(),r.convertIrradianceToLambertianRadiance(),$o.FromHarmonics(r)}};zl._FileFaces=[new mf("right",new b(1,0,0),new b(0,0,-1),new b(0,-1,0)),new mf("left",new b(-1,0,0),new b(0,0,1),new b(0,-1,0)),new mf("up",new b(0,1,0),new b(1,0,0),new b(0,0,1)),new mf("down",new b(0,-1,0),new b(1,0,0),new b(0,0,-1)),new mf("front",new b(0,0,1),new b(1,0,0),new b(0,-1,0)),new mf("back",new b(0,0,-1),new b(-1,0,0),new b(0,-1,0))];zl.MAX_HDRI_VALUE=4096;zl.PRESERVE_CLAMPED_COLORS=!1});var Xl,WM=C(()=>{yt();Hi();Xl=class{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];let t=vn(e);if(t)return t;te.Warn(e+" not found, you may have missed an import.");let i=e.split("."),r=window||this;for(let s=0,a=i.length;s=0;){let h=n[c];h<0?h=0:h>1&&(h=1),f[c]=h*255}n=f}let s=document.createElement("canvas");s.width=i,s.height=r;let a=s.getContext("2d");if(!a)return null;let o=a.createImageData(i,r);if(o.data.set(n),a.putImageData(o,0,0),t){let c=document.createElement("canvas");c.width=i,c.height=r;let f=c.getContext("2d");return f?(f.translate(0,r),f.scale(1,-1),f.drawImage(s,0,0),c.toDataURL("image/png")):null}return s.toDataURL("image/png")}function z2(n,e=0,t=0){let i=n.getInternalTexture();if(!i)return null;let r=n._readPixelsSync(e,t);return r?H2(r,n.getSize(),i.invertY):null}async function X2(n,e=0,t=0){let i=n.getInternalTexture();if(!i)return null;let r=await n.readPixels(e,t);return r?H2(r,n.getSize(),i.invertY):null}var Y2=C(()=>{});var It,en=C(()=>{It=!1});var _e,Fr=C(()=>{Gt();Ut();hi();Ve();k_();Hi();hn();jo();WM();Zu();V_();Y2();en();Tr();_e=class n extends pi{static _CreateVideoTexture(e,t,i,r=!1,s=!1,a=n.TRILINEAR_SAMPLINGMODE,o={},l,c=5){throw Ze("VideoTexture")}get noMipmap(){return this._noMipmap}get mimeType(){return this._mimeType}set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}get invertY(){return this._invertY}constructor(e,t,i,r,s=n.TRILINEAR_SAMPLINGMODE,a=null,o=null,l=null,c=!1,f,h,d,u,m){var R,I,y,M,D,O,V,N,F,U,k;super(t),this.url=null,this.uOffset=0,this.vOffset=0,this.uScale=1,this.vScale=1,this.uAng=0,this.vAng=0,this.wAng=0,this.uRotationCenter=.5,this.vRotationCenter=.5,this.wRotationCenter=.5,this.homogeneousRotationInUVTransform=!1,this.inspectableCustomProperties=null,this._noMipmap=!1,this._invertY=!1,this._rowGenerationMatrix=null,this._cachedTextureMatrix=null,this._projectionModeMatrix=null,this._t0=null,this._t1=null,this._t2=null,this._cachedUOffset=-1,this._cachedVOffset=-1,this._cachedUScale=0,this._cachedVScale=0,this._cachedUAng=-1,this._cachedVAng=-1,this._cachedWAng=-1,this._cachedReflectionProjectionMatrixId=-1,this._cachedURotationCenter=-1,this._cachedVRotationCenter=-1,this._cachedWRotationCenter=-1,this._cachedHomogeneousRotationInUVTransform=!1,this._cachedIdentity3x2=!0,this._cachedReflectionTextureMatrix=null,this._cachedReflectionUOffset=-1,this._cachedReflectionVOffset=-1,this._cachedReflectionUScale=0,this._cachedReflectionVScale=0,this._cachedReflectionCoordinatesMode=-1,this._buffer=null,this._deleteBuffer=!1,this._format=null,this._delayedOnLoad=null,this._delayedOnError=null,this.onLoadObservable=new ie,this._isBlocking=!0,this.name=e||"",this.url=e;let p,_=!1,g=null,v=!0;typeof i=="object"&&i!==null?(p=(R=i.noMipmap)!=null?R:!1,r=(I=i.invertY)!=null?I:!It,s=(y=i.samplingMode)!=null?y:n.TRILINEAR_SAMPLINGMODE,a=(M=i.onLoad)!=null?M:null,o=(D=i.onError)!=null?D:null,l=(O=i.buffer)!=null?O:null,c=(V=i.deleteBuffer)!=null?V:!1,f=i.format,h=i.mimeType,d=i.loaderOptions,u=i.creationFlags,_=(N=i.useSRGBBuffer)!=null?N:!1,g=(F=i.internalTexture)!=null?F:null,v=(U=i.gammaSpace)!=null?U:v,m=(k=i.forcedExtension)!=null?k:m):p=!!i,this._gammaSpace=v,this._noMipmap=p,this._invertY=r===void 0?!It:r,this._initialSamplingMode=s,this._buffer=l,this._deleteBuffer=c,this._mimeType=h,this._loaderOptions=d,this._creationFlags=u,this._useSRGBBuffer=_,this._forcedExtension=m,f!==void 0&&(this._format=f);let x=this.getScene(),A=this._getEngine();if(!A)return;A.onBeforeTextureInitObservable.notifyObservers(this);let S=()=>{this._texture&&(this._texture._invertVScale&&(this.vScale*=-1,this.vOffset+=1),this._texture._cachedWrapU!==null&&(this.wrapU=this._texture._cachedWrapU,this._texture._cachedWrapU=null),this._texture._cachedWrapV!==null&&(this.wrapV=this._texture._cachedWrapV,this._texture._cachedWrapV=null),this._texture._cachedWrapR!==null&&(this.wrapR=this._texture._cachedWrapR,this._texture._cachedWrapR=null)),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this),a&&a(),!this.isBlocking&&x&&x.resetCachedMaterial()},E=(ee,q)=>{this._loadingError=!0,this._errorObject={message:ee,exception:q},o&&o(ee,q),n.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!g){this._delayedOnLoad=S,this._delayedOnError=E;return}if(this._texture=g!=null?g:this._getFromCache(this.url,p,s,this._invertY,_,this.isCube),this._texture)if(this._texture.isReady)Qa.SetImmediate(()=>S());else{let ee=this._texture.onLoadedObservable.add(S);this._texture.onErrorObservable.add(q=>{var Q;E(q.message,q.exception),(Q=this._texture)==null||Q.onLoadedObservable.remove(ee)})}else if(!x||!x.useDelayedTextureLoading){try{this._texture=A.createTexture(this.url,p,this._invertY,x,s,S,E,this._buffer,void 0,this._format,this._forcedExtension,h,d,u,_)}catch(ee){throw E("error loading",ee),ee}c&&(this._buffer=null)}else this.delayLoadState=4,this._delayedOnLoad=S,this._delayedOnError=E}updateURL(e,t=null,i,r){this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(1,o=>o.hasTexture(this))),(!this.name||this.name.startsWith("data:"))&&(this.name=e),this.url=e,this._buffer=t,this._forcedExtension=r,this.delayLoadState=4;let s=this._delayedOnLoad,a=()=>{s?s():this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this),i&&i()};this._delayedOnLoad=a,this.delayLoad()}delayLoad(){if(this.delayLoadState!==4)return;let e=this.getScene();if(!e)return;let t=this.url;!t&&(this.name.indexOf("://")>0||this.name.startsWith("data:"))&&(t=this.name),this.delayLoadState=1,this._texture=this._getFromCache(t,this._noMipmap,this.samplingMode,this._invertY,this._useSRGBBuffer,this.isCube),this._texture?this._delayedOnLoad&&(this._texture.isReady?Qa.SetImmediate(this._delayedOnLoad):this._texture.onLoadedObservable.add(this._delayedOnLoad)):(this._texture=e.getEngine().createTexture(t,this._noMipmap,this._invertY,e,this.samplingMode,this._delayedOnLoad,this._delayedOnError,this._buffer,null,this._format,this._forcedExtension,this._mimeType,this._loaderOptions,this._creationFlags,this._useSRGBBuffer),this._deleteBuffer&&(this._buffer=null)),this._delayedOnLoad=null,this._delayedOnError=null}_prepareRowForTextureGeneration(e,t,i,r){e*=this._cachedUScale,t*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,t-=this.vRotationCenter*this._cachedVScale,i-=this.wRotationCenter,b.TransformCoordinatesFromFloatsToRef(e,t,i,this._rowGenerationMatrix,r),r.x+=this.uRotationCenter*this._cachedUScale+this._cachedUOffset,r.y+=this.vRotationCenter*this._cachedVScale+this._cachedVOffset,r.z+=this.wRotationCenter}getTextureMatrix(e=1){if(this.uOffset===this._cachedUOffset&&this.vOffset===this._cachedVOffset&&this.uScale*e===this._cachedUScale&&this.vScale===this._cachedVScale&&this.uAng===this._cachedUAng&&this.vAng===this._cachedVAng&&this.wAng===this._cachedWAng&&this.uRotationCenter===this._cachedURotationCenter&&this.vRotationCenter===this._cachedVRotationCenter&&this.wRotationCenter===this._cachedWRotationCenter&&this.homogeneousRotationInUVTransform===this._cachedHomogeneousRotationInUVTransform)return this._cachedTextureMatrix;this._cachedUOffset=this.uOffset,this._cachedVOffset=this.vOffset,this._cachedUScale=this.uScale*e,this._cachedVScale=this.vScale,this._cachedUAng=this.uAng,this._cachedVAng=this.vAng,this._cachedWAng=this.wAng,this._cachedURotationCenter=this.uRotationCenter,this._cachedVRotationCenter=this.vRotationCenter,this._cachedWRotationCenter=this.wRotationCenter,this._cachedHomogeneousRotationInUVTransform=this.homogeneousRotationInUVTransform,(!this._cachedTextureMatrix||!this._rowGenerationMatrix)&&(this._cachedTextureMatrix=j.Zero(),this._rowGenerationMatrix=new j,this._t0=b.Zero(),this._t1=b.Zero(),this._t2=b.Zero()),j.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(j.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,$.Matrix[0]),j.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,$.Matrix[1]),j.ScalingToRef(this._cachedUScale,this._cachedVScale,0,$.Matrix[2]),j.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,$.Matrix[3]),$.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef($.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef($.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef($.Matrix[3],this._cachedTextureMatrix),this._cachedTextureMatrix.setRowFromFloats(2,this._cachedTextureMatrix.m[12],this._cachedTextureMatrix.m[13],this._cachedTextureMatrix.m[14],1)):(this._prepareRowForTextureGeneration(0,0,0,this._t0),this._prepareRowForTextureGeneration(1,0,0,this._t1),this._prepareRowForTextureGeneration(0,1,0,this._t2),this._t1.subtractInPlace(this._t0),this._t2.subtractInPlace(this._t0),j.FromValuesToRef(this._t1.x,this._t1.y,this._t1.z,0,this._t2.x,this._t2.y,this._t2.z,0,this._t0.x,this._t0.y,this._t0.z,0,0,0,0,1,this._cachedTextureMatrix));let t=this.getScene();if(!t)return this._cachedTextureMatrix;let i=this._cachedIdentity3x2;return this._cachedIdentity3x2=this._cachedTextureMatrix.isIdentityAs3x2(),this.optimizeUVAllocation&&i!==this._cachedIdentity3x2&&t.markAllMaterialsAsDirty(1,r=>r.hasTexture(this)),this._cachedTextureMatrix}getReflectionTextureMatrix(){let e=this.getScene();if(!e)return this._cachedReflectionTextureMatrix;if(this.uOffset===this._cachedReflectionUOffset&&this.vOffset===this._cachedReflectionVOffset&&this.uScale===this._cachedReflectionUScale&&this.vScale===this._cachedReflectionVScale&&this.coordinatesMode===this._cachedReflectionCoordinatesMode)if(this.coordinatesMode===n.PROJECTION_MODE){if(this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag)return this._cachedReflectionTextureMatrix}else return this._cachedReflectionTextureMatrix;this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=j.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=j.Zero());let t=this._cachedReflectionCoordinatesMode!==this.coordinatesMode;switch(this._cachedReflectionUOffset=this.uOffset,this._cachedReflectionVOffset=this.vOffset,this._cachedReflectionUScale=this.uScale,this._cachedReflectionVScale=this.vScale,this._cachedReflectionCoordinatesMode=this.coordinatesMode,this.coordinatesMode){case n.PLANAR_MODE:{j.IdentityToRef(this._cachedReflectionTextureMatrix),this._cachedReflectionTextureMatrix[0]=this.uScale,this._cachedReflectionTextureMatrix[5]=this.vScale,this._cachedReflectionTextureMatrix[12]=this.uOffset,this._cachedReflectionTextureMatrix[13]=this.vOffset;break}case n.PROJECTION_MODE:{j.FromValuesToRef(.5,0,0,0,0,-.5,0,0,0,0,0,0,.5,.5,1,1,this._projectionModeMatrix);let i=e.getProjectionMatrix();this._cachedReflectionProjectionMatrixId=i.updateFlag,i.multiplyToRef(this._projectionModeMatrix,this._cachedReflectionTextureMatrix);break}default:j.IdentityToRef(this._cachedReflectionTextureMatrix);break}return t&&e.markAllMaterialsAsDirty(1,i=>i.hasTexture(this)),this._cachedReflectionTextureMatrix}clone(){let e={noMipmap:this._noMipmap,invertY:this._invertY,samplingMode:this.samplingMode,onLoad:void 0,onError:void 0,buffer:this._texture?this._texture._buffer:void 0,deleteBuffer:this._deleteBuffer,format:this.textureFormat,mimeType:this.mimeType,loaderOptions:this._loaderOptions,creationFlags:this._creationFlags,useSRGBBuffer:this._useSRGBBuffer};return it.Clone(()=>new n(this._texture?this._texture.url:null,this.getScene(),e),this)}serialize(){var i,r;let e=this.name;n.SerializeBuffers||this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");let t=super.serialize(n._SerializeInternalTextureUniqueId);if(!t)return null;if(n.SerializeBuffers||n.ForceSerializeBuffers)if(typeof this._buffer=="string"&&this._buffer.startsWith("data:"))t.base64String=this._buffer,t.name=t.name.replace("data:","");else if(this.url&&this.url.startsWith("data:")&&this._buffer instanceof Uint8Array){let s=this.mimeType||"image/png";t.base64String=`data:${s};base64,${rm(this._buffer)}`}else(n.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(t.base64String=!this._engine||this._engine._features.supportSyncTextureRead?z2(this):X2(this));return t.invertY=this._invertY,t.samplingMode=this.samplingMode,t._creationFlags=this._creationFlags,t._useSRGBBuffer=this._useSRGBBuffer,n._SerializeInternalTextureUniqueId&&(t.internalTextureUniqueId=(i=this._texture)==null?void 0:i.uniqueId),t.internalTextureLabel=(r=this._texture)==null?void 0:r.label,t.noMipmap=this._noMipmap,this.name=e,t}getClassName(){return"Texture"}dispose(){super.dispose(),this.onLoadObservable.clear(),this._delayedOnLoad=null,this._delayedOnError=null,this._buffer=null}static Parse(e,t,i){if(e.customType){let c=Xl.Instantiate(e.customType).Parse(e,t,i);return e.samplingMode&&c.updateSamplingMode&&c._samplingMode&&c._samplingMode!==e.samplingMode&&c.updateSamplingMode(e.samplingMode),c}if(e.isCube&&!e.isRenderTarget)return n._CubeTextureParser(e,t,i);let r=e.internalTextureUniqueId!==void 0;if(!e.name&&!e.isRenderTarget&&!r)return null;let s;if(r){let l=t.getEngine().getLoadedTexturesCache();for(let c of l)if(c.uniqueId===e.internalTextureUniqueId){s=c;break}}let a=l=>{if(l&&l._texture&&(l._texture._cachedWrapU=null,l._texture._cachedWrapV=null,l._texture._cachedWrapR=null),e.samplingMode){let c=e.samplingMode;l&&l.samplingMode!==c&&l.updateSamplingMode(c)}if(l&&e.animations)for(let c=0;c{var c,f,h,d,u;let l=!0;if(e.noMipmap&&(l=!1),e.mirrorPlane){let m=n._CreateMirror(e.name,e.renderTargetSize,t,l);return m._waitingRenderList=e.renderList,m.mirrorPlane=to.FromArray(e.mirrorPlane),a(m),m}else if(e.isRenderTarget&&!e.base64String){let m=null;if(e.isCube){if(t.reflectionProbes)for(let p=0;p{a(m)}},_=e.base64String,g=_.startsWith("data:")?_.substring(5):_;m=n.CreateFromBase64String("",g,t,p),m.name=e.name}else{let p;e.name&&(e.name.indexOf("://")>0||e.name.startsWith("data:"))?p=e.name:p=i+e.name,e.url&&(e.url.startsWith("data:")||n.UseSerializedUrlIfAny)&&(p=e.url);let _={noMipmap:!l,invertY:e.invertY,samplingMode:e.samplingMode,useSRGBBuffer:(d=e._useSRGBBuffer)!=null?d:!1,creationFlags:(u=e._creationFlags)!=null?u:0,onLoad:()=>{a(m)},internalTexture:s};m=new n(p,t,_)}return m}},e,t)}static CreateFromBase64String(e,t,i,r,s,a=n.TRILINEAR_SAMPLINGMODE,o=null,l=null,c=5,f,h){return new n("data:"+t,i,r,s,a,o,l,e,!1,c,void 0,void 0,f,h)}static LoadFromDataString(e,t,i,r=!1,s,a=!0,o=n.TRILINEAR_SAMPLINGMODE,l=null,c=null,f=5,h,d){return e.substring(0,5)!=="data:"&&(e="data:"+e),new n(e,i,s,a,o,l,c,t,r,f,void 0,void 0,h,d)}};_e.SerializeBuffers=!0;_e.ForceSerializeBuffers=!1;_e.OnTextureLoadErrorObservable=new ie;_e._SerializeInternalTextureUniqueId=!1;_e._CubeTextureParser=(n,e,t)=>{throw Ze("CubeTexture")};_e._CreateMirror=(n,e,t,i)=>{throw Ze("MirrorTexture")};_e._CreateRenderTargetTexture=(n,e,t,i,r)=>{throw Ze("RenderTargetTexture")};_e.NEAREST_SAMPLINGMODE=1;_e.NEAREST_NEAREST_MIPLINEAR=8;_e.BILINEAR_SAMPLINGMODE=2;_e.LINEAR_LINEAR_MIPNEAREST=11;_e.TRILINEAR_SAMPLINGMODE=3;_e.LINEAR_LINEAR_MIPLINEAR=3;_e.NEAREST_NEAREST_MIPNEAREST=4;_e.NEAREST_LINEAR_MIPNEAREST=5;_e.NEAREST_LINEAR_MIPLINEAR=6;_e.NEAREST_LINEAR=7;_e.NEAREST_NEAREST=1;_e.LINEAR_NEAREST_MIPNEAREST=9;_e.LINEAR_NEAREST_MIPLINEAR=10;_e.LINEAR_LINEAR=2;_e.LINEAR_NEAREST=12;_e.EXPLICIT_MODE=0;_e.SPHERICAL_MODE=1;_e.PLANAR_MODE=2;_e.CUBIC_MODE=3;_e.PROJECTION_MODE=4;_e.SKYBOX_MODE=5;_e.INVCUBIC_MODE=6;_e.EQUIRECTANGULAR_MODE=7;_e.FIXED_EQUIRECTANGULAR_MODE=8;_e.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;_e.CLAMP_ADDRESSMODE=0;_e.WRAP_ADDRESSMODE=1;_e.MIRROR_ADDRESSMODE=2;_e.UseSerializedUrlIfAny=!1;P([w()],_e.prototype,"url",void 0);P([w()],_e.prototype,"uOffset",void 0);P([w()],_e.prototype,"vOffset",void 0);P([w()],_e.prototype,"uScale",void 0);P([w()],_e.prototype,"vScale",void 0);P([w()],_e.prototype,"uAng",void 0);P([w()],_e.prototype,"vAng",void 0);P([w()],_e.prototype,"wAng",void 0);P([w()],_e.prototype,"uRotationCenter",void 0);P([w()],_e.prototype,"vRotationCenter",void 0);P([w()],_e.prototype,"wRotationCenter",void 0);P([w()],_e.prototype,"homogeneousRotationInUVTransform",void 0);P([w()],_e.prototype,"isBlocking",null);wt("BABYLON.Texture",_e);it._TextureParser=_e.Parse});var ro,L,Gi=C(()=>{bM();yt();nm();ro=class{get isDisposed(){return this._isDisposed}constructor(e,t,i,r=0,s=!1,a=!1,o=!1,l,c){this._isAlreadyOwned=!1,this._isDisposed=!1,e&&e.getScene?this._engine=e.getScene().getEngine():this._engine=e,this._updatable=i,this._instanced=a,this._divisor=l||1,this._label=c,t instanceof Dh?(this._data=null,this._buffer=t):(this._data=t,this._buffer=null),this.byteStride=o?r:r*Float32Array.BYTES_PER_ELEMENT,s||this.create()}createVertexBuffer(e,t,i,r,s,a=!1,o){let l=a?t:t*Float32Array.BYTES_PER_ELEMENT,c=r?a?r:r*Float32Array.BYTES_PER_ELEMENT:this.byteStride;return new L(this._engine,this,e,this._updatable,!0,c,s===void 0?this._instanced:s,l,i,void 0,void 0,!0,this._divisor||o)}isUpdatable(){return this._updatable}getData(){return this._data}getBuffer(){return this._buffer}getStrideSize(){return this.byteStride/Float32Array.BYTES_PER_ELEMENT}create(e=null){!e&&this._buffer||(e=e||this._data,e&&(this._buffer?this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e),this._data=e):this._updatable?(this._buffer=this._engine.createDynamicVertexBuffer(e,this._label),this._data=e):this._buffer=this._engine.createVertexBuffer(e,void 0,this._label)))}_rebuild(){if(this._data)this._buffer=null,this.create(this._data);else{if(!this._buffer)return;if(this._buffer.capacity>0){this._updatable?this._buffer=this._engine.createDynamicVertexBuffer(this._buffer.capacity,this._label):this._buffer=this._engine.createVertexBuffer(this._buffer.capacity,void 0,this._label);return}te.Warn(`Missing data for buffer "${this._label}" ${this._buffer?"(uniqueId: "+this._buffer.uniqueId+")":""}. Buffer reconstruction failed.`),this._buffer=null}}update(e){this.create(e)}updateDirectly(e,t,i,r=!1){this._buffer&&this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e,r?t:t*Float32Array.BYTES_PER_ELEMENT,i?i*this.byteStride:void 0),t===0&&i===void 0?this._data=e:this._data=null)}_increaseReferences(){if(this._buffer){if(!this._isAlreadyOwned){this._isAlreadyOwned=!0;return}this._buffer.references++}}dispose(){this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._isDisposed=!0,this._data=null,this._buffer=null)}},L=class n{get isDisposed(){return this._isDisposed}get instanceDivisor(){return this._instanceDivisor}set instanceDivisor(e){let t=e!=0;this._instanceDivisor=e,t!==this._instanced&&(this._instanced=t,this._computeHashCode())}get _maxVerticesCount(){let e=this.getData();return e?Array.isArray(e)?e.length/(this.byteStride/4)-this.byteOffset/4:(e.byteLength-this.byteOffset)/this.byteStride:0}constructor(e,t,i,r,s,a,o,l,c,f,h=!1,d=!1,u=1,m=!1){var g,v,x,A,S;this._isDisposed=!1;let p;if(this.engine=e,typeof r=="object"&&r!==null?(p=(g=r.updatable)!=null?g:!1,s=r.postponeInternalCreation,a=r.stride,o=r.instanced,l=r.offset,c=r.size,f=r.type,h=(v=r.normalized)!=null?v:!1,d=(x=r.useBytes)!=null?x:!1,u=(A=r.divisor)!=null?A:1,m=(S=r.takeBufferOwnership)!=null?S:!1,this._label=r.label):p=!!r,t instanceof ro?(this._buffer=t,this._ownsBuffer=m):(this._buffer=new ro(e,t,p,a,s,o,d,u,this._label),this._ownsBuffer=!0),this.uniqueId=n._Counter++,this._kind=i,f===void 0){let E=this.getData();this.type=E?n.GetDataType(E):n.FLOAT}else this.type=f;let _=Jo(this.type);d?(this._size=c||(a?a/_:n.DeduceStride(i)),this.byteStride=a||this._buffer.byteStride||this._size*_,this.byteOffset=l||0):(this._size=c||a||n.DeduceStride(i),this.byteStride=a?a*_:this._buffer.byteStride||this._size*_,this.byteOffset=(l||0)*_),this.normalized=h,this._instanced=o!==void 0?o:!1,this._instanceDivisor=o?u:0,this._alignBuffer(),this._computeHashCode()}_computeHashCode(){this.hashCode=(this.type-5120<<0)+((this.normalized?1:0)<<3)+(this._size<<4)+((this._instanced?1:0)<<6)+(this.byteStride<<12)}_rebuild(){var e;(e=this._buffer)==null||e._rebuild()}getKind(){return this._kind}isUpdatable(){return this._buffer.isUpdatable()}getData(){return this._buffer.getData()}getFloatData(e,t){let i=this.getData();return i?VM(i,this._size,this.type,this.byteOffset,this.byteStride,this.normalized,e,t):null}getBuffer(){return this._buffer.getBuffer()}getWrapperBuffer(){return this._buffer}getStrideSize(){return this.byteStride/Jo(this.type)}getOffset(){return this.byteOffset/Jo(this.type)}getSize(e=!1){return e?this._size*Jo(this.type):this._size}getIsInstanced(){return this._instanced}getInstanceDivisor(){return this._instanceDivisor}create(e){this._buffer.create(e),this._alignBuffer()}update(e){this._buffer.update(e),this._alignBuffer()}updateDirectly(e,t,i=!1){this._buffer.updateDirectly(e,t,void 0,i),this._alignBuffer()}dispose(){this._ownsBuffer&&this._buffer.dispose(),this._isDisposed=!0}forEach(e,t){Uh(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,(i,r)=>{for(let s=0;s{for(let h=0;h{Gi();hi();Yl=class{constructor(e){this._vertexBuffers={},this._activePostProcesses=[],this.onBeforeRenderObservable=new ie,this._scene=e}_prepareBuffers(){if(this._vertexBuffers[L.PositionKind])return;let e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[L.PositionKind]=new L(this._scene.getEngine(),e,L.PositionKind,!1,!1,2),this._buildIndexBuffer()}_buildIndexBuffer(){let e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(e)}_getActivePostProcesses(e){let t=this._activePostProcesses;t.length=0;for(let i=0;i{yt();K2=(n,e,t)=>!n||n.getClassName&&n.getClassName()==="Mesh"?null:n.getClassName&&(n.getClassName()==="SubMesh"||n.getClassName()==="PhysicsBody")?n.clone(e):n.clone?n.clone():Array.isArray(n)?n.slice():t&&typeof n=="object"?{...n}:null;tl=class{static DeepCopy(e,t,i,r,s=!1){let a=wre(e);for(let o of a){if(o[0]==="_"&&(!r||r.indexOf(o)===-1)||o.endsWith("Observable")||i&&i.indexOf(o)!==-1)continue;let l=e[o],c=typeof l;if(c!=="function")try{if(c==="object")if(l instanceof Uint8Array)t[o]=Uint8Array.from(l);else if(l instanceof Array){if(t[o]=[],l.length>0)if(typeof l[0]=="object")for(let f=0;f{hi();va();yt();W_();Fl();hn();Bh();Pi();Hl();jo();WM();B_();$a();pe=class{static get BaseUrl(){return Vi.BaseUrl}static set BaseUrl(e){Vi.BaseUrl=e}static get CleanUrl(){return Vi.CleanUrl}static set CleanUrl(e){Vi.CleanUrl=e}static IsAbsoluteUrl(e){return e.indexOf("//")===0?!0:e.indexOf("://")===-1||e.indexOf(".")===-1||e.indexOf("/")===-1||e.indexOf(":")>e.indexOf("/")?!1:e.indexOf("://"){el(e,s=>{i(s)},void 0,void 0,t,(s,a)=>{r(a)})})}static GetAssetUrl(e){if(!e)return"";if(_t.AssetBaseUrl&&e.startsWith(_t._DefaultAssetsUrl)){let t=_t.AssetBaseUrl.endsWith("/")?_t.AssetBaseUrl.slice(0,-1):_t.AssetBaseUrl;return e.replace(_t._DefaultAssetsUrl,t)}return e}static GetBabylonScriptURL(e,t){if(!e)return"";if(e.startsWith(_t._DefaultCdnUrl)){if(_t.ScriptBaseUrl){let i=_t.ScriptBaseUrl.endsWith("/")?_t.ScriptBaseUrl.slice(0,-1):_t.ScriptBaseUrl;e=e.replace(_t._DefaultCdnUrl,i)}else if(_t._CdnVersion){let i=`${_t._DefaultCdnUrl}/v${_t._CdnVersion}`;e.startsWith(i)||(e=e.replace(_t._DefaultCdnUrl,i))}}return e=_t.ScriptPreprocessUrl(e),t&&!_t.IsAbsoluteUrl(e)&&(e=_t.GetAbsoluteUrl(e)),e}static LoadBabylonScript(e,t,i,r){e=_t.GetBabylonScriptURL(e),_t.LoadScript(e,t,i)}static async LoadBabylonScriptAsync(e){return e=_t.GetBabylonScriptURL(e),await _t.LoadScriptAsync(e)}static _LoadScriptNative(e,t,i){let r=new Error(`[AI3D] Babylon script loading is disabled in this plugin build. Refused script URL: ${e}`);i==null||i(r.message,r)}static _LoadScriptWeb(e,t,i,r,s=!1){let a=new Error(`[AI3D] Babylon script loading is disabled in this plugin build. Refused script URL: ${e}`);i==null||i(a.message,a)}static async LoadScriptAsync(e,t){return await new Promise((i,r)=>{this.LoadScript(e,()=>{i()},(s,a)=>{r(a||new Error(s))},t)})}static ReadFileAsDataURL(e,t,i){let r=new FileReader,s={onCompleteObservable:new ie,abort:()=>r.abort()};return r.onloadend=()=>{s.onCompleteObservable.notifyObservers(s)},r.onload=a=>{t(a.target.result)},r.onprogress=i,r.readAsDataURL(e),s}static ReadFile(e,t,i,r,s){return Vh(e,t,i,r,s)}static FileAsURL(e){let t=new Blob([e]);return window.URL.createObjectURL(t)}static Format(e,t=2){return e.toFixed(t)}static DeepCopy(e,t,i,r){tl.DeepCopy(e,t,i,r)}static IsEmpty(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}static RegisterTopRootEvents(e,t){for(let i=0;i{let l=atob(this.toDataURL(a,o).split(",")[1]),c=l.length,f=new Uint8Array(c);for(let h=0;ht(s)):e.toBlob(function(s){t(s)},i,r)}static DownloadBlob(e,t){if("download"in document.createElement("a")){if(!t){let i=new Date;t="screenshot_"+((i.getFullYear()+"-"+(i.getMonth()+1)).slice(2)+"-"+i.getDate()+"_"+i.getHours()+"-"+("0"+i.getMinutes()).slice(-2))+".png"}_t.Download(e,t)}else if(e&&typeof URL!="undefined"){let i=URL.createObjectURL(e),r=window.open("");if(!r)return;let s=r.document.createElement("img");s.onload=function(){URL.revokeObjectURL(i)},s.src=i,r.document.body.appendChild(s)}}static EncodeScreenshotCanvasData(e,t,i="image/png",r,s){if(typeof r=="string"||!t)this.ToBlob(e,function(a){a&&_t.DownloadBlob(a,r),t&&t("")},i,s);else if(t){if(_t._IsOffScreenCanvas(e)){e.convertToBlob({type:i,quality:s}).then(o=>{let l=new FileReader;l.readAsDataURL(o),l.onloadend=()=>{let c=l.result;t(c)}});return}let a=e.toDataURL(i,s);t(a)}}static Download(e,t){if(typeof URL=="undefined")return;let i=window.URL.createObjectURL(e),r=document.createElement("a");document.body.appendChild(r),r.style.display="none",r.href=i,r.download=t,r.addEventListener("click",()=>{r.parentElement&&r.parentElement.removeChild(r)}),r.click(),window.URL.revokeObjectURL(i)}static BackCompatCameraNoPreventDefault(e){return typeof e[0]=="boolean"?e[0]:typeof e[1]=="boolean"?e[1]:!1}static CreateScreenshot(e,t,i,r,s="image/png",a=!1,o){throw Ze("ScreenshotTools")}static async CreateScreenshotAsync(e,t,i,r="image/png",s){throw Ze("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,r,s="image/png",a=1,o=!1,l,c=!1,f=!1,h=!0,d,u){throw Ze("ScreenshotTools")}static async CreateScreenshotUsingRenderTargetAsync(e,t,i,r="image/png",s=1,a=!1,o,l=!1,c=!1,f=!0,h,d){throw Ze("ScreenshotTools")}static RandomId(){return cf()}static IsBase64(e){return hf(e)}static DecodeBase64(e){return df(e)}static get errorsCount(){return te.errorsCount}static Log(e){te.Log(e)}static Warn(e){te.Warn(e)}static Error(e){te.Error(e)}static get LogCache(){return te.LogCache}static ClearLogCache(){te.ClearLogCache()}static set LogLevels(e){te.LogLevels=e}static set PerformanceLogLevel(e){var t;if((e&_t.PerformanceUserMarkLogLevel)===_t.PerformanceUserMarkLogLevel){_native!=null&&_native.enablePerformanceLogging?(_native.enablePerformanceLogging(1),_t.StartPerformanceCounter=_t._StartMarkNative,_t.EndPerformanceCounter=_t._EndMarkNative):(_t.StartPerformanceCounter=_t._StartUserMark,_t.EndPerformanceCounter=_t._EndUserMark);return}if((e&_t.PerformanceConsoleLogLevel)===_t.PerformanceConsoleLogLevel){_native!=null&&_native.enablePerformanceLogging?(_native.enablePerformanceLogging(2),_t.StartPerformanceCounter=_t._StartMarkNative,_t.EndPerformanceCounter=_t._EndMarkNative):(_t.StartPerformanceCounter=_t._StartPerformanceConsole,_t.EndPerformanceCounter=_t._EndPerformanceConsole);return}_t.StartPerformanceCounter=_t._StartPerformanceCounterDisabled,_t.EndPerformanceCounter=_t._EndPerformanceCounterDisabled,(t=_native==null?void 0:_native.disablePerformanceLogging)==null||t.call(_native)}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!_t._Performance){if(!cr())return;_t._Performance=window.performance}!t||!_t._Performance.mark||_t._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){!t||!_t._Performance.mark||(_t._Performance.mark(e+"-End"),_t._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(_t._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(_t._EndUserMark(e,t),console.timeEnd(e))}static _StartMarkNative(e,t=!0){if(t&&(_native!=null&&_native.startPerformanceCounter))if(_t._NativePerformanceCounterHandles.has(e))_t.Warn(`Performance counter with name ${e} is already started.`);else{let i=_native.startPerformanceCounter(e);_t._NativePerformanceCounterHandles.set(e,i)}}static _EndMarkNative(e,t=!0){if(t&&(_native!=null&&_native.endPerformanceCounter)){let i=_t._NativePerformanceCounterHandles.get(e);i?(_native.endPerformanceCounter(i),_t._NativePerformanceCounterHandles.delete(e)):_t.Warn(`Performance counter with name ${e} was not started.`)}}static get Now(){return mr.Now}static GetClassName(e,t=!1){let i=null;return!t&&e.getClassName?i=e.getClassName():(e instanceof Object&&(i=(t?e:Object.getPrototypeOf(e)).constructor.__bjsclassName__),i||(i=typeof e)),i}static First(e,t){for(let i of e)if(t(i))return i;return null}static getFullClassName(e,t=!1){let i=null,r=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){let s=t?e:Object.getPrototypeOf(e);i=s.constructor.__bjsclassName__,r=s.constructor.__bjsmoduleName__}i||(i=typeof e)}return i?(r!=null?r+".":"")+i:null}static async DelayAsync(e){await new Promise(t=>{setTimeout(()=>{t()},e)})}static IsSafari(){return wl()?/^((?!chrome|android).)*safari/i.test(navigator.userAgent):!1}};_t=pe;pe.AssetBaseUrl="";pe.UseCustomRequestHeaders=!1;pe.CustomRequestHeaders=Ir.CustomRequestHeaders;pe.GetDOMTextContent=nT;pe._DefaultCdnUrl="https://cdn.babylonjs.com";pe._CdnVersion="9.6.0";pe._DefaultAssetsUrl="https://assets.babylonjs.com/core";pe.LoadScript=typeof _native=="undefined"?_t._LoadScriptWeb:_t._LoadScriptNative;pe.GetAbsoluteUrl=typeof document=="object"?n=>{let e=document.createElement("a");return e.href=n,e.href}:typeof URL=="function"&&typeof location=="object"?n=>new URL(n,location.origin).href:()=>{throw new Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")};pe.NoneLogLevel=te.NoneLogLevel;pe.MessageLogLevel=te.MessageLogLevel;pe.WarningLogLevel=te.WarningLogLevel;pe.ErrorLogLevel=te.ErrorLogLevel;pe.AllLogLevel=te.AllLogLevel;pe.IsWindowObjectExist=cr;pe.PerformanceNoneLogLevel=0;pe.PerformanceUserMarkLogLevel=1;pe.PerformanceConsoleLogLevel=2;pe._NativePerformanceCounterHandles=new Map;pe.StartPerformanceCounter=_t._StartPerformanceCounterDisabled;pe.EndPerformanceCounter=_t._EndPerformanceCounterDisabled;qT=class n{constructor(e,t,i,r=0){this.iterations=e,this.index=r-1,this._done=!1,this._fn=t,this._successCallback=i}executeNext(){this._done||(this.index+1{s&&s()?o.breakLoop():setTimeout(()=>{for(let l=0;l=e)break;if(i(c),s&&s()){o.breakLoop();break}}o.executeNext()},a)},r)}};pe.Mix=L_;pe.IsExponentOfTwo=Lh;Le.FallbackTexture="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z"});var fr,pf=C(()=>{yt();bi();fr=class n{constructor(e,t,i=!1,r,s=!1,a){this._uniformNames=[],this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||s,this._dynamic=i,this._name=r!=null?r:"no-name",this._data=t||[],this._uniformLocations={},this._uniformSizes={},this._uniformArraySizes={},this._uniformLocationPointer=0,this._needSync=!1,this._trackUBOsInFrame=!1,(a===void 0&&this._engine._features.trackUbosInFrame||a===!0)&&(this._buffers=[],this._bufferIndex=-1,this._bufferUpdatedLastFrame=!1,this._createBufferOnWrite=!1,this._currentFrameId=0,this._trackUBOsInFrame=!0),this._noUBO?(this.updateMatrix3x3=this._updateMatrix3x3ForEffect,this.updateMatrix2x2=this._updateMatrix2x2ForEffect,this.updateFloat=this._updateFloatForEffect,this.updateFloat2=this._updateFloat2ForEffect,this.updateFloat3=this._updateFloat3ForEffect,this.updateFloat4=this._updateFloat4ForEffect,this.updateFloatArray=this._updateFloatArrayForEffect,this.updateArray=this._updateArrayForEffect,this.updateIntArray=this._updateIntArrayForEffect,this.updateUIntArray=this._updateUIntArrayForEffect,this.updateMatrix=this._updateMatrixForEffect,this.updateMatrices=this._updateMatricesForEffect,this.updateVector3=this._updateVector3ForEffect,this.updateVector4=this._updateVector4ForEffect,this.updateColor3=this._updateColor3ForEffect,this.updateColor4=this._updateColor4ForEffect,this.updateDirectColor4=this._updateDirectColor4ForEffect,this.updateInt=this._updateIntForEffect,this.updateInt2=this._updateInt2ForEffect,this.updateInt3=this._updateInt3ForEffect,this.updateInt4=this._updateInt4ForEffect,this.updateUInt=this._updateUIntForEffect,this.updateUInt2=this._updateUInt2ForEffect,this.updateUInt3=this._updateUInt3ForEffect,this.updateUInt4=this._updateUInt4ForEffect):(this._engine._uniformBuffers.push(this),this.updateMatrix3x3=this._updateMatrix3x3ForUniform,this.updateMatrix2x2=this._updateMatrix2x2ForUniform,this.updateFloat=this._updateFloatForUniform,this.updateFloat2=this._updateFloat2ForUniform,this.updateFloat3=this._updateFloat3ForUniform,this.updateFloat4=this._updateFloat4ForUniform,this.updateFloatArray=this._updateFloatArrayForUniform,this.updateArray=this._updateArrayForUniform,this.updateIntArray=this._updateIntArrayForUniform,this.updateUIntArray=this._updateUIntArrayForUniform,this.updateMatrix=this._updateMatrixForUniform,this.updateMatrices=this._updateMatricesForUniform,this.updateVector3=this._updateVector3ForUniform,this.updateVector4=this._updateVector4ForUniform,this.updateColor3=this._updateColor3ForUniform,this.updateColor4=this._updateColor4ForUniform,this.updateDirectColor4=this._updateDirectColor4ForUniform,this.updateInt=this._updateIntForUniform,this.updateInt2=this._updateInt2ForUniform,this.updateInt3=this._updateInt3ForUniform,this.updateInt4=this._updateInt4ForUniform,this.updateUInt=this._updateUIntForUniform,this.updateUInt2=this._updateUInt2ForUniform,this.updateUInt3=this._updateUInt3ForUniform,this.updateUInt4=this._updateUInt4ForUniform)}get useUbo(){return!this._noUBO}get isSync(){return!this._needSync}isDynamic(){return this._dynamic}getData(){return this._bufferData}getBuffer(){return this._buffer}getUniformNames(){return this._uniformNames}_fillAlignment(e){let t;if(e<=2?t=e:t=4,this._uniformLocationPointer%t!==0){let i=this._uniformLocationPointer;this._uniformLocationPointer+=t-this._uniformLocationPointer%t;let r=this._uniformLocationPointer-i;for(let s=0;s0&&typeof t=="number"&&(this._uniformArraySizes[e]={strideSize:t,arraySize:i}),this._uniformLocations[e]!==void 0||(this._uniformNames.push(e),this._noUBO))return;let r;if(i>0){if(t instanceof Array)throw"addUniform should not be use with Array in UBO: "+e;if(this._fillAlignment(4),t==16)t=t*i;else{let a=(4-t)*i;t=t*i+a}r=[];for(let s=0;s1&&this._buffers[this._bufferIndex][1])if(this._buffersEqual(this._bufferData,this._buffers[this._bufferIndex][1])){this._needSync=!1,this._createBufferOnWrite=this._trackUBOsInFrame;return}else this._copyBuffer(this._bufferData,this._buffers[this._bufferIndex][1]);this._bufferUpdatedLastFrame=!0,this._engine.updateUniformBuffer(this._buffer,this._bufferData),this._needSync=!1,this._createBufferOnWrite=this._trackUBOsInFrame}}_createNewBuffer(){this._bufferIndex+10?(this._buffers.length===1?this._needSync=!this._bufferUpdatedLastFrame:this._needSync=this._bufferIndex!==0,this._bufferIndex=0,this._buffer=this._buffers[this._bufferIndex][0]):this._bufferIndex=-1)}updateUniform(e,t,i){this._checkNewFrame();let r=this._uniformLocations[e];if(r===void 0){if(this._buffer){te.Error("Cannot add an uniform after UBO has been created. uniformName="+e);return}this.addUniform(e,i),r=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let s=0;s1&&this._buffers[t][1]&&this._bufferData.set(this._buffers[t][1]),this._valueCache={},this._currentFrameId=this._engine.frameId,!0;return!1}has(e){return this._uniformLocations[e]!==void 0}dispose(){if(this._noUBO)return;let e=this._engine._uniformBuffers,t=e.indexOf(this);if(t!==-1&&(e[t]=e[e.length-1],e.pop()),this._trackUBOsInFrame&&this._buffers)for(let i=0;i{wi=class n{constructor(e){this.length=0,this.data=new Array(e),this._id=n._GlobalId++}push(e){this.data[this.length++]=e,this.length>this.data.length&&(this.data.length*=2)}forEach(e){for(let t=0;tthis.data.length&&(this.data.length=(this.length+e.length)*2);for(let t=0;t=this.length?-1:t}contains(e){return this.indexOf(e)!==-1}};wi._GlobalId=0;no=class extends wi{constructor(){super(...arguments),this._duplicateId=0}push(e){super.push(e),e.__smartArrayFlags||(e.__smartArrayFlags={}),e.__smartArrayFlags[this._id]=this._duplicateId}pushNoDuplicate(e){return e.__smartArrayFlags&&e.__smartArrayFlags[this._id]===this._duplicateId?!1:(this.push(e),!0)}reset(){super.reset(),this._duplicateId++}concatWithNoDuplicate(e){if(e.length!==0){this.length+e.length>this.data.length&&(this.data.length=(this.length+e.length)*2);for(let t=0;t{so();Ve();H_=class n{set opaqueSortCompareFn(e){e?this._opaqueSortCompareFn=e:this._opaqueSortCompareFn=n.PainterSortCompare,this._renderOpaque=this._renderOpaqueSorted}set alphaTestSortCompareFn(e){e?this._alphaTestSortCompareFn=e:this._alphaTestSortCompareFn=n.PainterSortCompare,this._renderAlphaTest=this._renderAlphaTestSorted}set transparentSortCompareFn(e){e?this._transparentSortCompareFn=e:this._transparentSortCompareFn=n.defaultTransparentSortCompare,this._renderTransparent=this._renderTransparentSorted}constructor(e,t,i=null,r=null,s=null){this.index=e,this._opaqueSubMeshes=new wi(256),this._transparentSubMeshes=new wi(256),this._alphaTestSubMeshes=new wi(256),this._depthOnlySubMeshes=new wi(256),this._particleSystems=new wi(256),this._spriteManagers=new wi(256),this._empty=!0,this._edgesRenderers=new no(16),this.disableDepthPrePass=!1,this._scene=t,this.opaqueSortCompareFn=i,this.alphaTestSortCompareFn=r,this.transparentSortCompareFn=s}render(e,t,i,r,s=!0,a=!0,o=!0,l=!0,c){if(e){e(this._opaqueSubMeshes,this._alphaTestSubMeshes,this._transparentSubMeshes,this._depthOnlySubMeshes);return}let f=this._scene.getEngine();s&&this._depthOnlySubMeshes.length!==0&&(f.setColorWrite(!1),this._renderAlphaTest(this._depthOnlySubMeshes),f.setColorWrite(!0)),a&&this._opaqueSubMeshes.length!==0&&this._renderOpaque(this._opaqueSubMeshes),o&&this._alphaTestSubMeshes.length!==0&&this._renderAlphaTest(this._alphaTestSubMeshes);let h=f.getStencilBuffer();if(f.setStencilBuffer(!1),t&&this._renderSprites(),i&&this._renderParticles(r),this.onBeforeTransparentRendering&&this.onBeforeTransparentRendering(),l&&(c||this._transparentSubMeshes.length!==0||this._scene.useOrderIndependentTransparency)){if(f.setStencilBuffer(h),c)c(this._transparentSubMeshes,this);else if(this._scene.useOrderIndependentTransparency){let d=this._scene.depthPeelingRenderer.render(this._transparentSubMeshes);d.length&&this._renderTransparent(d)}else this._renderTransparent(this._transparentSubMeshes);f.setAlphaMode(0)}if(f.setStencilBuffer(!1),a&&this._edgesRenderers.length){for(let d=0;dt._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0}static frontToBackSortCompare(e,t){return e._distanceToCamerat._distanceToCamera?1:0}static PainterSortCompare(e,t){let i=e.getMesh(),r=t.getMesh();return i.material&&r.material?i.material.uniqueId-r.material.uniqueId:i.uniqueId-r.uniqueId}prepare(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset(),this._depthOnlySubMeshes.reset(),this._particleSystems.reset(),this.prepareSprites(),this._edgesRenderers.reset(),this._empty=!0}prepareSprites(){this._spriteManagers.reset()}dispose(){this._opaqueSubMeshes.dispose(),this._transparentSubMeshes.dispose(),this._alphaTestSubMeshes.dispose(),this._depthOnlySubMeshes.dispose(),this._particleSystems.dispose(),this._spriteManagers.dispose(),this._edgesRenderers.dispose()}dispatch(e,t,i){t===void 0&&(t=e.getMesh()),i===void 0&&(i=e.getMaterial()),i!=null&&(i.needAlphaBlendingForMesh(t)?this._transparentSubMeshes.push(e):i.needAlphaTestingForMesh(t)?(i.needDepthPrePass&&!this.disableDepthPrePass&&this._depthOnlySubMeshes.push(e),this._alphaTestSubMeshes.push(e)):(i.needDepthPrePass&&!this.disableDepthPrePass&&this._depthOnlySubMeshes.push(e),this._opaqueSubMeshes.push(e)),t._renderingGroup=this,t._edgesRenderer&&t.isEnabled()&&t.isVisible&&t._edgesRenderer.isEnabled&&this._edgesRenderers.pushNoDuplicate(t._edgesRenderer),this._empty=!1)}dispatchSprites(e){this._spriteManagers.push(e),this._empty=!1}dispatchParticles(e){this._particleSystems.push(e),this._empty=!1}_renderParticles(e){if(this._particleSystems.length===0)return;let t=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(let i=0;i{j2();HM=class{},Ta=class n{get disableDepthPrePass(){return this._disableDepthPrePass}set disableDepthPrePass(e){this._disableDepthPrePass=e;for(let t of this._renderingGroups)t.disableDepthPrePass=e}get maintainStateBetweenFrames(){return this._maintainStateBetweenFrames}set maintainStateBetweenFrames(e){e!==this._maintainStateBetweenFrames&&(this._maintainStateBetweenFrames=e,this._maintainStateBetweenFrames||this.restoreDispachedFlags())}restoreDispachedFlags(){for(let e of this._scene.meshes)if(e.subMeshes)for(let t of e.subMeshes)t._wasDispatched=!1;if(this._scene.spriteManagers)for(let e of this._scene.spriteManagers)e._wasDispatched=!1;for(let e of this._scene.particleSystems)e._wasDispatched=!1}constructor(e){this._useSceneAutoClearSetup=!1,this._disableDepthPrePass=!1,this._renderingGroups=new Array,this._autoClearDepthStencil={},this._customOpaqueSortCompareFn={},this._customAlphaTestSortCompareFn={},this._customTransparentSortCompareFn={},this._renderingGroupInfo=new HM,this._maintainStateBetweenFrames=!1,this._scene=e;for(let t=n.MIN_RENDERINGGROUPS;t{Yt=class{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}};Yt.FALLOFF_DEFAULT=0;Yt.FALLOFF_PHYSICAL=1;Yt.FALLOFF_GLTF=2;Yt.FALLOFF_STANDARD=3;Yt.LIGHTMAP_DEFAULT=0;Yt.LIGHTMAP_SPECULAR=1;Yt.LIGHTMAP_SHADOWSONLY=2;Yt.INTENSITYMODE_AUTOMATIC=0;Yt.INTENSITYMODE_LUMINOUSPOWER=1;Yt.INTENSITYMODE_LUMINOUSINTENSITY=2;Yt.INTENSITYMODE_ILLUMINANCE=3;Yt.INTENSITYMODE_LUMINANCE=4;Yt.LIGHTTYPEID_POINTLIGHT=0;Yt.LIGHTTYPEID_DIRECTIONALLIGHT=1;Yt.LIGHTTYPEID_SPOTLIGHT=2;Yt.LIGHTTYPEID_HEMISPHERICLIGHT=3;Yt.LIGHTTYPEID_RECT_AREALIGHT=4;Yt.LIGHTTYPEID_CLUSTERED_CONTAINER=5});var Aa,zM=C(()=>{pf();hi();ZT();Zo();jo();yt();so();z_();Aa=class n{get renderList(){return this._renderList}set renderList(e){this._renderList!==e&&(this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=OT(e,this._renderListHasChanged)),this._renderList=e)}get disableImageProcessing(){return this._disableImageProcessing}set disableImageProcessing(e){e!==this._disableImageProcessing&&(this._disableImageProcessing=e,this._scene.markAllMaterialsAsDirty(64))}get disableDepthPrePass(){return this._disableDepthPrePass}set disableDepthPrePass(e){this._disableDepthPrePass=e,this._renderingManager.disableDepthPrePass=e}get name(){return this._name}set name(e){if(this._name!==e){if(this._name=e,this._sceneUBOs)for(let t=0;tthis._checkReadiness(),()=>{if(this._freezeActiveMeshesCancel=null,e)for(let t=0;t{this._freezeActiveMeshesCancel=null,i?(te.Error("ObjectRenderer: Timeout while waiting for the renderer to be ready."),t&&te.Error(t)):(te.Error("ObjectRenderer: An unexpected error occurred while waiting for the renderer to be ready."),t&&(te.Error(t),t.stack&&te.Error(t.stack)))})}_unfreezeActiveMeshes(){var e;(e=this._freezeActiveMeshesCancel)==null||e.call(this),this._freezeActiveMeshesCancel=null;for(let t=0;t{let a=this._renderList?this._renderList.length:0;if(s===0&&a>0||a===0)for(let o of this._scene.meshes)o._markSubMeshesAsLightDirty()},this.particleSystemList=null,this.getCustomRenderList=null,this.renderMeshes=!0,this.renderDepthOnlyMeshes=!0,this.renderOpaqueMeshes=!0,this.renderAlphaTestMeshes=!0,this.renderTransparentMeshes=!0,this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.enableBoundingBoxRendering=!1,this.enableOutlineRendering=!0,this._disableImageProcessing=!1,this.dontSetTransformationMatrix=!1,this._disableDepthPrePass=!1,this.onBeforeRenderObservable=new ie,this.onAfterRenderObservable=new ie,this.onBeforeRenderingManagerRenderObservable=new ie,this.onAfterRenderingManagerRenderObservable=new ie,this.onInitRenderingObservable=new ie,this.onFinishRenderingObservable=new ie,this.onFastPathRenderObservable=new ie,this._currentRefreshId=-1,this._refreshRate=1,this._currentApplyByPostProcessSetting=!1,this._activeMeshes=new wi(256),this._activeBoundingBoxes=new wi(32),this._currentFrameId=-1,this._currentSceneUBOIndex=0,this._isFrozen=!1,this._freezeActiveMeshesCancel=null,this._currentSceneCamera=null,this.name=e,this._scene=t,this._engine=this._scene.getEngine(),this._useUBO=this._engine.supportsUniformBuffers,this.renderList=[],this._renderPassIds=[],this.options={numPasses:1,doNotChangeAspectRatio:!0,enableClusteredLights:!1,...i},this._createRenderPassId(),this.renderPassId=this._renderPassIds[0],this._renderingManager=new Ta(t),this._renderingManager._useSceneAutoClearSetup=!0,this.options.enableClusteredLights&&this.onInitRenderingObservable.add(()=>{for(let r of this._scene.lights)r.getTypeID()===Yt.LIGHTTYPEID_CLUSTERED_CONTAINER&&r.isSupported&&r._updateBatches(this.activeCamera).render()}),this._scene.addObjectRenderer(this)}_releaseRenderPassId(){for(let e=0;e=this._sceneUBOs.length){let s=this._sceneUBOs.length;this._sceneUBOs.push(this._createSceneUBO(`Scene ubo #${s} for ${this.name}`,t)),this._sceneUBOIsMultiview.push(t)}else this._sceneUBOIsMultiview[this._currentSceneUBOIndex]!==t&&(this._sceneUBOs[this._currentSceneUBOIndex].dispose(),this._sceneUBOs[this._currentSceneUBOIndex]=this._createSceneUBO(`Scene ubo #${this._currentSceneUBOIndex} for ${this.name}`,t),this._sceneUBOIsMultiview[this._currentSceneUBOIndex]=t);let i=this._sceneUBOs[this._currentSceneUBOIndex++];return i.unbindEffect(),i}resetRefreshCounter(){this._currentRefreshId=-1}get refreshRate(){return this._refreshRate}set refreshRate(e){this._refreshRate=e,this.resetRefreshCounter()}shouldRender(){return this._engine.snapshotRendering?!0:this._currentRefreshId===-1?(this._currentRefreshId=1,!0):this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)}isReadyForRendering(e,t){this.prepareRenderList(),this.initRender(e,t);let i=this._checkReadiness();return this.finishRender(),i}prepareRenderList(){let e=this._scene;if(this._waitingRenderList){if(!this.renderListPredicate){this.renderList=[];for(let t=0;t1&&(e.incrementRenderId(),e.resetCachedMaterial())}let s=this.particleSystemList||e.particleSystems;for(let a of s)a.isReady()||(i=!1);return this._engine.currentRenderPassId=t,i}_prepareRenderingManager(e=0,t=!1){var d,u;let i=this._scene,r=null,s,a,o=this.renderList?this.renderList:i.frameGraph?i.meshes:i.getActiveMeshes().data,l=this.renderList||i.frameGraph?o.length:i.getActiveMeshes().length;if(this.getCustomRenderList&&(r=this.getCustomRenderList(e,o,l)),r)s=r.length,a=this.forceLayerMaskCheck;else{if(this._defaultRenderListPrepared&&!t&&!this._engine.isWebGPU)return o;this._defaultRenderListPrepared=!0,r=o,s=l,a=!this.renderList||this.forceLayerMaskCheck}let c=i.activeCamera,f=(d=this.cameraForLOD)!=null?d:c,h=(u=i.getBoundingBoxRenderer)==null?void 0:u.call(i);if(i._activeMeshesFrozen&&this._isFrozen){if(this._renderingManager.resetSprites(),this.enableBoundingBoxRendering&&h){h.reset();for(let m=0;m{jo();Jn=class{static GetEffect(e){return e.getPipelineContext===void 0?e.effect:e}constructor(e,t=!0){this._wasPreviouslyReady=!1,this._forceRebindOnNextCall=!0,this._wasPreviouslyUsingInstances=null,this.effect=null,this.defines=null,this.drawContext=e.createDrawContext(),t&&(this.materialContext=e.createMaterialContext())}setEffect(e,t,i=!0){var r;this.effect=e,t!==void 0&&(this.defines=t),i&&((r=this.drawContext)==null||r.reset())}dispose(e=!1){var t;if(this.effect){let i=this.effect;e?i.dispose():Qa.SetImmediate(()=>{i.getEngine().onEndFrameObservable.addOnce(()=>{i.dispose()})}),this.effect=null}(t=this.drawContext)==null||t.dispose()}}});var Z2={};tt(Z2,{postprocessVertexShader:()=>Fre});var XM,q2,Fre,YM=C(()=>{W();XM="postprocessVertexShader",q2=`attribute vec2 position;uniform vec2 scale;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); +${this.m[12]}, ${this.m[13]}, ${this.m[14]}, ${this.m[15]}}`}toArray(e=null,t=0){if(!e)return this._m;let i=this._m;for(let r=0;r<16;r++)e[t+r]=i[r];return this}asArray(){return this._m}fromArray(e,t=0){return n.FromArrayToRef(e,t,this)}copyFromFloats(...e){return n.FromArrayToRef(e,0,this)}set(...e){let t=this._m;for(let i=0;i<16;i++)t[i]=e[i];return this.markAsUpdated(),this}setAll(e){let t=this._m;for(let i=0;i<16;i++)t[i]=e;return this.markAsUpdated(),this}invert(){return this.invertToRef(this),this}reset(){return n.FromValuesToRef(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,this),this._updateIdentityStatus(!1),this}add(e){let t=new n;return this.addToRef(e,t),t}addToRef(e,t){let i=this._m,r=t._m,s=e.m;for(let a=0;a<16;a++)r[a]=i[a]+s[a];return t.markAsUpdated(),t}addToSelf(e){let t=this._m,i=e.m;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.markAsUpdated(),this}addInPlace(e){let t=this._m,i=e.m;for(let r=0;r<16;r++)t[r]+=i[r];return this.markAsUpdated(),this}addInPlaceFromFloats(...e){let t=this._m;for(let i=0;i<16;i++)t[i]+=e[i];return this.markAsUpdated(),this}subtract(e){let t=this._m,i=e.m;for(let r=0;r<16;r++)t[r]-=i[r];return this.markAsUpdated(),this}subtractToRef(e,t){let i=this._m,r=e.m,s=t._m;for(let a=0;a<16;a++)s[a]=i[a]-r[a];return t.markAsUpdated(),t}subtractInPlace(e){let t=this._m,i=e.m;for(let r=0;r<16;r++)t[r]-=i[r];return this.markAsUpdated(),this}subtractFromFloats(...e){return this.subtractFromFloatsToRef(...e,new n)}subtractFromFloatsToRef(...e){let t=e.pop(),i=this._m,r=t._m,s=e;for(let a=0;a<16;a++)r[a]=i[a]-s[a];return t.markAsUpdated(),t}invertToRef(e){return this._isIdentity===!0?(n.IdentityToRef(e),e):(OM(this,e.asArray())?e.markAsUpdated():e.copyFrom(this),e)}addAtIndex(e,t){return this._m[e]+=t,this.markAsUpdated(),this}multiplyAtIndex(e,t){return this._m[e]*=t,this.markAsUpdated(),this}setTranslationFromFloats(e,t,i){return this._m[12]=e,this._m[13]=t,this._m[14]=i,this.markAsUpdated(),this}addTranslationFromFloats(e,t,i){return this._m[12]+=e,this._m[13]+=t,this._m[14]+=i,this.markAsUpdated(),this}setTranslation(e){return this.setTranslationFromFloats(e._x,e._y,e._z)}getTranslation(){return new b(this._m[12],this._m[13],this._m[14])}getTranslationToRef(e){return e.x=this._m[12],e.y=this._m[13],e.z=this._m[14],e}removeRotationAndScaling(){let e=this.m;return n.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e[12],e[13],e[14],e[15],this),this._updateIdentityStatus(e[12]===0&&e[13]===0&&e[14]===0&&e[15]===1),this}copyFrom(e){e.copyToArray(this._m);let t=e;return this.updateFlag=t.updateFlag,this._updateIdentityStatus(t._isIdentity,t._isIdentityDirty,t._isIdentity3x2,t._isIdentity3x2Dirty),this}copyToArray(e,t=0){return g2(this,e,t),this}multiply(e){let t=new n;return this.multiplyToRef(e,t),t}multiplyInPlace(e){let t=this._m,i=e.m;for(let r=0;r<16;r++)t[r]*=i[r];return this.markAsUpdated(),this}multiplyByFloats(...e){let t=this._m;for(let i=0;i<16;i++)t[i]*=e[i];return this.markAsUpdated(),this}multiplyByFloatsToRef(...e){let t=e.pop(),i=this._m,r=t._m,s=e;for(let a=0;a<16;a++)r[a]=i[a]*s[a];return t.markAsUpdated(),t}multiplyToRef(e,t){return this._isIdentity?(t.copyFrom(e),t):e._isIdentity?(t.copyFrom(this),t):(this.multiplyToArray(e,t._m,0),t.markAsUpdated(),t)}multiplyToArray(e,t,i){return LM(this,e,t,i),this}divide(e){return this.divideToRef(e,new n)}divideToRef(e,t){let i=this._m,r=e.m,s=t._m;for(let a=0;a<16;a++)s[a]=i[a]/r[a];return t.markAsUpdated(),t}divideInPlace(e){let t=this._m,i=e.m;for(let r=0;r<16;r++)t[r]/=i[r];return this.markAsUpdated(),this}minimizeInPlace(e){let t=this._m,i=e.m;for(let r=0;r<16;r++)t[r]=Math.min(t[r],i[r]);return this.markAsUpdated(),this}minimizeInPlaceFromFloats(...e){let t=this._m;for(let i=0;i<16;i++)t[i]=Math.min(t[i],e[i]);return this.markAsUpdated(),this}maximizeInPlace(e){let t=this._m,i=e.m;for(let r=0;r<16;r++)t[r]=Math.min(t[r],i[r]);return this.markAsUpdated(),this}maximizeInPlaceFromFloats(...e){let t=this._m;for(let i=0;i<16;i++)t[i]=Math.min(t[i],e[i]);return this.markAsUpdated(),this}negate(){return this.negateToRef(new n)}negateInPlace(){let e=this._m;for(let t=0;t<16;t++)e[t]=-e[t];return this.markAsUpdated(),this}negateToRef(e){let t=this._m,i=e._m;for(let r=0;r<16;r++)i[r]=-t[r];return e.markAsUpdated(),e}equals(e){let t=e;if(!t)return!1;if((this._isIdentity||t._isIdentity)&&!this._isIdentityDirty&&!t._isIdentityDirty)return this._isIdentity&&t._isIdentity;let i=this.m,r=t.m;return i[0]===r[0]&&i[1]===r[1]&&i[2]===r[2]&&i[3]===r[3]&&i[4]===r[4]&&i[5]===r[5]&&i[6]===r[6]&&i[7]===r[7]&&i[8]===r[8]&&i[9]===r[9]&&i[10]===r[10]&&i[11]===r[11]&&i[12]===r[12]&&i[13]===r[13]&&i[14]===r[14]&&i[15]===r[15]}equalsWithEpsilon(e,t=0){let i=this._m,r=e.m;for(let s=0;s<16;s++)if(!Si(i[s],r[s],t))return!1;return!0}equalsToFloats(...e){let t=this._m;for(let i=0;i<16;i++)if(t[i]!=e[i])return!1;return!0}floor(){return this.floorToRef(new n)}floorToRef(e){let t=this._m,i=e._m;for(let r=0;r<16;r++)i[r]=Math.floor(t[r]);return e.markAsUpdated(),e}fract(){return this.fractToRef(new n)}fractToRef(e){let t=this._m,i=e._m;for(let r=0;r<16;r++)i[r]=t[r]-Math.floor(t[r]);return e.markAsUpdated(),e}clone(){let e=new n;return e.copyFrom(this),e}getClassName(){return"Matrix"}getHashCode(){let e=Qn(this._m[0]);for(let t=1;t<16;t++)e=e*397^Qn(this._m[t]);return e}decomposeToTransformNode(e){return e.rotationQuaternion=e.rotationQuaternion||new Xe,this.decompose(e.scaling,e.rotationQuaternion,e.position)}decompose(e,t,i,r,s=!0){if(this._isIdentity)return i&&i.setAll(0),e&&e.setAll(1),t&&t.copyFromFloats(0,0,0,1),!0;let a=this._m;if(i&&i.copyFromFloats(a[12],a[13],a[14]),e=e||He.Vector3[0],e.x=Math.sqrt(a[0]*a[0]+a[1]*a[1]+a[2]*a[2]),e.y=Math.sqrt(a[4]*a[4]+a[5]*a[5]+a[6]*a[6]),e.z=Math.sqrt(a[8]*a[8]+a[9]*a[9]+a[10]*a[10]),r){let o=(s?r.absoluteScaling.x:r.scaling.x)<0?-1:1,l=(s?r.absoluteScaling.y:r.scaling.y)<0?-1:1,c=(s?r.absoluteScaling.z:r.scaling.z)<0?-1:1;e.x*=o,e.y*=l,e.z*=c}else this.determinant()<=0&&(e.y*=-1);if(e._x===0||e._y===0||e._z===0)return t&&t.copyFromFloats(0,0,0,1),!1;if(t){let o=1/e._x,l=1/e._y,c=1/e._z;n.FromValuesToRef(a[0]*o,a[1]*o,a[2]*o,0,a[4]*l,a[5]*l,a[6]*l,0,a[8]*c,a[9]*c,a[10]*c,0,0,0,0,1,He.Matrix[0]),Xe.FromRotationMatrixToRef(He.Matrix[0],t)}return!0}getRow(e){if(e<0||e>3)return null;let t=e*4;return new bi(this._m[t+0],this._m[t+1],this._m[t+2],this._m[t+3])}getRowToRef(e,t){if(e>=0&&e<=3){let i=e*4;t.x=this._m[i+0],t.y=this._m[i+1],t.z=this._m[i+2],t.w=this._m[i+3]}return t}setRow(e,t){return this.setRowFromFloats(e,t.x,t.y,t.z,t.w)}transpose(){let e=new n;return n.TransposeToRef(this,e),e}transposeToRef(e){return n.TransposeToRef(this,e),e}setRowFromFloats(e,t,i,r,s){if(e<0||e>3)return this;let a=e*4;return this._m[a+0]=t,this._m[a+1]=i,this._m[a+2]=r,this._m[a+3]=s,this.markAsUpdated(),this}scale(e){let t=new n;return this.scaleToRef(e,t),t}scaleToRef(e,t){for(let i=0;i<16;i++)t._m[i]=this._m[i]*e;return t.markAsUpdated(),t}scaleAndAddToRef(e,t){for(let i=0;i<16;i++)t._m[i]+=this._m[i]*e;return t.markAsUpdated(),t}scaleInPlace(e){let t=this._m;for(let i=0;i<16;i++)t[i]*=e;return this.markAsUpdated(),this}toNormalMatrix(e){let t=He.Matrix[0];this.invertToRef(t),t.transposeToRef(e);let i=e._m;return n.FromValuesToRef(i[0],i[1],i[2],0,i[4],i[5],i[6],0,i[8],i[9],i[10],0,0,0,0,1,e),e}getRotationMatrix(){let e=new n;return this.getRotationMatrixToRef(e),e}getRotationMatrixToRef(e){let t=He.Vector3[0];if(!this.decompose(t))return n.IdentityToRef(e),e;let i=this._m,r=1/t._x,s=1/t._y,a=1/t._z;return n.FromValuesToRef(i[0]*r,i[1]*r,i[2]*r,0,i[4]*s,i[5]*s,i[6]*s,0,i[8]*a,i[9]*a,i[10]*a,0,0,0,0,1,e),e}toggleModelMatrixHandInPlace(){let e=this._m;return e[2]*=-1,e[6]*=-1,e[8]*=-1,e[9]*=-1,e[14]*=-1,this.markAsUpdated(),this}toggleProjectionMatrixHandInPlace(){let e=this._m;return e[8]*=-1,e[9]*=-1,e[10]*=-1,e[11]*=-1,this.markAsUpdated(),this}static FromArray(e,t=0){let i=new n;return n.FromArrayToRef(e,t,i),i}static FromArrayToRef(e,t,i){for(let r=0;r<16;r++)i._m[r]=e[r+t];return i.markAsUpdated(),i}static FromFloat32ArrayToRefScaled(e,t,i,r){return r._m[0]=e[0+t]*i,r._m[1]=e[1+t]*i,r._m[2]=e[2+t]*i,r._m[3]=e[3+t]*i,r._m[4]=e[4+t]*i,r._m[5]=e[5+t]*i,r._m[6]=e[6+t]*i,r._m[7]=e[7+t]*i,r._m[8]=e[8+t]*i,r._m[9]=e[9+t]*i,r._m[10]=e[10+t]*i,r._m[11]=e[11+t]*i,r._m[12]=e[12+t]*i,r._m[13]=e[13+t]*i,r._m[14]=e[14+t]*i,r._m[15]=e[15+t]*i,r.markAsUpdated(),r}static get IdentityReadOnly(){return n._IdentityReadOnly}static FromValuesToRef(e,t,i,r,s,a,o,l,c,f,h,d,u,m,p,_,g){let v=g._m;v[0]=e,v[1]=t,v[2]=i,v[3]=r,v[4]=s,v[5]=a,v[6]=o,v[7]=l,v[8]=c,v[9]=f,v[10]=h,v[11]=d,v[12]=u,v[13]=m,v[14]=p,v[15]=_,g.markAsUpdated()}static FromValues(e,t,i,r,s,a,o,l,c,f,h,d,u,m,p,_){let g=new n,v=g._m;return v[0]=e,v[1]=t,v[2]=i,v[3]=r,v[4]=s,v[5]=a,v[6]=o,v[7]=l,v[8]=c,v[9]=f,v[10]=h,v[11]=d,v[12]=u,v[13]=m,v[14]=p,v[15]=_,g.markAsUpdated(),g}static Compose(e,t,i){let r=new n;return n.ComposeToRef(e,t,i,r),r}static ComposeToRef(e,t,i,r){let s=r._m,a=t._x,o=t._y,l=t._z,c=t._w,f=a+a,h=o+o,d=l+l,u=a*f,m=a*h,p=a*d,_=o*h,g=o*d,v=l*d,x=c*f,A=c*h,S=c*d,E=e._x,R=e._y,I=e._z;return s[0]=(1-(_+v))*E,s[1]=(m+S)*E,s[2]=(p-A)*E,s[3]=0,s[4]=(m-S)*R,s[5]=(1-(u+v))*R,s[6]=(g+x)*R,s[7]=0,s[8]=(p+A)*I,s[9]=(g-x)*I,s[10]=(1-(u+_))*I,s[11]=0,s[12]=i._x,s[13]=i._y,s[14]=i._z,s[15]=1,r.markAsUpdated(),r}static Identity(){let e=n.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return e._updateIdentityStatus(!0),e}static IdentityToRef(e){return n.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,e),e._updateIdentityStatus(!0),e}static Zero(){let e=n.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return e._updateIdentityStatus(!1),e}static RotationX(e){let t=new n;return n.RotationXToRef(e,t),t}static Invert(e){let t=new n;return e.invertToRef(t),t}static RotationXToRef(e,t){let i=Math.sin(e),r=Math.cos(e);return n.FromValuesToRef(1,0,0,0,0,r,i,0,0,-i,r,0,0,0,0,1,t),t._updateIdentityStatus(r===1&&i===0),t}static RotationY(e){let t=new n;return n.RotationYToRef(e,t),t}static RotationYToRef(e,t){let i=Math.sin(e),r=Math.cos(e);return n.FromValuesToRef(r,0,-i,0,0,1,0,0,i,0,r,0,0,0,0,1,t),t._updateIdentityStatus(r===1&&i===0),t}static RotationZ(e){let t=new n;return n.RotationZToRef(e,t),t}static RotationZToRef(e,t){let i=Math.sin(e),r=Math.cos(e);return n.FromValuesToRef(r,i,0,0,-i,r,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(r===1&&i===0),t}static RotationAxis(e,t){let i=new n;return n.RotationAxisToRef(e,t,i),i}static RotationAxisToRef(e,t,i){let r=Math.sin(-t),s=Math.cos(-t),a=1-s;e=e.normalizeToRef(He.Vector3[0]);let o=i._m;return o[0]=e._x*e._x*a+s,o[1]=e._x*e._y*a-e._z*r,o[2]=e._x*e._z*a+e._y*r,o[3]=0,o[4]=e._y*e._x*a+e._z*r,o[5]=e._y*e._y*a+s,o[6]=e._y*e._z*a-e._x*r,o[7]=0,o[8]=e._z*e._x*a-e._y*r,o[9]=e._z*e._y*a+e._x*r,o[10]=e._z*e._z*a+s,o[11]=0,o[12]=0,o[13]=0,o[14]=0,o[15]=1,i.markAsUpdated(),i}static RotationAlignToRef(e,t,i,r=!1){let s=b.Dot(t,e),a=i._m;if(s<-1+Nt)a[0]=-1,a[1]=0,a[2]=0,a[3]=0,a[4]=0,a[5]=r?1:-1,a[6]=0,a[7]=0,a[8]=0,a[9]=0,a[10]=r?-1:1,a[11]=0;else{let o=b.Cross(t,e),l=1/(1+s);a[0]=o._x*o._x*l+s,a[1]=o._y*o._x*l-o._z,a[2]=o._z*o._x*l+o._y,a[3]=0,a[4]=o._x*o._y*l+o._z,a[5]=o._y*o._y*l+s,a[6]=o._z*o._y*l-o._x,a[7]=0,a[8]=o._x*o._z*l-o._y,a[9]=o._y*o._z*l+o._x,a[10]=o._z*o._z*l+s,a[11]=0}return a[12]=0,a[13]=0,a[14]=0,a[15]=1,i.markAsUpdated(),i}static RotationYawPitchRoll(e,t,i){let r=new n;return n.RotationYawPitchRollToRef(e,t,i,r),r}static RotationYawPitchRollToRef(e,t,i,r){return Xe.RotationYawPitchRollToRef(e,t,i,He.Quaternion[0]),He.Quaternion[0].toRotationMatrix(r),r}static Scaling(e,t,i){let r=new n;return n.ScalingToRef(e,t,i,r),r}static ScalingToRef(e,t,i,r){return n.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1,r),r._updateIdentityStatus(e===1&&t===1&&i===1),r}static Translation(e,t,i){let r=new n;return n.TranslationToRef(e,t,i,r),r}static TranslationToRef(e,t,i,r){return n.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1,r),r._updateIdentityStatus(e===0&&t===0&&i===0),r}static Lerp(e,t,i){let r=new n;return n.LerpToRef(e,t,i,r),r}static LerpToRef(e,t,i,r){let s=r._m,a=e.m,o=t.m;for(let l=0;l<16;l++)s[l]=a[l]*(1-i)+o[l]*i;return r.markAsUpdated(),r}static DecomposeLerp(e,t,i){let r=new n;return n.DecomposeLerpToRef(e,t,i,r),r}static DecomposeLerpToRef(e,t,i,r){let s=He.Vector3[0],a=He.Quaternion[0],o=He.Vector3[1];e.decompose(s,a,o);let l=He.Vector3[2],c=He.Quaternion[1],f=He.Vector3[3];t.decompose(l,c,f);let h=He.Vector3[4];b.LerpToRef(s,l,i,h);let d=He.Quaternion[2];Xe.SlerpToRef(a,c,i,d);let u=He.Vector3[5];return b.LerpToRef(o,f,i,u),n.ComposeToRef(h,d,u,r),r}static LookAtLH(e,t,i){let r=new n;return n.LookAtLHToRef(e,t,i,r),r}static LookAtLHToRef(e,t,i,r){let s=He.Vector3[0],a=He.Vector3[1],o=He.Vector3[2];t.subtractToRef(e,o),o.normalize(),b.CrossToRef(i,o,s);let l=s.lengthSquared();l===0?s.x=1:s.normalizeFromLength(Math.sqrt(l)),b.CrossToRef(o,s,a),a.normalize();let c=-b.Dot(s,e),f=-b.Dot(a,e),h=-b.Dot(o,e);return n.FromValuesToRef(s._x,a._x,o._x,0,s._y,a._y,o._y,0,s._z,a._z,o._z,0,c,f,h,1,r),r}static LookAtRH(e,t,i){let r=new n;return n.LookAtRHToRef(e,t,i,r),r}static LookAtRHToRef(e,t,i,r){let s=He.Vector3[0],a=He.Vector3[1],o=He.Vector3[2];e.subtractToRef(t,o),o.normalize(),b.CrossToRef(i,o,s);let l=s.lengthSquared();l===0?s.x=1:s.normalizeFromLength(Math.sqrt(l)),b.CrossToRef(o,s,a),a.normalize();let c=-b.Dot(s,e),f=-b.Dot(a,e),h=-b.Dot(o,e);return n.FromValuesToRef(s._x,a._x,o._x,0,s._y,a._y,o._y,0,s._z,a._z,o._z,0,c,f,h,1,r),r}static LookDirectionLH(e,t){let i=new n;return n.LookDirectionLHToRef(e,t,i),i}static LookDirectionLHToRef(e,t,i){let r=He.Vector3[0];r.copyFrom(e),r.scaleInPlace(-1);let s=He.Vector3[1];return b.CrossToRef(t,r,s),n.FromValuesToRef(s._x,s._y,s._z,0,t._x,t._y,t._z,0,r._x,r._y,r._z,0,0,0,0,1,i),i}static LookDirectionRH(e,t){let i=new n;return n.LookDirectionRHToRef(e,t,i),i}static LookDirectionRHToRef(e,t,i){let r=He.Vector3[2];return b.CrossToRef(t,e,r),n.FromValuesToRef(r._x,r._y,r._z,0,t._x,t._y,t._z,0,e._x,e._y,e._z,0,0,0,0,1,i),i}static OrthoLH(e,t,i,r,s){let a=new n;return n.OrthoLHToRef(e,t,i,r,a,s),a}static OrthoLHToRef(e,t,i,r,s,a){let o=i,l=r,c=2/e,f=2/t,h=2/(l-o),d=-(l+o)/(l-o);return n.FromValuesToRef(c,0,0,0,0,f,0,0,0,0,h,0,0,0,d,1,s),a&&s.multiplyToRef(Nh,s),s._updateIdentityStatus(c===1&&f===1&&h===1&&d===0),s}static OrthoOffCenterLH(e,t,i,r,s,a,o){let l=new n;return n.OrthoOffCenterLHToRef(e,t,i,r,s,a,l,o),l}static OrthoOffCenterLHToRef(e,t,i,r,s,a,o,l){let c=s,f=a,h=2/(t-e),d=2/(r-i),u=2/(f-c),m=-(f+c)/(f-c),p=(e+t)/(e-t),_=(r+i)/(i-r);return n.FromValuesToRef(h,0,0,0,0,d,0,0,0,0,u,0,p,_,m,1,o),l&&o.multiplyToRef(Nh,o),o.markAsUpdated(),o}static ObliqueOffCenterLHToRef(e,t,i,r,s,a,o,l,c,f,h){let d=-o*Math.cos(l),u=-o*Math.sin(l);return n.TranslationToRef(0,0,-c,He.Matrix[1]),n.FromValuesToRef(1,0,0,0,0,1,0,0,d,u,1,0,0,0,0,1,He.Matrix[0]),He.Matrix[1].multiplyToRef(He.Matrix[0],He.Matrix[0]),n.TranslationToRef(0,0,c,He.Matrix[1]),He.Matrix[0].multiplyToRef(He.Matrix[1],He.Matrix[0]),n.OrthoOffCenterLHToRef(e,t,i,r,s,a,f,h),He.Matrix[0].multiplyToRef(f,f),f}static OrthoOffCenterRH(e,t,i,r,s,a,o){let l=new n;return n.OrthoOffCenterRHToRef(e,t,i,r,s,a,l,o),l}static OrthoOffCenterRHToRef(e,t,i,r,s,a,o,l){return n.OrthoOffCenterLHToRef(e,t,i,r,s,a,o,l),o._m[10]*=-1,o}static ObliqueOffCenterRHToRef(e,t,i,r,s,a,o,l,c,f,h){let d=o*Math.cos(l),u=o*Math.sin(l);return n.TranslationToRef(0,0,c,He.Matrix[1]),n.FromValuesToRef(1,0,0,0,0,1,0,0,d,u,1,0,0,0,0,1,He.Matrix[0]),He.Matrix[1].multiplyToRef(He.Matrix[0],He.Matrix[0]),n.TranslationToRef(0,0,-c,He.Matrix[1]),He.Matrix[0].multiplyToRef(He.Matrix[1],He.Matrix[0]),n.OrthoOffCenterRHToRef(e,t,i,r,s,a,f,h),He.Matrix[0].multiplyToRef(f,f),f}static PerspectiveLH(e,t,i,r,s,a=0){let o=new n,l=i,c=r,f=2*l/e,h=2*l/t,d=(c+l)/(c-l),u=-2*c*l/(c-l),m=Math.tan(a);return n.FromValuesToRef(f,0,0,0,0,h,0,m,0,0,d,1,0,0,u,0,o),s&&o.multiplyToRef(Nh,o),o._updateIdentityStatus(!1),o}static PerspectiveFovLH(e,t,i,r,s,a=0,o=!1){let l=new n;return n.PerspectiveFovLHToRef(e,t,i,r,l,!0,s,a,o),l}static PerspectiveFovLHToRef(e,t,i,r,s,a=!0,o,l=0,c=!1){let f=i,h=r,d=1/Math.tan(e*.5),u=a?d/t:d,m=a?d:d*t,p=c&&f===0?-1:h!==0?(h+f)/(h-f):1,_=c&&f===0?2*h:h!==0?-2*h*f/(h-f):-2*f,g=Math.tan(l);return n.FromValuesToRef(u,0,0,0,0,m,0,g,0,0,p,1,0,0,_,0,s),o&&s.multiplyToRef(Nh,s),s._updateIdentityStatus(!1),s}static PerspectiveFovReverseLHToRef(e,t,i,r,s,a=!0,o,l=0){let c=1/Math.tan(e*.5),f=a?c/t:c,h=a?c:c*t,d=Math.tan(l);return n.FromValuesToRef(f,0,0,0,0,h,0,d,0,0,-i,1,0,0,1,0,s),o&&s.multiplyToRef(Nh,s),s._updateIdentityStatus(!1),s}static PerspectiveFovRH(e,t,i,r,s,a=0,o=!1){let l=new n;return n.PerspectiveFovRHToRef(e,t,i,r,l,!0,s,a,o),l}static PerspectiveFovRHToRef(e,t,i,r,s,a=!0,o,l=0,c=!1){let f=i,h=r,d=1/Math.tan(e*.5),u=a?d/t:d,m=a?d:d*t,p=c&&f===0?1:h!==0?-(h+f)/(h-f):-1,_=c&&f===0?2*h:h!==0?-2*h*f/(h-f):-2*f,g=Math.tan(l);return n.FromValuesToRef(u,0,0,0,0,m,0,g,0,0,p,-1,0,0,_,0,s),o&&s.multiplyToRef(Nh,s),s._updateIdentityStatus(!1),s}static PerspectiveFovReverseRHToRef(e,t,i,r,s,a=!0,o,l=0){let c=1/Math.tan(e*.5),f=a?c/t:c,h=a?c:c*t,d=Math.tan(l);return n.FromValuesToRef(f,0,0,0,0,h,0,d,0,0,-i,-1,0,0,-1,0,s),o&&s.multiplyToRef(Nh,s),s._updateIdentityStatus(!1),s}static GetFinalMatrix(e,t,i,r,s,a){let o=e.width,l=e.height,c=e.x,f=e.y,h=n.FromValues(o/2,0,0,0,0,-l/2,0,0,0,0,a-s,0,c+o/2,l/2+f,s,1),d=new n;return t.multiplyToRef(i,d),d.multiplyToRef(r,d),d.multiplyToRef(h,d)}static GetAsMatrix2x2(e){let t=e.m,i=[t[0],t[1],t[4],t[5]];return qn.MatrixUse64Bits?i:new Float32Array(i)}static GetAsMatrix3x3(e){let t=e.m,i=[t[0],t[1],t[2],t[4],t[5],t[6],t[8],t[9],t[10]];return qn.MatrixUse64Bits?i:new Float32Array(i)}static Transpose(e){let t=new n;return n.TransposeToRef(e,t),t}static TransposeToRef(e,t){let i=e.m,r=i[0],s=i[4],a=i[8],o=i[12],l=i[1],c=i[5],f=i[9],h=i[13],d=i[2],u=i[6],m=i[10],p=i[14],_=i[3],g=i[7],v=i[11],x=i[15],A=t._m;return A[0]=r,A[1]=s,A[2]=a,A[3]=o,A[4]=l,A[5]=c,A[6]=f,A[7]=h,A[8]=d,A[9]=u,A[10]=m,A[11]=p,A[12]=_,A[13]=g,A[14]=v,A[15]=x,t.markAsUpdated(),t._updateIdentityStatus(e._isIdentity,e._isIdentityDirty),t}static Reflection(e){let t=new n;return n.ReflectionToRef(e,t),t}static ReflectionToRef(e,t){e.normalize();let i=e.normal.x,r=e.normal.y,s=e.normal.z,a=-2*i,o=-2*r,l=-2*s;return n.FromValuesToRef(a*i+1,o*i,l*i,0,a*r,o*r+1,l*r,0,a*s,o*s,l*s+1,0,a*e.d,o*e.d,l*e.d,1,t),t}static FromXYZAxesToRef(e,t,i,r){return n.FromValuesToRef(e._x,e._y,e._z,0,t._x,t._y,t._z,0,i._x,i._y,i._z,0,0,0,0,1,r),r}static FromQuaternionToRef(e,t){let i=e._x*e._x,r=e._y*e._y,s=e._z*e._z,a=e._x*e._y,o=e._z*e._w,l=e._z*e._x,c=e._y*e._w,f=e._y*e._z,h=e._x*e._w;return t._m[0]=1-2*(r+s),t._m[1]=2*(a+o),t._m[2]=2*(l-c),t._m[3]=0,t._m[4]=2*(a-o),t._m[5]=1-2*(s+i),t._m[6]=2*(f+h),t._m[7]=0,t._m[8]=2*(l+c),t._m[9]=2*(f-h),t._m[10]=1-2*(r+i),t._m[11]=0,t._m[12]=0,t._m[13]=0,t._m[14]=0,t._m[15]=1,t.markAsUpdated(),t}};K._IdentityReadOnly=K.Identity();Object.defineProperties(K.prototype,{dimension:{value:[4,4]},rank:{value:2}});He=class{};He.Vector3=Bl(11,b.Zero);He.Matrix=Bl(2,K.Identity);He.Quaternion=Bl(3,Xe.Zero);$=class{};$.Vector2=Bl(3,we.Zero);$.Vector3=Bl(13,b.Zero);$.Vector4=Bl(3,bi.Zero);$.Quaternion=Bl(3,Xe.Zero);$.Matrix=Bl(8,K.Identity);Ft("BABYLON.Vector2",we);Ft("BABYLON.Vector3",b);Ft("BABYLON.Vector4",bi);Ft("BABYLON.Matrix",K);Nh=K.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1)});var v2,Es,E2,zu=C(()=>{Ge();(function(n){n[n.LOCAL=0]="LOCAL",n[n.WORLD=1]="WORLD",n[n.BONE=2]="BONE"})(v2||(v2={}));Es=class{};Es.X=new b(1,0,0);Es.Y=new b(0,1,0);Es.Z=new b(0,0,1);(function(n){n[n.X=0]="X",n[n.Y=1]="Y",n[n.Z=2]="Z"})(E2||(E2={}))});function Xu(n){return Math.pow(n,Wu)}function Yu(n){return n<=.04045?.0773993808*n:Math.pow(.947867299*(n+.055),2.4)}function Ku(n){return Math.pow(n,h2)}function ju(n){return n<=.0031308?12.92*n:1.055*Math.pow(n,.41666)-.055}var ve,lt,En,zt=C(()=>{Zo();Hi();Dn();Ln();ve=class n{constructor(e=0,t=0,i=0){this.r=e,this.g=t,this.b=i}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+"}"}getClassName(){return"Color3"}getHashCode(){let e=this.r*255|0;return e=e*397^(this.g*255|0),e=e*397^(this.b*255|0),e}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,this}fromArray(e,t=0){return n.FromArrayToRef(e,t,this),this}toColor4(e=1){return new lt(this.r,this.g,this.b,e)}asArray(){return[this.r,this.g,this.b]}toLuminance(){return this.r*.3+this.g*.59+this.b*.11}multiply(e){return new n(this.r*e.r,this.g*e.g,this.b*e.b)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyByFloats(e,t,i){return new n(this.r*e,this.g*t,this.b*i)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e.r,e.g,e.b)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e.r,e.g,e.b)}minimizeInPlaceFromFloats(e,t,i){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this}maximizeInPlaceFromFloats(e,t,i){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,this.b),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b}equalsFloats(e,t,i){return this.equalsToFloats(e,t,i)}equalsToFloats(e,t,i){return this.r===e&&this.g===t&&this.b===i}equalsWithEpsilon(e,t=Nt){return Si(this.r,e.r,t)&&Si(this.g,e.g,t)&&Si(this.b,e.b,t)}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}scale(e){return new n(this.r*e,this.g*e,this.b*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t}clampToRef(e=0,t=1,i){return i.r=wt(this.r,e,t),i.g=wt(this.g,e,t),i.b=wt(this.b,e,t),i}add(e){return new n(this.r+e.r,this.g+e.g,this.b+e.b)}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addInPlaceFromFloats(e,t,i){return this.r+=e,this.g+=t,this.b+=i,this}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t}subtract(e){return new n(this.r-e.r,this.g-e.g,this.b-e.b)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this}subtractFromFloats(e,t,i){return new n(this.r-e,this.g-t,this.b-i)}subtractFromFloatsToRef(e,t,i,r){return r.r=this.r-e,r.g=this.g-t,r.b=this.b-i,r}clone(){return new n(this.r,this.g,this.b)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copyFromFloats(e,t,i){return this.r=e,this.g=t,this.b=i,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this.r=this.g=this.b=e,this}toHexString(){let e=Math.round(this.r*255),t=Math.round(this.g*255),i=Math.round(this.b*255);return"#"+eo(e)+eo(t)+eo(i)}fromHexString(e){return e.substring(0,1)!=="#"||e.length!==7?this:(this.r=parseInt(e.substring(1,3),16)/255,this.g=parseInt(e.substring(3,5),16)/255,this.b=parseInt(e.substring(5,7),16)/255,this)}toHSV(){return this.toHSVToRef(new n)}toHSVToRef(e){let t=this.r,i=this.g,r=this.b,s=Math.max(t,i,r),a=Math.min(t,i,r),o=0,l=0,c=s,f=s-a;return s!==0&&(l=f/s),s!=a&&(s==t?(o=(i-r)/f,i=0&&a<=1?(l=s,c=o):a>=1&&a<=2?(l=o,c=s):a>=2&&a<=3?(c=s,f=o):a>=3&&a<=4?(c=o,f=s):a>=4&&a<=5?(l=o,f=s):a>=5&&a<=6&&(l=s,f=o);let h=i-s;return r.r=l+h,r.g=c+h,r.b=f+h,r}static FromHSV(e,t,i){let r=new n(0,0,0);return n.HSVtoRGBToRef(e,t,i,r),r}static FromHexString(e){return new n(0,0,0).fromHexString(e)}static FromArray(e,t=0){return new n(e[t],e[t+1],e[t+2])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2]}static FromInts(e,t,i){return new n(e/255,t/255,i/255)}static Lerp(e,t,i){let r=new n(0,0,0);return n.LerpToRef(e,t,i,r),r}static LerpToRef(e,t,i,r){r.r=e.r+(t.r-e.r)*i,r.g=e.g+(t.g-e.g)*i,r.b=e.b+(t.b-e.b)*i}static Hermite(e,t,i,r,s){let a=s*s,o=s*a,l=2*o-3*a+1,c=-2*o+3*a,f=o-2*a+s,h=o-a,d=e.r*l+i.r*c+t.r*f+r.r*h,u=e.g*l+i.g*c+t.g*f+r.g*h,m=e.b*l+i.b*c+t.b*f+r.b*h;return new n(d,u,m)}static Hermite1stDerivative(e,t,i,r,s){let a=n.Black();return this.Hermite1stDerivativeToRef(e,t,i,r,s,a),a}static Hermite1stDerivativeToRef(e,t,i,r,s,a){let o=s*s;a.r=(o-s)*6*e.r+(3*o-4*s+1)*t.r+(-o+s)*6*i.r+(3*o-2*s)*r.r,a.g=(o-s)*6*e.g+(3*o-4*s+1)*t.g+(-o+s)*6*i.g+(3*o-2*s)*r.g,a.b=(o-s)*6*e.b+(3*o-4*s+1)*t.b+(-o+s)*6*i.b+(3*o-2*s)*r.b}static Red(){return new n(1,0,0)}static Green(){return new n(0,1,0)}static Blue(){return new n(0,0,1)}static Black(){return new n(0,0,0)}static get BlackReadOnly(){return n._BlackReadOnly}static White(){return new n(1,1,1)}static Purple(){return new n(.5,0,.5)}static Magenta(){return new n(1,0,1)}static Yellow(){return new n(1,1,0)}static Gray(){return new n(.5,.5,.5)}static Teal(){return new n(0,1,1)}static Random(){return new n(Math.random(),Math.random(),Math.random())}};ve._V8PerformanceHack=new ve(.5,.5,.5);ve._BlackReadOnly=ve.Black();Object.defineProperties(ve.prototype,{dimension:{value:[3]},rank:{value:1}});lt=class n{constructor(e=0,t=0,i=0,r=1){this.r=e,this.g=t,this.b=i,this.a=r}asArray(){return[this.r,this.g,this.b,this.a]}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e[t+3]=this.a,this}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this.a=e[t+3],this}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b&&this.a===e.a}add(e){return new n(this.r+e.r,this.g+e.g,this.b+e.b,this.a+e.a)}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t.a=this.a+e.a,t}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this}addInPlaceFromFloats(e,t,i,r){return this.r+=e,this.g+=t,this.b+=i,this.a+=r,this}subtract(e){return new n(this.r-e.r,this.g-e.g,this.b-e.b,this.a-e.a)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t.a=this.a-e.a,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this.a-=e.a,this}subtractFromFloats(e,t,i,r){return new n(this.r-e,this.g-t,this.b-i,this.a-r)}subtractFromFloatsToRef(e,t,i,r,s){return s.r=this.r-e,s.g=this.g-t,s.b=this.b-i,s.a=this.a-r,s}scale(e){return new n(this.r*e,this.g*e,this.b*e,this.a*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this.a*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t.a=this.a*e,t}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t.a+=this.a*e,t}clampToRef(e=0,t=1,i){return i.r=wt(this.r,e,t),i.g=wt(this.g,e,t),i.b=wt(this.b,e,t),i.a=wt(this.a,e,t),i}multiply(e){return new n(this.r*e.r,this.g*e.g,this.b*e.b,this.a*e.a)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t.a=this.a*e.a,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this.a*=e.a,this}multiplyByFloats(e,t,i,r){return new n(this.r*e,this.g*t,this.b*i,this.a*r)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.r=Math.min(this.r,e.r),this.g=Math.min(this.g,e.g),this.b=Math.min(this.b,e.b),this.a=Math.min(this.a,e.a),this}maximizeInPlace(e){return this.r=Math.max(this.r,e.r),this.g=Math.max(this.g,e.g),this.b=Math.max(this.b,e.b),this.a=Math.max(this.a,e.a),this}minimizeInPlaceFromFloats(e,t,i,r){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(i,this.b),this.a=Math.min(r,this.a),this}maximizeInPlaceFromFloats(e,t,i,r){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(i,this.b),this.a=Math.max(r,this.a),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}equalsWithEpsilon(e,t=Nt){return Si(this.r,e.r,t)&&Si(this.g,e.g,t)&&Si(this.b,e.b,t)&&Si(this.a,e.a,t)}equalsToFloats(e,t,i,r){return this.r===e&&this.g===t&&this.b===i&&this.a===r}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+" A:"+this.a+"}"}getClassName(){return"Color4"}getHashCode(){let e=this.r*255|0;return e=e*397^(this.g*255|0),e=e*397^(this.b*255|0),e=e*397^(this.a*255|0),e}clone(){return new n().copyFrom(this)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this}copyFromFloats(e,t,i,r){return this.r=e,this.g=t,this.b=i,this.a=r,this}set(e,t,i,r){return this.copyFromFloats(e,t,i,r)}setAll(e){return this.r=this.g=this.b=this.a=e,this}toHexString(e=!1){let t=Math.round(this.r*255),i=Math.round(this.g*255),r=Math.round(this.b*255);if(e)return"#"+eo(t)+eo(i)+eo(r);let s=Math.round(this.a*255);return"#"+eo(t)+eo(i)+eo(r)+eo(s)}fromHexString(e){return e.substring(0,1)!=="#"||e.length!==9&&e.length!==7?this:(this.r=parseInt(e.substring(1,3),16)/255,this.g=parseInt(e.substring(3,5),16)/255,this.b=parseInt(e.substring(5,7),16)/255,e.length===9&&(this.a=parseInt(e.substring(7,9),16)/255),this)}toLinearSpace(e=!1){let t=new n;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=Yu(this.r),e.g=Yu(this.g),e.b=Yu(this.b)):(e.r=Xu(this.r),e.g=Xu(this.g),e.b=Xu(this.b)),e.a=this.a,this}toGammaSpace(e=!1){let t=new n;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=ju(this.r),e.g=ju(this.g),e.b=ju(this.b)):(e.r=Ku(this.r),e.g=Ku(this.g),e.b=Ku(this.b)),e.a=this.a,this}static FromHexString(e){return e.substring(0,1)!=="#"||e.length!==9&&e.length!==7?new n(0,0,0,0):new n(0,0,0,1).fromHexString(e)}static Lerp(e,t,i){return n.LerpToRef(e,t,i,new n)}static LerpToRef(e,t,i,r){return r.r=e.r+(t.r-e.r)*i,r.g=e.g+(t.g-e.g)*i,r.b=e.b+(t.b-e.b)*i,r.a=e.a+(t.a-e.a)*i,r}static Hermite(e,t,i,r,s){let a=s*s,o=s*a,l=2*o-3*a+1,c=-2*o+3*a,f=o-2*a+s,h=o-a,d=e.r*l+i.r*c+t.r*f+r.r*h,u=e.g*l+i.g*c+t.g*f+r.g*h,m=e.b*l+i.b*c+t.b*f+r.b*h,p=e.a*l+i.a*c+t.a*f+r.a*h;return new n(d,u,m,p)}static Hermite1stDerivative(e,t,i,r,s){let a=new n;return this.Hermite1stDerivativeToRef(e,t,i,r,s,a),a}static Hermite1stDerivativeToRef(e,t,i,r,s,a){let o=s*s;a.r=(o-s)*6*e.r+(3*o-4*s+1)*t.r+(-o+s)*6*i.r+(3*o-2*s)*r.r,a.g=(o-s)*6*e.g+(3*o-4*s+1)*t.g+(-o+s)*6*i.g+(3*o-2*s)*r.g,a.b=(o-s)*6*e.b+(3*o-4*s+1)*t.b+(-o+s)*6*i.b+(3*o-2*s)*r.b,a.a=(o-s)*6*e.a+(3*o-4*s+1)*t.a+(-o+s)*6*i.a+(3*o-2*s)*r.a}static FromColor3(e,t=1){return new n(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new n(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2],i.a=e[t+3]}static FromInts(e,t,i,r){return new n(e/255,t/255,i/255,r/255)}static CheckColors4(e,t){if(e.length===t*3){let i=[];for(let r=0;rnew lt(0,0,0,0));Ft("BABYLON.Color3",ve);Ft("BABYLON.Color4",lt)});var to,qu=C(()=>{Ge();to=class n{constructor(e,t,i,r){this.normal=new b(e,t,i),this.d=r}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new n(this.normal.x,this.normal.y,this.normal.z,this.d)}getClassName(){return"Plane"}getHashCode(){let e=this.normal.getHashCode();return e=e*397^(this.d|0),e}normalize(){let e=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),t=0;return e!==0&&(t=1/e),this.normal.x*=t,this.normal.y*=t,this.normal.z*=t,this.d*=t,this}transform(e){let t=n._TmpMatrix;e.invertToRef(t);let i=t.m,r=this.normal.x,s=this.normal.y,a=this.normal.z,o=this.d,l=r*i[0]+s*i[1]+a*i[2]+o*i[3],c=r*i[4]+s*i[5]+a*i[6]+o*i[7],f=r*i[8]+s*i[9]+a*i[10]+o*i[11],h=r*i[12]+s*i[13]+a*i[14]+o*i[15];return new n(l,c,f,h)}dotCoordinate(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d}copyFromPoints(e,t,i){let r=t.x-e.x,s=t.y-e.y,a=t.z-e.z,o=i.x-e.x,l=i.y-e.y,c=i.z-e.z,f=s*c-a*l,h=a*o-r*c,d=r*l-s*o,u=Math.sqrt(f*f+h*h+d*d),m;return u!==0?m=1/u:m=0,this.normal.x=f*m,this.normal.y=h*m,this.normal.z=d*m,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){return b.Dot(this.normal,e)<=t}signedDistanceTo(e){return b.Dot(e,this.normal)+this.d}static FromArray(e){return new n(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){let r=new n(0,0,0,0);return r.copyFromPoints(e,t,i),r}static FromPositionAndNormal(e,t){let i=new n(0,0,0,0);return this.FromPositionAndNormalToRef(e,t,i)}static FromPositionAndNormalToRef(e,t,i){return i.normal.copyFrom(t),i.normal.normalize(),i.d=-e.dot(i.normal),i}static SignedDistanceToPlaneFromPositionAndNormal(e,t,i){let r=-(t.x*e.x+t.y*e.y+t.z*e.z);return b.Dot(i,t)+r}};to._TmpMatrix=K.Identity()});var of,FT=C(()=>{qu();of=class n{static GetPlanes(e){let t=[];for(let i=0;i<6;i++)t.push(new to(0,0,0,0));return n.GetPlanesToRef(e,t),t}static GetNearPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]+i[2],t.normal.y=i[7]+i[6],t.normal.z=i[11]+i[10],t.d=i[15]+i[14],t.normalize()}static GetFarPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]-i[2],t.normal.y=i[7]-i[6],t.normal.z=i[11]-i[10],t.d=i[15]-i[14],t.normalize()}static GetLeftPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]+i[0],t.normal.y=i[7]+i[4],t.normal.z=i[11]+i[8],t.d=i[15]+i[12],t.normalize()}static GetRightPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]-i[0],t.normal.y=i[7]-i[4],t.normal.z=i[11]-i[8],t.d=i[15]-i[12],t.normalize()}static GetTopPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]-i[1],t.normal.y=i[7]-i[5],t.normal.z=i[11]-i[9],t.d=i[15]-i[13],t.normalize()}static GetBottomPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]+i[1],t.normal.y=i[7]+i[5],t.normal.z=i[11]+i[9],t.d=i[15]+i[13],t.normalize()}static GetPlanesToRef(e,t){n.GetNearPlaneToRef(e,t[0]),n.GetFarPlaneToRef(e,t[1]),n.GetLeftPlaneToRef(e,t[2]),n.GetRightPlaneToRef(e,t[3]),n.GetTopPlaneToRef(e,t[4]),n.GetBottomPlaneToRef(e,t[5])}static IsPointInFrustum(e,t){for(let i=0;i<6;i++)if(t[i].dotCoordinate(e)<0)return!1;return!0}}});var S2,Zu,wM,Qu,wh,Fh=C(()=>{Ln();Ge();Dn();(function(n){n[n.CW=0]="CW",n[n.CCW=1]="CCW"})(S2||(S2={}));Zu=class n{constructor(e){this._radians=e,this._radians<0&&(this._radians+=2*Math.PI)}degrees(){return this._radians*180/Math.PI}radians(){return this._radians}static BetweenTwoPoints(e,t){let i=t.subtract(e),r=Math.atan2(i.y,i.x);return new n(r)}static BetweenTwoVectors(e,t){let i=e.lengthSquared()*t.lengthSquared();if(i===0)return new n(Math.PI/2);i=Math.sqrt(i);let r=e.dot(t)/i;r=wt(r,-1,1);let s=Math.acos(r);return new n(s)}static FromRadians(e){return new n(e)}static FromDegrees(e){return new n(e*Math.PI/180)}},wM=class{constructor(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;let r=Math.pow(t.x,2)+Math.pow(t.y,2),s=(Math.pow(e.x,2)+Math.pow(e.y,2)-r)/2,a=(r-Math.pow(i.x,2)-Math.pow(i.y,2))/2,o=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new we((s*(t.y-i.y)-a*(e.y-t.y))/o,((e.x-t.x)*a-(t.x-i.x)*s)/o),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=Zu.BetweenTwoPoints(this.centerPoint,this.startPoint);let l=this.startAngle.degrees(),c=Zu.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),f=Zu.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();c-l>180&&(c-=360),c-l<-180&&(c+=360),f-c>180&&(f-=360),f-c<-180&&(f+=360),this.orientation=c-l<0?0:1,this.angle=Zu.FromDegrees(this.orientation===0?l-f:f-l)}},Qu=class n{constructor(e,t){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new we(e,t))}addLineTo(e,t){if(this.closed)return this;let i=new we(e,t),r=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(r).length(),this}addArcTo(e,t,i,r,s=36){if(this.closed)return this;let a=this._points[this._points.length-1],o=new we(e,t),l=new we(i,r),c=new wM(a,o,l),f=c.angle.radians()/s;c.orientation===0&&(f*=-1);let h=c.startAngle.radians()+f;for(let d=0;d(1-l)*(1-l)*c+2*l*(1-l)*f+l*l*h,o=this._points[this._points.length-1];for(let l=0;l<=s;l++){let c=l/s,f=a(c,o.x,e,i),h=a(c,o.y,t,r);this.addLineTo(f,h)}return this}addBezierCurveTo(e,t,i,r,s,a,o=36){if(this.closed)return this;let l=(f,h,d,u,m)=>(1-f)*(1-f)*(1-f)*h+3*f*(1-f)*(1-f)*d+3*f*f*(1-f)*u+f*f*f*m,c=this._points[this._points.length-1];for(let f=0;f<=o;f++){let h=f/o,d=l(h,c.x,e,i,s),u=l(h,c.y,t,r,a);this.addLineTo(d,u)}return this}isPointInside(e){let t=!1,i=this._points.length;for(let r=i-1,s=0;sNumber.EPSILON){if(c<0&&(a=this._points[s],l=-l,o=this._points[r],c=-c),e.yo.y)continue;if(e.y===a.y&&e.x===a.x)return!0;{let f=c*(e.x-a.x)-l*(e.y-a.y);if(f===0)return!0;if(f<0)continue;t=!t}}else{if(e.y!==a.y)continue;if(o.x<=e.x&&e.x<=a.x||a.x<=e.x&&e.x<=o.x)return!0}}return t}close(){return this.closed=!0,this}length(){let e=this._length;if(this.closed){let t=this._points[this._points.length-1],i=this._points[0];e+=i.subtract(t).length()}return e}area(){let e=this._points.length,t=0;for(let i=e-1,r=0;r1)return we.Zero();let t=e*this.length(),i=0;for(let r=0;r=i&&t<=c){let f=l.normalize(),h=t-i;return new we(a.x+f.x*h,a.y+f.y*h)}i=c}return we.Zero()}static StartingAt(e,t){return new n(e,t)}},wh=class n{constructor(e,t=null,i,r=!1){this.path=e,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array,this._pointAtData={id:0,point:b.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:K.Identity()};for(let s=0;st){let c=e;e=t,t=c}let i=this.getCurve(),r=this.getPointAt(e),s=this.getPreviousPointIndexAt(e),a=this.getPointAt(t),o=this.getPreviousPointIndexAt(t)+1,l=[];return e!==0&&(s++,l.push(r)),l.push(...i.slice(s,o)),(t!==1||e===1)&&l.push(a),new n(l,this.getNormalAt(e),this._raw,this._alignTangentsWithPath)}update(e,t=null,i=!1){for(let r=0;rt+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i}_normalVector(e,t){let i,r=e.length();if(r===0&&(r=1),t==null){let s;Si(Math.abs(e.y)/r,1,Nt)?Si(Math.abs(e.x)/r,1,Nt)?Si(Math.abs(e.z)/r,1,Nt)?s=b.Zero():s=new b(0,0,1):s=new b(1,0,0):s=new b(0,-1,0),i=b.Cross(e,s)}else i=b.Cross(e,t),b.CrossToRef(i,e,i);return i.normalize(),i}_updatePointAtData(e,t=!1){if(this._pointAtData.id===e)return this._pointAtData.interpolateReady||this._updateInterpolationMatrix(),this._pointAtData;this._pointAtData.id=e;let i=this.getPoints();if(e<=0)return this._setPointAtData(0,0,i[0],0,t);if(e>=1)return this._setPointAtData(1,1,i[i.length-1],i.length-1,t);let r=i[0],s,a=0,o=e*this.length();for(let l=1;lo){let h=(a-o)/c,d=r.subtract(s),u=s.add(d.scaleInPlace(h));return this._setPointAtData(e,1-h,u,l-1,t)}r=s}return this._pointAtData}_setPointAtData(e,t,i,r,s){return this._pointAtData.point=i,this._pointAtData.position=e,this._pointAtData.subPosition=t,this._pointAtData.previousPointArrayIndex=r,this._pointAtData.interpolateReady=s,s&&this._updateInterpolationMatrix(),this._pointAtData}_updateInterpolationMatrix(){this._pointAtData.interpolationMatrix=K.Identity();let e=this._pointAtData.previousPointArrayIndex;if(e!==this._tangents.length-1){let t=e+1,i=this._tangents[e].clone(),r=this._normals[e].clone(),s=this._binormals[e].clone(),a=this._tangents[t].clone(),o=this._normals[t].clone(),l=this._binormals[t].clone(),c=Xe.RotationQuaternionFromAxis(r,s,i),f=Xe.RotationQuaternionFromAxis(o,l,a);Xe.Slerp(c,f,this._pointAtData.subPosition).toRotationMatrix(this._pointAtData.interpolationMatrix)}}}});var Ul,BT=C(()=>{Ul=class n{constructor(e,t){this.width=e,this.height=t}toString(){return`{W: ${this.width}, H: ${this.height}}`}getClassName(){return"Size"}getHashCode(){let e=this.width|0;return e=e*397^(this.height|0),e}copyFrom(e){this.width=e.width,this.height=e.height}copyFromFloats(e,t){return this.width=e,this.height=t,this}set(e,t){return this.copyFromFloats(e,t)}multiplyByFloats(e,t){return new n(this.width*e,this.height*t)}clone(){return new n(this.width,this.height)}equals(e){return e?this.width===e.width&&this.height===e.height:!1}get surface(){return this.width*this.height}static Zero(){return new n(0,0)}add(e){return new n(this.width+e.width,this.height+e.height)}subtract(e){return new n(this.width-e.width,this.height-e.height)}scale(e){return new n(this.width*e,this.height*e)}static Lerp(e,t,i){let r=e.width+(t.width-e.width)*i,s=e.height+(t.height-e.height)*i;return new n(r,s)}}});var T2=C(()=>{Ge()});var io,$u=C(()=>{io=class n{constructor(e,t,i,r){this.x=e,this.y=t,this.width=i,this.height=r}toGlobal(e,t){return new n(this.x*e,this.y*t,this.width*e,this.height*t)}toGlobalToRef(e,t,i){return i.x=this.x*e,i.y=this.y*t,i.width=this.width*e,i.height=this.height*t,this}clone(){return new n(this.x,this.y,this.width,this.height)}}});var A2=C(()=>{zu();zt();Dn();FT();Fh();qu();BT();Ge();T2();$u()});var Qo,bre,Vl,Gl,w_,$o,F_=C(()=>{Ge();A2();Qo=[Math.sqrt(1/(4*Math.PI)),-Math.sqrt(3/(4*Math.PI)),Math.sqrt(3/(4*Math.PI)),-Math.sqrt(3/(4*Math.PI)),Math.sqrt(15/(4*Math.PI)),-Math.sqrt(15/(4*Math.PI)),Math.sqrt(5/(16*Math.PI)),-Math.sqrt(15/(4*Math.PI)),Math.sqrt(15/(16*Math.PI))],bre=[()=>1,n=>n.y,n=>n.z,n=>n.x,n=>n.x*n.y,n=>n.y*n.z,n=>3*n.z*n.z-1,n=>n.x*n.z,n=>n.x*n.x-n.y*n.y],Vl=(n,e)=>Qo[n]*bre[n](e),Gl=[Math.PI,2*Math.PI/3,2*Math.PI/3,2*Math.PI/3,Math.PI/4,Math.PI/4,Math.PI/4,Math.PI/4,Math.PI/4],w_=class n{constructor(){this.preScaled=!1,this.l00=b.Zero(),this.l1_1=b.Zero(),this.l10=b.Zero(),this.l11=b.Zero(),this.l2_2=b.Zero(),this.l2_1=b.Zero(),this.l20=b.Zero(),this.l21=b.Zero(),this.l22=b.Zero()}addLight(e,t,i){$.Vector3[0].set(t.r,t.g,t.b);let r=$.Vector3[0],s=$.Vector3[1];r.scaleToRef(i,s),s.scaleToRef(Vl(0,e),$.Vector3[2]),this.l00.addInPlace($.Vector3[2]),s.scaleToRef(Vl(1,e),$.Vector3[2]),this.l1_1.addInPlace($.Vector3[2]),s.scaleToRef(Vl(2,e),$.Vector3[2]),this.l10.addInPlace($.Vector3[2]),s.scaleToRef(Vl(3,e),$.Vector3[2]),this.l11.addInPlace($.Vector3[2]),s.scaleToRef(Vl(4,e),$.Vector3[2]),this.l2_2.addInPlace($.Vector3[2]),s.scaleToRef(Vl(5,e),$.Vector3[2]),this.l2_1.addInPlace($.Vector3[2]),s.scaleToRef(Vl(6,e),$.Vector3[2]),this.l20.addInPlace($.Vector3[2]),s.scaleToRef(Vl(7,e),$.Vector3[2]),this.l21.addInPlace($.Vector3[2]),s.scaleToRef(Vl(8,e),$.Vector3[2]),this.l22.addInPlace($.Vector3[2])}scaleInPlace(e){this.l00.scaleInPlace(e),this.l1_1.scaleInPlace(e),this.l10.scaleInPlace(e),this.l11.scaleInPlace(e),this.l2_2.scaleInPlace(e),this.l2_1.scaleInPlace(e),this.l20.scaleInPlace(e),this.l21.scaleInPlace(e),this.l22.scaleInPlace(e)}convertIncidentRadianceToIrradiance(){this.l00.scaleInPlace(Gl[0]),this.l1_1.scaleInPlace(Gl[1]),this.l10.scaleInPlace(Gl[2]),this.l11.scaleInPlace(Gl[3]),this.l2_2.scaleInPlace(Gl[4]),this.l2_1.scaleInPlace(Gl[5]),this.l20.scaleInPlace(Gl[6]),this.l21.scaleInPlace(Gl[7]),this.l22.scaleInPlace(Gl[8])}convertIrradianceToLambertianRadiance(){this.scaleInPlace(1/Math.PI)}preScaleForRendering(){this.preScaled=!0,this.l00.scaleInPlace(Qo[0]),this.l1_1.scaleInPlace(Qo[1]),this.l10.scaleInPlace(Qo[2]),this.l11.scaleInPlace(Qo[3]),this.l2_2.scaleInPlace(Qo[4]),this.l2_1.scaleInPlace(Qo[5]),this.l20.scaleInPlace(Qo[6]),this.l21.scaleInPlace(Qo[7]),this.l22.scaleInPlace(Qo[8])}updateFromArray(e){return b.FromArrayToRef(e[0],0,this.l00),b.FromArrayToRef(e[1],0,this.l1_1),b.FromArrayToRef(e[2],0,this.l10),b.FromArrayToRef(e[3],0,this.l11),b.FromArrayToRef(e[4],0,this.l2_2),b.FromArrayToRef(e[5],0,this.l2_1),b.FromArrayToRef(e[6],0,this.l20),b.FromArrayToRef(e[7],0,this.l21),b.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return b.FromFloatsToRef(e[0],e[1],e[2],this.l00),b.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),b.FromFloatsToRef(e[6],e[7],e[8],this.l10),b.FromFloatsToRef(e[9],e[10],e[11],this.l11),b.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),b.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),b.FromFloatsToRef(e[18],e[19],e[20],this.l20),b.FromFloatsToRef(e[21],e[22],e[23],this.l21),b.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){return new n().updateFromArray(e)}static FromPolynomial(e){let t=new n;return t.l00=e.xx.scale(.376127).add(e.yy.scale(.376127)).add(e.zz.scale(.376126)),t.l1_1=e.y.scale(.977204),t.l10=e.z.scale(.977204),t.l11=e.x.scale(.977204),t.l2_2=e.xy.scale(1.16538),t.l2_1=e.yz.scale(1.16538),t.l20=e.zz.scale(1.34567).subtract(e.xx.scale(.672834)).subtract(e.yy.scale(.672834)),t.l21=e.zx.scale(1.16538),t.l22=e.xx.scale(1.16538).subtract(e.yy.scale(1.16538)),t.l1_1.scaleInPlace(-1),t.l11.scaleInPlace(-1),t.l2_1.scaleInPlace(-1),t.l21.scaleInPlace(-1),t.scaleInPlace(Math.PI),t}},$o=class n{constructor(){this.x=b.Zero(),this.y=b.Zero(),this.z=b.Zero(),this.xx=b.Zero(),this.yy=b.Zero(),this.zz=b.Zero(),this.xy=b.Zero(),this.yz=b.Zero(),this.zx=b.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=w_.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){$.Vector3[0].copyFromFloats(e.r,e.g,e.b);let t=$.Vector3[0];this.xx.addInPlace(t),this.yy.addInPlace(t),this.zz.addInPlace(t)}scaleInPlace(e){this.x.scaleInPlace(e),this.y.scaleInPlace(e),this.z.scaleInPlace(e),this.xx.scaleInPlace(e),this.yy.scaleInPlace(e),this.zz.scaleInPlace(e),this.yz.scaleInPlace(e),this.zx.scaleInPlace(e),this.xy.scaleInPlace(e)}updateFromHarmonics(e){return this._harmonics=e,this.x.copyFrom(e.l11),this.x.scaleInPlace(1.02333).scaleInPlace(-1),this.y.copyFrom(e.l1_1),this.y.scaleInPlace(1.02333).scaleInPlace(-1),this.z.copyFrom(e.l10),this.z.scaleInPlace(1.02333),this.xx.copyFrom(e.l00),$.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),$.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace($.Vector3[0]).addInPlace($.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace($.Vector3[0]).subtractInPlace($.Vector3[1]),this.zz.copyFrom(e.l00),$.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace($.Vector3[0]),this.yz.copyFrom(e.l2_1),this.yz.scaleInPlace(.858086).scaleInPlace(-1),this.zx.copyFrom(e.l21),this.zx.scaleInPlace(.858086).scaleInPlace(-1),this.xy.copyFrom(e.l2_2),this.xy.scaleInPlace(.858086),this.scaleInPlace(1/Math.PI),this}static FromHarmonics(e){return new n().updateFromHarmonics(e)}static FromArray(e){let t=new n;return b.FromArrayToRef(e[0],0,t.x),b.FromArrayToRef(e[1],0,t.y),b.FromArrayToRef(e[2],0,t.z),b.FromArrayToRef(e[3],0,t.xx),b.FromArrayToRef(e[4],0,t.yy),b.FromArrayToRef(e[5],0,t.zz),b.FromArrayToRef(e[6],0,t.yz),b.FromArrayToRef(e[7],0,t.zx),b.FromArrayToRef(e[8],0,t.xy),t}}});function P(n,e,t,i){var r=arguments.length,s=r<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,t):i,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(n,e,t,i);else for(var o=n.length-1;o>=0;o--)(a=n[o])&&(s=(r<3?a(s):r>3?a(e,t,s):a(e,t))||s);return r>3&&s&&Object.defineProperty(e,t,s),s}var Gt=C(()=>{});function x2(n){let e=n.getClassName();return VT[e]||(VT[e]={}),VT[e]}function GT(n){let e=n.getClassName();if(UT[e])return UT[e];UT[e]={};let t=UT[e],i=n,r=e;for(;r;){let s=VT[r];for(let l in s)t[l]=s[l];let a,o=!1;do{if(a=Object.getPrototypeOf(i),!a.getClassName){o=!0;break}if(a.getClassName()!==r)break;i=a}while(a);if(o)break;r=a.getClassName(),i=a}return t}var UT,VT,FM=C(()=>{UT={},VT={}});function va(n,e){return(t,i)=>{let r=x2(t);r[i]||(r[i]={type:n,sourceName:e})}}function Ire(n,e=null){return(t,i)=>{let r=e||"_"+i;Object.defineProperty(t,i,{get:function(){return this[r]},set:function(s){var a;typeof((a=this[r])==null?void 0:a.equals)=="function"&&this[r].equals(s)||this[r]!==s&&(this[r]=s,t[n].apply(this))},enumerable:!0,configurable:!0})}}function le(n,e=null){return Ire(n,e)}function w(n){return va(0,n)}function Ut(n){return va(1,n)}function gr(n){return va(2,n)}function Ju(n){return va(3,n)}function em(n){return va(4,n)}function Hr(n){return va(5,n)}function kT(n){return va(6,n)}function R2(n){return va(7,n)}function tm(n){return va(8,n)}function b2(n){return va(9,n)}function I2(n){return va(10,n)}function M2(n){return va(11,n)}function Ss(n,e,t,i){let r=t.value;t.value=(...s)=>{let a=r;if(typeof _native!="undefined"&&_native[e]){let o=_native[e];i?a=(...l)=>i(...l)?o(...l):r(...l):a=o}return n[e]=a,a(...s)}}function ut(n,e=null){return(t,i)=>{let r=i;Object.defineProperty(t,e||"",{get:function(){return this[r].value},set:function(a){var o,l;typeof((l=(o=this[r])==null?void 0:o.value)==null?void 0:l.equals)=="function"&&this[r].value.equals(a)||this[r].value!==a&&(this[r].value=a,t[n].apply(this))},enumerable:!0,configurable:!0})}}var Vt=C(()=>{FM();Ss.filter=function(n){return(e,t,i)=>Ss(e,t,i,n)}});function lf(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{let e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}var B_=C(()=>{});function Mre(){return typeof _native!="undefined"&&_native.XMLHttpRequest?new _native.XMLHttpRequest:new XMLHttpRequest}var Ir,Bh=C(()=>{Ir=class n{constructor(){this._xhr=Mre(),this._requestURL=""}static get IsCustomRequestAvailable(){return Object.keys(n.CustomRequestHeaders).length>0||n.CustomRequestModifiers.length>0}static _CleanUrl(e){return e=e.replace("file:http:","http:"),e=e.replace("file:https:","https:"),e}static _ShouldSkipRequestModifications(e){return n.SkipRequestModificationForBabylonCDN&&(e.includes("preview.babylonjs.com")||e.includes("cdn.babylonjs.com"))}static _CollectCustomizations(e,t={}){let i={...t};if(n._ShouldSkipRequestModifications(e))return{url:e,headers:i};for(let s in n.CustomRequestHeaders){let a=n.CustomRequestHeaders[s];a&&(i[s]=a)}let r={setRequestHeader:(s,a)=>{i[s]=a}};for(let s of n.CustomRequestModifiers){if(n._ShouldSkipRequestModifications(e))break;let a=s(r,e);typeof a=="string"&&(e=a)}return{url:e,headers:i}}static async FetchAsync(e,t={}){var r,s,a;let i=(r=t.method)!=null?r:"GET";if(typeof fetch!="undefined"){let{url:o,headers:l}=n._CollectCustomizations(n._CleanUrl(e),(s=t.headers)!=null?s:{});return await fetch(o,{method:i,headers:l,body:(a=t.body)!=null?a:void 0})}return await new Promise((o,l)=>{var f;let c=new n;c.responseType="arraybuffer",c.addEventListener("readystatechange",()=>{if(c.readyState===4)if(c.status>=200&&c.status<300){let h=typeof Headers!="undefined"?new Headers:void 0,d=c.getResponseHeader("Content-Type");d&&h&&h.set("Content-Type",d),o(typeof Response!="undefined"?new Response(c.response,{status:c.status,statusText:c.statusText,headers:h}):{ok:!0,status:c.status,statusText:c.statusText,headers:{get:u=>c.getResponseHeader(u)},arrayBuffer:async()=>await Promise.resolve(c.response)})}else l(new Error(`HTTP ${c.status} loading '${c.requestURL}': ${c.statusText}`))}),c.open(i,e,t.headers),c.send((f=t.body)!=null?f:null)})}get requestURL(){return this._requestURL}get onprogress(){return this._xhr.onprogress}set onprogress(e){this._xhr.onprogress=e}get readyState(){return this._xhr.readyState}get status(){return this._xhr.status}get statusText(){return this._xhr.statusText}get response(){return this._xhr.response}get responseURL(){return this._xhr.responseURL}get responseText(){return this._xhr.responseText}get responseType(){return this._xhr.responseType}set responseType(e){this._xhr.responseType=e}get timeout(){return this._xhr.timeout}set timeout(e){this._xhr.timeout=e}addEventListener(e,t,i){this._xhr.addEventListener(e,t,i)}removeEventListener(e,t,i){this._xhr.removeEventListener(e,t,i)}abort(){this._xhr.abort()}send(e){this._xhr.send(e)}open(e,t,i){let{url:r,headers:s}=n._CollectCustomizations(t,i);this._requestURL=n._CleanUrl(r),this._xhr.open(e,this._requestURL,!0);for(let a in s)this._xhr.setRequestHeader(a,s[a])}setRequestHeader(e,t){this._xhr.setRequestHeader(e,t)}getResponseHeader(e){return this._xhr.getResponseHeader(e)}};Ir.CustomRequestHeaders={};Ir.CustomRequestModifiers=new Array;Ir.SkipRequestModificationForBabylonCDN=!0});var cf,C2=C(()=>{cf=class{};cf.FilesToLoad={}});var WT,y2=C(()=>{WT=class{static ExponentialBackoff(e=3,t=500){return(i,r,s)=>r.status!==0||s>=e||i.indexOf("file:")!==-1?-1:Math.pow(2,s)*t}}});var kl,Ea,Ts,U_=C(()=>{kl=class extends Error{};kl._setPrototypeOf=Object.setPrototypeOf||((n,e)=>(n.__proto__=e,n));Ea={MeshInvalidPositionsError:0,UnsupportedTextureError:1e3,GLTFLoaderUnexpectedMagicError:2e3,SceneLoaderError:3e3,LoadFileError:4e3,RequestFileError:4001,ReadFileError:4002},Ts=class n extends kl{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",kl._setPrototypeOf(this,n.prototype)}}});function Cre(n){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",i,r,s,a,o,l,c,f=0;for(;f>2,o=(i&3)<<4|r>>4,l=(r&15)<<2|s>>6,c=s&63,isNaN(r)?l=c=64:isNaN(s)&&(c=64),t+=e.charAt(a)+e.charAt(o)+e.charAt(l)+e.charAt(c);return t}function yre(n){let e=BM(n),t=e.length,i=new Uint8Array(new ArrayBuffer(t));for(let r=0;r{P2=n=>{if(typeof TextDecoder!="undefined")return new TextDecoder().decode(n);let e="";for(let t=0;t{let e=ArrayBuffer.isView(n)?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n);return typeof e.toBase64=="function"?e.toBase64():Cre(e)},BM=n=>atob(n),D2=n=>typeof Uint8Array.fromBase64=="function"?Uint8Array.fromBase64(n).buffer:yre(n)});function Pre(n,e,t,i){switch(e){case 5120:{let r=n.getInt8(t);return i&&(r=Math.max(r/127,-1)),r}case 5121:{let r=n.getUint8(t);return i&&(r=r/255),r}case 5122:{let r=n.getInt16(t,!0);return i&&(r=Math.max(r/32767,-1)),r}case 5123:{let r=n.getUint16(t,!0);return i&&(r=r/65535),r}case 5124:return n.getInt32(t,!0);case 5125:return n.getUint32(t,!0);case 5126:return n.getFloat32(t,!0);default:throw new Error(`Invalid component type ${e}`)}}function Dre(n,e,t,i,r){switch(e){case 5120:{i&&(r=Math.round(r*127)),n.setInt8(t,r);break}case 5121:{i&&(r=Math.round(r*255)),n.setUint8(t,r);break}case 5122:{i&&(r=Math.round(r*32767)),n.setInt16(t,r,!0);break}case 5123:{i&&(r=Math.round(r*65535)),n.setUint16(t,r,!0);break}case 5124:{n.setInt32(t,r,!0);break}case 5125:{n.setUint32(t,r,!0);break}case 5126:{n.setFloat32(t,r,!0);break}default:throw new Error(`Invalid component type ${e}`)}}function Jo(n){switch(n){case 5120:case 5121:return 1;case 5122:case 5123:return 2;case 5124:case 5125:case 5126:return 4;default:throw new Error(`Invalid type '${n}'`)}}function UM(n){switch(n){case 5120:return Int8Array;case 5121:return Uint8Array;case 5122:return Int16Array;case 5123:return Uint16Array;case 5124:return Int32Array;case 5125:return Uint32Array;case 5126:return Float32Array;default:throw new Error(`Invalid component type '${n}'`)}}function Uh(n,e,t,i,r,s,a,o){let l=new Array(i),c=new Array(i);if(n instanceof Array){let f=e/4,h=t/4;for(let d=0;d{for(let u=0;un.length)throw new Error("Last accessed index is out of bounds.");if(p{for(let A=0;Af.byteLength)throw new Error("Last accessed byte is out of bounds.");let u=e*o;if(r{for(let g=0;g{for(let d=0;d{Pt()});function hf(n){return D2(n.split(",")[1])}var w2,nm,zT,GM,Lre,Gi,XT,N2,sm,Vh,el,YT,F2,B2,ff,U2,V2,Ore,G_,Nre,Wl=C(()=>{Bh();ga();di();C2();y2();U_();V_();TT();Di();Pt();jo();af();wr();rm();w2=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i),nm=class n extends Ts{constructor(e,t){super(e,Ea.LoadFileError),this.name="LoadFileError",kl._setPrototypeOf(this,n.prototype),t instanceof Ir?this.request=t:this.file=t}},zT=class n extends Ts{constructor(e,t){super(e,Ea.RequestFileError),this.request=t,this.name="RequestFileError",kl._setPrototypeOf(this,n.prototype)}},GM=class n extends Ts{constructor(e,t){super(e,Ea.ReadFileError),this.file=t,this.name="ReadFileError",kl._setPrototypeOf(this,n.prototype)}},Lre=n=>(n=n.replace(/#/gm,"%23"),n),Gi={DefaultRetryStrategy:WT.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:n=>n,ScriptBaseUrl:"",ScriptPreprocessUrl:n=>n,CleanUrl:Lre},XT=(n,e)=>{if(!(n&&n.indexOf("data:")===0)&&Gi.CorsBehavior)if(typeof Gi.CorsBehavior=="string"||Gi.CorsBehavior instanceof String)e.crossOrigin=Gi.CorsBehavior;else{let t=Gi.CorsBehavior(n);t&&(e.crossOrigin=t)}},N2={getRequiredSize:null},sm=(n,e,t,i,r="",s,a=Oe.LastCreatedEngine)=>{if(typeof HTMLImageElement=="undefined"&&!(a!=null&&a._features.forceBitmapOverHTMLImageElement))return t("LoadImage is only supported in web or BabylonNative environments."),null;let o,l=!1;if(n instanceof ArrayBuffer||ArrayBuffer.isView(n))if(typeof Blob!="undefined"&&typeof URL!="undefined"){let S;n instanceof ArrayBuffer?S=n:S=HT(n),o=URL.createObjectURL(new Blob([S],{type:r})),l=!0}else o=`data:${r};base64,`+im(n);else n instanceof Blob?(o=URL.createObjectURL(n),l=!0):(o=Gi.CleanUrl(n),o=Gi.PreprocessUrl(o));let c=S=>{if(t){let E=o||n.toString();t(`Error while trying to load image: ${E.indexOf("http")===0||E.length<=128?E:E.slice(0,128)+"..."}`,S)}};if(a!=null&&a._features.forceBitmapOverHTMLImageElement)return el(o,S=>{a.createImageBitmap(new Blob([S],{type:r}),{premultiplyAlpha:"none",colorSpaceConversion:"none",...s}).then(E=>{e(E),l&&URL.revokeObjectURL(o)}).catch(E=>{t&&t("Error while trying to load image: "+n,E)})},void 0,i||void 0,!0,(S,E)=>{c(E)}),null;let f=new Image;if(N2.getRequiredSize){let S=N2.getRequiredSize(n);S.width&&(f.width=S.width),S.height&&(f.height=S.height)}XT(o,f);let h=[],d=()=>{for(let S of h)S.target.addEventListener(S.name,S.handler)},u=()=>{for(let S of h)S.target.removeEventListener(S.name,S.handler);h.length=0},m=()=>{u(),e(f),l&&f.src&&URL.revokeObjectURL(f.src)},p=S=>{u(),c(S),l&&f.src&&URL.revokeObjectURL(f.src)},_=S=>{if(S.blockedURI!==f.src||S.disposition==="report")return;u();let E=new Error(`CSP violation of policy ${S.effectiveDirective} ${S.blockedURI}. Current policy is ${S.originalPolicy}`);Oe.UseFallbackTexture=!1,c(E),l&&f.src&&URL.revokeObjectURL(f.src),f.src=""};h.push({target:f,name:"load",handler:m}),h.push({target:f,name:"error",handler:p}),h.push({target:document,name:"securitypolicyviolation",handler:_}),d();let g=o.substring(0,5)==="blob:",v=o.substring(0,5)==="data:",x=()=>{g||v||!Ir.IsCustomRequestAvailable?f.src=o:el(o,(S,E,R)=>{let I=!r&&R?R:r,y=new Blob([S],{type:I}),M=URL.createObjectURL(y);l=!0,f.src=M},void 0,i||void 0,!0,(S,E)=>{c(E)})},A=()=>{i&&i.loadImage(o,f)};if(!g&&!v&&i&&i.enableTexturesOffline)i.open(A,x);else{if(o.indexOf("file:")!==-1){let S=decodeURIComponent(o.substring(5).toLowerCase());if(cf.FilesToLoad[S]&&typeof URL!="undefined"){try{let E;try{E=URL.createObjectURL(cf.FilesToLoad[S])}catch(R){E=URL.createObjectURL(cf.FilesToLoad[S])}f.src=E,l=!0}catch(E){f.src=""}return f}}x()}return f},Vh=(n,e,t,i,r)=>{let s=new FileReader,a={onCompleteObservable:new ie,abort:()=>s.abort()};return s.onloadend=()=>a.onCompleteObservable.notifyObservers(a),r&&(s.onerror=()=>{r(new GM(`Unable to read ${n.name}`,n))}),s.onload=o=>{e(o.target.result)},t&&(s.onprogress=t),i?s.readAsArrayBuffer(n):s.readAsText(n),a},el=(n,e,t,i,r,s,a)=>{if(n.name)return Vh(n,e,t,r,s?f=>{s(void 0,f)}:void 0);let o=n;if(o.indexOf("file:")!==-1){let f=decodeURIComponent(o.substring(5).toLowerCase());f.indexOf("./")===0&&(f=f.substring(2));let h=cf.FilesToLoad[f];if(h)return Vh(h,e,t,r,s?d=>s(void 0,new nm(d.message,d.file)):void 0)}let{match:l,type:c}=U2(o);if(l){let f={onCompleteObservable:new ie,abort:()=>()=>{}};try{let h=r?hf(o):V2(o);e(h,void 0,c)}catch(h){s?s(void 0,h):te.Error(h.message||"Failed to parse the Data URL")}return Qa.SetImmediate(()=>{f.onCompleteObservable.notifyObservers(f)}),f}return YT(o,(f,h)=>{e(f,h==null?void 0:h.responseURL,h==null?void 0:h.getResponseHeader("content-type"))},t,i,r,s?f=>{s(f.request,new nm(f.message,f.request))}:void 0,a)},YT=(n,e,t,i,r,s,a)=>{var h;i!==null&&(i!=null||(i=(h=Oe.LastCreatedScene)==null?void 0:h.offlineProvider)),n=Gi.CleanUrl(n),n=Gi.PreprocessUrl(n);let o=Gi.BaseUrl+n,l=!1,c={onCompleteObservable:new ie,abort:()=>l=!0},f=()=>{let d=new Ir,u=null,m,p=()=>{d&&(t&&d.removeEventListener("progress",t),m&&d.removeEventListener("readystatechange",m),d.removeEventListener("loadend",_))},_=()=>{p(),c.onCompleteObservable.notifyObservers(c),c.onCompleteObservable.clear(),t=void 0,m=null,_=null,s=void 0,a=void 0,e=void 0};c.abort=()=>{l=!0,_&&_(),d&&d.readyState!==(XMLHttpRequest.DONE||4)&&d.abort(),u!==null&&(clearTimeout(u),u=null),d=null};let g=x=>{let A=x.message||"Unknown error";s&&d?s(new zT(A,d)):te.Error(A)},v=x=>{if(d){if(d.open("GET",o),a)try{a(d)}catch(A){g(A);return}r&&(d.responseType="arraybuffer"),t&&d.addEventListener("progress",t),_&&d.addEventListener("loadend",_),m=()=>{if(!(l||!d)&&d.readyState===(XMLHttpRequest.DONE||4)){if(m&&d.removeEventListener("readystatechange",m),d.status>=200&&d.status<300||d.status===0&&(!fr()||B2())){let E=r?d.response:d.responseText;if(E!==null){try{e&&e(E,d)}catch(R){g(R)}return}}let A=Gi.DefaultRetryStrategy;if(A){let E=A(o,d,x);if(E!==-1){p(),d=new Ir,u=setTimeout(()=>v(x+1),E);return}}let S=new zT("Error status: "+d.status+" "+d.statusText+" - Unable to load "+o,d);s&&s(S)}},d.addEventListener("readystatechange",m),d.send()}};v(0)};if(i&&i.enableSceneOffline&&!n.startsWith("blob:")){let d=m=>{m&&m.status>400?s&&s(m):f()},u=()=>{i&&i.loadFile(Gi.BaseUrl+n,m=>{!l&&e&&e(m),c.onCompleteObservable.notifyObservers(c)},t?m=>{!l&&t&&t(m)}:void 0,d,r)};i.open(u,d)}else f();return c},F2=n=>{let{match:e,type:t}=U2(n);if(e)return t||void 0;let i=n.lastIndexOf(".");switch(n.substring(i+1).toLowerCase()){case"glb":return"model/gltf-binary";case"bin":return"application/octet-stream";case"gltf":return"model/gltf+json";case"jpg":case"jpeg":return"image/jpeg";case"png":return"image/png";case"webp":return"image/webp";case"ktx":return"image/ktx";case"ktx2":return"image/ktx2";case"avif":return"image/avif";default:return}},B2=()=>typeof location!="undefined"&&location.protocol==="file:",ff=n=>w2.test(n),U2=n=>{let e=w2.exec(n);return e===null||e.length===0?{match:!1,type:""}:{match:!0,type:e[0].replace("data:","").replace(";base64,","")}};V2=n=>BM(n.split(",")[1]),Ore=()=>{Me._FileToolsLoadImage=sm,Bu.loadFile=el,SM.loadFile=el};Ore();Nre=(n,e,t,i,r,s,a,o,l,c)=>{G_={DecodeBase64UrlToBinary:n,DecodeBase64UrlToString:e,DefaultRetryStrategy:t.DefaultRetryStrategy,BaseUrl:t.BaseUrl,CorsBehavior:t.CorsBehavior,PreprocessUrl:t.PreprocessUrl,IsBase64DataUrl:i,IsFileURL:r,LoadFile:s,LoadImage:a,ReadFile:o,RequestFile:l,SetCorsBehavior:c},Object.defineProperty(G_,"DefaultRetryStrategy",{get:function(){return t.DefaultRetryStrategy},set:function(f){t.DefaultRetryStrategy=f}}),Object.defineProperty(G_,"BaseUrl",{get:function(){return t.BaseUrl},set:function(f){t.BaseUrl=f}}),Object.defineProperty(G_,"PreprocessUrl",{get:function(){return t.PreprocessUrl},set:function(f){t.PreprocessUrl=f}}),Object.defineProperty(G_,"CorsBehavior",{get:function(){return t.CorsBehavior},set:function(f){t.CorsBehavior=f}})};Nre(hf,V2,Gi,ff,B2,el,sm,Vh,YT,XT)});var KT,G2=C(()=>{BT();KT=class n{get wrapU(){return this._wrapU}set wrapU(e){this._wrapU=e}get wrapV(){return this._wrapV}set wrapV(e){this._wrapV=e}get coordinatesMode(){return 0}get isCube(){return this._texture?this._texture.isCube:!1}set isCube(e){this._texture&&(this._texture.isCube=e)}get is3D(){return this._texture?this._texture.is3D:!1}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return this._texture?this._texture.is2DArray:!1}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}getClassName(){return"ThinTexture"}static _IsRenderTargetWrapper(e){return(e==null?void 0:e.shareDepth)!==void 0}constructor(e){var t,i,r;this._wrapU=1,this._wrapV=1,this.wrapR=1,this.anisotropicFilteringLevel=4,this.delayLoadState=0,this._texture=null,this._engine=null,this._cachedSize=Ul.Zero(),this._cachedBaseSize=Ul.Zero(),this._initialSamplingMode=2,this._texture=n._IsRenderTargetWrapper(e)?e.texture:e,this._texture&&(this._engine=this._texture.getEngine(),this.wrapU=(t=this._texture._cachedWrapU)!=null?t:this.wrapU,this.wrapV=(i=this._texture._cachedWrapV)!=null?i:this.wrapV,this.wrapR=(r=this._texture._cachedWrapR)!=null?r:this.wrapR)}isReady(){return this.delayLoadState===4?(this.delayLoad(),!1):this._texture?this._texture.isReady:!1}delayLoad(){}getInternalTexture(){return this._texture}getSize(){if(this._texture){if(this._texture.width)return this._cachedSize.width=this._texture.width,this._cachedSize.height=this._texture.height,this._cachedSize;if(this._texture._size)return this._cachedSize.width=this._texture._size,this._cachedSize.height=this._texture._size,this._cachedSize}return this._cachedSize}getBaseSize(){return!this.isReady()||!this._texture?(this._cachedBaseSize.width=0,this._cachedBaseSize.height=0,this._cachedBaseSize):this._texture._size?(this._cachedBaseSize.width=this._texture._size,this._cachedBaseSize.height=this._texture._size,this._cachedBaseSize):(this._cachedBaseSize.width=this._texture.baseWidth,this._cachedBaseSize.height=this._texture.baseHeight,this._cachedBaseSize)}get samplingMode(){return this._texture?this._texture.samplingMode:this._initialSamplingMode}updateSamplingMode(e,t=!1){this._texture&&this._engine&&this._engine.updateTextureSamplingMode(e,this._texture,this._texture.generateMipMaps&&t)}releaseInternalTexture(){this._texture&&(this._texture.dispose(),this._texture=null)}dispose(){this._texture&&(this.releaseInternalTexture(),this._engine=null)}}});var jT,k2=C(()=>{jT=class n{static Eval(e,t){return e.match(/\([^()]*\)/g)?e=e.replace(/\([^()]*\)/g,i=>(i=i.slice(1,i.length-1),n._HandleParenthesisContent(i,t))):e=n._HandleParenthesisContent(e,t),e==="true"?!0:e==="false"?!1:n.Eval(e,t)}static _HandleParenthesisContent(e,t){t=t||(s=>s==="true");let i,r=e.split("||");for(let s in r)if(Object.prototype.hasOwnProperty.call(r,s)){let a=n._SimplifyNegation(r[s].trim()),o=a.split("&&");if(o.length>1)for(let l=0;l(t=t.replace(/[\s]/g,()=>""),t.length%2?"!":"")),e=e.trim(),e==="!true"?e="false":e==="!false"&&(e="true"),e}}});var Zt,df=C(()=>{k2();Zt=class n{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>n.HasTags(e),e.addTags=t=>n.AddTagsTo(e,t),e.removeTags=t=>n.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>n.MatchesQuery(e,t)}static DisableFor(e){delete e._tags,delete e.hasTags,delete e.addTags,delete e.removeTags,delete e.matchesTagsQuery}static HasTags(e){if(!e._tags)return!1;let t=e._tags;for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i))return!0;return!1}static GetTags(e,t=!0){if(!e._tags)return null;if(t){let i=[];for(let r in e._tags)Object.prototype.hasOwnProperty.call(e._tags,r)&&e._tags[r]===!0&&i.push(r);return i.join(" ")}else return e._tags}static AddTagsTo(e,t){if(!t||typeof t!="string")return;let i=t.split(" ");for(let r of i)n._AddTagTo(e,r)}static _AddTagTo(e,t){t=t.trim(),!(t===""||t==="true"||t==="false")&&(t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(n.EnableFor(e),e._tags[t]=!0))}static RemoveTagsFrom(e,t){if(!n.HasTags(e))return;let i=t.split(" ");for(let r in i)n._RemoveTagFrom(e,i[r])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return t===void 0?!0:t===""?n.HasTags(e):jT.Eval(t,i=>n.HasTags(e)&&e._tags[i])}}});var W2,it,Tr=C(()=>{hn();df();zt();Ge();FM();W2=function(n,e,t,i={}){let r=n();Zt&&Zt.HasTags(e)&&Zt.AddTagsTo(r,Zt.GetTags(e,!0));let s=GT(r),a={};for(let o in s){let l=s[o],c=e[o],f=l.type;if(c!=null&&(o!=="uniqueId"||it.AllowLoadingUniqueId))switch(f){case 0:case 6:case 9:case 11:typeof c.slice=="function"?r[o]=c.slice():r[o]=c;break;case 1:i.cloneTexturesOnlyOnce&&a[c.uniqueId]?r[o]=a[c.uniqueId]:(r[o]=t||c.isRenderTarget?c:c.clone(),a[c.uniqueId]=r[o]);break;case 2:case 3:case 4:case 5:case 7:case 8:case 10:case 12:r[o]=t?c:c.clone();break}}return r},it=class n{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i{throw qe("ImageProcessingConfiguration")};it._FresnelParametersParser=n=>{throw qe("FresnelParameters")};it._ColorCurvesParser=n=>{throw qe("ColorCurves")};it._TextureParser=(n,e,t)=>{throw qe("Texture")}});var pi,k_=C(()=>{Gt();Vt();di();Ge();Di();B_();Wl();G2();Tr();pi=class n extends KT{set hasAlpha(e){this._hasAlpha!==e&&(this._hasAlpha=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,t=>t.hasTexture(this)))}get hasAlpha(){return this._hasAlpha}set getAlphaFromRGB(e){this._getAlphaFromRGB!==e&&(this._getAlphaFromRGB=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,t=>t.hasTexture(this)))}get getAlphaFromRGB(){return this._getAlphaFromRGB}set coordinatesIndex(e){this._coordinatesIndex!==e&&(this._coordinatesIndex=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,t=>t.hasTexture(this)))}get coordinatesIndex(){return this._coordinatesIndex}set coordinatesMode(e){this._coordinatesMode!==e&&(this._coordinatesMode=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,t=>t.hasTexture(this)))}get coordinatesMode(){return this._coordinatesMode}get wrapU(){return this._wrapU}set wrapU(e){this._wrapU=e}get wrapV(){return this._wrapV}set wrapV(e){this._wrapV=e}get isCube(){return this._texture?this._texture.isCube:this._isCube}set isCube(e){this._texture?this._texture.isCube=e:this._isCube=e}get is3D(){return this._texture?this._texture.is3D:!1}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return this._texture?this._texture.is2DArray:!1}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}get gammaSpace(){if(this._texture)this._texture._gammaSpace===null&&(this._texture._gammaSpace=this._gammaSpace);else return this._gammaSpace;return this._texture._gammaSpace&&!this._texture._useSRGBBuffer}set gammaSpace(e){var t;if(this._texture){if(this._texture._gammaSpace===e)return;this._texture._gammaSpace=e}else{if(this._gammaSpace===e)return;this._gammaSpace=e}(t=this.getScene())==null||t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this))}get isRGBD(){return this._texture!=null&&this._texture._isRGBD}set isRGBD(e){var t;e!==this.isRGBD&&(this._texture&&(this._texture._isRGBD=e),(t=this.getScene())==null||t.markAllMaterialsAsDirty(1,i=>i.hasTexture(this)))}get noMipmap(){return!1}get lodGenerationOffset(){return this._texture?this._texture._lodGenerationOffset:0}set lodGenerationOffset(e){this._texture&&(this._texture._lodGenerationOffset=e)}get lodGenerationScale(){return this._texture?this._texture._lodGenerationScale:0}set lodGenerationScale(e){this._texture&&(this._texture._lodGenerationScale=e)}get linearSpecularLOD(){return this._texture?this._texture._linearSpecularLOD:!1}set linearSpecularLOD(e){this._texture&&(this._texture._linearSpecularLOD=e)}get irradianceTexture(){return this._texture?this._texture._irradianceTexture:null}set irradianceTexture(e){this._texture&&(this._texture._irradianceTexture=e)}get uid(){return this._uid||(this._uid=lf()),this._uid}toString(){return this.name}getClassName(){return"BaseTexture"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get isBlocking(){return!0}get loadingError(){return this._loadingError}get errorObject(){return this._errorObject}constructor(e,t=null){super(null),this.metadata=null,this.reservedDataStore=null,this._hasAlpha=!1,this._getAlphaFromRGB=!1,this.level=1,this._coordinatesIndex=0,this.optimizeUVAllocation=!0,this._coordinatesMode=0,this.wrapR=1,this.anisotropicFilteringLevel=n.DEFAULT_ANISOTROPIC_FILTERING_LEVEL,this._isCube=!1,this._gammaSpace=!0,this.invertZ=!1,this.lodLevelInAlpha=!1,this._dominantDirection=null,this.isRenderTarget=!1,this._prefiltered=!1,this._forceSerialize=!1,this.animations=[],this.onDisposeObservable=new ie,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?n._IsScene(e)?this._scene=e:this._engine=e:this._scene=Oe.LastCreatedScene,this._scene&&(this.uniqueId=this._scene.getUniqueId(),this._scene.addTexture(this),this._engine=this._scene.getEngine()),this._texture=t,this._uid=null}getScene(){return this._scene}_getEngine(){return this._engine}getTextureMatrix(){return K.IdentityReadOnly}getReflectionTextureMatrix(){return K.IdentityReadOnly}getRefractionTextureMatrix(){return this.getReflectionTextureMatrix()}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,i,r,s,a){let o=this._getEngine();if(!o)return null;let l=o._getUseSRGBBuffer(!!s,t),c=o.getLoadedTexturesCache();for(let f=0;f=0&&this._scene.textures.splice(e,1),this._scene.onTextureRemovedObservable.notifyObservers(this),this._scene=null,this._parentContainer){let t=this._parentContainer.textures.indexOf(this);t>-1&&this._parentContainer.textures.splice(t,1),this._parentContainer=null}}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.metadata=null,super.dispose()}serialize(e=!1){if(!this.name&&!e)return null;let t=it.Serialize(this);return it.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let i=e.length;if(i===0){t();return}for(let r=0;r{--i===0&&t()}):--i===0&&t()}}}static _IsScene(e){return e.getClassName()==="Scene"}};pi.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4;P([w()],pi.prototype,"uniqueId",void 0);P([w()],pi.prototype,"name",void 0);P([w()],pi.prototype,"displayName",void 0);P([w()],pi.prototype,"metadata",void 0);P([w("hasAlpha")],pi.prototype,"_hasAlpha",void 0);P([w("getAlphaFromRGB")],pi.prototype,"_getAlphaFromRGB",void 0);P([w()],pi.prototype,"level",void 0);P([w("coordinatesIndex")],pi.prototype,"_coordinatesIndex",void 0);P([w()],pi.prototype,"optimizeUVAllocation",void 0);P([w("coordinatesMode")],pi.prototype,"_coordinatesMode",void 0);P([w()],pi.prototype,"wrapU",null);P([w()],pi.prototype,"wrapV",null);P([w()],pi.prototype,"wrapR",void 0);P([w()],pi.prototype,"anisotropicFilteringLevel",void 0);P([w()],pi.prototype,"isCube",null);P([w()],pi.prototype,"is3D",null);P([w()],pi.prototype,"is2DArray",null);P([w()],pi.prototype,"gammaSpace",null);P([w()],pi.prototype,"invertZ",void 0);P([w()],pi.prototype,"lodLevelInAlpha",void 0);P([w()],pi.prototype,"lodGenerationOffset",null);P([w()],pi.prototype,"lodGenerationScale",null);P([w()],pi.prototype,"linearSpecularLOD",null);P([Ut()],pi.prototype,"irradianceTexture",null);P([w()],pi.prototype,"isRenderTarget",void 0)});var uf,Hl,kM=C(()=>{Ge();Ln();F_();Dn();zt();uf=class{constructor(e,t,i,r){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=r}},Hl=class{static _NearestPow2Floor(e){return e<=1?1:1<0?this._NearestPow2Floor(i):0,s=!e.noMipmap&&((x=e._texture)==null?void 0:x.generateMipMaps)===!0,a=r>0&&r0&&r{Promise.all([f,c,h,d,u,m]).then(([S,E,R,I,y,M])=>{let D=l;g&&(S=this._DownsampleFace(S,t,r,4),E=this._DownsampleFace(E,t,r,4),R=this._DownsampleFace(R,t,r,4),I=this._DownsampleFace(I,t,r,4),y=this._DownsampleFace(y,t,r,4),M=this._DownsampleFace(M,t,r,4),D=r);let O={size:D,right:E,left:S,up:R,down:I,front:y,back:M,format:_,type:S instanceof Float32Array?1:0,gammaSpace:p};A(this.ConvertCubeMapToSphericalPolynomial(O))})})}static _AreaElement(e,t){return Math.atan2(e*t,Math.sqrt(e*e+t*t+1))}static _DownsampleFace(e,t,i,r){let s=e instanceof Float32Array?e:Float32Array.from(e),a=i*i*r,o=new Float32Array(a),l=t/i,c=1/(l*l);for(let d=0;d0?this._NearestPow2Floor(t):0;if(i>0&&e.size>i){let m=e.format===5?4:3,p=["right","left","up","down","front","back"],_={};for(let g of p)_[g]=this._DownsampleFace(e[g],e.size,i,m);e={...e,..._,size:i}}let r=new w_,s=0,a=2/e.size,o=a,l=.5*a,c=l-1;for(let m=0;m<6;m++){let p=this._FileFaces[m],_=e[p.name],g=c,v=e.format===5?4:3;for(let x=0;xD){let N=D/V;I*=N,y*=N,M*=N}}else I=wt(I,0,D),y=wt(y,0,D),M=wt(M,0,D);let O=new ve(I,y,M);r.addLight(E,O,R),s+=R,A+=a}g+=o}}let u=4*Math.PI*6/6/s;return r.scaleInPlace(u),r.convertIncidentRadianceToIrradiance(),r.convertIrradianceToLambertianRadiance(),$o.FromHarmonics(r)}};Hl._FileFaces=[new uf("right",new b(1,0,0),new b(0,0,-1),new b(0,-1,0)),new uf("left",new b(-1,0,0),new b(0,0,1),new b(0,-1,0)),new uf("up",new b(0,1,0),new b(1,0,0),new b(0,0,1)),new uf("down",new b(0,-1,0),new b(1,0,0),new b(0,0,-1)),new uf("front",new b(0,0,1),new b(1,0,0),new b(0,-1,0)),new uf("back",new b(0,0,-1),new b(-1,0,0),new b(0,-1,0))];Hl.MAX_HDRI_VALUE=4096;Hl.PRESERVE_CLAMPED_COLORS=!1});var zl,WM=C(()=>{Pt();Hi();zl=class{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];let t=vn(e);if(t)return t;te.Warn(e+" not found, you may have missed an import.");let i=e.split("."),r=window||this;for(let s=0,a=i.length;s=0;){let h=n[c];h<0?h=0:h>1&&(h=1),f[c]=h*255}n=f}let s=document.createElement("canvas");s.width=i,s.height=r;let a=s.getContext("2d");if(!a)return null;let o=a.createImageData(i,r);if(o.data.set(n),a.putImageData(o,0,0),t){let c=document.createElement("canvas");c.width=i,c.height=r;let f=c.getContext("2d");return f?(f.translate(0,r),f.scale(1,-1),f.drawImage(s,0,0),c.toDataURL("image/png")):null}return s.toDataURL("image/png")}function z2(n,e=0,t=0){let i=n.getInternalTexture();if(!i)return null;let r=n._readPixelsSync(e,t);return r?H2(r,n.getSize(),i.invertY):null}async function X2(n,e=0,t=0){let i=n.getInternalTexture();if(!i)return null;let r=await n.readPixels(e,t);return r?H2(r,n.getSize(),i.invertY):null}var Y2=C(()=>{});var Mt,en=C(()=>{Mt=!1});var ge,Fr=C(()=>{Gt();Vt();di();Ge();k_();Hi();hn();jo();WM();qu();V_();Y2();en();Tr();ge=class n extends pi{static _CreateVideoTexture(e,t,i,r=!1,s=!1,a=n.TRILINEAR_SAMPLINGMODE,o={},l,c=5){throw qe("VideoTexture")}get noMipmap(){return this._noMipmap}get mimeType(){return this._mimeType}set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}get invertY(){return this._invertY}constructor(e,t,i,r,s=n.TRILINEAR_SAMPLINGMODE,a=null,o=null,l=null,c=!1,f,h,d,u,m){var R,I,y,M,D,O,V,N,F,U,G;super(t),this.url=null,this.uOffset=0,this.vOffset=0,this.uScale=1,this.vScale=1,this.uAng=0,this.vAng=0,this.wAng=0,this.uRotationCenter=.5,this.vRotationCenter=.5,this.wRotationCenter=.5,this.homogeneousRotationInUVTransform=!1,this.inspectableCustomProperties=null,this._noMipmap=!1,this._invertY=!1,this._rowGenerationMatrix=null,this._cachedTextureMatrix=null,this._projectionModeMatrix=null,this._t0=null,this._t1=null,this._t2=null,this._cachedUOffset=-1,this._cachedVOffset=-1,this._cachedUScale=0,this._cachedVScale=0,this._cachedUAng=-1,this._cachedVAng=-1,this._cachedWAng=-1,this._cachedReflectionProjectionMatrixId=-1,this._cachedURotationCenter=-1,this._cachedVRotationCenter=-1,this._cachedWRotationCenter=-1,this._cachedHomogeneousRotationInUVTransform=!1,this._cachedIdentity3x2=!0,this._cachedReflectionTextureMatrix=null,this._cachedReflectionUOffset=-1,this._cachedReflectionVOffset=-1,this._cachedReflectionUScale=0,this._cachedReflectionVScale=0,this._cachedReflectionCoordinatesMode=-1,this._buffer=null,this._deleteBuffer=!1,this._format=null,this._delayedOnLoad=null,this._delayedOnError=null,this.onLoadObservable=new ie,this._isBlocking=!0,this.name=e||"",this.url=e;let p,_=!1,g=null,v=!0;typeof i=="object"&&i!==null?(p=(R=i.noMipmap)!=null?R:!1,r=(I=i.invertY)!=null?I:!Mt,s=(y=i.samplingMode)!=null?y:n.TRILINEAR_SAMPLINGMODE,a=(M=i.onLoad)!=null?M:null,o=(D=i.onError)!=null?D:null,l=(O=i.buffer)!=null?O:null,c=(V=i.deleteBuffer)!=null?V:!1,f=i.format,h=i.mimeType,d=i.loaderOptions,u=i.creationFlags,_=(N=i.useSRGBBuffer)!=null?N:!1,g=(F=i.internalTexture)!=null?F:null,v=(U=i.gammaSpace)!=null?U:v,m=(G=i.forcedExtension)!=null?G:m):p=!!i,this._gammaSpace=v,this._noMipmap=p,this._invertY=r===void 0?!Mt:r,this._initialSamplingMode=s,this._buffer=l,this._deleteBuffer=c,this._mimeType=h,this._loaderOptions=d,this._creationFlags=u,this._useSRGBBuffer=_,this._forcedExtension=m,f!==void 0&&(this._format=f);let x=this.getScene(),A=this._getEngine();if(!A)return;A.onBeforeTextureInitObservable.notifyObservers(this);let S=()=>{this._texture&&(this._texture._invertVScale&&(this.vScale*=-1,this.vOffset+=1),this._texture._cachedWrapU!==null&&(this.wrapU=this._texture._cachedWrapU,this._texture._cachedWrapU=null),this._texture._cachedWrapV!==null&&(this.wrapV=this._texture._cachedWrapV,this._texture._cachedWrapV=null),this._texture._cachedWrapR!==null&&(this.wrapR=this._texture._cachedWrapR,this._texture._cachedWrapR=null)),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this),a&&a(),!this.isBlocking&&x&&x.resetCachedMaterial()},E=(ee,j)=>{this._loadingError=!0,this._errorObject={message:ee,exception:j},o&&o(ee,j),n.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!g){this._delayedOnLoad=S,this._delayedOnError=E;return}if(this._texture=g!=null?g:this._getFromCache(this.url,p,s,this._invertY,_,this.isCube),this._texture)if(this._texture.isReady)Qa.SetImmediate(()=>S());else{let ee=this._texture.onLoadedObservable.add(S);this._texture.onErrorObservable.add(j=>{var Z;E(j.message,j.exception),(Z=this._texture)==null||Z.onLoadedObservable.remove(ee)})}else if(!x||!x.useDelayedTextureLoading){try{this._texture=A.createTexture(this.url,p,this._invertY,x,s,S,E,this._buffer,void 0,this._format,this._forcedExtension,h,d,u,_)}catch(ee){throw E("error loading",ee),ee}c&&(this._buffer=null)}else this.delayLoadState=4,this._delayedOnLoad=S,this._delayedOnError=E}updateURL(e,t=null,i,r){this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(1,o=>o.hasTexture(this))),(!this.name||this.name.startsWith("data:"))&&(this.name=e),this.url=e,this._buffer=t,this._forcedExtension=r,this.delayLoadState=4;let s=this._delayedOnLoad,a=()=>{s?s():this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this),i&&i()};this._delayedOnLoad=a,this.delayLoad()}delayLoad(){if(this.delayLoadState!==4)return;let e=this.getScene();if(!e)return;let t=this.url;!t&&(this.name.indexOf("://")>0||this.name.startsWith("data:"))&&(t=this.name),this.delayLoadState=1,this._texture=this._getFromCache(t,this._noMipmap,this.samplingMode,this._invertY,this._useSRGBBuffer,this.isCube),this._texture?this._delayedOnLoad&&(this._texture.isReady?Qa.SetImmediate(this._delayedOnLoad):this._texture.onLoadedObservable.add(this._delayedOnLoad)):(this._texture=e.getEngine().createTexture(t,this._noMipmap,this._invertY,e,this.samplingMode,this._delayedOnLoad,this._delayedOnError,this._buffer,null,this._format,this._forcedExtension,this._mimeType,this._loaderOptions,this._creationFlags,this._useSRGBBuffer),this._deleteBuffer&&(this._buffer=null)),this._delayedOnLoad=null,this._delayedOnError=null}_prepareRowForTextureGeneration(e,t,i,r){e*=this._cachedUScale,t*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,t-=this.vRotationCenter*this._cachedVScale,i-=this.wRotationCenter,b.TransformCoordinatesFromFloatsToRef(e,t,i,this._rowGenerationMatrix,r),r.x+=this.uRotationCenter*this._cachedUScale+this._cachedUOffset,r.y+=this.vRotationCenter*this._cachedVScale+this._cachedVOffset,r.z+=this.wRotationCenter}getTextureMatrix(e=1){if(this.uOffset===this._cachedUOffset&&this.vOffset===this._cachedVOffset&&this.uScale*e===this._cachedUScale&&this.vScale===this._cachedVScale&&this.uAng===this._cachedUAng&&this.vAng===this._cachedVAng&&this.wAng===this._cachedWAng&&this.uRotationCenter===this._cachedURotationCenter&&this.vRotationCenter===this._cachedVRotationCenter&&this.wRotationCenter===this._cachedWRotationCenter&&this.homogeneousRotationInUVTransform===this._cachedHomogeneousRotationInUVTransform)return this._cachedTextureMatrix;this._cachedUOffset=this.uOffset,this._cachedVOffset=this.vOffset,this._cachedUScale=this.uScale*e,this._cachedVScale=this.vScale,this._cachedUAng=this.uAng,this._cachedVAng=this.vAng,this._cachedWAng=this.wAng,this._cachedURotationCenter=this.uRotationCenter,this._cachedVRotationCenter=this.vRotationCenter,this._cachedWRotationCenter=this.wRotationCenter,this._cachedHomogeneousRotationInUVTransform=this.homogeneousRotationInUVTransform,(!this._cachedTextureMatrix||!this._rowGenerationMatrix)&&(this._cachedTextureMatrix=K.Zero(),this._rowGenerationMatrix=new K,this._t0=b.Zero(),this._t1=b.Zero(),this._t2=b.Zero()),K.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(K.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,$.Matrix[0]),K.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,$.Matrix[1]),K.ScalingToRef(this._cachedUScale,this._cachedVScale,0,$.Matrix[2]),K.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,$.Matrix[3]),$.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef($.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef($.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef($.Matrix[3],this._cachedTextureMatrix),this._cachedTextureMatrix.setRowFromFloats(2,this._cachedTextureMatrix.m[12],this._cachedTextureMatrix.m[13],this._cachedTextureMatrix.m[14],1)):(this._prepareRowForTextureGeneration(0,0,0,this._t0),this._prepareRowForTextureGeneration(1,0,0,this._t1),this._prepareRowForTextureGeneration(0,1,0,this._t2),this._t1.subtractInPlace(this._t0),this._t2.subtractInPlace(this._t0),K.FromValuesToRef(this._t1.x,this._t1.y,this._t1.z,0,this._t2.x,this._t2.y,this._t2.z,0,this._t0.x,this._t0.y,this._t0.z,0,0,0,0,1,this._cachedTextureMatrix));let t=this.getScene();if(!t)return this._cachedTextureMatrix;let i=this._cachedIdentity3x2;return this._cachedIdentity3x2=this._cachedTextureMatrix.isIdentityAs3x2(),this.optimizeUVAllocation&&i!==this._cachedIdentity3x2&&t.markAllMaterialsAsDirty(1,r=>r.hasTexture(this)),this._cachedTextureMatrix}getReflectionTextureMatrix(){let e=this.getScene();if(!e)return this._cachedReflectionTextureMatrix;if(this.uOffset===this._cachedReflectionUOffset&&this.vOffset===this._cachedReflectionVOffset&&this.uScale===this._cachedReflectionUScale&&this.vScale===this._cachedReflectionVScale&&this.coordinatesMode===this._cachedReflectionCoordinatesMode)if(this.coordinatesMode===n.PROJECTION_MODE){if(this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag)return this._cachedReflectionTextureMatrix}else return this._cachedReflectionTextureMatrix;this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=K.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=K.Zero());let t=this._cachedReflectionCoordinatesMode!==this.coordinatesMode;switch(this._cachedReflectionUOffset=this.uOffset,this._cachedReflectionVOffset=this.vOffset,this._cachedReflectionUScale=this.uScale,this._cachedReflectionVScale=this.vScale,this._cachedReflectionCoordinatesMode=this.coordinatesMode,this.coordinatesMode){case n.PLANAR_MODE:{K.IdentityToRef(this._cachedReflectionTextureMatrix),this._cachedReflectionTextureMatrix[0]=this.uScale,this._cachedReflectionTextureMatrix[5]=this.vScale,this._cachedReflectionTextureMatrix[12]=this.uOffset,this._cachedReflectionTextureMatrix[13]=this.vOffset;break}case n.PROJECTION_MODE:{K.FromValuesToRef(.5,0,0,0,0,-.5,0,0,0,0,0,0,.5,.5,1,1,this._projectionModeMatrix);let i=e.getProjectionMatrix();this._cachedReflectionProjectionMatrixId=i.updateFlag,i.multiplyToRef(this._projectionModeMatrix,this._cachedReflectionTextureMatrix);break}default:K.IdentityToRef(this._cachedReflectionTextureMatrix);break}return t&&e.markAllMaterialsAsDirty(1,i=>i.hasTexture(this)),this._cachedReflectionTextureMatrix}clone(){let e={noMipmap:this._noMipmap,invertY:this._invertY,samplingMode:this.samplingMode,onLoad:void 0,onError:void 0,buffer:this._texture?this._texture._buffer:void 0,deleteBuffer:this._deleteBuffer,format:this.textureFormat,mimeType:this.mimeType,loaderOptions:this._loaderOptions,creationFlags:this._creationFlags,useSRGBBuffer:this._useSRGBBuffer};return it.Clone(()=>new n(this._texture?this._texture.url:null,this.getScene(),e),this)}serialize(){var i,r;let e=this.name;n.SerializeBuffers||this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");let t=super.serialize(n._SerializeInternalTextureUniqueId);if(!t)return null;if(n.SerializeBuffers||n.ForceSerializeBuffers)if(typeof this._buffer=="string"&&this._buffer.startsWith("data:"))t.base64String=this._buffer,t.name=t.name.replace("data:","");else if(this.url&&this.url.startsWith("data:")&&this._buffer instanceof Uint8Array){let s=this.mimeType||"image/png";t.base64String=`data:${s};base64,${im(this._buffer)}`}else(n.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(t.base64String=!this._engine||this._engine._features.supportSyncTextureRead?z2(this):X2(this));return t.invertY=this._invertY,t.samplingMode=this.samplingMode,t._creationFlags=this._creationFlags,t._useSRGBBuffer=this._useSRGBBuffer,n._SerializeInternalTextureUniqueId&&(t.internalTextureUniqueId=(i=this._texture)==null?void 0:i.uniqueId),t.internalTextureLabel=(r=this._texture)==null?void 0:r.label,t.noMipmap=this._noMipmap,this.name=e,t}getClassName(){return"Texture"}dispose(){super.dispose(),this.onLoadObservable.clear(),this._delayedOnLoad=null,this._delayedOnError=null,this._buffer=null}static Parse(e,t,i){if(e.customType){let c=zl.Instantiate(e.customType).Parse(e,t,i);return e.samplingMode&&c.updateSamplingMode&&c._samplingMode&&c._samplingMode!==e.samplingMode&&c.updateSamplingMode(e.samplingMode),c}if(e.isCube&&!e.isRenderTarget)return n._CubeTextureParser(e,t,i);let r=e.internalTextureUniqueId!==void 0;if(!e.name&&!e.isRenderTarget&&!r)return null;let s;if(r){let l=t.getEngine().getLoadedTexturesCache();for(let c of l)if(c.uniqueId===e.internalTextureUniqueId){s=c;break}}let a=l=>{if(l&&l._texture&&(l._texture._cachedWrapU=null,l._texture._cachedWrapV=null,l._texture._cachedWrapR=null),e.samplingMode){let c=e.samplingMode;l&&l.samplingMode!==c&&l.updateSamplingMode(c)}if(l&&e.animations)for(let c=0;c{var c,f,h,d,u;let l=!0;if(e.noMipmap&&(l=!1),e.mirrorPlane){let m=n._CreateMirror(e.name,e.renderTargetSize,t,l);return m._waitingRenderList=e.renderList,m.mirrorPlane=to.FromArray(e.mirrorPlane),a(m),m}else if(e.isRenderTarget&&!e.base64String){let m=null;if(e.isCube){if(t.reflectionProbes)for(let p=0;p{a(m)}},_=e.base64String,g=_.startsWith("data:")?_.substring(5):_;m=n.CreateFromBase64String("",g,t,p),m.name=e.name}else{let p;e.name&&(e.name.indexOf("://")>0||e.name.startsWith("data:"))?p=e.name:p=i+e.name,e.url&&(e.url.startsWith("data:")||n.UseSerializedUrlIfAny)&&(p=e.url);let _={noMipmap:!l,invertY:e.invertY,samplingMode:e.samplingMode,useSRGBBuffer:(d=e._useSRGBBuffer)!=null?d:!1,creationFlags:(u=e._creationFlags)!=null?u:0,onLoad:()=>{a(m)},internalTexture:s};m=new n(p,t,_)}return m}},e,t)}static CreateFromBase64String(e,t,i,r,s,a=n.TRILINEAR_SAMPLINGMODE,o=null,l=null,c=5,f,h){return new n("data:"+t,i,r,s,a,o,l,e,!1,c,void 0,void 0,f,h)}static LoadFromDataString(e,t,i,r=!1,s,a=!0,o=n.TRILINEAR_SAMPLINGMODE,l=null,c=null,f=5,h,d){return e.substring(0,5)!=="data:"&&(e="data:"+e),new n(e,i,s,a,o,l,c,t,r,f,void 0,void 0,h,d)}};ge.SerializeBuffers=!0;ge.ForceSerializeBuffers=!1;ge.OnTextureLoadErrorObservable=new ie;ge._SerializeInternalTextureUniqueId=!1;ge._CubeTextureParser=(n,e,t)=>{throw qe("CubeTexture")};ge._CreateMirror=(n,e,t,i)=>{throw qe("MirrorTexture")};ge._CreateRenderTargetTexture=(n,e,t,i,r)=>{throw qe("RenderTargetTexture")};ge.NEAREST_SAMPLINGMODE=1;ge.NEAREST_NEAREST_MIPLINEAR=8;ge.BILINEAR_SAMPLINGMODE=2;ge.LINEAR_LINEAR_MIPNEAREST=11;ge.TRILINEAR_SAMPLINGMODE=3;ge.LINEAR_LINEAR_MIPLINEAR=3;ge.NEAREST_NEAREST_MIPNEAREST=4;ge.NEAREST_LINEAR_MIPNEAREST=5;ge.NEAREST_LINEAR_MIPLINEAR=6;ge.NEAREST_LINEAR=7;ge.NEAREST_NEAREST=1;ge.LINEAR_NEAREST_MIPNEAREST=9;ge.LINEAR_NEAREST_MIPLINEAR=10;ge.LINEAR_LINEAR=2;ge.LINEAR_NEAREST=12;ge.EXPLICIT_MODE=0;ge.SPHERICAL_MODE=1;ge.PLANAR_MODE=2;ge.CUBIC_MODE=3;ge.PROJECTION_MODE=4;ge.SKYBOX_MODE=5;ge.INVCUBIC_MODE=6;ge.EQUIRECTANGULAR_MODE=7;ge.FIXED_EQUIRECTANGULAR_MODE=8;ge.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;ge.CLAMP_ADDRESSMODE=0;ge.WRAP_ADDRESSMODE=1;ge.MIRROR_ADDRESSMODE=2;ge.UseSerializedUrlIfAny=!1;P([w()],ge.prototype,"url",void 0);P([w()],ge.prototype,"uOffset",void 0);P([w()],ge.prototype,"vOffset",void 0);P([w()],ge.prototype,"uScale",void 0);P([w()],ge.prototype,"vScale",void 0);P([w()],ge.prototype,"uAng",void 0);P([w()],ge.prototype,"vAng",void 0);P([w()],ge.prototype,"wAng",void 0);P([w()],ge.prototype,"uRotationCenter",void 0);P([w()],ge.prototype,"vRotationCenter",void 0);P([w()],ge.prototype,"wRotationCenter",void 0);P([w()],ge.prototype,"homogeneousRotationInUVTransform",void 0);P([w()],ge.prototype,"isBlocking",null);Ft("BABYLON.Texture",ge);it._TextureParser=ge.Parse});var ro,L,ki=C(()=>{bM();Pt();rm();ro=class{get isDisposed(){return this._isDisposed}constructor(e,t,i,r=0,s=!1,a=!1,o=!1,l,c){this._isAlreadyOwned=!1,this._isDisposed=!1,e&&e.getScene?this._engine=e.getScene().getEngine():this._engine=e,this._updatable=i,this._instanced=a,this._divisor=l||1,this._label=c,t instanceof Dh?(this._data=null,this._buffer=t):(this._data=t,this._buffer=null),this.byteStride=o?r:r*Float32Array.BYTES_PER_ELEMENT,s||this.create()}createVertexBuffer(e,t,i,r,s,a=!1,o){let l=a?t:t*Float32Array.BYTES_PER_ELEMENT,c=r?a?r:r*Float32Array.BYTES_PER_ELEMENT:this.byteStride;return new L(this._engine,this,e,this._updatable,!0,c,s===void 0?this._instanced:s,l,i,void 0,void 0,!0,this._divisor||o)}isUpdatable(){return this._updatable}getData(){return this._data}getBuffer(){return this._buffer}getStrideSize(){return this.byteStride/Float32Array.BYTES_PER_ELEMENT}create(e=null){!e&&this._buffer||(e=e||this._data,e&&(this._buffer?this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e),this._data=e):this._updatable?(this._buffer=this._engine.createDynamicVertexBuffer(e,this._label),this._data=e):this._buffer=this._engine.createVertexBuffer(e,void 0,this._label)))}_rebuild(){if(this._data)this._buffer=null,this.create(this._data);else{if(!this._buffer)return;if(this._buffer.capacity>0){this._updatable?this._buffer=this._engine.createDynamicVertexBuffer(this._buffer.capacity,this._label):this._buffer=this._engine.createVertexBuffer(this._buffer.capacity,void 0,this._label);return}te.Warn(`Missing data for buffer "${this._label}" ${this._buffer?"(uniqueId: "+this._buffer.uniqueId+")":""}. Buffer reconstruction failed.`),this._buffer=null}}update(e){this.create(e)}updateDirectly(e,t,i,r=!1){this._buffer&&this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e,r?t:t*Float32Array.BYTES_PER_ELEMENT,i?i*this.byteStride:void 0),t===0&&i===void 0?this._data=e:this._data=null)}_increaseReferences(){if(this._buffer){if(!this._isAlreadyOwned){this._isAlreadyOwned=!0;return}this._buffer.references++}}dispose(){this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._isDisposed=!0,this._data=null,this._buffer=null)}},L=class n{get isDisposed(){return this._isDisposed}get instanceDivisor(){return this._instanceDivisor}set instanceDivisor(e){let t=e!=0;this._instanceDivisor=e,t!==this._instanced&&(this._instanced=t,this._computeHashCode())}get _maxVerticesCount(){let e=this.getData();return e?Array.isArray(e)?e.length/(this.byteStride/4)-this.byteOffset/4:(e.byteLength-this.byteOffset)/this.byteStride:0}constructor(e,t,i,r,s,a,o,l,c,f,h=!1,d=!1,u=1,m=!1){var g,v,x,A,S;this._isDisposed=!1;let p;if(this.engine=e,typeof r=="object"&&r!==null?(p=(g=r.updatable)!=null?g:!1,s=r.postponeInternalCreation,a=r.stride,o=r.instanced,l=r.offset,c=r.size,f=r.type,h=(v=r.normalized)!=null?v:!1,d=(x=r.useBytes)!=null?x:!1,u=(A=r.divisor)!=null?A:1,m=(S=r.takeBufferOwnership)!=null?S:!1,this._label=r.label):p=!!r,t instanceof ro?(this._buffer=t,this._ownsBuffer=m):(this._buffer=new ro(e,t,p,a,s,o,d,u,this._label),this._ownsBuffer=!0),this.uniqueId=n._Counter++,this._kind=i,f===void 0){let E=this.getData();this.type=E?n.GetDataType(E):n.FLOAT}else this.type=f;let _=Jo(this.type);d?(this._size=c||(a?a/_:n.DeduceStride(i)),this.byteStride=a||this._buffer.byteStride||this._size*_,this.byteOffset=l||0):(this._size=c||a||n.DeduceStride(i),this.byteStride=a?a*_:this._buffer.byteStride||this._size*_,this.byteOffset=(l||0)*_),this.normalized=h,this._instanced=o!==void 0?o:!1,this._instanceDivisor=o?u:0,this._alignBuffer(),this._computeHashCode()}_computeHashCode(){this.hashCode=(this.type-5120<<0)+((this.normalized?1:0)<<3)+(this._size<<4)+((this._instanced?1:0)<<6)+(this.byteStride<<12)}_rebuild(){var e;(e=this._buffer)==null||e._rebuild()}getKind(){return this._kind}isUpdatable(){return this._buffer.isUpdatable()}getData(){return this._buffer.getData()}getFloatData(e,t){let i=this.getData();return i?VM(i,this._size,this.type,this.byteOffset,this.byteStride,this.normalized,e,t):null}getBuffer(){return this._buffer.getBuffer()}getWrapperBuffer(){return this._buffer}getStrideSize(){return this.byteStride/Jo(this.type)}getOffset(){return this.byteOffset/Jo(this.type)}getSize(e=!1){return e?this._size*Jo(this.type):this._size}getIsInstanced(){return this._instanced}getInstanceDivisor(){return this._instanceDivisor}create(e){this._buffer.create(e),this._alignBuffer()}update(e){this._buffer.update(e),this._alignBuffer()}updateDirectly(e,t,i=!1){this._buffer.updateDirectly(e,t,void 0,i),this._alignBuffer()}dispose(){this._ownsBuffer&&this._buffer.dispose(),this._isDisposed=!0}forEach(e,t){Uh(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,(i,r)=>{for(let s=0;s{for(let h=0;h{ki();di();Xl=class{constructor(e){this._vertexBuffers={},this._activePostProcesses=[],this.onBeforeRenderObservable=new ie,this._scene=e}_prepareBuffers(){if(this._vertexBuffers[L.PositionKind])return;let e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[L.PositionKind]=new L(this._scene.getEngine(),e,L.PositionKind,!1,!1,2),this._buildIndexBuffer()}_buildIndexBuffer(){let e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(e)}_getActivePostProcesses(e){let t=this._activePostProcesses;t.length=0;for(let i=0;i{Pt();K2=(n,e,t)=>!n||n.getClassName&&n.getClassName()==="Mesh"?null:n.getClassName&&(n.getClassName()==="SubMesh"||n.getClassName()==="PhysicsBody")?n.clone(e):n.clone?n.clone():Array.isArray(n)?n.slice():t&&typeof n=="object"?{...n}:null;tl=class{static DeepCopy(e,t,i,r,s=!1){let a=wre(e);for(let o of a){if(o[0]==="_"&&(!r||r.indexOf(o)===-1)||o.endsWith("Observable")||i&&i.indexOf(o)!==-1)continue;let l=e[o],c=typeof l;if(c!=="function")try{if(c==="object")if(l instanceof Uint8Array)t[o]=Uint8Array.from(l);else if(l instanceof Array){if(t[o]=[],l.length>0)if(typeof l[0]=="object")for(let f=0;f{di();ga();Pt();W_();wl();hn();Bh();Di();Wl();jo();WM();B_();$a();_e=class{static get BaseUrl(){return Gi.BaseUrl}static set BaseUrl(e){Gi.BaseUrl=e}static get CleanUrl(){return Gi.CleanUrl}static set CleanUrl(e){Gi.CleanUrl=e}static IsAbsoluteUrl(e){return e.indexOf("//")===0?!0:e.indexOf("://")===-1||e.indexOf(".")===-1||e.indexOf("/")===-1||e.indexOf(":")>e.indexOf("/")?!1:e.indexOf("://"){el(e,s=>{i(s)},void 0,void 0,t,(s,a)=>{r(a)})})}static GetAssetUrl(e){if(!e)return"";if(gt.AssetBaseUrl&&e.startsWith(gt._DefaultAssetsUrl)){let t=gt.AssetBaseUrl.endsWith("/")?gt.AssetBaseUrl.slice(0,-1):gt.AssetBaseUrl;return e.replace(gt._DefaultAssetsUrl,t)}return e}static GetBabylonScriptURL(e,t){if(!e)return"";if(e.startsWith(gt._DefaultCdnUrl)){if(gt.ScriptBaseUrl){let i=gt.ScriptBaseUrl.endsWith("/")?gt.ScriptBaseUrl.slice(0,-1):gt.ScriptBaseUrl;e=e.replace(gt._DefaultCdnUrl,i)}else if(gt._CdnVersion){let i=`${gt._DefaultCdnUrl}/v${gt._CdnVersion}`;e.startsWith(i)||(e=e.replace(gt._DefaultCdnUrl,i))}}return e=gt.ScriptPreprocessUrl(e),t&&!gt.IsAbsoluteUrl(e)&&(e=gt.GetAbsoluteUrl(e)),e}static LoadBabylonScript(e,t,i,r){e=gt.GetBabylonScriptURL(e),gt.LoadScript(e,t,i)}static async LoadBabylonScriptAsync(e){return e=gt.GetBabylonScriptURL(e),await gt.LoadScriptAsync(e)}static _LoadScriptNative(e,t,i){let r=new Error(`[AI3D] Babylon script loading is disabled in this plugin build. Refused script URL: ${e}`);i==null||i(r.message,r)}static _LoadScriptWeb(e,t,i,r,s=!1){let a=new Error(`[AI3D] Babylon script loading is disabled in this plugin build. Refused script URL: ${e}`);i==null||i(a.message,a)}static async LoadScriptAsync(e,t){return await new Promise((i,r)=>{this.LoadScript(e,()=>{i()},(s,a)=>{r(a||new Error(s))},t)})}static ReadFileAsDataURL(e,t,i){let r=new FileReader,s={onCompleteObservable:new ie,abort:()=>r.abort()};return r.onloadend=()=>{s.onCompleteObservable.notifyObservers(s)},r.onload=a=>{t(a.target.result)},r.onprogress=i,r.readAsDataURL(e),s}static ReadFile(e,t,i,r,s){return Vh(e,t,i,r,s)}static FileAsURL(e){let t=new Blob([e]);return window.URL.createObjectURL(t)}static Format(e,t=2){return e.toFixed(t)}static DeepCopy(e,t,i,r){tl.DeepCopy(e,t,i,r)}static IsEmpty(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}static RegisterTopRootEvents(e,t){for(let i=0;i{let l=atob(this.toDataURL(a,o).split(",")[1]),c=l.length,f=new Uint8Array(c);for(let h=0;ht(s)):e.toBlob(function(s){t(s)},i,r)}static DownloadBlob(e,t){if("download"in document.createElement("a")){if(!t){let i=new Date;t="screenshot_"+((i.getFullYear()+"-"+(i.getMonth()+1)).slice(2)+"-"+i.getDate()+"_"+i.getHours()+"-"+("0"+i.getMinutes()).slice(-2))+".png"}gt.Download(e,t)}else if(e&&typeof URL!="undefined"){let i=URL.createObjectURL(e),r=window.open("");if(!r)return;let s=r.document.createElement("img");s.onload=function(){URL.revokeObjectURL(i)},s.src=i,r.document.body.appendChild(s)}}static EncodeScreenshotCanvasData(e,t,i="image/png",r,s){if(typeof r=="string"||!t)this.ToBlob(e,function(a){a&>.DownloadBlob(a,r),t&&t("")},i,s);else if(t){if(gt._IsOffScreenCanvas(e)){e.convertToBlob({type:i,quality:s}).then(o=>{let l=new FileReader;l.readAsDataURL(o),l.onloadend=()=>{let c=l.result;t(c)}});return}let a=e.toDataURL(i,s);t(a)}}static Download(e,t){if(typeof URL=="undefined")return;let i=window.URL.createObjectURL(e),r=document.createElement("a");document.body.appendChild(r),r.style.display="none",r.href=i,r.download=t,r.addEventListener("click",()=>{r.parentElement&&r.parentElement.removeChild(r)}),r.click(),window.URL.revokeObjectURL(i)}static BackCompatCameraNoPreventDefault(e){return typeof e[0]=="boolean"?e[0]:typeof e[1]=="boolean"?e[1]:!1}static CreateScreenshot(e,t,i,r,s="image/png",a=!1,o){throw qe("ScreenshotTools")}static async CreateScreenshotAsync(e,t,i,r="image/png",s){throw qe("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,r,s="image/png",a=1,o=!1,l,c=!1,f=!1,h=!0,d,u){throw qe("ScreenshotTools")}static async CreateScreenshotUsingRenderTargetAsync(e,t,i,r="image/png",s=1,a=!1,o,l=!1,c=!1,f=!0,h,d){throw qe("ScreenshotTools")}static RandomId(){return lf()}static IsBase64(e){return ff(e)}static DecodeBase64(e){return hf(e)}static get errorsCount(){return te.errorsCount}static Log(e){te.Log(e)}static Warn(e){te.Warn(e)}static Error(e){te.Error(e)}static get LogCache(){return te.LogCache}static ClearLogCache(){te.ClearLogCache()}static set LogLevels(e){te.LogLevels=e}static set PerformanceLogLevel(e){var t;if((e>.PerformanceUserMarkLogLevel)===gt.PerformanceUserMarkLogLevel){_native!=null&&_native.enablePerformanceLogging?(_native.enablePerformanceLogging(1),gt.StartPerformanceCounter=gt._StartMarkNative,gt.EndPerformanceCounter=gt._EndMarkNative):(gt.StartPerformanceCounter=gt._StartUserMark,gt.EndPerformanceCounter=gt._EndUserMark);return}if((e>.PerformanceConsoleLogLevel)===gt.PerformanceConsoleLogLevel){_native!=null&&_native.enablePerformanceLogging?(_native.enablePerformanceLogging(2),gt.StartPerformanceCounter=gt._StartMarkNative,gt.EndPerformanceCounter=gt._EndMarkNative):(gt.StartPerformanceCounter=gt._StartPerformanceConsole,gt.EndPerformanceCounter=gt._EndPerformanceConsole);return}gt.StartPerformanceCounter=gt._StartPerformanceCounterDisabled,gt.EndPerformanceCounter=gt._EndPerformanceCounterDisabled,(t=_native==null?void 0:_native.disablePerformanceLogging)==null||t.call(_native)}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!gt._Performance){if(!fr())return;gt._Performance=window.performance}!t||!gt._Performance.mark||gt._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){!t||!gt._Performance.mark||(gt._Performance.mark(e+"-End"),gt._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(gt._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(gt._EndUserMark(e,t),console.timeEnd(e))}static _StartMarkNative(e,t=!0){if(t&&(_native!=null&&_native.startPerformanceCounter))if(gt._NativePerformanceCounterHandles.has(e))gt.Warn(`Performance counter with name ${e} is already started.`);else{let i=_native.startPerformanceCounter(e);gt._NativePerformanceCounterHandles.set(e,i)}}static _EndMarkNative(e,t=!0){if(t&&(_native!=null&&_native.endPerformanceCounter)){let i=gt._NativePerformanceCounterHandles.get(e);i?(_native.endPerformanceCounter(i),gt._NativePerformanceCounterHandles.delete(e)):gt.Warn(`Performance counter with name ${e} was not started.`)}}static get Now(){return pr.Now}static GetClassName(e,t=!1){let i=null;return!t&&e.getClassName?i=e.getClassName():(e instanceof Object&&(i=(t?e:Object.getPrototypeOf(e)).constructor.__bjsclassName__),i||(i=typeof e)),i}static First(e,t){for(let i of e)if(t(i))return i;return null}static getFullClassName(e,t=!1){let i=null,r=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){let s=t?e:Object.getPrototypeOf(e);i=s.constructor.__bjsclassName__,r=s.constructor.__bjsmoduleName__}i||(i=typeof e)}return i?(r!=null?r+".":"")+i:null}static async DelayAsync(e){await new Promise(t=>{setTimeout(()=>{t()},e)})}static IsSafari(){return Nl()?/^((?!chrome|android).)*safari/i.test(navigator.userAgent):!1}};gt=_e;_e.AssetBaseUrl="";_e.UseCustomRequestHeaders=!1;_e.CustomRequestHeaders=Ir.CustomRequestHeaders;_e.GetDOMTextContent=sT;_e._DefaultCdnUrl="https://cdn.babylonjs.com";_e._CdnVersion="9.6.0";_e._DefaultAssetsUrl="https://assets.babylonjs.com/core";_e.LoadScript=typeof _native=="undefined"?gt._LoadScriptWeb:gt._LoadScriptNative;_e.GetAbsoluteUrl=typeof document=="object"?n=>{let e=document.createElement("a");return e.href=n,e.href}:typeof URL=="function"&&typeof location=="object"?n=>new URL(n,location.origin).href:()=>{throw new Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")};_e.NoneLogLevel=te.NoneLogLevel;_e.MessageLogLevel=te.MessageLogLevel;_e.WarningLogLevel=te.WarningLogLevel;_e.ErrorLogLevel=te.ErrorLogLevel;_e.AllLogLevel=te.AllLogLevel;_e.IsWindowObjectExist=fr;_e.PerformanceNoneLogLevel=0;_e.PerformanceUserMarkLogLevel=1;_e.PerformanceConsoleLogLevel=2;_e._NativePerformanceCounterHandles=new Map;_e.StartPerformanceCounter=gt._StartPerformanceCounterDisabled;_e.EndPerformanceCounter=gt._EndPerformanceCounterDisabled;ZT=class n{constructor(e,t,i,r=0){this.iterations=e,this.index=r-1,this._done=!1,this._fn=t,this._successCallback=i}executeNext(){this._done||(this.index+1{s&&s()?o.breakLoop():setTimeout(()=>{for(let l=0;l=e)break;if(i(c),s&&s()){o.breakLoop();break}}o.executeNext()},a)},r)}};_e.Mix=L_;_e.IsExponentOfTwo=Lh;Oe.FallbackTexture="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z"});var hr,mf=C(()=>{Pt();Ii();hr=class n{constructor(e,t,i=!1,r,s=!1,a){this._uniformNames=[],this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||s,this._dynamic=i,this._name=r!=null?r:"no-name",this._data=t||[],this._uniformLocations={},this._uniformSizes={},this._uniformArraySizes={},this._uniformLocationPointer=0,this._needSync=!1,this._trackUBOsInFrame=!1,(a===void 0&&this._engine._features.trackUbosInFrame||a===!0)&&(this._buffers=[],this._bufferIndex=-1,this._bufferUpdatedLastFrame=!1,this._createBufferOnWrite=!1,this._currentFrameId=0,this._trackUBOsInFrame=!0),this._noUBO?(this.updateMatrix3x3=this._updateMatrix3x3ForEffect,this.updateMatrix2x2=this._updateMatrix2x2ForEffect,this.updateFloat=this._updateFloatForEffect,this.updateFloat2=this._updateFloat2ForEffect,this.updateFloat3=this._updateFloat3ForEffect,this.updateFloat4=this._updateFloat4ForEffect,this.updateFloatArray=this._updateFloatArrayForEffect,this.updateArray=this._updateArrayForEffect,this.updateIntArray=this._updateIntArrayForEffect,this.updateUIntArray=this._updateUIntArrayForEffect,this.updateMatrix=this._updateMatrixForEffect,this.updateMatrices=this._updateMatricesForEffect,this.updateVector3=this._updateVector3ForEffect,this.updateVector4=this._updateVector4ForEffect,this.updateColor3=this._updateColor3ForEffect,this.updateColor4=this._updateColor4ForEffect,this.updateDirectColor4=this._updateDirectColor4ForEffect,this.updateInt=this._updateIntForEffect,this.updateInt2=this._updateInt2ForEffect,this.updateInt3=this._updateInt3ForEffect,this.updateInt4=this._updateInt4ForEffect,this.updateUInt=this._updateUIntForEffect,this.updateUInt2=this._updateUInt2ForEffect,this.updateUInt3=this._updateUInt3ForEffect,this.updateUInt4=this._updateUInt4ForEffect):(this._engine._uniformBuffers.push(this),this.updateMatrix3x3=this._updateMatrix3x3ForUniform,this.updateMatrix2x2=this._updateMatrix2x2ForUniform,this.updateFloat=this._updateFloatForUniform,this.updateFloat2=this._updateFloat2ForUniform,this.updateFloat3=this._updateFloat3ForUniform,this.updateFloat4=this._updateFloat4ForUniform,this.updateFloatArray=this._updateFloatArrayForUniform,this.updateArray=this._updateArrayForUniform,this.updateIntArray=this._updateIntArrayForUniform,this.updateUIntArray=this._updateUIntArrayForUniform,this.updateMatrix=this._updateMatrixForUniform,this.updateMatrices=this._updateMatricesForUniform,this.updateVector3=this._updateVector3ForUniform,this.updateVector4=this._updateVector4ForUniform,this.updateColor3=this._updateColor3ForUniform,this.updateColor4=this._updateColor4ForUniform,this.updateDirectColor4=this._updateDirectColor4ForUniform,this.updateInt=this._updateIntForUniform,this.updateInt2=this._updateInt2ForUniform,this.updateInt3=this._updateInt3ForUniform,this.updateInt4=this._updateInt4ForUniform,this.updateUInt=this._updateUIntForUniform,this.updateUInt2=this._updateUInt2ForUniform,this.updateUInt3=this._updateUInt3ForUniform,this.updateUInt4=this._updateUInt4ForUniform)}get useUbo(){return!this._noUBO}get isSync(){return!this._needSync}isDynamic(){return this._dynamic}getData(){return this._bufferData}getBuffer(){return this._buffer}getUniformNames(){return this._uniformNames}_fillAlignment(e){let t;if(e<=2?t=e:t=4,this._uniformLocationPointer%t!==0){let i=this._uniformLocationPointer;this._uniformLocationPointer+=t-this._uniformLocationPointer%t;let r=this._uniformLocationPointer-i;for(let s=0;s0&&typeof t=="number"&&(this._uniformArraySizes[e]={strideSize:t,arraySize:i}),this._uniformLocations[e]!==void 0||(this._uniformNames.push(e),this._noUBO))return;let r;if(i>0){if(t instanceof Array)throw"addUniform should not be use with Array in UBO: "+e;if(this._fillAlignment(4),t==16)t=t*i;else{let a=(4-t)*i;t=t*i+a}r=[];for(let s=0;s1&&this._buffers[this._bufferIndex][1])if(this._buffersEqual(this._bufferData,this._buffers[this._bufferIndex][1])){this._needSync=!1,this._createBufferOnWrite=this._trackUBOsInFrame;return}else this._copyBuffer(this._bufferData,this._buffers[this._bufferIndex][1]);this._bufferUpdatedLastFrame=!0,this._engine.updateUniformBuffer(this._buffer,this._bufferData),this._needSync=!1,this._createBufferOnWrite=this._trackUBOsInFrame}}_createNewBuffer(){this._bufferIndex+10?(this._buffers.length===1?this._needSync=!this._bufferUpdatedLastFrame:this._needSync=this._bufferIndex!==0,this._bufferIndex=0,this._buffer=this._buffers[this._bufferIndex][0]):this._bufferIndex=-1)}updateUniform(e,t,i){this._checkNewFrame();let r=this._uniformLocations[e];if(r===void 0){if(this._buffer){te.Error("Cannot add an uniform after UBO has been created. uniformName="+e);return}this.addUniform(e,i),r=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let s=0;s1&&this._buffers[t][1]&&this._bufferData.set(this._buffers[t][1]),this._valueCache={},this._currentFrameId=this._engine.frameId,!0;return!1}has(e){return this._uniformLocations[e]!==void 0}dispose(){if(this._noUBO)return;let e=this._engine._uniformBuffers,t=e.indexOf(this);if(t!==-1&&(e[t]=e[e.length-1],e.pop()),this._trackUBOsInFrame&&this._buffers)for(let i=0;i{Bi=class n{constructor(e){this.length=0,this.data=new Array(e),this._id=n._GlobalId++}push(e){this.data[this.length++]=e,this.length>this.data.length&&(this.data.length*=2)}forEach(e){for(let t=0;tthis.data.length&&(this.data.length=(this.length+e.length)*2);for(let t=0;t=this.length?-1:t}contains(e){return this.indexOf(e)!==-1}};Bi._GlobalId=0;no=class extends Bi{constructor(){super(...arguments),this._duplicateId=0}push(e){super.push(e),e.__smartArrayFlags||(e.__smartArrayFlags={}),e.__smartArrayFlags[this._id]=this._duplicateId}pushNoDuplicate(e){return e.__smartArrayFlags&&e.__smartArrayFlags[this._id]===this._duplicateId?!1:(this.push(e),!0)}reset(){super.reset(),this._duplicateId++}concatWithNoDuplicate(e){if(e.length!==0){this.length+e.length>this.data.length&&(this.data.length=(this.length+e.length)*2);for(let t=0;t{so();Ge();H_=class n{set opaqueSortCompareFn(e){e?this._opaqueSortCompareFn=e:this._opaqueSortCompareFn=n.PainterSortCompare,this._renderOpaque=this._renderOpaqueSorted}set alphaTestSortCompareFn(e){e?this._alphaTestSortCompareFn=e:this._alphaTestSortCompareFn=n.PainterSortCompare,this._renderAlphaTest=this._renderAlphaTestSorted}set transparentSortCompareFn(e){e?this._transparentSortCompareFn=e:this._transparentSortCompareFn=n.defaultTransparentSortCompare,this._renderTransparent=this._renderTransparentSorted}constructor(e,t,i=null,r=null,s=null){this.index=e,this._opaqueSubMeshes=new Bi(256),this._transparentSubMeshes=new Bi(256),this._alphaTestSubMeshes=new Bi(256),this._depthOnlySubMeshes=new Bi(256),this._particleSystems=new Bi(256),this._spriteManagers=new Bi(256),this._empty=!0,this._edgesRenderers=new no(16),this.disableDepthPrePass=!1,this._scene=t,this.opaqueSortCompareFn=i,this.alphaTestSortCompareFn=r,this.transparentSortCompareFn=s}render(e,t,i,r,s=!0,a=!0,o=!0,l=!0,c){if(e){e(this._opaqueSubMeshes,this._alphaTestSubMeshes,this._transparentSubMeshes,this._depthOnlySubMeshes);return}let f=this._scene.getEngine();s&&this._depthOnlySubMeshes.length!==0&&(f.setColorWrite(!1),this._renderAlphaTest(this._depthOnlySubMeshes),f.setColorWrite(!0)),a&&this._opaqueSubMeshes.length!==0&&this._renderOpaque(this._opaqueSubMeshes),o&&this._alphaTestSubMeshes.length!==0&&this._renderAlphaTest(this._alphaTestSubMeshes);let h=f.getStencilBuffer();if(f.setStencilBuffer(!1),t&&this._renderSprites(),i&&this._renderParticles(r),this.onBeforeTransparentRendering&&this.onBeforeTransparentRendering(),l&&(c||this._transparentSubMeshes.length!==0||this._scene.useOrderIndependentTransparency)){if(f.setStencilBuffer(h),c)c(this._transparentSubMeshes,this);else if(this._scene.useOrderIndependentTransparency){let d=this._scene.depthPeelingRenderer.render(this._transparentSubMeshes);d.length&&this._renderTransparent(d)}else this._renderTransparent(this._transparentSubMeshes);f.setAlphaMode(0)}if(f.setStencilBuffer(!1),a&&this._edgesRenderers.length){for(let d=0;dt._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0}static frontToBackSortCompare(e,t){return e._distanceToCamerat._distanceToCamera?1:0}static PainterSortCompare(e,t){let i=e.getMesh(),r=t.getMesh();return i.material&&r.material?i.material.uniqueId-r.material.uniqueId:i.uniqueId-r.uniqueId}prepare(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset(),this._depthOnlySubMeshes.reset(),this._particleSystems.reset(),this.prepareSprites(),this._edgesRenderers.reset(),this._empty=!0}prepareSprites(){this._spriteManagers.reset()}dispose(){this._opaqueSubMeshes.dispose(),this._transparentSubMeshes.dispose(),this._alphaTestSubMeshes.dispose(),this._depthOnlySubMeshes.dispose(),this._particleSystems.dispose(),this._spriteManagers.dispose(),this._edgesRenderers.dispose()}dispatch(e,t,i){t===void 0&&(t=e.getMesh()),i===void 0&&(i=e.getMaterial()),i!=null&&(i.needAlphaBlendingForMesh(t)?this._transparentSubMeshes.push(e):i.needAlphaTestingForMesh(t)?(i.needDepthPrePass&&!this.disableDepthPrePass&&this._depthOnlySubMeshes.push(e),this._alphaTestSubMeshes.push(e)):(i.needDepthPrePass&&!this.disableDepthPrePass&&this._depthOnlySubMeshes.push(e),this._opaqueSubMeshes.push(e)),t._renderingGroup=this,t._edgesRenderer&&t.isEnabled()&&t.isVisible&&t._edgesRenderer.isEnabled&&this._edgesRenderers.pushNoDuplicate(t._edgesRenderer),this._empty=!1)}dispatchSprites(e){this._spriteManagers.push(e),this._empty=!1}dispatchParticles(e){this._particleSystems.push(e),this._empty=!1}_renderParticles(e){if(this._particleSystems.length===0)return;let t=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(let i=0;i{j2();HM=class{},Sa=class n{get disableDepthPrePass(){return this._disableDepthPrePass}set disableDepthPrePass(e){this._disableDepthPrePass=e;for(let t of this._renderingGroups)t.disableDepthPrePass=e}get maintainStateBetweenFrames(){return this._maintainStateBetweenFrames}set maintainStateBetweenFrames(e){e!==this._maintainStateBetweenFrames&&(this._maintainStateBetweenFrames=e,this._maintainStateBetweenFrames||this.restoreDispachedFlags())}restoreDispachedFlags(){for(let e of this._scene.meshes)if(e.subMeshes)for(let t of e.subMeshes)t._wasDispatched=!1;if(this._scene.spriteManagers)for(let e of this._scene.spriteManagers)e._wasDispatched=!1;for(let e of this._scene.particleSystems)e._wasDispatched=!1}constructor(e){this._useSceneAutoClearSetup=!1,this._disableDepthPrePass=!1,this._renderingGroups=new Array,this._autoClearDepthStencil={},this._customOpaqueSortCompareFn={},this._customAlphaTestSortCompareFn={},this._customTransparentSortCompareFn={},this._renderingGroupInfo=new HM,this._maintainStateBetweenFrames=!1,this._scene=e;for(let t=n.MIN_RENDERINGGROUPS;t{Yt=class{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}};Yt.FALLOFF_DEFAULT=0;Yt.FALLOFF_PHYSICAL=1;Yt.FALLOFF_GLTF=2;Yt.FALLOFF_STANDARD=3;Yt.LIGHTMAP_DEFAULT=0;Yt.LIGHTMAP_SPECULAR=1;Yt.LIGHTMAP_SHADOWSONLY=2;Yt.INTENSITYMODE_AUTOMATIC=0;Yt.INTENSITYMODE_LUMINOUSPOWER=1;Yt.INTENSITYMODE_LUMINOUSINTENSITY=2;Yt.INTENSITYMODE_ILLUMINANCE=3;Yt.INTENSITYMODE_LUMINANCE=4;Yt.LIGHTTYPEID_POINTLIGHT=0;Yt.LIGHTTYPEID_DIRECTIONALLIGHT=1;Yt.LIGHTTYPEID_SPOTLIGHT=2;Yt.LIGHTTYPEID_HEMISPHERICLIGHT=3;Yt.LIGHTTYPEID_RECT_AREALIGHT=4;Yt.LIGHTTYPEID_CLUSTERED_CONTAINER=5});var Ta,zM=C(()=>{mf();di();QT();Zo();jo();Pt();so();z_();Ta=class n{get renderList(){return this._renderList}set renderList(e){this._renderList!==e&&(this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=NT(e,this._renderListHasChanged)),this._renderList=e)}get disableImageProcessing(){return this._disableImageProcessing}set disableImageProcessing(e){e!==this._disableImageProcessing&&(this._disableImageProcessing=e,this._scene.markAllMaterialsAsDirty(64))}get disableDepthPrePass(){return this._disableDepthPrePass}set disableDepthPrePass(e){this._disableDepthPrePass=e,this._renderingManager.disableDepthPrePass=e}get name(){return this._name}set name(e){if(this._name!==e){if(this._name=e,this._sceneUBOs)for(let t=0;tthis._checkReadiness(),()=>{if(this._freezeActiveMeshesCancel=null,e)for(let t=0;t{this._freezeActiveMeshesCancel=null,i?(te.Error("ObjectRenderer: Timeout while waiting for the renderer to be ready."),t&&te.Error(t)):(te.Error("ObjectRenderer: An unexpected error occurred while waiting for the renderer to be ready."),t&&(te.Error(t),t.stack&&te.Error(t.stack)))})}_unfreezeActiveMeshes(){var e;(e=this._freezeActiveMeshesCancel)==null||e.call(this),this._freezeActiveMeshesCancel=null;for(let t=0;t{let a=this._renderList?this._renderList.length:0;if(s===0&&a>0||a===0)for(let o of this._scene.meshes)o._markSubMeshesAsLightDirty()},this.particleSystemList=null,this.getCustomRenderList=null,this.renderMeshes=!0,this.renderDepthOnlyMeshes=!0,this.renderOpaqueMeshes=!0,this.renderAlphaTestMeshes=!0,this.renderTransparentMeshes=!0,this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.enableBoundingBoxRendering=!1,this.enableOutlineRendering=!0,this._disableImageProcessing=!1,this.dontSetTransformationMatrix=!1,this._disableDepthPrePass=!1,this.onBeforeRenderObservable=new ie,this.onAfterRenderObservable=new ie,this.onBeforeRenderingManagerRenderObservable=new ie,this.onAfterRenderingManagerRenderObservable=new ie,this.onInitRenderingObservable=new ie,this.onFinishRenderingObservable=new ie,this.onFastPathRenderObservable=new ie,this._currentRefreshId=-1,this._refreshRate=1,this._currentApplyByPostProcessSetting=!1,this._activeMeshes=new Bi(256),this._activeBoundingBoxes=new Bi(32),this._currentFrameId=-1,this._currentSceneUBOIndex=0,this._isFrozen=!1,this._freezeActiveMeshesCancel=null,this._currentSceneCamera=null,this.name=e,this._scene=t,this._engine=this._scene.getEngine(),this._useUBO=this._engine.supportsUniformBuffers,this.renderList=[],this._renderPassIds=[],this.options={numPasses:1,doNotChangeAspectRatio:!0,enableClusteredLights:!1,...i},this._createRenderPassId(),this.renderPassId=this._renderPassIds[0],this._renderingManager=new Sa(t),this._renderingManager._useSceneAutoClearSetup=!0,this.options.enableClusteredLights&&this.onInitRenderingObservable.add(()=>{for(let r of this._scene.lights)r.getTypeID()===Yt.LIGHTTYPEID_CLUSTERED_CONTAINER&&r.isSupported&&r._updateBatches(this.activeCamera).render()}),this._scene.addObjectRenderer(this)}_releaseRenderPassId(){for(let e=0;e=this._sceneUBOs.length){let s=this._sceneUBOs.length;this._sceneUBOs.push(this._createSceneUBO(`Scene ubo #${s} for ${this.name}`,t)),this._sceneUBOIsMultiview.push(t)}else this._sceneUBOIsMultiview[this._currentSceneUBOIndex]!==t&&(this._sceneUBOs[this._currentSceneUBOIndex].dispose(),this._sceneUBOs[this._currentSceneUBOIndex]=this._createSceneUBO(`Scene ubo #${this._currentSceneUBOIndex} for ${this.name}`,t),this._sceneUBOIsMultiview[this._currentSceneUBOIndex]=t);let i=this._sceneUBOs[this._currentSceneUBOIndex++];return i.unbindEffect(),i}resetRefreshCounter(){this._currentRefreshId=-1}get refreshRate(){return this._refreshRate}set refreshRate(e){this._refreshRate=e,this.resetRefreshCounter()}shouldRender(){return this._engine.snapshotRendering?!0:this._currentRefreshId===-1?(this._currentRefreshId=1,!0):this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)}isReadyForRendering(e,t){this.prepareRenderList(),this.initRender(e,t);let i=this._checkReadiness();return this.finishRender(),i}prepareRenderList(){let e=this._scene;if(this._waitingRenderList){if(!this.renderListPredicate){this.renderList=[];for(let t=0;t1&&(e.incrementRenderId(),e.resetCachedMaterial())}let s=this.particleSystemList||e.particleSystems;for(let a of s)a.isReady()||(i=!1);return this._engine.currentRenderPassId=t,i}_prepareRenderingManager(e=0,t=!1){var d,u;let i=this._scene,r=null,s,a,o=this.renderList?this.renderList:i.frameGraph?i.meshes:i.getActiveMeshes().data,l=this.renderList||i.frameGraph?o.length:i.getActiveMeshes().length;if(this.getCustomRenderList&&(r=this.getCustomRenderList(e,o,l)),r)s=r.length,a=this.forceLayerMaskCheck;else{if(this._defaultRenderListPrepared&&!t&&!this._engine.isWebGPU)return o;this._defaultRenderListPrepared=!0,r=o,s=l,a=!this.renderList||this.forceLayerMaskCheck}let c=i.activeCamera,f=(d=this.cameraForLOD)!=null?d:c,h=(u=i.getBoundingBoxRenderer)==null?void 0:u.call(i);if(i._activeMeshesFrozen&&this._isFrozen){if(this._renderingManager.resetSprites(),this.enableBoundingBoxRendering&&h){h.reset();for(let m=0;m{jo();$n=class{static GetEffect(e){return e.getPipelineContext===void 0?e.effect:e}constructor(e,t=!0){this._wasPreviouslyReady=!1,this._forceRebindOnNextCall=!0,this._wasPreviouslyUsingInstances=null,this.effect=null,this.defines=null,this.drawContext=e.createDrawContext(),t&&(this.materialContext=e.createMaterialContext())}setEffect(e,t,i=!0){var r;this.effect=e,t!==void 0&&(this.defines=t),i&&((r=this.drawContext)==null||r.reset())}dispose(e=!1){var t;if(this.effect){let i=this.effect;e?i.dispose():Qa.SetImmediate(()=>{i.getEngine().onEndFrameObservable.addOnce(()=>{i.dispose()})}),this.effect=null}(t=this.drawContext)==null||t.dispose()}}});var Z2={};tt(Z2,{postprocessVertexShader:()=>Fre});var XM,q2,Fre,YM=C(()=>{k();XM="postprocessVertexShader",q2=`attribute vec2 position;uniform vec2 scale;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN vUV=(position*madd+madd)*scale;gl_Position=vec4(position,0.0,1.0); #define CUSTOM_VERTEX_MAIN_END -}`;T.ShadersStore[XM]||(T.ShadersStore[XM]=q2);Fre={name:XM,shader:q2}});var $2={};tt($2,{postprocessVertexShaderWGSL:()=>Bre});var KM,Q2,Bre,jM=C(()=>{W();KM="postprocessVertexShader",Q2=`attribute position: vec2;uniform scale: vec2;varying vUV: vec2;const madd=vec2(0.5,0.5); +}`;T.ShadersStore[XM]||(T.ShadersStore[XM]=q2);Fre={name:XM,shader:q2}});var $2={};tt($2,{postprocessVertexShaderWGSL:()=>Bre});var KM,Q2,Bre,jM=C(()=>{k();KM="postprocessVertexShader",Q2=`attribute position: vec2;uniform scale: vec2;varying vUV: vec2;const madd=vec2(0.5,0.5); #define CUSTOM_VERTEX_DEFINITIONS @vertex fn main(input : VertexInputs)->FragmentInputs { @@ -4155,16 +4155,16 @@ fn main(input : VertexInputs)->FragmentInputs { vertexOutputs.vUV=(vertexInputs.position*madd+madd)*uniforms.scale;vertexOutputs.position=vec4(vertexInputs.position,0.0,1.0); #define CUSTOM_VERTEX_MAIN_END } -`;T.ShadersStoreWGSL[KM]||(T.ShadersStoreWGSL[KM]=Q2);Bre={name:KM,shader:Q2}});var qM,QT,zr,kh=C(()=>{Gi();Ju();hi();yh();Gh();YM();jM();qM={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]},QT=class{constructor(e,t=qM){var s,a;this._fullscreenViewport=new io(0,0,1,1);let i=(s=t.positions)!=null?s:qM.positions,r=(a=t.indices)!=null?a:qM.indices;this.engine=e,this._vertexBuffers={[L.PositionKind]:new L(e,i,L.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(r),this._indexBufferLength=r.length,this._onContextRestoredObserver=e.onContextRestoredObservable.add(()=>{this._indexBuffer=e.createIndexBuffer(r);for(let o in this._vertexBuffers)this._vertexBuffers[o]._rebuild()})}setViewport(e=this._fullscreenViewport){this.engine.setViewport(e)}bindBuffers(e){this.engine.bindBuffers(this._vertexBuffers,this._indexBuffer,e)}applyEffectWrapper(e,t=!1,i=!1){this.engine.setState(!0),this.engine.depthCullingState.depthTest=t,this.engine.stencilState.stencilTest=i,this.engine.enableEffect(e.drawWrapper),this.bindBuffers(e.effect),e.onApplyObservable.notifyObservers({})}saveStates(){this._savedStateDepthTest=this.engine.depthCullingState.depthTest,this._savedStateStencilTest=this.engine.stencilState.stencilTest}restoreStates(){this.engine.depthCullingState.depthTest=this._savedStateDepthTest,this.engine.stencilState.stencilTest=this._savedStateStencilTest}draw(){this.engine.drawElementsType(0,0,this._indexBufferLength)}_isRenderTargetTexture(e){return e.renderTarget!==void 0}render(e,t=null){if(!e.effect.isReady())return;this.saveStates(),this.setViewport();let i=t===null?null:this._isRenderTargetTexture(t)?t.renderTarget:t;i&&this.engine.bindFramebuffer(i),this.applyEffectWrapper(e),this.draw(),i&&this.engine.unBindFramebuffer(i),this.restoreStates()}dispose(){let e=this._vertexBuffers[L.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[L.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}},zr=class n{static RegisterShaderCodeProcessing(e,t){if(!t){delete n._CustomShaderCodeProcessing[e!=null?e:""];return}n._CustomShaderCodeProcessing[e!=null?e:""]=t}static _GetShaderCodeProcessing(e){var t;return(t=n._CustomShaderCodeProcessing[e])!=null?t:n._CustomShaderCodeProcessing[""]}get name(){return this.options.name}set name(e){this.options.name=e}isReady(){var e,t;return(t=(e=this._drawWrapper.effect)==null?void 0:e.isReady())!=null?t:!1}get drawWrapper(){return this._drawWrapper}get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){var i,r;this.alphaMode=0,this.onEffectCreatedObservable=new ie(void 0,!0),this.onApplyObservable=new ie,this._shadersLoaded=!1,this._webGPUReady=!1,this._importPromises=[],this.options={...e,name:e.name||"effectWrapper",engine:e.engine,uniforms:e.uniforms||e.uniformNames||[],uniformNames:void 0,samplers:e.samplers||e.samplerNames||[],samplerNames:void 0,attributeNames:e.attributeNames||["position"],uniformBuffers:e.uniformBuffers||[],defines:e.defines||"",useShaderStore:e.useShaderStore||!1,vertexUrl:e.vertexUrl||e.vertexShader||"postprocess",vertexShader:void 0,fragmentShader:e.fragmentShader||"pass",indexParameters:e.indexParameters,blockCompilation:e.blockCompilation||!1,shaderLanguage:e.shaderLanguage||0,onCompiled:e.onCompiled||void 0,extraInitializations:e.extraInitializations||void 0,extraInitializationsAsync:e.extraInitializationsAsync||void 0,useAsPostProcess:(i=e.useAsPostProcess)!=null?i:!1,allowEmptySourceTexture:(r=e.allowEmptySourceTexture)!=null?r:!1},this.options.uniformNames=this.options.uniforms,this.options.samplerNames=this.options.samplers,this.options.vertexShader=this.options.vertexUrl,this.options.useAsPostProcess&&(!this.options.allowEmptySourceTexture&&this.options.samplers.indexOf("textureSampler")===-1&&this.options.samplers.push("textureSampler"),this.options.uniforms.indexOf("scale")===-1&&this.options.uniforms.push("scale")),e.vertexUrl||e.vertexShader?this._shaderPath={vertexSource:this.options.vertexShader}:(this.options.useAsPostProcess||(this.options.uniforms.push("scale"),this.onApplyObservable.add(()=>{this.effect.setFloat2("scale",1,1)})),this._shaderPath={vertex:this.options.vertexShader}),this._shaderPath.fragmentSource=this.options.fragmentShader,this._shaderPath.spectorName=this.options.name,this.options.useShaderStore&&(this._shaderPath.fragment=this._shaderPath.fragmentSource,this._shaderPath.vertex||(this._shaderPath.vertex=this._shaderPath.vertexSource),delete this._shaderPath.fragmentSource,delete this._shaderPath.vertexSource),this.onApplyObservable.add(()=>{this.bind()}),this.options.useShaderStore||(this._onContextRestoredObserver=this.options.engine.onContextRestoredObservable.add(()=>{this.effect._pipelineContext=null,this.effect._prepareEffect()})),this._drawWrapper=new Jn(this.options.engine),this._webGPUReady=this.options.shaderLanguage===1;let t=Array.isArray(this.options.defines)?this.options.defines.join(` -`):this.options.defines;this._postConstructor(this.options.blockCompilation,t,this.options.extraInitializations)}_gatherImports(e=!1,t){}_postConstructor(e,t=null,i,r){this._importPromises.length=0,r&&this._importPromises.push(...r);let s=this.options.engine.isWebGPU&&!n.ForceGLSL;this._gatherImports(s,this._importPromises),i!==void 0&&i(s,this._importPromises),s&&this._webGPUReady&&(this.options.shaderLanguage=1),e||this.updateEffect(t)}updateEffect(e=null,t=null,i=null,r,s,a,o,l){var d,u;let c=n._GetShaderCodeProcessing(this.name);if(c!=null&&c.defineCustomBindings){let m=(d=t==null?void 0:t.slice())!=null?d:[];m.push(...this.options.uniforms);let p=(u=i==null?void 0:i.slice())!=null?u:[];p.push(...this.options.samplers),e=c.defineCustomBindings(this.name,e,m,p),t=m,i=p}this.options.defines=e||"";let f=this._shadersLoaded||this._importPromises.length===0?void 0:async()=>{await Promise.all(this._importPromises),this._shadersLoaded=!0},h;this.options.extraInitializationsAsync?h=async()=>{f==null||f(),await this.options.extraInitializationsAsync()}:h=f,this.options.useShaderStore?this._drawWrapper.effect=this.options.engine.createEffect({vertex:o!=null?o:this._shaderPath.vertex,fragment:l!=null?l:this._shaderPath.fragment},{attributes:this.options.attributeNames,uniformsNames:t||this.options.uniforms,uniformBuffersNames:this.options.uniformBuffers,samplers:i||this.options.samplers,defines:e!==null?e:"",fallbacks:null,onCompiled:s!=null?s:this.options.onCompiled,onError:a!=null?a:null,indexParameters:r||this.options.indexParameters,processCodeAfterIncludes:c!=null&&c.processCodeAfterIncludes?(m,p)=>c.processCodeAfterIncludes(this.name,m,p):null,processFinalCode:c!=null&&c.processFinalCode?(m,p)=>c.processFinalCode(this.name,m,p):null,shaderLanguage:this.options.shaderLanguage,extraInitializationsAsync:h},this.options.engine):this._drawWrapper.effect=new tr(this._shaderPath,this.options.attributeNames,t||this.options.uniforms,i||this.options.samplerNames,this.options.engine,e,void 0,s||this.options.onCompiled,void 0,void 0,void 0,this.options.shaderLanguage,h),this.onEffectCreatedObservable.notifyObservers(this._drawWrapper.effect)}bind(e=!1){var t,i;this.options.useAsPostProcess&&!e&&(this.options.engine.setAlphaMode(this.alphaMode),this.drawWrapper.effect.setFloat2("scale",1,1)),(i=(t=n._GetShaderCodeProcessing(this.name))==null?void 0:t.bindCustomBindings)==null||i.call(t,this.name,this._drawWrapper.effect)}dispose(e=!1){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),this.onEffectCreatedObservable.clear(),this._drawWrapper.dispose(!0)}};zr.ForceGLSL=!1;zr._CustomShaderCodeProcessing={}});var QM={};tt(QM,{passPixelShader:()=>Ure});var ZM,J2,Ure,$M=C(()=>{W();ZM="passPixelShader",J2=`varying vec2 vUV;uniform sampler2D textureSampler; +`;T.ShadersStoreWGSL[KM]||(T.ShadersStoreWGSL[KM]=Q2);Bre={name:KM,shader:Q2}});var qM,$T,zr,kh=C(()=>{ki();$u();di();yh();Gh();YM();jM();qM={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]},$T=class{constructor(e,t=qM){var s,a;this._fullscreenViewport=new io(0,0,1,1);let i=(s=t.positions)!=null?s:qM.positions,r=(a=t.indices)!=null?a:qM.indices;this.engine=e,this._vertexBuffers={[L.PositionKind]:new L(e,i,L.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(r),this._indexBufferLength=r.length,this._onContextRestoredObserver=e.onContextRestoredObservable.add(()=>{this._indexBuffer=e.createIndexBuffer(r);for(let o in this._vertexBuffers)this._vertexBuffers[o]._rebuild()})}setViewport(e=this._fullscreenViewport){this.engine.setViewport(e)}bindBuffers(e){this.engine.bindBuffers(this._vertexBuffers,this._indexBuffer,e)}applyEffectWrapper(e,t=!1,i=!1){this.engine.setState(!0),this.engine.depthCullingState.depthTest=t,this.engine.stencilState.stencilTest=i,this.engine.enableEffect(e.drawWrapper),this.bindBuffers(e.effect),e.onApplyObservable.notifyObservers({})}saveStates(){this._savedStateDepthTest=this.engine.depthCullingState.depthTest,this._savedStateStencilTest=this.engine.stencilState.stencilTest}restoreStates(){this.engine.depthCullingState.depthTest=this._savedStateDepthTest,this.engine.stencilState.stencilTest=this._savedStateStencilTest}draw(){this.engine.drawElementsType(0,0,this._indexBufferLength)}_isRenderTargetTexture(e){return e.renderTarget!==void 0}render(e,t=null){if(!e.effect.isReady())return;this.saveStates(),this.setViewport();let i=t===null?null:this._isRenderTargetTexture(t)?t.renderTarget:t;i&&this.engine.bindFramebuffer(i),this.applyEffectWrapper(e),this.draw(),i&&this.engine.unBindFramebuffer(i),this.restoreStates()}dispose(){let e=this._vertexBuffers[L.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[L.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}},zr=class n{static RegisterShaderCodeProcessing(e,t){if(!t){delete n._CustomShaderCodeProcessing[e!=null?e:""];return}n._CustomShaderCodeProcessing[e!=null?e:""]=t}static _GetShaderCodeProcessing(e){var t;return(t=n._CustomShaderCodeProcessing[e])!=null?t:n._CustomShaderCodeProcessing[""]}get name(){return this.options.name}set name(e){this.options.name=e}isReady(){var e,t;return(t=(e=this._drawWrapper.effect)==null?void 0:e.isReady())!=null?t:!1}get drawWrapper(){return this._drawWrapper}get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){var i,r;this.alphaMode=0,this.onEffectCreatedObservable=new ie(void 0,!0),this.onApplyObservable=new ie,this._shadersLoaded=!1,this._webGPUReady=!1,this._importPromises=[],this.options={...e,name:e.name||"effectWrapper",engine:e.engine,uniforms:e.uniforms||e.uniformNames||[],uniformNames:void 0,samplers:e.samplers||e.samplerNames||[],samplerNames:void 0,attributeNames:e.attributeNames||["position"],uniformBuffers:e.uniformBuffers||[],defines:e.defines||"",useShaderStore:e.useShaderStore||!1,vertexUrl:e.vertexUrl||e.vertexShader||"postprocess",vertexShader:void 0,fragmentShader:e.fragmentShader||"pass",indexParameters:e.indexParameters,blockCompilation:e.blockCompilation||!1,shaderLanguage:e.shaderLanguage||0,onCompiled:e.onCompiled||void 0,extraInitializations:e.extraInitializations||void 0,extraInitializationsAsync:e.extraInitializationsAsync||void 0,useAsPostProcess:(i=e.useAsPostProcess)!=null?i:!1,allowEmptySourceTexture:(r=e.allowEmptySourceTexture)!=null?r:!1},this.options.uniformNames=this.options.uniforms,this.options.samplerNames=this.options.samplers,this.options.vertexShader=this.options.vertexUrl,this.options.useAsPostProcess&&(!this.options.allowEmptySourceTexture&&this.options.samplers.indexOf("textureSampler")===-1&&this.options.samplers.push("textureSampler"),this.options.uniforms.indexOf("scale")===-1&&this.options.uniforms.push("scale")),e.vertexUrl||e.vertexShader?this._shaderPath={vertexSource:this.options.vertexShader}:(this.options.useAsPostProcess||(this.options.uniforms.push("scale"),this.onApplyObservable.add(()=>{this.effect.setFloat2("scale",1,1)})),this._shaderPath={vertex:this.options.vertexShader}),this._shaderPath.fragmentSource=this.options.fragmentShader,this._shaderPath.spectorName=this.options.name,this.options.useShaderStore&&(this._shaderPath.fragment=this._shaderPath.fragmentSource,this._shaderPath.vertex||(this._shaderPath.vertex=this._shaderPath.vertexSource),delete this._shaderPath.fragmentSource,delete this._shaderPath.vertexSource),this.onApplyObservable.add(()=>{this.bind()}),this.options.useShaderStore||(this._onContextRestoredObserver=this.options.engine.onContextRestoredObservable.add(()=>{this.effect._pipelineContext=null,this.effect._prepareEffect()})),this._drawWrapper=new $n(this.options.engine),this._webGPUReady=this.options.shaderLanguage===1;let t=Array.isArray(this.options.defines)?this.options.defines.join(` +`):this.options.defines;this._postConstructor(this.options.blockCompilation,t,this.options.extraInitializations)}_gatherImports(e=!1,t){}_postConstructor(e,t=null,i,r){this._importPromises.length=0,r&&this._importPromises.push(...r);let s=this.options.engine.isWebGPU&&!n.ForceGLSL;this._gatherImports(s,this._importPromises),i!==void 0&&i(s,this._importPromises),s&&this._webGPUReady&&(this.options.shaderLanguage=1),e||this.updateEffect(t)}updateEffect(e=null,t=null,i=null,r,s,a,o,l){var d,u;let c=n._GetShaderCodeProcessing(this.name);if(c!=null&&c.defineCustomBindings){let m=(d=t==null?void 0:t.slice())!=null?d:[];m.push(...this.options.uniforms);let p=(u=i==null?void 0:i.slice())!=null?u:[];p.push(...this.options.samplers),e=c.defineCustomBindings(this.name,e,m,p),t=m,i=p}this.options.defines=e||"";let f=this._shadersLoaded||this._importPromises.length===0?void 0:async()=>{await Promise.all(this._importPromises),this._shadersLoaded=!0},h;this.options.extraInitializationsAsync?h=async()=>{f==null||f(),await this.options.extraInitializationsAsync()}:h=f,this.options.useShaderStore?this._drawWrapper.effect=this.options.engine.createEffect({vertex:o!=null?o:this._shaderPath.vertex,fragment:l!=null?l:this._shaderPath.fragment},{attributes:this.options.attributeNames,uniformsNames:t||this.options.uniforms,uniformBuffersNames:this.options.uniformBuffers,samplers:i||this.options.samplers,defines:e!==null?e:"",fallbacks:null,onCompiled:s!=null?s:this.options.onCompiled,onError:a!=null?a:null,indexParameters:r||this.options.indexParameters,processCodeAfterIncludes:c!=null&&c.processCodeAfterIncludes?(m,p)=>c.processCodeAfterIncludes(this.name,m,p):null,processFinalCode:c!=null&&c.processFinalCode?(m,p)=>c.processFinalCode(this.name,m,p):null,shaderLanguage:this.options.shaderLanguage,extraInitializationsAsync:h},this.options.engine):this._drawWrapper.effect=new rr(this._shaderPath,this.options.attributeNames,t||this.options.uniforms,i||this.options.samplerNames,this.options.engine,e,void 0,s||this.options.onCompiled,void 0,void 0,void 0,this.options.shaderLanguage,h),this.onEffectCreatedObservable.notifyObservers(this._drawWrapper.effect)}bind(e=!1){var t,i;this.options.useAsPostProcess&&!e&&(this.options.engine.setAlphaMode(this.alphaMode),this.drawWrapper.effect.setFloat2("scale",1,1)),(i=(t=n._GetShaderCodeProcessing(this.name))==null?void 0:t.bindCustomBindings)==null||i.call(t,this.name,this._drawWrapper.effect)}dispose(e=!1){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),this.onEffectCreatedObservable.clear(),this._drawWrapper.dispose(!0)}};zr.ForceGLSL=!1;zr._CustomShaderCodeProcessing={}});var QM={};tt(QM,{passPixelShader:()=>Ure});var ZM,J2,Ure,$M=C(()=>{k();ZM="passPixelShader",J2=`varying vec2 vUV;uniform sampler2D textureSampler; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) -{gl_FragColor=texture2D(textureSampler,vUV);}`;T.ShadersStore[ZM]||(T.ShadersStore[ZM]=J2);Ure={name:ZM,shader:J2}});var eB={};tt(eB,{Dispose:()=>eC,DumpData:()=>$T,DumpDataAsync:()=>Y_,DumpFramebuffer:()=>JM,DumpTools:()=>Wre,EncodeImageAsync:()=>kre});async function Vre(){var o,l;let n=(l=(o=Le.LastCreatedEngine)==null?void 0:o.createCanvas(100,100))!=null?l:new OffscreenCanvas(100,100);n instanceof OffscreenCanvas&&te.Warn("DumpData: OffscreenCanvas will be used for dumping data. This may result in lossy alpha values.");let{ThinEngine:e}=await Promise.resolve().then(()=>(Qn(),Z3));if(!e.IsSupported)throw new Error("DumpData: No WebGL context available. Cannot dump data.");let t={preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1},i=new e(n,!1,t);Le.Instances.pop(),Le.OnEnginesDisposedObservable.add(c=>{i&&c!==i&&!i.isDisposed&&Le.Instances.length===0&&eC()}),i.getCaps().parallelShaderCompile=void 0;let r=new QT(i),{passPixelShader:s}=await Promise.resolve().then(()=>($M(),QM)),a=new zr({engine:i,name:s.name,fragmentShader:s.shader,samplerNames:["textureSampler"]});return{canvas:n,dumpEngine:{engine:i,renderer:r,wrapper:a}}}async function Gre(){return _f||(_f=Vre()),await _f}async function JM(n,e,t,i,r="image/png",s,a){let o=await t.readPixels(0,0,n,e),l=new Uint8Array(o.buffer);$T(n,e,l,i,r,s,!0,void 0,a)}async function Y_(n,e,t,i="image/png",r,s=!1,a=!1,o){if(t instanceof Float32Array){let f=new Uint8Array(t.length),h=t.length;for(;h--;){let d=t[h];f[h]=Math.round(Nt(d)*255)}t=f}let l=await X_.EncodeImageAsync(t,n,e,i,s,o);r!==void 0&&pe.DownloadBlob(l,r),l.type!==i&&te.Warn(`DumpData: The requested mimeType '${i}' is not supported. The result has mimeType '${l.type}' instead.`);let c=await l.arrayBuffer();return a?c:`data:${i};base64,${rm(c)}`}function $T(n,e,t,i,r="image/png",s,a=!1,o=!1,l){s===void 0&&!i&&(s=""),Y_(n,e,t,r,s,a,o,l).then(c=>{i&&i(c)})}function eC(){_f&&(_f==null||_f.then(n=>{n.canvas instanceof HTMLCanvasElement&&n.canvas.remove(),n.dumpEngine&&(n.dumpEngine.engine.dispose(),n.dumpEngine.renderer.dispose(),n.dumpEngine.wrapper.dispose())}),_f=null)}var _f,X_,kre,Wre,Hre,tC=C(()=>{Gt();kh();bi();Ln();Pi();yt();V_();Ut();_f=null;X_=class{static async EncodeImageAsync(e,t,i,r,s,a){let o=await Gre(),l=o.dumpEngine;l.engine.setSize(t,i,!0);let c=l.engine.createRawTexture(e,t,i,5,!1,!s,1);return l.renderer.setViewport(),l.renderer.applyEffectWrapper(l.wrapper),l.wrapper.effect._bindTexture("textureSampler",c),l.renderer.draw(),c.dispose(),await new Promise((f,h)=>{pe.ToBlob(o.canvas,d=>{d?f(d):h(new Error("EncodeImageAsync: Failed to convert canvas to blob."))},r,a)})}};P([Ts],X_,"EncodeImageAsync",null);kre=X_.EncodeImageAsync;Wre={DumpData:$T,DumpDataAsync:Y_,DumpFramebuffer:JM,Dispose:eC},Hre=()=>{pe.DumpData=$T,pe.DumpDataAsync=Y_,pe.DumpFramebuffer=JM};Hre()});var Br,gf=C(()=>{hi();Ve();Fr();jT();$a();yh();yt();zM();tr.prototype.setDepthStencilTexture=function(n,e){this._engine.setDepthStencilTexture(this._samplers[n],this._uniforms[n],e,n)};Br=class n extends _e{get renderListPredicate(){return this._objectRenderer.renderListPredicate}set renderListPredicate(e){this._objectRenderer.renderListPredicate=e}get renderList(){return this._objectRenderer.renderList}set renderList(e){this._objectRenderer.renderList=e}get particleSystemList(){return this._objectRenderer.particleSystemList}set particleSystemList(e){this._objectRenderer.particleSystemList=e}get getCustomRenderList(){return this._objectRenderer.getCustomRenderList}set getCustomRenderList(e){this._objectRenderer.getCustomRenderList=e}get renderParticles(){return this._objectRenderer.renderParticles}set renderParticles(e){this._objectRenderer.renderParticles=e}get renderSprites(){return this._objectRenderer.renderSprites}set renderSprites(e){this._objectRenderer.renderSprites=e}get enableBoundingBoxRendering(){return this._objectRenderer.enableBoundingBoxRendering}set enableBoundingBoxRendering(e){this._objectRenderer.enableBoundingBoxRendering=e}get enableOutlineRendering(){return this._objectRenderer.enableOutlineRendering}set enableOutlineRendering(e){this._objectRenderer.enableOutlineRendering=e}get forceLayerMaskCheck(){return this._objectRenderer.forceLayerMaskCheck}set forceLayerMaskCheck(e){this._objectRenderer.forceLayerMaskCheck=e}get activeCamera(){return this._objectRenderer.activeCamera}set activeCamera(e){this._objectRenderer.activeCamera=e}get cameraForLOD(){return this._objectRenderer.cameraForLOD}set cameraForLOD(e){this._objectRenderer.cameraForLOD=e}get disableImageProcessing(){return this._objectRenderer.disableImageProcessing}set disableImageProcessing(e){this._objectRenderer.disableImageProcessing=e}get customIsReadyFunction(){return this._objectRenderer.customIsReadyFunction}set customIsReadyFunction(e){this._objectRenderer.customIsReadyFunction=e}get customRenderFunction(){return this._objectRenderer.customRenderFunction}set customRenderFunction(e){this._objectRenderer.customRenderFunction=e}get postProcesses(){return this._postProcesses}get _prePassEnabled(){return!!this._prePassRenderTarget&&this._prePassRenderTarget.enabled}set onAfterUnbind(e){this._onAfterUnbindObserver&&this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=this.onAfterUnbindObservable.add(e)}get onBeforeRenderObservable(){return this._objectRenderer.onBeforeRenderObservable}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}get onAfterRenderObservable(){return this._objectRenderer.onAfterRenderObservable}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}set onClear(e){this._onClearObserver&&this.onClearObservable.remove(this._onClearObserver),this._onClearObserver=this.onClearObservable.add(e)}get _waitingRenderList(){return this._objectRenderer._waitingRenderList}set _waitingRenderList(e){this._objectRenderer._waitingRenderList=e}get renderPassId(){return this._objectRenderer.renderPassId}get renderPassIds(){return this._objectRenderer.renderPassIds}get currentRefreshId(){return this._objectRenderer.currentRefreshId}setMaterialForRendering(e,t){this._objectRenderer.setMaterialForRendering(e,t)}get isMulti(){var e,t;return(t=(e=this._renderTarget)==null?void 0:e.isMulti)!=null?t:!1}get renderTargetOptions(){return this._renderTargetOptions}get renderTarget(){return this._renderTarget}_onRatioRescale(){this._sizeRatio&&this.resize(this._initialSizeParameter)}set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;let t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}get depthStencilTexture(){var e,t;return(t=(e=this._renderTarget)==null?void 0:e._depthStencilTexture)!=null?t:null}constructor(e,t,i,r=!1,s=!0,a=0,o=!1,l=_e.TRILINEAR_SAMPLINGMODE,c=!0,f=!1,h=!1,d=5,u=!1,m,p,_=!1,g=!1){var R,I,y,M,D,O,V;let v,x=!0,A,S=!1;if(typeof r=="object"){let N=r;r=!!N.generateMipMaps,s=(R=N.doNotChangeAspectRatio)!=null?R:!0,a=(I=N.type)!=null?I:0,o=!!N.isCube,l=(y=N.samplingMode)!=null?y:_e.TRILINEAR_SAMPLINGMODE,c=(M=N.generateDepthBuffer)!=null?M:!0,f=!!N.generateStencilBuffer,h=!!N.isMulti,d=(D=N.format)!=null?D:5,u=!!N.delayAllocation,m=N.samples,p=N.creationFlags,_=!!N.noColorAttachment,g=!!N.useSRGBBuffer,v=N.colorAttachment,x=(O=N.gammaSpace)!=null?O:x,A=N.existingObjectRenderer,S=!!N.enableClusteredLights}if(super(null,i,!r,void 0,l,void 0,void 0,void 0,void 0,d),this.ignoreCameraViewport=!1,this.onBeforeBindObservable=new ie,this.onAfterUnbindObservable=new ie,this.onClearObservable=new ie,this.onResizeObservable=new ie,this._cleared=!1,this.skipInitialClear=!1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this._dontDisposeObjectRenderer=!1,this.boundingBoxPosition=b.Zero(),this._disableEngineStages=!1,this._dumpToolsLoading=!1,i=this.getScene(),!i)return;let E=this.getScene().getEngine();this._gammaSpace=x,this._coordinatesMode=_e.PROJECTION_MODE,this.name=e,this.isRenderTarget=!0,this._initialSizeParameter=t,this._dontDisposeObjectRenderer=!!A,this._processSizeParameter(t),this._objectRenderer=A!=null?A:new Aa(e,i,{numPasses:o?6:this.getRenderLayers()||1,doNotChangeAspectRatio:s,enableClusteredLights:S}),this._onBeforeRenderingManagerRenderObserver=this._objectRenderer.onBeforeRenderingManagerRenderObservable.add(()=>{var F;let N=this._scene;if(!this._disableEngineStages)for(let U of N._beforeRenderTargetClearStage)U.action(this,this._currentFaceIndex,this._currentLayer);if(this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(E):this.skipInitialClear||E.clear((F=this.clearColor)!=null?F:N.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||N.updateTransformMatrix(!0),!this._disableEngineStages)for(let U of N._beforeRenderTargetDrawStage)U.action(this,this._currentFaceIndex,this._currentLayer);E._debugPushGroup&&E._debugPushGroup(`Render to ${this.name} (face #${this._currentFaceIndex} layer #${this._currentLayer})`)}),this._onAfterRenderingManagerRenderObserver=this._objectRenderer.onAfterRenderingManagerRenderObservable.add(()=>{var F,U,k,ee;if(E._debugPopGroup&&E._debugPopGroup(),!this._disableEngineStages)for(let q of this._scene._afterRenderTargetDrawStage)q.action(this,this._currentFaceIndex,this._currentLayer);let N=(U=(F=this._texture)==null?void 0:F.generateMipMaps)!=null?U:!1;if(this._texture&&(this._texture.generateMipMaps=!1),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,(k=this._renderTarget)!=null?k:void 0,this._currentFaceIndex,this._postProcesses,this.ignoreCameraViewport):this._currentUseCameraPostProcess&&this._scene.postProcessManager._finalizeFrame(!1,(ee=this._renderTarget)!=null?ee:void 0,this._currentFaceIndex),!this._disableEngineStages)for(let q of this._scene._afterRenderTargetPostProcessStage)q.action(this,this._currentFaceIndex,this._currentLayer);this._texture&&(this._texture.generateMipMaps=N),this._doNotChangeAspectRatio||this._scene.updateTransformMatrix(!0),this._currentDumpForDebug&&(this._dumpTools?this._dumpTools.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),E):te.Error("dumpTools module is still being loaded. To speed up the process import dump tools directly in your project"))}),this._onFastPathRenderObserver=this._objectRenderer.onFastPathRenderObservable.add(()=>{this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(E):this.skipInitialClear||E.clear(this.clearColor||this._scene.clearColor,!0,!0,!0)}),this._resizeObserver=E.onResizeObservable.add(()=>{}),this._generateMipMaps=!!r,this._doNotChangeAspectRatio=s,!h&&(this._renderTargetOptions={generateMipMaps:r,type:a,format:(V=this._format)!=null?V:void 0,samplingMode:this.samplingMode,generateDepthBuffer:c,generateStencilBuffer:f,samples:m,creationFlags:p,noColorAttachment:_,useSRGBBuffer:g,colorAttachment:v,label:this.name},this.samplingMode===_e.NEAREST_SAMPLINGMODE&&(this.wrapU=_e.CLAMP_ADDRESSMODE,this.wrapV=_e.CLAMP_ADDRESSMODE),u||(o?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=_e.INVCUBIC_MODE,this._textureMatrix=j.Identity()):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,m!==void 0&&(this.samples=m)))}createDepthStencilTexture(e=0,t=!0,i=!1,r=1,s=14,a){var o;(o=this._renderTarget)==null||o.createDepthStencilTexture(e,t,i,r,s,a)}_processSizeParameter(e){if(e.ratio){this._sizeRatio=e.ratio;let t=this._getEngine();this._size={width:this._bestReflectionRenderTargetDimension(t.getRenderWidth(),this._sizeRatio),height:this._bestReflectionRenderTargetDimension(t.getRenderHeight(),this._sizeRatio)}}else this._size=e}get samples(){var e,t;return(t=(e=this._renderTarget)==null?void 0:e.samples)!=null?t:this._samples}set samples(e){this._renderTarget&&(this._samples=this._renderTarget.setSamples(e))}addPostProcess(e){if(!this._postProcessManager){let t=this.getScene();if(!t)return;this._postProcessManager=new Yl(t),this._postProcesses=new Array}this._postProcesses.push(e),this._postProcesses[0].autoClear=!1}clearPostProcesses(e=!1){if(this._postProcesses){if(e)for(let t of this._postProcesses)t.dispose();this._postProcesses=[]}}removePostProcess(e){if(!this._postProcesses)return;let t=this._postProcesses.indexOf(e);t!==-1&&(this._postProcesses.splice(t,1),this._postProcesses.length>0&&(this._postProcesses[0].autoClear=!1))}resetRefreshCounter(){this._objectRenderer.resetRefreshCounter()}get refreshRate(){return this._objectRenderer.refreshRate}set refreshRate(e){this._objectRenderer.refreshRate=e}_shouldRender(){return this._objectRenderer.shouldRender()}getRenderSize(){return this.getRenderWidth()}getRenderWidth(){return this._size.width?this._size.width:this._size}getRenderHeight(){return this._size.width?this._size.height:this._size}getRenderLayers(){let e=this._size.layers;if(e)return e;let t=this._size.depth;return t||0}disableRescaling(){this._canRescale=!1}get canRescale(){return this._canRescale}scale(e){let t=Math.max(1,this.getRenderSize()*e);this.resize(t)}getReflectionTextureMatrix(){return this.isCube?this._textureMatrix:super.getReflectionTextureMatrix()}resize(e){var r;let t=this.isCube;(r=this._renderTarget)==null||r.dispose(),this._renderTarget=null;let i=this.getScene();i&&(this._processSizeParameter(e),t?this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,this._renderTargetOptions.samples!==void 0&&(this.samples=this._renderTargetOptions.samples),this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this))}render(e=!1,t=!1){this._render(e,t)}isReadyForRendering(){this._dumpToolsLoading||(this._dumpToolsLoading=!0,Promise.resolve().then(()=>(tC(),eB)).then(t=>this._dumpTools=t)),this._objectRenderer.prepareRenderList(),this.onBeforeBindObservable.notifyObservers(this),this._objectRenderer.initRender(this.getRenderWidth(),this.getRenderHeight());let e=this._objectRenderer._checkReadiness();return this.onAfterUnbindObservable.notifyObservers(this),this._objectRenderer.finishRender(),e}_render(e=!1,t=!1){let i=this.getScene();if(!i)return;this.useCameraPostProcesses!==void 0&&(e=this.useCameraPostProcesses);let r=i.getEngine();if(r._debugPushGroup&&r._debugPushGroup(`Render to ${this.name}`),this._objectRenderer.prepareRenderList(),this.onBeforeBindObservable.notifyObservers(this),this._objectRenderer.initRender(this.getRenderWidth(),this.getRenderHeight()),(this.is2DArray||this.is3D)&&!this.isMulti)for(let s=0;s{this.onAfterRenderObservable.notifyObservers(t)})}_prepareFrame(e,t,i,r){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses)||this._bindFrameBuffer(t,i):(!r||!e.postProcessManager._prepareFrame(this._texture))&&this._bindFrameBuffer(t,i)}_renderToTarget(e,t,i,r=0){let s=this.getScene();if(!s)return;let a=s.getEngine();this._currentFaceIndex=e,this._currentLayer=r,this._currentUseCameraPostProcess=t,this._currentDumpForDebug=i,this._prepareFrame(s,e,r,t),this._objectRenderer.render(e+r,!0),this._unbindFrameBuffer(a,e),this._texture&&this.isCube&&e===5&&a.generateMipMapsForCubemap(this._texture,!0)}setRenderingOrder(e,t=null,i=null,r=null){this._objectRenderer.setRenderingOrder(e,t,i,r)}setRenderingAutoClearDepthStencil(e,t){this._objectRenderer.setRenderingAutoClearDepthStencil(e,t)}clone(){let e=this.getSize(),t=new n(this.name,e,this.getScene(),this._renderTargetOptions.generateMipMaps,this._doNotChangeAspectRatio,this._renderTargetOptions.type,this.isCube,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer,this._renderTargetOptions.generateStencilBuffer,void 0,this._renderTargetOptions.format,void 0,this._renderTargetOptions.samples);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,this.renderList&&(t.renderList=this.renderList.slice(0)),t}serialize(){if(!this.name)return null;let e=super.serialize();if(e.renderTargetSize=this.getRenderSize(),e.renderList=[],this.renderList)for(let t=0;t=0&&e.customRenderTargets.splice(t,1);for(let r of e.cameras)t=r.customRenderTargets.indexOf(this),t>=0&&r.customRenderTargets.splice(t,1);(i=this._renderTarget)==null||i.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this._objectRenderer._rebuild(),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._objectRenderer.freeRenderingGroups()}getViewCount(){return 1}};Br.REFRESHRATE_RENDER_ONCE=Aa.REFRESHRATE_RENDER_ONCE;Br.REFRESHRATE_RENDER_ONEVERYFRAME=Aa.REFRESHRATE_RENDER_ONEVERYFRAME;Br.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=Aa.REFRESHRATE_RENDER_ONEVERYTWOFRAMES;_e._CreateRenderTargetTexture=(n,e,t,i,r)=>new Br(n,e,t,i)});var xi,Kl=C(()=>{Gt();so();hi();Ve();yh();Ut();Tr();Hi();wr();$a();kh();Ie.prototype.setTextureFromPostProcess=function(n,e,t){var r;let i=null;e&&(e._forcedOutputTexture?i=e._forcedOutputTexture:e._textures.data[e._currentRenderTextureInd]&&(i=e._textures.data[e._currentRenderTextureInd])),this._bindTexture(n,(r=i==null?void 0:i.texture)!=null?r:null,t)};Ie.prototype.setTextureFromPostProcessOutput=function(n,e,t){var i,r;this._bindTexture(n,(r=(i=e==null?void 0:e._outputTexture)==null?void 0:i.texture)!=null?r:null,t)};tr.prototype.setTextureFromPostProcess=function(n,e){this._engine.setTextureFromPostProcess(this._samplers[n],e,n)};tr.prototype.setTextureFromPostProcessOutput=function(n,e){this._engine.setTextureFromPostProcessOutput(this._samplers[n],e,n)};xi=class n{static get ForceGLSL(){return zr.ForceGLSL}static set ForceGLSL(e){zr.ForceGLSL=e}static RegisterShaderCodeProcessing(e,t){zr.RegisterShaderCodeProcessing(e,t)}get name(){return this._effectWrapper.name}set name(e){this._effectWrapper.name=e}get alphaMode(){return this._effectWrapper.alphaMode}set alphaMode(e){this._effectWrapper.alphaMode=e}get samples(){return this._samples}set samples(e){this._samples=Math.min(e,this._engine.getCaps().maxMSAASamples),this._textures.forEach(t=>{t.setSamples(this._samples)})}get shaderLanguage(){return this._shaderLanguage}getEffectName(){return this._fragmentUrl}set onActivate(e){this._onActivateObserver&&this.onActivateObservable.remove(this._onActivateObserver),e&&(this._onActivateObserver=this.onActivateObservable.add(e))}set onSizeChanged(e){this._onSizeChangedObserver&&this.onSizeChangedObservable.remove(this._onSizeChangedObserver),this._onSizeChangedObserver=this.onSizeChangedObservable.add(e)}set onApply(e){this._onApplyObserver&&this.onApplyObservable.remove(this._onApplyObserver),this._onApplyObserver=this.onApplyObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}get inputTexture(){return this._textures.data[this._currentRenderTextureInd]}set inputTexture(e){this._forcedOutputTexture=e}restoreDefaultInputTexture(){this._forcedOutputTexture&&(this._forcedOutputTexture=null,this.markTextureDirty())}getCamera(){return this._camera}get texelSize(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.texelSize:(this._forcedOutputTexture&&this._texelSize.copyFromFloats(1/this._forcedOutputTexture.width,1/this._forcedOutputTexture.height),this._texelSize)}constructor(e,t,i,r,s,a,o=1,l,c,f=null,h=0,d="postprocess",u,m=!1,p=5,_,g){var S,E,R,I,y,M,D,O,V,N,F,U;this._parentContainer=null,this.width=-1,this.height=-1,this.nodeMaterialSource=null,this._outputTexture=null,this.autoClear=!0,this.forceAutoClearInAlphaMode=!1,this.animations=[],this.enablePixelPerfectMode=!1,this.forceFullscreenViewport=!0,this.scaleMode=1,this.alwaysForcePOT=!1,this._samples=1,this.adaptScaleToCurrentViewport=!1,this.doNotSerialize=!1,this._webGPUReady=!1,this._reusable=!1,this._renderId=0,this.externalTextureSamplerBinding=!1,this._textures=new wi(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new we(1,1),this._texelSize=we.Zero(),this.onActivateObservable=new ie,this.onSizeChangedObservable=new ie,this.onApplyObservable=new ie,this.onBeforeRenderObservable=new ie,this.onAfterRenderObservable=new ie,this.onDisposeObservable=new ie;let v=1,x=null,A;if(i&&!Array.isArray(i)){let k=i;i=(S=k.uniforms)!=null?S:null,r=(E=k.samplers)!=null?E:null,v=(R=k.size)!=null?R:1,a=(I=k.camera)!=null?I:null,o=(y=k.samplingMode)!=null?y:1,l=k.engine,c=k.reusable,f=Array.isArray(k.defines)?k.defines.join(` -`):(M=k.defines)!=null?M:null,h=(D=k.textureType)!=null?D:0,d=(O=k.vertexUrl)!=null?O:"postprocess",u=k.indexParameters,m=(V=k.blockCompilation)!=null?V:!1,p=(N=k.textureFormat)!=null?N:5,_=(F=k.shaderLanguage)!=null?F:0,x=(U=k.uniformBuffers)!=null?U:null,g=k.extraInitializations,A=k.effectWrapper}else s&&(typeof s=="number"?v=s:v={width:s.width,height:s.height});if(this._useExistingThinPostProcess=!!A,this._effectWrapper=A!=null?A:new zr({name:e,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:t,engine:l||(a==null?void 0:a.getScene().getEngine()),uniforms:i,samplers:r,uniformBuffers:x,defines:f,vertexUrl:d,indexParameters:u,blockCompilation:!0,shaderLanguage:_,extraInitializations:void 0}),this.name=e,this.onEffectCreatedObservable=this._effectWrapper.onEffectCreatedObservable,a!=null?(this._camera=a,this._scene=a.getScene(),a.attachPostProcess(this),this._engine=this._scene.getEngine(),this._scene.addPostProcess(this),this.uniqueId=this._scene.getUniqueId()):l&&(this._engine=l,this._engine.postProcesses.push(this)),this._options=v,this.renderTargetSamplingMode=o||1,this._reusable=c||!1,this._textureType=h,this._textureFormat=p,this._shaderLanguage=_||0,this._samplers=r||[],this._samplers.indexOf("textureSampler")===-1&&this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=d,this._parameters=i||[],this._parameters.indexOf("scale")===-1&&this._parameters.push("scale"),this._uniformBuffers=x||[],this._indexParameters=u,!this._useExistingThinPostProcess){this._webGPUReady=this._shaderLanguage===1;let k=[];this._gatherImports(this._engine.isWebGPU&&!n.ForceGLSL,k),this._effectWrapper._webGPUReady=this._webGPUReady,this._effectWrapper._postConstructor(m,f,g,k)}}_gatherImports(e=!1,t){e&&this._webGPUReady?t.push(Promise.all([Promise.resolve().then(()=>(jM(),$2))])):t.push(Promise.all([Promise.resolve().then(()=>(YM(),Z2))]))}getClassName(){return"PostProcess"}getEngine(){return this._engine}getEffect(){return this._effectWrapper.drawWrapper.effect}shareOutputWith(e){return this._disposeTextures(),this._shareOutputWithPostProcess=e,this}useOwnOutput(){this._textures.length==0&&(this._textures=new wi(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,r,s,a,o,l){this._effectWrapper.updateEffect(e,t,i,r,s,a,o,l),this._postProcessDefines=Array.isArray(this._effectWrapper.options.defines)?this._effectWrapper.options.defines.join(` -`):this._effectWrapper.options.defines}isReusable(){return this._reusable}markTextureDirty(){this.width=-1}_createRenderTargetTexture(e,t,i=0){for(let s=0;s=0;t--)if(e-this._textureCache[t].lastUsedRenderId>100){let i=!1;for(let r=0;r0&&this._textures.reset(),this.width=e,this.height=t;let a=null;if(i){for(let c=0;c{g.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(g,this.samples)}),this._flushTextureCache(),this._renderId++}return u||(u=this._getTarget()),this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(l/f,c/h),this._engine.bindFramebuffer(u,0,l,c,this.forceFullscreenViewport)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(u,0,void 0,void 0,this.forceFullscreenViewport)),(_=(p=this._engine)._debugInsertMarker)==null||_.call(p,`post process ${this.name} input`),this.onActivateObservable.notifyObservers(r),this.autoClear&&(this.alphaMode===0||this.forceAutoClearInAlphaMode)&&this._engine.clear(this.clearColor?this.clearColor:s.clearColor,s._allowPostProcessClearColor,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2),u}get isSupported(){return this._effectWrapper.drawWrapper.effect.isSupported}get aspectRatio(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.aspectRatio:this._forcedOutputTexture?this._forcedOutputTexture.width/this._forcedOutputTexture.height:this.width/this.height}isReady(){return this._effectWrapper.isReady()}apply(){if(!this._effectWrapper.isReady())return null;this._engine.enableEffect(this._effectWrapper.drawWrapper),this._engine.setState(!1),this._engine.setDepthBuffer(!1),this._engine.setDepthWrite(!1),this.alphaConstants&&this.getEngine().setAlphaConstants(this.alphaConstants.r,this.alphaConstants.g,this.alphaConstants.b,this.alphaConstants.a),this._engine.setAlphaMode(this.alphaMode);let e;return this._shareOutputWithPostProcess?e=this._shareOutputWithPostProcess.inputTexture:this._forcedOutputTexture?e=this._forcedOutputTexture:e=this.inputTexture,this.externalTextureSamplerBinding||this._effectWrapper.drawWrapper.effect._bindTexture("textureSampler",e==null?void 0:e.texture),this._effectWrapper.drawWrapper.effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._effectWrapper.drawWrapper.effect),this._effectWrapper.bind(!0),this._effectWrapper.drawWrapper.effect}_disposeTextures(){if(this._shareOutputWithPostProcess||this._forcedOutputTexture){this._disposeTextureCache();return}this._disposeTextureCache(),this._textures.dispose()}_disposeTextureCache(){for(let e=this._textureCache.length-1;e>=0;e--)this._textureCache[e].texture.dispose();this._textureCache.length=0}setPrePassRenderer(e){return this._prePassEffectConfiguration?(this._prePassEffectConfiguration=e.addEffectConfiguration(this._prePassEffectConfiguration),this._prePassEffectConfiguration.enabled=!0,!0):!1}dispose(e){e=e||this._camera,this._useExistingThinPostProcess||this._effectWrapper.dispose(),this._disposeTextures(),this._scene&&this._scene.removePostProcess(this);let t;if(this._parentContainer&&(t=this._parentContainer.postProcesses.indexOf(this),t>-1&&this._parentContainer.postProcesses.splice(t,1),this._parentContainer=null),t=this._engine.postProcesses.indexOf(this),t!==-1&&this._engine.postProcesses.splice(t,1),this.onDisposeObservable.notifyObservers(),!!e){if(e.detachPostProcess(this),t=e._postProcesses.indexOf(this),t===0&&e._postProcesses.length>0){let i=this._camera._getFirstPostProcess();i&&i.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear(),this.onEffectCreatedObservable.clear()}}serialize(){let e=it.Serialize(this),t=this.getCamera()||this._scene&&this._scene.activeCamera;return e.customType="BABYLON."+this.getClassName(),e.cameraId=t?t.id:null,e.reusable=this._reusable,e.textureType=this._textureType,e.fragmentUrl=this._fragmentUrl,e.parameters=this._parameters,e.samplers=this._samplers,e.uniformBuffers=this._uniformBuffers,e.options=this._options,e.defines=this._postProcessDefines,e.textureFormat=this._textureFormat,e.vertexUrl=this._vertexUrl,e.indexParameters=this._indexParameters,e}clone(){let e=this.serialize();e._engine=this._engine,e.cameraId=null;let t=n.Parse(e,this._scene,"");return t?(t.onActivateObservable=this.onActivateObservable.clone(),t.onSizeChangedObservable=this.onSizeChangedObservable.clone(),t.onApplyObservable=this.onApplyObservable.clone(),t.onBeforeRenderObservable=this.onBeforeRenderObservable.clone(),t.onAfterRenderObservable=this.onAfterRenderObservable.clone(),t._prePassEffectConfiguration=this._prePassEffectConfiguration,t):null}static Parse(e,t,i){let r=vn(e.customType);if(!r||!r._Parse)return null;let s=t?t.getCameraById(e.cameraId):null;return r._Parse(e,s,t,i)}static _Parse(e,t,i,r){return it.Parse(()=>new n(e.name,e.fragmentUrl,e.parameters,e.samplers,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable,e.defines,e.textureType,e.vertexUrl,e.indexParameters,!1,e.textureFormat),e,i,r)}};P([w()],xi.prototype,"uniqueId",void 0);P([w()],xi.prototype,"name",null);P([w()],xi.prototype,"width",void 0);P([w()],xi.prototype,"height",void 0);P([w()],xi.prototype,"renderTargetSamplingMode",void 0);P([im()],xi.prototype,"clearColor",void 0);P([w()],xi.prototype,"autoClear",void 0);P([w()],xi.prototype,"forceAutoClearInAlphaMode",void 0);P([w()],xi.prototype,"alphaMode",null);P([w()],xi.prototype,"alphaConstants",void 0);P([w()],xi.prototype,"enablePixelPerfectMode",void 0);P([w()],xi.prototype,"forceFullscreenViewport",void 0);P([w()],xi.prototype,"scaleMode",void 0);P([w()],xi.prototype,"alwaysForcePOT",void 0);P([w("samples")],xi.prototype,"_samples",void 0);P([w()],xi.prototype,"adaptScaleToCurrentViewport",void 0);wt("BABYLON.PostProcess",xi)});var iB={};tt(iB,{passPixelShaderWGSL:()=>zre});var iC,tB,zre,rB=C(()=>{W();iC="passPixelShader",tB=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d; +{gl_FragColor=texture2D(textureSampler,vUV);}`;T.ShadersStore[ZM]||(T.ShadersStore[ZM]=J2);Ure={name:ZM,shader:J2}});var eB={};tt(eB,{Dispose:()=>eC,DumpData:()=>JT,DumpDataAsync:()=>Y_,DumpFramebuffer:()=>JM,DumpTools:()=>Wre,EncodeImageAsync:()=>kre});async function Vre(){var o,l;let n=(l=(o=Oe.LastCreatedEngine)==null?void 0:o.createCanvas(100,100))!=null?l:new OffscreenCanvas(100,100);n instanceof OffscreenCanvas&&te.Warn("DumpData: OffscreenCanvas will be used for dumping data. This may result in lossy alpha values.");let{ThinEngine:e}=await Promise.resolve().then(()=>(Zn(),Z3));if(!e.IsSupported)throw new Error("DumpData: No WebGL context available. Cannot dump data.");let t={preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1},i=new e(n,!1,t);Oe.Instances.pop(),Oe.OnEnginesDisposedObservable.add(c=>{i&&c!==i&&!i.isDisposed&&Oe.Instances.length===0&&eC()}),i.getCaps().parallelShaderCompile=void 0;let r=new $T(i),{passPixelShader:s}=await Promise.resolve().then(()=>($M(),QM)),a=new zr({engine:i,name:s.name,fragmentShader:s.shader,samplerNames:["textureSampler"]});return{canvas:n,dumpEngine:{engine:i,renderer:r,wrapper:a}}}async function Gre(){return pf||(pf=Vre()),await pf}async function JM(n,e,t,i,r="image/png",s,a){let o=await t.readPixels(0,0,n,e),l=new Uint8Array(o.buffer);JT(n,e,l,i,r,s,!0,void 0,a)}async function Y_(n,e,t,i="image/png",r,s=!1,a=!1,o){if(t instanceof Float32Array){let f=new Uint8Array(t.length),h=t.length;for(;h--;){let d=t[h];f[h]=Math.round(wt(d)*255)}t=f}let l=await X_.EncodeImageAsync(t,n,e,i,s,o);r!==void 0&&_e.DownloadBlob(l,r),l.type!==i&&te.Warn(`DumpData: The requested mimeType '${i}' is not supported. The result has mimeType '${l.type}' instead.`);let c=await l.arrayBuffer();return a?c:`data:${i};base64,${im(c)}`}function JT(n,e,t,i,r="image/png",s,a=!1,o=!1,l){s===void 0&&!i&&(s=""),Y_(n,e,t,r,s,a,o,l).then(c=>{i&&i(c)})}function eC(){pf&&(pf==null||pf.then(n=>{n.canvas instanceof HTMLCanvasElement&&n.canvas.remove(),n.dumpEngine&&(n.dumpEngine.engine.dispose(),n.dumpEngine.renderer.dispose(),n.dumpEngine.wrapper.dispose())}),pf=null)}var pf,X_,kre,Wre,Hre,tC=C(()=>{Gt();kh();Ii();Ln();Di();Pt();V_();Vt();pf=null;X_=class{static async EncodeImageAsync(e,t,i,r,s,a){let o=await Gre(),l=o.dumpEngine;l.engine.setSize(t,i,!0);let c=l.engine.createRawTexture(e,t,i,5,!1,!s,1);return l.renderer.setViewport(),l.renderer.applyEffectWrapper(l.wrapper),l.wrapper.effect._bindTexture("textureSampler",c),l.renderer.draw(),c.dispose(),await new Promise((f,h)=>{_e.ToBlob(o.canvas,d=>{d?f(d):h(new Error("EncodeImageAsync: Failed to convert canvas to blob."))},r,a)})}};P([Ss],X_,"EncodeImageAsync",null);kre=X_.EncodeImageAsync;Wre={DumpData:JT,DumpDataAsync:Y_,DumpFramebuffer:JM,Dispose:eC},Hre=()=>{_e.DumpData=JT,_e.DumpDataAsync=Y_,_e.DumpFramebuffer=JM};Hre()});var Br,_f=C(()=>{di();Ge();Fr();qT();$a();yh();Pt();zM();rr.prototype.setDepthStencilTexture=function(n,e){this._engine.setDepthStencilTexture(this._samplers[n],this._uniforms[n],e,n)};Br=class n extends ge{get renderListPredicate(){return this._objectRenderer.renderListPredicate}set renderListPredicate(e){this._objectRenderer.renderListPredicate=e}get renderList(){return this._objectRenderer.renderList}set renderList(e){this._objectRenderer.renderList=e}get particleSystemList(){return this._objectRenderer.particleSystemList}set particleSystemList(e){this._objectRenderer.particleSystemList=e}get getCustomRenderList(){return this._objectRenderer.getCustomRenderList}set getCustomRenderList(e){this._objectRenderer.getCustomRenderList=e}get renderParticles(){return this._objectRenderer.renderParticles}set renderParticles(e){this._objectRenderer.renderParticles=e}get renderSprites(){return this._objectRenderer.renderSprites}set renderSprites(e){this._objectRenderer.renderSprites=e}get enableBoundingBoxRendering(){return this._objectRenderer.enableBoundingBoxRendering}set enableBoundingBoxRendering(e){this._objectRenderer.enableBoundingBoxRendering=e}get enableOutlineRendering(){return this._objectRenderer.enableOutlineRendering}set enableOutlineRendering(e){this._objectRenderer.enableOutlineRendering=e}get forceLayerMaskCheck(){return this._objectRenderer.forceLayerMaskCheck}set forceLayerMaskCheck(e){this._objectRenderer.forceLayerMaskCheck=e}get activeCamera(){return this._objectRenderer.activeCamera}set activeCamera(e){this._objectRenderer.activeCamera=e}get cameraForLOD(){return this._objectRenderer.cameraForLOD}set cameraForLOD(e){this._objectRenderer.cameraForLOD=e}get disableImageProcessing(){return this._objectRenderer.disableImageProcessing}set disableImageProcessing(e){this._objectRenderer.disableImageProcessing=e}get customIsReadyFunction(){return this._objectRenderer.customIsReadyFunction}set customIsReadyFunction(e){this._objectRenderer.customIsReadyFunction=e}get customRenderFunction(){return this._objectRenderer.customRenderFunction}set customRenderFunction(e){this._objectRenderer.customRenderFunction=e}get postProcesses(){return this._postProcesses}get _prePassEnabled(){return!!this._prePassRenderTarget&&this._prePassRenderTarget.enabled}set onAfterUnbind(e){this._onAfterUnbindObserver&&this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=this.onAfterUnbindObservable.add(e)}get onBeforeRenderObservable(){return this._objectRenderer.onBeforeRenderObservable}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}get onAfterRenderObservable(){return this._objectRenderer.onAfterRenderObservable}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}set onClear(e){this._onClearObserver&&this.onClearObservable.remove(this._onClearObserver),this._onClearObserver=this.onClearObservable.add(e)}get _waitingRenderList(){return this._objectRenderer._waitingRenderList}set _waitingRenderList(e){this._objectRenderer._waitingRenderList=e}get renderPassId(){return this._objectRenderer.renderPassId}get renderPassIds(){return this._objectRenderer.renderPassIds}get currentRefreshId(){return this._objectRenderer.currentRefreshId}setMaterialForRendering(e,t){this._objectRenderer.setMaterialForRendering(e,t)}get isMulti(){var e,t;return(t=(e=this._renderTarget)==null?void 0:e.isMulti)!=null?t:!1}get renderTargetOptions(){return this._renderTargetOptions}get renderTarget(){return this._renderTarget}_onRatioRescale(){this._sizeRatio&&this.resize(this._initialSizeParameter)}set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;let t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}get depthStencilTexture(){var e,t;return(t=(e=this._renderTarget)==null?void 0:e._depthStencilTexture)!=null?t:null}constructor(e,t,i,r=!1,s=!0,a=0,o=!1,l=ge.TRILINEAR_SAMPLINGMODE,c=!0,f=!1,h=!1,d=5,u=!1,m,p,_=!1,g=!1){var R,I,y,M,D,O,V;let v,x=!0,A,S=!1;if(typeof r=="object"){let N=r;r=!!N.generateMipMaps,s=(R=N.doNotChangeAspectRatio)!=null?R:!0,a=(I=N.type)!=null?I:0,o=!!N.isCube,l=(y=N.samplingMode)!=null?y:ge.TRILINEAR_SAMPLINGMODE,c=(M=N.generateDepthBuffer)!=null?M:!0,f=!!N.generateStencilBuffer,h=!!N.isMulti,d=(D=N.format)!=null?D:5,u=!!N.delayAllocation,m=N.samples,p=N.creationFlags,_=!!N.noColorAttachment,g=!!N.useSRGBBuffer,v=N.colorAttachment,x=(O=N.gammaSpace)!=null?O:x,A=N.existingObjectRenderer,S=!!N.enableClusteredLights}if(super(null,i,!r,void 0,l,void 0,void 0,void 0,void 0,d),this.ignoreCameraViewport=!1,this.onBeforeBindObservable=new ie,this.onAfterUnbindObservable=new ie,this.onClearObservable=new ie,this.onResizeObservable=new ie,this._cleared=!1,this.skipInitialClear=!1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this._dontDisposeObjectRenderer=!1,this.boundingBoxPosition=b.Zero(),this._disableEngineStages=!1,this._dumpToolsLoading=!1,i=this.getScene(),!i)return;let E=this.getScene().getEngine();this._gammaSpace=x,this._coordinatesMode=ge.PROJECTION_MODE,this.name=e,this.isRenderTarget=!0,this._initialSizeParameter=t,this._dontDisposeObjectRenderer=!!A,this._processSizeParameter(t),this._objectRenderer=A!=null?A:new Ta(e,i,{numPasses:o?6:this.getRenderLayers()||1,doNotChangeAspectRatio:s,enableClusteredLights:S}),this._onBeforeRenderingManagerRenderObserver=this._objectRenderer.onBeforeRenderingManagerRenderObservable.add(()=>{var F;let N=this._scene;if(!this._disableEngineStages)for(let U of N._beforeRenderTargetClearStage)U.action(this,this._currentFaceIndex,this._currentLayer);if(this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(E):this.skipInitialClear||E.clear((F=this.clearColor)!=null?F:N.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||N.updateTransformMatrix(!0),!this._disableEngineStages)for(let U of N._beforeRenderTargetDrawStage)U.action(this,this._currentFaceIndex,this._currentLayer);E._debugPushGroup&&E._debugPushGroup(`Render to ${this.name} (face #${this._currentFaceIndex} layer #${this._currentLayer})`)}),this._onAfterRenderingManagerRenderObserver=this._objectRenderer.onAfterRenderingManagerRenderObservable.add(()=>{var F,U,G,ee;if(E._debugPopGroup&&E._debugPopGroup(),!this._disableEngineStages)for(let j of this._scene._afterRenderTargetDrawStage)j.action(this,this._currentFaceIndex,this._currentLayer);let N=(U=(F=this._texture)==null?void 0:F.generateMipMaps)!=null?U:!1;if(this._texture&&(this._texture.generateMipMaps=!1),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,(G=this._renderTarget)!=null?G:void 0,this._currentFaceIndex,this._postProcesses,this.ignoreCameraViewport):this._currentUseCameraPostProcess&&this._scene.postProcessManager._finalizeFrame(!1,(ee=this._renderTarget)!=null?ee:void 0,this._currentFaceIndex),!this._disableEngineStages)for(let j of this._scene._afterRenderTargetPostProcessStage)j.action(this,this._currentFaceIndex,this._currentLayer);this._texture&&(this._texture.generateMipMaps=N),this._doNotChangeAspectRatio||this._scene.updateTransformMatrix(!0),this._currentDumpForDebug&&(this._dumpTools?this._dumpTools.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),E):te.Error("dumpTools module is still being loaded. To speed up the process import dump tools directly in your project"))}),this._onFastPathRenderObserver=this._objectRenderer.onFastPathRenderObservable.add(()=>{this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(E):this.skipInitialClear||E.clear(this.clearColor||this._scene.clearColor,!0,!0,!0)}),this._resizeObserver=E.onResizeObservable.add(()=>{}),this._generateMipMaps=!!r,this._doNotChangeAspectRatio=s,!h&&(this._renderTargetOptions={generateMipMaps:r,type:a,format:(V=this._format)!=null?V:void 0,samplingMode:this.samplingMode,generateDepthBuffer:c,generateStencilBuffer:f,samples:m,creationFlags:p,noColorAttachment:_,useSRGBBuffer:g,colorAttachment:v,label:this.name},this.samplingMode===ge.NEAREST_SAMPLINGMODE&&(this.wrapU=ge.CLAMP_ADDRESSMODE,this.wrapV=ge.CLAMP_ADDRESSMODE),u||(o?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=ge.INVCUBIC_MODE,this._textureMatrix=K.Identity()):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,m!==void 0&&(this.samples=m)))}createDepthStencilTexture(e=0,t=!0,i=!1,r=1,s=14,a){var o;(o=this._renderTarget)==null||o.createDepthStencilTexture(e,t,i,r,s,a)}_processSizeParameter(e){if(e.ratio){this._sizeRatio=e.ratio;let t=this._getEngine();this._size={width:this._bestReflectionRenderTargetDimension(t.getRenderWidth(),this._sizeRatio),height:this._bestReflectionRenderTargetDimension(t.getRenderHeight(),this._sizeRatio)}}else this._size=e}get samples(){var e,t;return(t=(e=this._renderTarget)==null?void 0:e.samples)!=null?t:this._samples}set samples(e){this._renderTarget&&(this._samples=this._renderTarget.setSamples(e))}addPostProcess(e){if(!this._postProcessManager){let t=this.getScene();if(!t)return;this._postProcessManager=new Xl(t),this._postProcesses=new Array}this._postProcesses.push(e),this._postProcesses[0].autoClear=!1}clearPostProcesses(e=!1){if(this._postProcesses){if(e)for(let t of this._postProcesses)t.dispose();this._postProcesses=[]}}removePostProcess(e){if(!this._postProcesses)return;let t=this._postProcesses.indexOf(e);t!==-1&&(this._postProcesses.splice(t,1),this._postProcesses.length>0&&(this._postProcesses[0].autoClear=!1))}resetRefreshCounter(){this._objectRenderer.resetRefreshCounter()}get refreshRate(){return this._objectRenderer.refreshRate}set refreshRate(e){this._objectRenderer.refreshRate=e}_shouldRender(){return this._objectRenderer.shouldRender()}getRenderSize(){return this.getRenderWidth()}getRenderWidth(){return this._size.width?this._size.width:this._size}getRenderHeight(){return this._size.width?this._size.height:this._size}getRenderLayers(){let e=this._size.layers;if(e)return e;let t=this._size.depth;return t||0}disableRescaling(){this._canRescale=!1}get canRescale(){return this._canRescale}scale(e){let t=Math.max(1,this.getRenderSize()*e);this.resize(t)}getReflectionTextureMatrix(){return this.isCube?this._textureMatrix:super.getReflectionTextureMatrix()}resize(e){var r;let t=this.isCube;(r=this._renderTarget)==null||r.dispose(),this._renderTarget=null;let i=this.getScene();i&&(this._processSizeParameter(e),t?this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,this._renderTargetOptions.samples!==void 0&&(this.samples=this._renderTargetOptions.samples),this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this))}render(e=!1,t=!1){this._render(e,t)}isReadyForRendering(){this._dumpToolsLoading||(this._dumpToolsLoading=!0,Promise.resolve().then(()=>(tC(),eB)).then(t=>this._dumpTools=t)),this._objectRenderer.prepareRenderList(),this.onBeforeBindObservable.notifyObservers(this),this._objectRenderer.initRender(this.getRenderWidth(),this.getRenderHeight());let e=this._objectRenderer._checkReadiness();return this.onAfterUnbindObservable.notifyObservers(this),this._objectRenderer.finishRender(),e}_render(e=!1,t=!1){let i=this.getScene();if(!i)return;this.useCameraPostProcesses!==void 0&&(e=this.useCameraPostProcesses);let r=i.getEngine();if(r._debugPushGroup&&r._debugPushGroup(`Render to ${this.name}`),this._objectRenderer.prepareRenderList(),this.onBeforeBindObservable.notifyObservers(this),this._objectRenderer.initRender(this.getRenderWidth(),this.getRenderHeight()),(this.is2DArray||this.is3D)&&!this.isMulti)for(let s=0;s{this.onAfterRenderObservable.notifyObservers(t)})}_prepareFrame(e,t,i,r){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses)||this._bindFrameBuffer(t,i):(!r||!e.postProcessManager._prepareFrame(this._texture))&&this._bindFrameBuffer(t,i)}_renderToTarget(e,t,i,r=0){let s=this.getScene();if(!s)return;let a=s.getEngine();this._currentFaceIndex=e,this._currentLayer=r,this._currentUseCameraPostProcess=t,this._currentDumpForDebug=i,this._prepareFrame(s,e,r,t),this._objectRenderer.render(e+r,!0),this._unbindFrameBuffer(a,e),this._texture&&this.isCube&&e===5&&a.generateMipMapsForCubemap(this._texture,!0)}setRenderingOrder(e,t=null,i=null,r=null){this._objectRenderer.setRenderingOrder(e,t,i,r)}setRenderingAutoClearDepthStencil(e,t){this._objectRenderer.setRenderingAutoClearDepthStencil(e,t)}clone(){let e=this.getSize(),t=new n(this.name,e,this.getScene(),this._renderTargetOptions.generateMipMaps,this._doNotChangeAspectRatio,this._renderTargetOptions.type,this.isCube,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer,this._renderTargetOptions.generateStencilBuffer,void 0,this._renderTargetOptions.format,void 0,this._renderTargetOptions.samples);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,this.renderList&&(t.renderList=this.renderList.slice(0)),t}serialize(){if(!this.name)return null;let e=super.serialize();if(e.renderTargetSize=this.getRenderSize(),e.renderList=[],this.renderList)for(let t=0;t=0&&e.customRenderTargets.splice(t,1);for(let r of e.cameras)t=r.customRenderTargets.indexOf(this),t>=0&&r.customRenderTargets.splice(t,1);(i=this._renderTarget)==null||i.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this._objectRenderer._rebuild(),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._objectRenderer.freeRenderingGroups()}getViewCount(){return 1}};Br.REFRESHRATE_RENDER_ONCE=Ta.REFRESHRATE_RENDER_ONCE;Br.REFRESHRATE_RENDER_ONEVERYFRAME=Ta.REFRESHRATE_RENDER_ONEVERYFRAME;Br.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=Ta.REFRESHRATE_RENDER_ONEVERYTWOFRAMES;ge._CreateRenderTargetTexture=(n,e,t,i,r)=>new Br(n,e,t,i)});var Ri,Yl=C(()=>{Gt();so();di();Ge();yh();Vt();Tr();Hi();wr();$a();kh();Me.prototype.setTextureFromPostProcess=function(n,e,t){var r;let i=null;e&&(e._forcedOutputTexture?i=e._forcedOutputTexture:e._textures.data[e._currentRenderTextureInd]&&(i=e._textures.data[e._currentRenderTextureInd])),this._bindTexture(n,(r=i==null?void 0:i.texture)!=null?r:null,t)};Me.prototype.setTextureFromPostProcessOutput=function(n,e,t){var i,r;this._bindTexture(n,(r=(i=e==null?void 0:e._outputTexture)==null?void 0:i.texture)!=null?r:null,t)};rr.prototype.setTextureFromPostProcess=function(n,e){this._engine.setTextureFromPostProcess(this._samplers[n],e,n)};rr.prototype.setTextureFromPostProcessOutput=function(n,e){this._engine.setTextureFromPostProcessOutput(this._samplers[n],e,n)};Ri=class n{static get ForceGLSL(){return zr.ForceGLSL}static set ForceGLSL(e){zr.ForceGLSL=e}static RegisterShaderCodeProcessing(e,t){zr.RegisterShaderCodeProcessing(e,t)}get name(){return this._effectWrapper.name}set name(e){this._effectWrapper.name=e}get alphaMode(){return this._effectWrapper.alphaMode}set alphaMode(e){this._effectWrapper.alphaMode=e}get samples(){return this._samples}set samples(e){this._samples=Math.min(e,this._engine.getCaps().maxMSAASamples),this._textures.forEach(t=>{t.setSamples(this._samples)})}get shaderLanguage(){return this._shaderLanguage}getEffectName(){return this._fragmentUrl}set onActivate(e){this._onActivateObserver&&this.onActivateObservable.remove(this._onActivateObserver),e&&(this._onActivateObserver=this.onActivateObservable.add(e))}set onSizeChanged(e){this._onSizeChangedObserver&&this.onSizeChangedObservable.remove(this._onSizeChangedObserver),this._onSizeChangedObserver=this.onSizeChangedObservable.add(e)}set onApply(e){this._onApplyObserver&&this.onApplyObservable.remove(this._onApplyObserver),this._onApplyObserver=this.onApplyObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}get inputTexture(){return this._textures.data[this._currentRenderTextureInd]}set inputTexture(e){this._forcedOutputTexture=e}restoreDefaultInputTexture(){this._forcedOutputTexture&&(this._forcedOutputTexture=null,this.markTextureDirty())}getCamera(){return this._camera}get texelSize(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.texelSize:(this._forcedOutputTexture&&this._texelSize.copyFromFloats(1/this._forcedOutputTexture.width,1/this._forcedOutputTexture.height),this._texelSize)}constructor(e,t,i,r,s,a,o=1,l,c,f=null,h=0,d="postprocess",u,m=!1,p=5,_,g){var S,E,R,I,y,M,D,O,V,N,F,U;this._parentContainer=null,this.width=-1,this.height=-1,this.nodeMaterialSource=null,this._outputTexture=null,this.autoClear=!0,this.forceAutoClearInAlphaMode=!1,this.animations=[],this.enablePixelPerfectMode=!1,this.forceFullscreenViewport=!0,this.scaleMode=1,this.alwaysForcePOT=!1,this._samples=1,this.adaptScaleToCurrentViewport=!1,this.doNotSerialize=!1,this._webGPUReady=!1,this._reusable=!1,this._renderId=0,this.externalTextureSamplerBinding=!1,this._textures=new Bi(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new we(1,1),this._texelSize=we.Zero(),this.onActivateObservable=new ie,this.onSizeChangedObservable=new ie,this.onApplyObservable=new ie,this.onBeforeRenderObservable=new ie,this.onAfterRenderObservable=new ie,this.onDisposeObservable=new ie;let v=1,x=null,A;if(i&&!Array.isArray(i)){let G=i;i=(S=G.uniforms)!=null?S:null,r=(E=G.samplers)!=null?E:null,v=(R=G.size)!=null?R:1,a=(I=G.camera)!=null?I:null,o=(y=G.samplingMode)!=null?y:1,l=G.engine,c=G.reusable,f=Array.isArray(G.defines)?G.defines.join(` +`):(M=G.defines)!=null?M:null,h=(D=G.textureType)!=null?D:0,d=(O=G.vertexUrl)!=null?O:"postprocess",u=G.indexParameters,m=(V=G.blockCompilation)!=null?V:!1,p=(N=G.textureFormat)!=null?N:5,_=(F=G.shaderLanguage)!=null?F:0,x=(U=G.uniformBuffers)!=null?U:null,g=G.extraInitializations,A=G.effectWrapper}else s&&(typeof s=="number"?v=s:v={width:s.width,height:s.height});if(this._useExistingThinPostProcess=!!A,this._effectWrapper=A!=null?A:new zr({name:e,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:t,engine:l||(a==null?void 0:a.getScene().getEngine()),uniforms:i,samplers:r,uniformBuffers:x,defines:f,vertexUrl:d,indexParameters:u,blockCompilation:!0,shaderLanguage:_,extraInitializations:void 0}),this.name=e,this.onEffectCreatedObservable=this._effectWrapper.onEffectCreatedObservable,a!=null?(this._camera=a,this._scene=a.getScene(),a.attachPostProcess(this),this._engine=this._scene.getEngine(),this._scene.addPostProcess(this),this.uniqueId=this._scene.getUniqueId()):l&&(this._engine=l,this._engine.postProcesses.push(this)),this._options=v,this.renderTargetSamplingMode=o||1,this._reusable=c||!1,this._textureType=h,this._textureFormat=p,this._shaderLanguage=_||0,this._samplers=r||[],this._samplers.indexOf("textureSampler")===-1&&this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=d,this._parameters=i||[],this._parameters.indexOf("scale")===-1&&this._parameters.push("scale"),this._uniformBuffers=x||[],this._indexParameters=u,!this._useExistingThinPostProcess){this._webGPUReady=this._shaderLanguage===1;let G=[];this._gatherImports(this._engine.isWebGPU&&!n.ForceGLSL,G),this._effectWrapper._webGPUReady=this._webGPUReady,this._effectWrapper._postConstructor(m,f,g,G)}}_gatherImports(e=!1,t){e&&this._webGPUReady?t.push(Promise.all([Promise.resolve().then(()=>(jM(),$2))])):t.push(Promise.all([Promise.resolve().then(()=>(YM(),Z2))]))}getClassName(){return"PostProcess"}getEngine(){return this._engine}getEffect(){return this._effectWrapper.drawWrapper.effect}shareOutputWith(e){return this._disposeTextures(),this._shareOutputWithPostProcess=e,this}useOwnOutput(){this._textures.length==0&&(this._textures=new Bi(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,r,s,a,o,l){this._effectWrapper.updateEffect(e,t,i,r,s,a,o,l),this._postProcessDefines=Array.isArray(this._effectWrapper.options.defines)?this._effectWrapper.options.defines.join(` +`):this._effectWrapper.options.defines}isReusable(){return this._reusable}markTextureDirty(){this.width=-1}_createRenderTargetTexture(e,t,i=0){for(let s=0;s=0;t--)if(e-this._textureCache[t].lastUsedRenderId>100){let i=!1;for(let r=0;r0&&this._textures.reset(),this.width=e,this.height=t;let a=null;if(i){for(let c=0;c{g.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(g,this.samples)}),this._flushTextureCache(),this._renderId++}return u||(u=this._getTarget()),this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(l/f,c/h),this._engine.bindFramebuffer(u,0,l,c,this.forceFullscreenViewport)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(u,0,void 0,void 0,this.forceFullscreenViewport)),(_=(p=this._engine)._debugInsertMarker)==null||_.call(p,`post process ${this.name} input`),this.onActivateObservable.notifyObservers(r),this.autoClear&&(this.alphaMode===0||this.forceAutoClearInAlphaMode)&&this._engine.clear(this.clearColor?this.clearColor:s.clearColor,s._allowPostProcessClearColor,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2),u}get isSupported(){return this._effectWrapper.drawWrapper.effect.isSupported}get aspectRatio(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.aspectRatio:this._forcedOutputTexture?this._forcedOutputTexture.width/this._forcedOutputTexture.height:this.width/this.height}isReady(){return this._effectWrapper.isReady()}apply(){if(!this._effectWrapper.isReady())return null;this._engine.enableEffect(this._effectWrapper.drawWrapper),this._engine.setState(!1),this._engine.setDepthBuffer(!1),this._engine.setDepthWrite(!1),this.alphaConstants&&this.getEngine().setAlphaConstants(this.alphaConstants.r,this.alphaConstants.g,this.alphaConstants.b,this.alphaConstants.a),this._engine.setAlphaMode(this.alphaMode);let e;return this._shareOutputWithPostProcess?e=this._shareOutputWithPostProcess.inputTexture:this._forcedOutputTexture?e=this._forcedOutputTexture:e=this.inputTexture,this.externalTextureSamplerBinding||this._effectWrapper.drawWrapper.effect._bindTexture("textureSampler",e==null?void 0:e.texture),this._effectWrapper.drawWrapper.effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._effectWrapper.drawWrapper.effect),this._effectWrapper.bind(!0),this._effectWrapper.drawWrapper.effect}_disposeTextures(){if(this._shareOutputWithPostProcess||this._forcedOutputTexture){this._disposeTextureCache();return}this._disposeTextureCache(),this._textures.dispose()}_disposeTextureCache(){for(let e=this._textureCache.length-1;e>=0;e--)this._textureCache[e].texture.dispose();this._textureCache.length=0}setPrePassRenderer(e){return this._prePassEffectConfiguration?(this._prePassEffectConfiguration=e.addEffectConfiguration(this._prePassEffectConfiguration),this._prePassEffectConfiguration.enabled=!0,!0):!1}dispose(e){e=e||this._camera,this._useExistingThinPostProcess||this._effectWrapper.dispose(),this._disposeTextures(),this._scene&&this._scene.removePostProcess(this);let t;if(this._parentContainer&&(t=this._parentContainer.postProcesses.indexOf(this),t>-1&&this._parentContainer.postProcesses.splice(t,1),this._parentContainer=null),t=this._engine.postProcesses.indexOf(this),t!==-1&&this._engine.postProcesses.splice(t,1),this.onDisposeObservable.notifyObservers(),!!e){if(e.detachPostProcess(this),t=e._postProcesses.indexOf(this),t===0&&e._postProcesses.length>0){let i=this._camera._getFirstPostProcess();i&&i.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear(),this.onEffectCreatedObservable.clear()}}serialize(){let e=it.Serialize(this),t=this.getCamera()||this._scene&&this._scene.activeCamera;return e.customType="BABYLON."+this.getClassName(),e.cameraId=t?t.id:null,e.reusable=this._reusable,e.textureType=this._textureType,e.fragmentUrl=this._fragmentUrl,e.parameters=this._parameters,e.samplers=this._samplers,e.uniformBuffers=this._uniformBuffers,e.options=this._options,e.defines=this._postProcessDefines,e.textureFormat=this._textureFormat,e.vertexUrl=this._vertexUrl,e.indexParameters=this._indexParameters,e}clone(){let e=this.serialize();e._engine=this._engine,e.cameraId=null;let t=n.Parse(e,this._scene,"");return t?(t.onActivateObservable=this.onActivateObservable.clone(),t.onSizeChangedObservable=this.onSizeChangedObservable.clone(),t.onApplyObservable=this.onApplyObservable.clone(),t.onBeforeRenderObservable=this.onBeforeRenderObservable.clone(),t.onAfterRenderObservable=this.onAfterRenderObservable.clone(),t._prePassEffectConfiguration=this._prePassEffectConfiguration,t):null}static Parse(e,t,i){let r=vn(e.customType);if(!r||!r._Parse)return null;let s=t?t.getCameraById(e.cameraId):null;return r._Parse(e,s,t,i)}static _Parse(e,t,i,r){return it.Parse(()=>new n(e.name,e.fragmentUrl,e.parameters,e.samplers,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable,e.defines,e.textureType,e.vertexUrl,e.indexParameters,!1,e.textureFormat),e,i,r)}};P([w()],Ri.prototype,"uniqueId",void 0);P([w()],Ri.prototype,"name",null);P([w()],Ri.prototype,"width",void 0);P([w()],Ri.prototype,"height",void 0);P([w()],Ri.prototype,"renderTargetSamplingMode",void 0);P([tm()],Ri.prototype,"clearColor",void 0);P([w()],Ri.prototype,"autoClear",void 0);P([w()],Ri.prototype,"forceAutoClearInAlphaMode",void 0);P([w()],Ri.prototype,"alphaMode",null);P([w()],Ri.prototype,"alphaConstants",void 0);P([w()],Ri.prototype,"enablePixelPerfectMode",void 0);P([w()],Ri.prototype,"forceFullscreenViewport",void 0);P([w()],Ri.prototype,"scaleMode",void 0);P([w()],Ri.prototype,"alwaysForcePOT",void 0);P([w("samples")],Ri.prototype,"_samples",void 0);P([w()],Ri.prototype,"adaptScaleToCurrentViewport",void 0);Ft("BABYLON.PostProcess",Ri)});var iB={};tt(iB,{passPixelShaderWGSL:()=>zre});var iC,tB,zre,rB=C(()=>{k();iC="passPixelShader",tB=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d; #define CUSTOM_FRAGMENT_DEFINITIONS @fragment -fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);}`;T.ShadersStoreWGSL[iC]||(T.ShadersStoreWGSL[iC]=tB);zre={name:iC,shader:tB}});var sB={};tt(sB,{passCubePixelShaderWGSL:()=>Xre});var rC,nB,Xre,aB=C(()=>{W();rC="passCubePixelShader",nB=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_cube; +fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);}`;T.ShadersStoreWGSL[iC]||(T.ShadersStoreWGSL[iC]=tB);zre={name:iC,shader:tB}});var sB={};tt(sB,{passCubePixelShaderWGSL:()=>Xre});var rC,nB,Xre,aB=C(()=>{k();rC="passCubePixelShader",nB=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_cube; #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {var uv: vec2f=input.vUV*2.0-1.0; @@ -4186,7 +4186,7 @@ fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(u #ifdef NEGATIVEZ fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(uv,-1.001)); #endif -}`;T.ShadersStoreWGSL[rC]||(T.ShadersStoreWGSL[rC]=nB);Xre={name:rC,shader:nB}});var lB={};tt(lB,{passCubePixelShader:()=>Yre});var nC,oB,Yre,cB=C(()=>{W();nC="passCubePixelShader",oB=`varying vec2 vUV;uniform samplerCube textureSampler; +}`;T.ShadersStoreWGSL[rC]||(T.ShadersStoreWGSL[rC]=nB);Xre={name:rC,shader:nB}});var lB={};tt(lB,{passCubePixelShader:()=>Yre});var nC,oB,Yre,cB=C(()=>{k();nC="passCubePixelShader",oB=`varying vec2 vUV;uniform samplerCube textureSampler; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec2 uv=vUV*2.0-1.0; @@ -4208,8 +4208,8 @@ gl_FragColor=textureCube(textureSampler,vec3(uv,1.001)); #ifdef NEGATIVEZ gl_FragColor=textureCube(textureSampler,vec3(uv,-1.001)); #endif -}`;T.ShadersStore[nC]||(T.ShadersStore[nC]=oB);Yre={name:nC,shader:oB}});var jl,K_,sC=C(()=>{kh();Pi();jl=class n extends zr{_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Promise.resolve().then(()=>(rB(),iB))]))):t.push(Promise.all([Promise.resolve().then(()=>($M(),QM))])),super._gatherImports(e,t)}constructor(e,t=null,i){let r={name:e,engine:t||Le.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:n.FragmentUrl,...i};r.engine||(r.engine=Le.LastCreatedEngine),super(r)}};jl.FragmentUrl="pass";K_=class n extends zr{_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Promise.resolve().then(()=>(aB(),sB))]))):t.push(Promise.all([Promise.resolve().then(()=>(cB(),lB))])),super._gatherImports(e,t)}constructor(e,t=null,i){super({...i,name:e,engine:t||Le.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:n.FragmentUrl,defines:"#define POSITIVEX"}),this._face=0}get face(){return this._face}set face(e){if(!(e<0||e>5))switch(this._face=e,this._face){case 0:this.updateEffect("#define POSITIVEX");break;case 1:this.updateEffect("#define NEGATIVEX");break;case 2:this.updateEffect("#define POSITIVEY");break;case 3:this.updateEffect("#define NEGATIVEY");break;case 4:this.updateEffect("#define POSITIVEZ");break;case 5:this.updateEffect("#define NEGATIVEZ");break}}};K_.FragmentUrl="passCube"});var Wh,aC,oC=C(()=>{Gt();Kl();wr();Hi();Tr();sC();Ut();Wh=class n extends xi{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,r,s,a,o=0,l=!1){let c={size:typeof t=="number"?t:void 0,camera:i,samplingMode:r,engine:s,reusable:a,textureType:o,blockCompilation:l,...t};super(e,jl.FragmentUrl,{effectWrapper:typeof t=="number"||!t.effectWrapper?new jl(e,s,c):void 0,...c})}static _Parse(e,t,i,r){return it.Parse(()=>new n(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable),e,i,r)}};wt("BABYLON.PassPostProcess",Wh);aC=class n extends xi{get face(){return this._effectWrapper.face}set face(e){this._effectWrapper.face=e}getClassName(){return"PassCubePostProcess"}constructor(e,t,i=null,r,s,a,o=0,l=!1){let c={size:typeof t=="number"?t:void 0,camera:i,samplingMode:r,engine:s,reusable:a,textureType:o,blockCompilation:l,...t};super(e,jl.FragmentUrl,{effectWrapper:typeof t=="number"||!t.effectWrapper?new K_(e,s,c):void 0,...c})}static _Parse(e,t,i,r){return it.Parse(()=>new n(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable),e,i,r)}};P([w()],aC.prototype,"face",null);Ie._RescalePostProcessFactory=n=>new Wh("rescale",1,null,2,n,!1,0)});function hB(n,e,t,i,r,s,a,o){let l=e.getEngine();return e.isReady=!1,r=r!=null?r:e.samplingMode,i=i!=null?i:e.type,s=s!=null?s:e.format,a=a!=null?a:e.width,o=o!=null?o:e.height,i===-1&&(i=0),new Promise(c=>{let f=new xi("postprocess",n,null,null,1,null,r,l,!1,void 0,i,void 0,null,!1,s);f.externalTextureSamplerBinding=!0;let h=l.createRenderTargetTexture({width:a,height:o},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:r,type:i,format:s});f.onEffectCreatedObservable.addOnce(d=>{d.executeWhenCompiled(()=>{f.onApply=u=>{u._bindTexture("textureSampler",e),u.setFloat2("scale",1,1)},t.postProcessManager.directRender([f],h,!0),l.restoreDefaultFramebuffer(),l._releaseTexture(e),f&&f.dispose(),h._swapAndDie(e),e.type=i,e.format=5,e.isReady=!0,c(e)})})})}function Hh(n){JT||(JT=new Float32Array(1),fB=new Int32Array(JT.buffer)),JT[0]=n;let e=fB[0],t=e>>16&32768,i=e>>12&2047,r=e>>23&255;return r<103?t:r>142?(t|=31744,t|=(r==255?0:1)&&e&8388607,t):r<113?(i|=2048,t|=(i>>114-r)+(i>>113-r&1),t):(t|=r-112<<10|i>>1,t+=i&1,t)}function ql(n){let e=(n&32768)>>15,t=(n&31744)>>10,i=n&1023;return t===0?(e?-1:1)*Math.pow(2,-14)*(i/Math.pow(2,10)):t==31?i?NaN:(e?-1:1)*(1/0):(e?-1:1)*Math.pow(2,t-15)*(1+i/Math.pow(2,10))}var JT,fB,lC=C(()=>{Fr();gf();oC();Kl();Ln()});function fC(n){return n.split(" ").filter(e=>e!=="").map(e=>parseFloat(e))}function cC(n,e,t){for(;t.length!==e;){let i=fC(n.lines[n.index++]);t.push(...i)}}function Kre(n,e,t){let i=0,r=0,s=0,a=0,o=0,l=0;for(let g=0;g0&&!i.lines[i.index].includes("TILT=");)i.index++;i.lines[i.index].includes("INCLUDE"),i.index++;let s=fC(i.lines[i.index++]);r.numberOfLights=s[0],r.lumensPerLamp=s[1],r.candelaMultiplier=s[2],r.numberOfVerticalAngles=s[3],r.numberOfHorizontalAngles=s[4],r.photometricType=s[5],r.unitsType=s[6],r.width=s[7],r.length=s[8],r.height=s[9];let a=fC(i.lines[i.index++]);r.ballastFactor=a[0],r.fileGenerationType=a[1],r.inputWatts=a[2];for(let m=0;m0)for(let m=0;m=u)&&(p%=u*2,p>u&&(p=u*2-p)),h[_+p*l]=Kre(r,_,p)}return{width:c/2,height:1,data:h}}var uB=C(()=>{Ln()});var mB={};tt(mB,{_IESTextureLoader:()=>hC});var hC,pB=C(()=>{uB();hC=class{constructor(){this.supportCascades=!1}loadCubeData(){throw".ies not supported in Cube."}loadData(e,t,i){let r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=dB(r);i(s.width,s.height,!!t.useMipMaps,!1,()=>{let a=t.getEngine();t.type=1,t.format=6,t._gammaSpace=!1,a._uploadDataToTextureDirectly(t,s.data)})}}});var _B={};tt(_B,{_DDSTextureLoader:()=>dC});var dC,gB=C(()=>{F_();uC();dC=class{constructor(){this.supportCascades=!0}loadCubeData(e,t,i,r){let s=t.getEngine(),a,o=!1,l=1e3;if(Array.isArray(e))for(let c=0;c1)&&t.generateMipMaps,s._unpackFlipY(a.isCompressed),ao.UploadDDSLevels(s,t,f,a,o,6,-1,c),!a.isFourCC&&a.mipmapCount===1?s.generateMipMapsForCubemap(t):l=a.mipmapCount-1}else{let c=e;a=ao.GetDDSInfo(c),t.width=a.width,t.height=a.height,i&&(a.sphericalPolynomial=new $o),o=(a.isRGB||a.isLuminance||a.mipmapCount>1)&&t.generateMipMaps,s._unpackFlipY(a.isCompressed),ao.UploadDDSLevels(s,t,c,a,o,6),!a.isFourCC&&a.mipmapCount===1?s.generateMipMapsForCubemap(t,!1):l=a.mipmapCount-1}s._setCubeMapTextureParams(t,o,l),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r({isDDS:!0,width:t.width,info:a,data:e,texture:t})}loadData(e,t,i){let r=ao.GetDDSInfo(e),s=(r.isRGB||r.isLuminance||r.mipmapCount>1)&&t.generateMipMaps&&Math.max(r.width,r.height)>>r.mipmapCount-1===1;i(r.width,r.height,s,r.isFourCC,()=>{ao.UploadDDSLevels(t.getEngine(),t,e,r,s,1)})}}});function vB(){let n={cTFETC1:0,cTFETC2:1,cTFBC1:2,cTFBC3:3,cTFBC4:4,cTFBC5:5,cTFBC7:6,cTFPVRTC1_4_RGB:8,cTFPVRTC1_4_RGBA:9,cTFASTC_4x4:10,cTFATC_RGB:11,cTFATC_RGBA_INTERPOLATED_ALPHA:12,cTFRGBA32:13,cTFRGB565:14,cTFBGR565:15,cTFRGBA4444:16,cTFFXT1_RGB:17,cTFPVRTC2_4_RGB:18,cTFPVRTC2_4_RGBA:19,cTFETC2_EAC_R11:20,cTFETC2_EAC_RG11:21},e=null;onmessage=a=>{if(a.data.action==="init"){if(a.data.url)try{importScripts(a.data.url)}catch(o){postMessage({action:"error",error:o})}e||(e=BASIS({wasmBinary:a.data.wasmBinary})),e!==null&&e.then(o=>{BASIS=o,o.initializeBasis(),postMessage({action:"init"})})}else if(a.data.action==="transcode"){let o=a.data.config,l=a.data.imageData,c=new BASIS.BasisFile(l),f=i(c),h=a.data.ignoreSupportedFormats?null:t(a.data.config,f),d=!1;h===null&&(d=!0,h=f.hasAlpha?n.cTFBC3:n.cTFBC1);let u=!0;c.startTranscoding()||(u=!1);let m=[];for(let p=0;p>2&3],h[x++]=f[v>>4&3],h[x]=f[v>>6&3]}}return h}}async function EB(n,e,t){return await new Promise((i,r)=>{let s=a=>{a.data.action==="init"?(n.removeEventListener("message",s),i(n)):a.data.action==="error"&&r(a.data.error||"error initializing worker")};n.addEventListener("message",s),n.postMessage({action:"init",url:t?pe.GetBabylonScriptURL(t):void 0,wasmBinary:e},[e])})}var SB=C(()=>{bi()});var Zl,vf,jre,mC,zh,qre,Zre,Qre,tA,eA,iA,pC,TB=C(()=>{bi();Fr();Es();SB();(function(n){n[n.cTFETC1=0]="cTFETC1",n[n.cTFETC2=1]="cTFETC2",n[n.cTFBC1=2]="cTFBC1",n[n.cTFBC3=3]="cTFBC3",n[n.cTFBC4=4]="cTFBC4",n[n.cTFBC5=5]="cTFBC5",n[n.cTFBC7=6]="cTFBC7",n[n.cTFPVRTC1_4_RGB=8]="cTFPVRTC1_4_RGB",n[n.cTFPVRTC1_4_RGBA=9]="cTFPVRTC1_4_RGBA",n[n.cTFASTC_4x4=10]="cTFASTC_4x4",n[n.cTFATC_RGB=11]="cTFATC_RGB",n[n.cTFATC_RGBA_INTERPOLATED_ALPHA=12]="cTFATC_RGBA_INTERPOLATED_ALPHA",n[n.cTFRGBA32=13]="cTFRGBA32",n[n.cTFRGB565=14]="cTFRGB565",n[n.cTFBGR565=15]="cTFBGR565",n[n.cTFRGBA4444=16]="cTFRGBA4444",n[n.cTFFXT1_RGB=17]="cTFFXT1_RGB",n[n.cTFPVRTC2_4_RGB=18]="cTFPVRTC2_4_RGB",n[n.cTFPVRTC2_4_RGBA=19]="cTFPVRTC2_4_RGBA",n[n.cTFETC2_EAC_R11=20]="cTFETC2_EAC_R11",n[n.cTFETC2_EAC_RG11=21]="cTFETC2_EAC_RG11"})(Zl||(Zl={}));vf={JSModuleURL:`${pe._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.js`,WasmModuleURL:`${pe._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.wasm`},jre=(n,e)=>{let t;switch(n){case Zl.cTFETC1:t=36196;break;case Zl.cTFBC1:t=33776;break;case Zl.cTFBC4:t=33779;break;case Zl.cTFASTC_4x4:t=37808;break;case Zl.cTFETC2:t=37496;break;case Zl.cTFBC7:t=36492;break}if(t===void 0)throw"The chosen Basis transcoder format is not currently supported";return t},mC=null,zh=null,qre=0,Zre=!1,Qre=async()=>(mC||(mC=new Promise((n,e)=>{zh?n(zh):pe.LoadFileAsync(pe.GetBabylonScriptURL(vf.WasmModuleURL)).then(t=>{if(typeof URL!="function")return e("Basis transcoder requires an environment with a URL constructor");let i=URL.createObjectURL(new Blob([`(${vB})()`],{type:"application/javascript"}));zh=new Worker(i),EB(zh,t,vf.JSModuleURL).then(n,e)}).catch(e)})),await mC),tA=async(n,e)=>{let t=n instanceof ArrayBuffer?new Uint8Array(n):n;return await new Promise((i,r)=>{Qre().then(()=>{let s=qre++,a=l=>{l.data.action==="transcode"&&l.data.id===s&&(zh.removeEventListener("message",a),l.data.success?i(l.data):r("Transcode is not supported on this device"))};zh.addEventListener("message",a);let o=new Uint8Array(t.byteLength);o.set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),zh.postMessage({action:"transcode",id:s,imageData:o,config:e,ignoreSupportedFormats:Zre},[o.buffer])},s=>{r(s)})})},eA=(n,e)=>{var i,r;let t=(i=e._gl)==null?void 0:i.TEXTURE_2D;n.isCube&&(t=(r=e._gl)==null?void 0:r.TEXTURE_CUBE_MAP),e._bindTextureDirectly(t,n,!0)},iA=(n,e)=>{let t=n.getEngine();for(let i=0;i{t._releaseTexture(s),eA(n,t)})}else n._invertVScale=!n.invertY,n.width=r.width+3&-4,n.height=r.height+3&-4,n.samplingMode=2,eA(n,t),t._uploadDataToTextureDirectly(n,new Uint16Array(r.transcodedPixels.buffer),i,0,4,!0);else{n.width=r.width,n.height=r.height,n.generateMipMaps=e.fileInfo.images[i].levels.length>1;let s=pC.GetInternalFormatFromBasisFormat(e.format,t);n.format=s,eA(n,t);let a=e.fileInfo.images[i].levels;for(let o=0;o_C});var _C,xB=C(()=>{TB();bi();_C=class{constructor(){this.supportCascades=!1}loadCubeData(e,t,i,r,s){if(Array.isArray(e))return;let a=t.getEngine().getCaps(),o={supportedCompressionFormats:{etc1:!!a.etc1,s3tc:!!a.s3tc,pvrtc:!!a.pvrtc,etc2:!!a.etc2,astc:!!a.astc,bc7:!!a.bptc}};tA(e,o).then(l=>{let c=l.fileInfo.images[0].levels.length>1&&t.generateMipMaps;iA(t,l),t.getEngine()._setCubeMapTextureParams(t,c),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()}).catch(l=>{pe.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),t.isReady=!0,s&&s(l)})}loadData(e,t,i){let r=t.getEngine().getCaps(),s={supportedCompressionFormats:{etc1:!!r.etc1,s3tc:!!r.s3tc,pvrtc:!!r.pvrtc,etc2:!!r.etc2,astc:!!r.astc,bc7:!!r.bptc}};tA(e,s).then(a=>{let o=a.fileInfo.images[0].levels[0],l=a.fileInfo.images[0].levels.length>1&&t.generateMipMaps;i(o.width,o.height,l,a.format!==-1,()=>{iA(t,a)})}).catch(a=>{pe.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),pe.Warn(`Failed to transcode Basis file: ${a}`),i(0,0,!1,!1,()=>{},!0)})}}});var j_,RB=C(()=>{j_=class{constructor(){this._count=0,this._data={}}copyFrom(e){this.clear(),e.forEach((t,i)=>this.add(t,i))}get(e){let t=this._data[e];if(t!==void 0)return t}getOrAddWithFactory(e,t){let i=this.get(e);return i!==void 0||(i=t(e),i&&this.add(e,i)),i}getOrAdd(e,t){let i=this.get(e);return i!==void 0?i:(this.add(e,t),t)}contains(e){return this._data[e]!==void 0}add(e,t){return this._data[e]!==void 0?!1:(this._data[e]=t,++this._count,!0)}set(e,t){return this._data[e]===void 0?!1:(this._data[e]=t,!0)}getAndRemove(e){let t=this.get(e);return t!==void 0?(delete this._data[e],--this._count,t):null}remove(e){return this.contains(e)?(delete this._data[e],--this._count,!0):!1}clear(){this._data={},this._count=0}get count(){return this._count}forEach(e){for(let t in this._data){let i=this._data[t];e(t,i)}}first(e){for(let t in this._data){let i=this._data[t],r=e(t,i);if(r)return r}return null}}});function rA(n){n.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")}var gC=C(()=>{});var tn,bB=C(()=>{Gt();Ut();zt();Tr();gC();tn=class n{constructor(){this._dirty=!0,this._tempColor=new lt(0,0,0,0),this._globalCurve=new lt(0,0,0,0),this._highlightsCurve=new lt(0,0,0,0),this._midtonesCurve=new lt(0,0,0,0),this._shadowsCurve=new lt(0,0,0,0),this._positiveCurve=new lt(0,0,0,0),this._negativeCurve=new lt(0,0,0,0),this._globalHue=30,this._globalDensity=0,this._globalSaturation=0,this._globalExposure=0,this._highlightsHue=30,this._highlightsDensity=0,this._highlightsSaturation=0,this._highlightsExposure=0,this._midtonesHue=30,this._midtonesDensity=0,this._midtonesSaturation=0,this._midtonesExposure=0,this._shadowsHue=30,this._shadowsDensity=0,this._shadowsSaturation=0,this._shadowsExposure=0}get globalHue(){return this._globalHue}set globalHue(e){this._globalHue=e,this._dirty=!0}get globalDensity(){return this._globalDensity}set globalDensity(e){this._globalDensity=e,this._dirty=!0}get globalSaturation(){return this._globalSaturation}set globalSaturation(e){this._globalSaturation=e,this._dirty=!0}get globalExposure(){return this._globalExposure}set globalExposure(e){this._globalExposure=e,this._dirty=!0}get highlightsHue(){return this._highlightsHue}set highlightsHue(e){this._highlightsHue=e,this._dirty=!0}get highlightsDensity(){return this._highlightsDensity}set highlightsDensity(e){this._highlightsDensity=e,this._dirty=!0}get highlightsSaturation(){return this._highlightsSaturation}set highlightsSaturation(e){this._highlightsSaturation=e,this._dirty=!0}get highlightsExposure(){return this._highlightsExposure}set highlightsExposure(e){this._highlightsExposure=e,this._dirty=!0}get midtonesHue(){return this._midtonesHue}set midtonesHue(e){this._midtonesHue=e,this._dirty=!0}get midtonesDensity(){return this._midtonesDensity}set midtonesDensity(e){this._midtonesDensity=e,this._dirty=!0}get midtonesSaturation(){return this._midtonesSaturation}set midtonesSaturation(e){this._midtonesSaturation=e,this._dirty=!0}get midtonesExposure(){return this._midtonesExposure}set midtonesExposure(e){this._midtonesExposure=e,this._dirty=!0}get shadowsHue(){return this._shadowsHue}set shadowsHue(e){this._shadowsHue=e,this._dirty=!0}get shadowsDensity(){return this._shadowsDensity}set shadowsDensity(e){this._shadowsDensity=e,this._dirty=!0}get shadowsSaturation(){return this._shadowsSaturation}set shadowsSaturation(e){this._shadowsSaturation=e,this._dirty=!0}get shadowsExposure(){return this._shadowsExposure}set shadowsExposure(e){this._shadowsExposure=e,this._dirty=!0}getClassName(){return"ColorCurves"}static Bind(e,t,i="vCameraColorCurvePositive",r="vCameraColorCurveNeutral",s="vCameraColorCurveNegative"){e._dirty&&(e._dirty=!1,e._getColorGradingDataToRef(e._globalHue,e._globalDensity,e._globalSaturation,e._globalExposure,e._globalCurve),e._getColorGradingDataToRef(e._highlightsHue,e._highlightsDensity,e._highlightsSaturation,e._highlightsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._highlightsCurve),e._getColorGradingDataToRef(e._midtonesHue,e._midtonesDensity,e._midtonesSaturation,e._midtonesExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._midtonesCurve),e._getColorGradingDataToRef(e._shadowsHue,e._shadowsDensity,e._shadowsSaturation,e._shadowsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._shadowsCurve),e._highlightsCurve.subtractToRef(e._midtonesCurve,e._positiveCurve),e._midtonesCurve.subtractToRef(e._shadowsCurve,e._negativeCurve)),t&&(t.setFloat4(i,e._positiveCurve.r,e._positiveCurve.g,e._positiveCurve.b,e._positiveCurve.a),t.setFloat4(r,e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4(s,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))}_getColorGradingDataToRef(e,t,i,r,s){e!=null&&(e=n._Clamp(e,0,360),t=n._Clamp(t,-100,100),i=n._Clamp(i,-100,100),r=n._Clamp(r,-100,100),t=n._ApplyColorGradingSliderNonlinear(t),t*=.5,r=n._ApplyColorGradingSliderNonlinear(r),t<0&&(t*=-1,e=(e+180)%360),n._FromHSBToRef(e,t,50+.25*r,s),s.scaleToRef(2,s),s.a=1+.01*i)}static _ApplyColorGradingSliderNonlinear(e){e/=100;let t=Math.abs(e);return t=Math.pow(t,2),e<0&&(t*=-1),t*=100,t}static _FromHSBToRef(e,t,i,r){let s=n._Clamp(e,0,360),a=n._Clamp(t/100,0,1),o=n._Clamp(i/100,0,1);if(a===0)r.r=o,r.g=o,r.b=o;else{s/=60;let l=Math.floor(s),c=s-l,f=o*(1-a),h=o*(1-a*c),d=o*(1-a*(1-c));switch(l){case 0:r.r=o,r.g=d,r.b=f;break;case 1:r.r=h,r.g=o,r.b=f;break;case 2:r.r=f,r.g=o,r.b=d;break;case 3:r.r=f,r.g=h,r.b=o;break;case 4:r.r=d,r.g=f,r.b=o;break;default:r.r=o,r.g=f,r.b=h;break}}r.a=1}static _Clamp(e,t,i){return Math.min(Math.max(e,t),i)}clone(){return it.Clone(()=>new n,this)}serialize(){return it.Serialize(this)}static Parse(e){return it.Parse(()=>new n,e,null,null)}};tn.PrepareUniforms=rA;P([w()],tn.prototype,"_globalHue",void 0);P([w()],tn.prototype,"_globalDensity",void 0);P([w()],tn.prototype,"_globalSaturation",void 0);P([w()],tn.prototype,"_globalExposure",void 0);P([w()],tn.prototype,"_highlightsHue",void 0);P([w()],tn.prototype,"_highlightsDensity",void 0);P([w()],tn.prototype,"_highlightsSaturation",void 0);P([w()],tn.prototype,"_highlightsExposure",void 0);P([w()],tn.prototype,"_midtonesHue",void 0);P([w()],tn.prototype,"_midtonesDensity",void 0);P([w()],tn.prototype,"_midtonesSaturation",void 0);P([w()],tn.prototype,"_midtonesExposure",void 0);it._ColorCurvesParser=tn.Parse});function IB(n,e){e.EXPOSURE&&n.push("exposureLinear"),e.CONTRAST&&n.push("contrast"),e.COLORGRADING&&n.push("colorTransformSettings"),(e.VIGNETTE||e.DITHER)&&n.push("vInverseScreenSize"),e.VIGNETTE&&(n.push("vignetteSettings1"),n.push("vignetteSettings2")),e.COLORCURVES&&rA(n),e.DITHER&&n.push("ditherIntensity")}function MB(n,e){e.COLORGRADING&&n.push("txColorTransform")}var CB=C(()=>{gC()});var kt,q_=C(()=>{Gt();Ut();hi();zt();bB();$a();Tr();CB();Hi();kt=class n{constructor(){this.colorCurves=new tn,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=n.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new lt(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=n.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.outputTextureWidth=0,this.outputTextureHeight=0,this.onUpdateParameters=new ie}get colorCurvesEnabled(){return this._colorCurvesEnabled}set colorCurvesEnabled(e){this._colorCurvesEnabled!==e&&(this._colorCurvesEnabled=e,this._updateParameters())}get colorGradingTexture(){return this._colorGradingTexture}set colorGradingTexture(e){this._colorGradingTexture!==e&&(this._colorGradingTexture=e,this._updateParameters())}get colorGradingEnabled(){return this._colorGradingEnabled}set colorGradingEnabled(e){this._colorGradingEnabled!==e&&(this._colorGradingEnabled=e,this._updateParameters())}get colorGradingWithGreenDepth(){return this._colorGradingWithGreenDepth}set colorGradingWithGreenDepth(e){this._colorGradingWithGreenDepth!==e&&(this._colorGradingWithGreenDepth=e,this._updateParameters())}get colorGradingBGR(){return this._colorGradingBGR}set colorGradingBGR(e){this._colorGradingBGR!==e&&(this._colorGradingBGR=e,this._updateParameters())}get exposure(){return this._exposure}set exposure(e){this._exposure!==e&&(this._exposure=e,this._updateParameters())}get toneMappingEnabled(){return this._toneMappingEnabled}set toneMappingEnabled(e){this._toneMappingEnabled!==e&&(this._toneMappingEnabled=e,this._updateParameters())}get toneMappingType(){return this._toneMappingType}set toneMappingType(e){this._toneMappingType!==e&&(this._toneMappingType=e,this._updateParameters())}get contrast(){return this._contrast}set contrast(e){this._contrast!==e&&(this._contrast=e,this._updateParameters())}get vignetteCentreY(){return this.vignetteCenterY}set vignetteCentreY(e){this.vignetteCenterY=e}get vignetteCentreX(){return this.vignetteCenterX}set vignetteCentreX(e){this.vignetteCenterX=e}get vignetteBlendMode(){return this._vignetteBlendMode}set vignetteBlendMode(e){this._vignetteBlendMode!==e&&(this._vignetteBlendMode=e,this._updateParameters())}get vignetteEnabled(){return this._vignetteEnabled}set vignetteEnabled(e){this._vignetteEnabled!==e&&(this._vignetteEnabled=e,this._updateParameters())}get ditheringEnabled(){return this._ditheringEnabled}set ditheringEnabled(e){this._ditheringEnabled!==e&&(this._ditheringEnabled=e,this._updateParameters())}get ditheringIntensity(){return this._ditheringIntensity}set ditheringIntensity(e){this._ditheringIntensity!==e&&(this._ditheringIntensity=e,this._updateParameters())}get skipFinalColorClamp(){return this._skipFinalColorClamp}set skipFinalColorClamp(e){this._skipFinalColorClamp!==e&&(this._skipFinalColorClamp=e,this._updateParameters())}get applyByPostProcess(){return this._applyByPostProcess}set applyByPostProcess(e){this._applyByPostProcess!==e&&(this._applyByPostProcess=e,this._updateParameters())}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,this._updateParameters())}_updateParameters(){this.onUpdateParameters.notifyObservers(this)}getClassName(){return"ImageProcessingConfiguration"}prepareDefines(e,t=!1){if(t!==this.applyByPostProcess||!this._isEnabled){e.VIGNETTE=!1,e.TONEMAPPING=0,e.CONTRAST=!1,e.EXPOSURE=!1,e.COLORCURVES=!1,e.COLORGRADING=!1,e.COLORGRADING3D=!1,e.DITHER=!1,e.IMAGEPROCESSING=!1,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess&&this._isEnabled;return}if(e.VIGNETTE=this.vignetteEnabled,e.VIGNETTEBLENDMODEMULTIPLY=this.vignetteBlendMode===n._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,!this._toneMappingEnabled)e.TONEMAPPING=0;else switch(this._toneMappingType){case n.TONEMAPPING_KHR_PBR_NEUTRAL:e.TONEMAPPING=3;break;case n.TONEMAPPING_ACES:e.TONEMAPPING=2;break;default:e.TONEMAPPING=1;break}e.CONTRAST=this.contrast!==1,e.EXPOSURE=this.exposure!==1,e.COLORCURVES=this.colorCurvesEnabled&&!!this.colorCurves,e.COLORGRADING=this.colorGradingEnabled&&!!this.colorGradingTexture,e.COLORGRADING?e.COLORGRADING3D=this.colorGradingTexture.is3D:e.COLORGRADING3D=!1,e.SAMPLER3DGREENDEPTH=this.colorGradingWithGreenDepth,e.SAMPLER3DBGRMAP=this.colorGradingBGR,e.DITHER=this._ditheringEnabled,e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,e.IMAGEPROCESSING=e.VIGNETTE||!!e.TONEMAPPING||e.CONTRAST||e.EXPOSURE||e.COLORCURVES||e.COLORGRADING||e.DITHER}isReady(){return!this.colorGradingEnabled||!this.colorGradingTexture||this.colorGradingTexture.isReady()}bind(e,t){if(this._colorCurvesEnabled&&this.colorCurves&&tn.Bind(this.colorCurves,e),this._vignetteEnabled||this._ditheringEnabled){let i=1/(this.outputTextureWidth||e.getEngine().getRenderWidth()),r=1/(this.outputTextureHeight||e.getEngine().getRenderHeight());if(e.setFloat2("vInverseScreenSize",i,r),this._ditheringEnabled&&e.setFloat("ditherIntensity",.5*this._ditheringIntensity),this._vignetteEnabled){let s=t!=null?t:r/i,a=Math.tan(this.vignetteCameraFov*.5),o=a*s,l=Math.sqrt(o*a);o=L_(o,l,this.vignetteStretch),a=L_(a,l,this.vignetteStretch),e.setFloat4("vignetteSettings1",o,a,-o*this.vignetteCenterX,-a*this.vignetteCenterY);let c=-2*this.vignetteWeight;e.setFloat4("vignetteSettings2",this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b,c)}}if(e.setFloat("exposureLinear",this.exposure),e.setFloat("contrast",this.contrast),this.colorGradingTexture){e.setTexture("txColorTransform",this.colorGradingTexture);let i=this.colorGradingTexture.getSize().height;e.setFloat4("colorTransformSettings",(i-1)/i,.5/i,i,this.colorGradingTexture.level)}}clone(){return it.Clone(()=>new n,this)}serialize(){return it.Serialize(this)}static Parse(e){let t=it.Parse(()=>new n,e,null,null);return e.vignetteCentreX!==void 0&&(t.vignetteCenterX=e.vignetteCentreX),e.vignetteCentreY!==void 0&&(t.vignetteCenterY=e.vignetteCentreY),t}static get VIGNETTEMODE_MULTIPLY(){return this._VIGNETTEMODE_MULTIPLY}static get VIGNETTEMODE_OPAQUE(){return this._VIGNETTEMODE_OPAQUE}};kt.TONEMAPPING_STANDARD=0;kt.TONEMAPPING_ACES=1;kt.TONEMAPPING_KHR_PBR_NEUTRAL=2;kt.PrepareUniforms=IB;kt.PrepareSamplers=MB;kt._VIGNETTEMODE_MULTIPLY=0;kt._VIGNETTEMODE_OPAQUE=1;P([R2()],kt.prototype,"colorCurves",void 0);P([w()],kt.prototype,"_colorCurvesEnabled",void 0);P([Bt("colorGradingTexture")],kt.prototype,"_colorGradingTexture",void 0);P([w()],kt.prototype,"_colorGradingEnabled",void 0);P([w()],kt.prototype,"_colorGradingWithGreenDepth",void 0);P([w()],kt.prototype,"_colorGradingBGR",void 0);P([w()],kt.prototype,"_exposure",void 0);P([w()],kt.prototype,"_toneMappingEnabled",void 0);P([w()],kt.prototype,"_toneMappingType",void 0);P([w()],kt.prototype,"_contrast",void 0);P([w()],kt.prototype,"vignetteStretch",void 0);P([w()],kt.prototype,"vignetteCenterX",void 0);P([w()],kt.prototype,"vignetteCenterY",void 0);P([w()],kt.prototype,"vignetteWeight",void 0);P([im()],kt.prototype,"vignetteColor",void 0);P([w()],kt.prototype,"vignetteCameraFov",void 0);P([w()],kt.prototype,"_vignetteBlendMode",void 0);P([w()],kt.prototype,"_vignetteEnabled",void 0);P([w()],kt.prototype,"_ditheringEnabled",void 0);P([w()],kt.prototype,"_ditheringIntensity",void 0);P([w()],kt.prototype,"_skipFinalColorClamp",void 0);P([w()],kt.prototype,"_applyByPostProcess",void 0);P([w()],kt.prototype,"_isEnabled",void 0);P([w()],kt.prototype,"outputTextureWidth",void 0);P([w()],kt.prototype,"outputTextureHeight",void 0);it._ImageProcessingConfigurationParser=kt.Parse;wt("BABYLON.ImageProcessingConfiguration",kt)});var es,Z_=C(()=>{Ve();Gi();es=class{constructor(){this.hit=!1,this.distance=0,this.pickedPoint=null,this.pickedMesh=null,this.bu=0,this.bv=0,this.faceId=-1,this.subMeshFaceId=-1,this.subMeshId=0,this.pickedSprite=null,this.thinInstanceIndex=-1,this.ray=null,this.originMesh=null,this.aimTransform=null,this.gripTransform=null}getNormal(e=!1,t=!0){if(!this.pickedMesh||t&&!this.pickedMesh.isVerticesDataPresent(L.NormalKind))return null;let i=this.pickedMesh.getIndices();(i==null?void 0:i.length)===0&&(i=null);let r,s=$.Vector3[0],a=$.Vector3[1],o=$.Vector3[2];if(t){let c=this.pickedMesh.getVerticesData(L.NormalKind),f=i?b.FromArrayToRef(c,i[this.faceId*3]*3,s):s.copyFromFloats(c[this.faceId*3*3],c[this.faceId*3*3+1],c[this.faceId*3*3+2]),h=i?b.FromArrayToRef(c,i[this.faceId*3+1]*3,a):a.copyFromFloats(c[(this.faceId*3+1)*3],c[(this.faceId*3+1)*3+1],c[(this.faceId*3+1)*3+2]),d=i?b.FromArrayToRef(c,i[this.faceId*3+2]*3,o):o.copyFromFloats(c[(this.faceId*3+2)*3],c[(this.faceId*3+2)*3+1],c[(this.faceId*3+2)*3+2]);f=f.scale(this.bu),h=h.scale(this.bv),d=d.scale(1-this.bu-this.bv),r=new b(f.x+h.x+d.x,f.y+h.y+d.y,f.z+h.z+d.z)}else{let c=this.pickedMesh.getVerticesData(L.PositionKind),f=i?b.FromArrayToRef(c,i[this.faceId*3]*3,s):s.copyFromFloats(c[this.faceId*3*3],c[this.faceId*3*3+1],c[this.faceId*3*3+2]),h=i?b.FromArrayToRef(c,i[this.faceId*3+1]*3,a):a.copyFromFloats(c[(this.faceId*3+1)*3],c[(this.faceId*3+1)*3+1],c[(this.faceId*3+1)*3+2]),d=i?b.FromArrayToRef(c,i[this.faceId*3+2]*3,o):o.copyFromFloats(c[(this.faceId*3+2)*3],c[(this.faceId*3+2)*3+1],c[(this.faceId*3+2)*3+2]),u=f.subtract(h),m=d.subtract(h);r=b.Cross(u,m)}let l=(c,f)=>{if(this.thinInstanceIndex!==-1){let d=c._thinInstanceDataStorage.matrixData,u=this.thinInstanceIndex<<4;if(d&&d.length>u){let m=$.Matrix[0];j.FromArrayToRef(d,u,m),b.TransformNormalToRef(f,m,f)}}let h=c.getWorldMatrix();c.nonUniformScaling&&($.Matrix[0].copyFrom(h),h=$.Matrix[0],h.setTranslationFromFloats(0,0,0),h.invert(),h.transposeToRef($.Matrix[1]),h=$.Matrix[1]),b.TransformNormalToRef(f,h,f)};if(e&&l(this.pickedMesh,r),this.ray){let c=$.Vector3[0].copyFrom(r);e||l(this.pickedMesh,c),b.Dot(c,this.ray.direction)>0&&r.negateInPlace()}return r.normalize(),r}getTextureCoordinates(e=L.UVKind){if(!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(e))return null;let t=this.pickedMesh.getIndices();if(!t)return null;let i=this.pickedMesh.getVerticesData(e);if(!i)return null;let r=we.FromArray(i,t[this.faceId*3]*2),s=we.FromArray(i,t[this.faceId*3+1]*2),a=we.FromArray(i,t[this.faceId*3+2]*2);return r=r.scale(this.bu),s=s.scale(this.bv),a=a.scale(1-this.bu-this.bv),new we(r.x+s.x+a.x,r.y+s.y+a.y)}}});var rn,vC=C(()=>{rn=class n{constructor(e,t,i,r,s,a){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=r,this.sourceEvent=s,this.additionalData=a}static CreateNew(e,t,i){let r=e.getScene();return new n(e,r.pointerX,r.pointerY,r.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,r){return new n(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,r)}static CreateNewFromScene(e,t){return new n(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,r){return new n(e,t.x,t.y,null,i,r)}}});function Q_(n,e,t){let i=t.asArray(),r=e.asArray();for(let s=0;s<16;s++)i[s]=r[s];return i[12]-=n.x,i[13]-=n.y,i[14]-=n.z,t.markAsUpdated(),t}function LB(n,e,t){return N_(e,Ra),Q_(n,Ra,ba),N_(ba,t),t}function nA(n,e,t){if(!Ia.eyeAtCamera)return LB(n,e,t);let i=t.asArray(),r=e.asArray();for(let s=0;s<16;s++)i[s]=r[s];return i[12]=0,i[13]=0,i[14]=0,t.markAsUpdated(),t}function EC(n,e,t,i){return Oh(nA(n,e,i),t,i),i}function OB(n,e,t,i,r){for(let s=0;s{yh();Ve();NM();pf();xa=new j,Ra=new j,ba=new j,Ia={getScene:()=>{},eyeAtCamera:!0};$_=fr,SC=tr,NB=$_.prototype._updateMatrixForUniform,wB=tr.prototype.setMatrix});var $e,rr,om=C(()=>{$e=class{};$e.NAME_EFFECTLAYER="EffectLayer";$e.NAME_LAYER="Layer";$e.NAME_LENSFLARESYSTEM="LensFlareSystem";$e.NAME_BOUNDINGBOXRENDERER="BoundingBoxRenderer";$e.NAME_PARTICLESYSTEM="ParticleSystem";$e.NAME_GAMEPAD="Gamepad";$e.NAME_SIMPLIFICATIONQUEUE="SimplificationQueue";$e.NAME_GEOMETRYBUFFERRENDERER="GeometryBufferRenderer";$e.NAME_PREPASSRENDERER="PrePassRenderer";$e.NAME_DEPTHRENDERER="DepthRenderer";$e.NAME_DEPTHPEELINGRENDERER="DepthPeelingRenderer";$e.NAME_POSTPROCESSRENDERPIPELINEMANAGER="PostProcessRenderPipelineManager";$e.NAME_SPRITE="Sprite";$e.NAME_SUBSURFACE="SubSurface";$e.NAME_OUTLINERENDERER="Outline";$e.NAME_PROCEDURALTEXTURE="ProceduralTexture";$e.NAME_SHADOWGENERATOR="ShadowGenerator";$e.NAME_OCTREE="Octree";$e.NAME_PHYSICSENGINE="PhysicsEngine";$e.NAME_AUDIO="Audio";$e.NAME_FLUIDRENDERER="FluidRenderer";$e.NAME_IBLCDFGENERATOR="iblCDFGenerator";$e.NAME_CLUSTEREDLIGHTING="ClusteredLighting";$e.STEP_ISREADYFORMESH_EFFECTLAYER=0;$e.STEP_ISREADYFORMESH_DEPTHRENDERER=1;$e.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER=0;$e.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER=0;$e.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER=0;$e.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER=1;$e.STEP_BEFORECAMERADRAW_PREPASS=0;$e.STEP_BEFORECAMERADRAW_EFFECTLAYER=1;$e.STEP_BEFORECAMERADRAW_LAYER=2;$e.STEP_BEFORERENDERTARGETDRAW_PREPASS=0;$e.STEP_BEFORERENDERTARGETDRAW_LAYER=1;$e.STEP_BEFORERENDERINGMESH_PREPASS=0;$e.STEP_BEFORERENDERINGMESH_OUTLINE=1;$e.STEP_AFTERRENDERINGMESH_PREPASS=0;$e.STEP_AFTERRENDERINGMESH_OUTLINE=1;$e.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW=0;$e.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER=1;$e.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE=0;$e.STEP_BEFORECLEAR_PROCEDURALTEXTURE=0;$e.STEP_BEFORECLEAR_PREPASS=1;$e.STEP_BEFORERENDERTARGETCLEAR_PREPASS=0;$e.STEP_AFTERRENDERTARGETDRAW_PREPASS=0;$e.STEP_AFTERRENDERTARGETDRAW_LAYER=1;$e.STEP_AFTERCAMERADRAW_PREPASS=0;$e.STEP_AFTERCAMERADRAW_EFFECTLAYER=1;$e.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM=2;$e.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW=3;$e.STEP_AFTERCAMERADRAW_LAYER=4;$e.STEP_AFTERCAMERADRAW_FLUIDRENDERER=5;$e.STEP_AFTERCAMERAPOSTPROCESS_LAYER=0;$e.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER=0;$e.STEP_AFTERRENDER_AUDIO=0;$e.STEP_GATHERRENDERTARGETS_DEPTHRENDERER=0;$e.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER=1;$e.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR=2;$e.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER=3;$e.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER=0;$e.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER=1;$e.STEP_GATHERACTIVECAMERARENDERTARGETS_CLUSTEREDLIGHTING=2;$e.STEP_POINTERMOVE_SPRITE=0;$e.STEP_POINTERDOWN_SPRITE=0;$e.STEP_POINTERUP_SPRITE=0;rr=class n extends Array{constructor(e){super(...e)}static Create(){return Object.create(n.prototype)}registerStep(e,t,i){let r=0,s;for(;r{Ve();st=class{};st.POINTERDOWN=1;st.POINTERUP=2;st.POINTERMOVE=4;st.POINTERWHEEL=8;st.POINTERPICK=16;st.POINTERTAP=32;st.POINTERDOUBLETAP=64;sA=class{constructor(e,t){this.type=e,this.event=t}},aA=class extends sA{constructor(e,t,i,r){super(e,t),this.ray=null,this.originalPickingInfo=null,this.skipOnPointerObservable=!1,this.localPosition=new we(i,r)}},Ma=class extends sA{get pickInfo(){return this._pickInfo||this._generatePickInfo(),this._pickInfo}constructor(e,t,i,r=null){super(e,t),this._pickInfo=i,this._inputManager=r}_generatePickInfo(){this._inputManager&&(this._pickInfo=this._inputManager._pickMove(this.event),this._inputManager._setRayOnPointerInfo(this._pickInfo,this.event),this._inputManager=null)}}});var Ql,UB=C(()=>{Ql=class n{constructor(){this.hoverCursor="",this.actions=[],this.isRecursive=!1,this.disposeWhenUnowned=!0}static get HasTriggers(){for(let e in n.Triggers)if(Object.prototype.hasOwnProperty.call(n.Triggers,e))return!0;return!1}static get HasPickTriggers(){for(let e in n.Triggers)if(Object.prototype.hasOwnProperty.call(n.Triggers,e)){let t=parseInt(e);if(t>=1&&t<=7)return!0}return!1}static HasSpecificTrigger(e){for(let t in n.Triggers)if(Object.prototype.hasOwnProperty.call(n.Triggers,t)&&parseInt(t)===e)return!0;return!1}};Ql.Triggers={}});var lo,lm,eg,oA=C(()=>{lo=class{};lo.KEYDOWN=1;lo.KEYUP=2;lm=class{constructor(e,t){this.type=e,this.event=t}},eg=class extends lm{get skipOnPointerObservable(){return this.skipOnKeyboardObservable}set skipOnPointerObservable(e){this.skipOnKeyboardObservable=e}constructor(e,t){super(e,t),this.type=e,this.event=t,this.skipOnKeyboardObservable=!1}}});var Qe,gt,VB,GB,kB,WB,HB,Xh=C(()=>{(function(n){n[n.Generic=0]="Generic",n[n.Keyboard=1]="Keyboard",n[n.Mouse=2]="Mouse",n[n.Touch=3]="Touch",n[n.DualShock=4]="DualShock",n[n.Xbox=5]="Xbox",n[n.Switch=6]="Switch",n[n.DualSense=7]="DualSense"})(Qe||(Qe={}));(function(n){n[n.Horizontal=0]="Horizontal",n[n.Vertical=1]="Vertical",n[n.LeftClick=2]="LeftClick",n[n.MiddleClick=3]="MiddleClick",n[n.RightClick=4]="RightClick",n[n.BrowserBack=5]="BrowserBack",n[n.BrowserForward=6]="BrowserForward",n[n.MouseWheelX=7]="MouseWheelX",n[n.MouseWheelY=8]="MouseWheelY",n[n.MouseWheelZ=9]="MouseWheelZ",n[n.Move=12]="Move"})(gt||(gt={}));(function(n){n[n.Horizontal=0]="Horizontal",n[n.Vertical=1]="Vertical",n[n.LeftClick=2]="LeftClick",n[n.MiddleClick=3]="MiddleClick",n[n.RightClick=4]="RightClick",n[n.BrowserBack=5]="BrowserBack",n[n.BrowserForward=6]="BrowserForward",n[n.MouseWheelX=7]="MouseWheelX",n[n.MouseWheelY=8]="MouseWheelY",n[n.MouseWheelZ=9]="MouseWheelZ",n[n.DeltaHorizontal=10]="DeltaHorizontal",n[n.DeltaVertical=11]="DeltaVertical"})(VB||(VB={}));(function(n){n[n.Cross=0]="Cross",n[n.Circle=1]="Circle",n[n.Square=2]="Square",n[n.Triangle=3]="Triangle",n[n.L1=4]="L1",n[n.R1=5]="R1",n[n.L2=6]="L2",n[n.R2=7]="R2",n[n.Share=8]="Share",n[n.Options=9]="Options",n[n.L3=10]="L3",n[n.R3=11]="R3",n[n.DPadUp=12]="DPadUp",n[n.DPadDown=13]="DPadDown",n[n.DPadLeft=14]="DPadLeft",n[n.DPadRight=15]="DPadRight",n[n.Home=16]="Home",n[n.TouchPad=17]="TouchPad",n[n.LStickXAxis=18]="LStickXAxis",n[n.LStickYAxis=19]="LStickYAxis",n[n.RStickXAxis=20]="RStickXAxis",n[n.RStickYAxis=21]="RStickYAxis"})(GB||(GB={}));(function(n){n[n.Cross=0]="Cross",n[n.Circle=1]="Circle",n[n.Square=2]="Square",n[n.Triangle=3]="Triangle",n[n.L1=4]="L1",n[n.R1=5]="R1",n[n.L2=6]="L2",n[n.R2=7]="R2",n[n.Create=8]="Create",n[n.Options=9]="Options",n[n.L3=10]="L3",n[n.R3=11]="R3",n[n.DPadUp=12]="DPadUp",n[n.DPadDown=13]="DPadDown",n[n.DPadLeft=14]="DPadLeft",n[n.DPadRight=15]="DPadRight",n[n.Home=16]="Home",n[n.TouchPad=17]="TouchPad",n[n.LStickXAxis=18]="LStickXAxis",n[n.LStickYAxis=19]="LStickYAxis",n[n.RStickXAxis=20]="RStickXAxis",n[n.RStickYAxis=21]="RStickYAxis"})(kB||(kB={}));(function(n){n[n.A=0]="A",n[n.B=1]="B",n[n.X=2]="X",n[n.Y=3]="Y",n[n.LB=4]="LB",n[n.RB=5]="RB",n[n.LT=6]="LT",n[n.RT=7]="RT",n[n.Back=8]="Back",n[n.Start=9]="Start",n[n.LS=10]="LS",n[n.RS=11]="RS",n[n.DPadUp=12]="DPadUp",n[n.DPadDown=13]="DPadDown",n[n.DPadLeft=14]="DPadLeft",n[n.DPadRight=15]="DPadRight",n[n.Home=16]="Home",n[n.LStickXAxis=17]="LStickXAxis",n[n.LStickYAxis=18]="LStickYAxis",n[n.RStickXAxis=19]="RStickXAxis",n[n.RStickYAxis=20]="RStickYAxis"})(WB||(WB={}));(function(n){n[n.B=0]="B",n[n.A=1]="A",n[n.Y=2]="Y",n[n.X=3]="X",n[n.L=4]="L",n[n.R=5]="R",n[n.ZL=6]="ZL",n[n.ZR=7]="ZR",n[n.Minus=8]="Minus",n[n.Plus=9]="Plus",n[n.LS=10]="LS",n[n.RS=11]="RS",n[n.DPadUp=12]="DPadUp",n[n.DPadDown=13]="DPadDown",n[n.DPadLeft=14]="DPadLeft",n[n.DPadRight=15]="DPadRight",n[n.Home=16]="Home",n[n.Capture=17]="Capture",n[n.LStickXAxis=18]="LStickXAxis",n[n.LStickYAxis=19]="LStickYAxis",n[n.RStickXAxis=20]="RStickXAxis",n[n.RStickYAxis=21]="RStickYAxis"})(HB||(HB={}))});var zB,co,lA=C(()=>{(function(n){n[n.PointerMove=0]="PointerMove",n[n.PointerDown=1]="PointerDown",n[n.PointerUp=2]="PointerUp"})(zB||(zB={}));co=class{};co.DOM_DELTA_PIXEL=0;co.DOM_DELTA_LINE=1;co.DOM_DELTA_PAGE=2});var fo,AC=C(()=>{lA();Xh();fo=class{static CreateDeviceEvent(e,t,i,r,s,a,o){switch(e){case Qe.Keyboard:return this._CreateKeyboardEvent(i,r,s,a);case Qe.Mouse:if(i===gt.MouseWheelX||i===gt.MouseWheelY||i===gt.MouseWheelZ)return this._CreateWheelEvent(e,t,i,r,s,a);case Qe.Touch:return this._CreatePointerEvent(e,t,i,r,s,a,o);default:throw`Unable to generate event for device ${Qe[e]}`}}static _CreatePointerEvent(e,t,i,r,s,a,o){let l=this._CreateMouseEvent(e,t,i,r,s,a);e===Qe.Mouse?(l.deviceType=Qe.Mouse,l.pointerId=1,l.pointerType="mouse"):(l.deviceType=Qe.Touch,l.pointerId=o!=null?o:t,l.pointerType="touch");let c=0;return c+=s.pollInput(e,t,gt.LeftClick),c+=s.pollInput(e,t,gt.RightClick)*2,c+=s.pollInput(e,t,gt.MiddleClick)*4,l.buttons=c,i===gt.Move?l.type="pointermove":i>=gt.LeftClick&&i<=gt.RightClick&&(l.type=r===1?"pointerdown":"pointerup",l.button=i-2),l}static _CreateWheelEvent(e,t,i,r,s,a){let o=this._CreateMouseEvent(e,t,i,r,s,a);switch(o.pointerId=1,o.type="wheel",o.deltaMode=co.DOM_DELTA_PIXEL,o.deltaX=0,o.deltaY=0,o.deltaZ=0,i){case gt.MouseWheelX:o.deltaX=r;break;case gt.MouseWheelY:o.deltaY=r;break;case gt.MouseWheelZ:o.deltaZ=r;break}return o}static _CreateMouseEvent(e,t,i,r,s,a){let o=this._CreateEvent(a),l=s.pollInput(e,t,gt.Horizontal),c=s.pollInput(e,t,gt.Vertical);return a?(o.movementX=0,o.movementY=0,o.offsetX=o.movementX-a.getBoundingClientRect().x,o.offsetY=o.movementY-a.getBoundingClientRect().y):(o.movementX=s.pollInput(e,t,10),o.movementY=s.pollInput(e,t,11),o.offsetX=0,o.offsetY=0),this._CheckNonCharacterKeys(o,s),o.clientX=l,o.clientY=c,o.x=l,o.y=c,o.deviceType=e,o.deviceSlot=t,o.inputIndex=i,o}static _CreateKeyboardEvent(e,t,i,r){let s=this._CreateEvent(r);return this._CheckNonCharacterKeys(s,i),s.deviceType=Qe.Keyboard,s.deviceSlot=0,s.inputIndex=e,s.type=t===1?"keydown":"keyup",s.key=String.fromCharCode(e),s.keyCode=e,s}static _CheckNonCharacterKeys(e,t){let i=t.isDeviceAvailable(Qe.Keyboard),r=i&&t.pollInput(Qe.Keyboard,0,18)===1,s=i&&t.pollInput(Qe.Keyboard,0,17)===1,a=i&&(t.pollInput(Qe.Keyboard,0,91)===1||t.pollInput(Qe.Keyboard,0,92)===1||t.pollInput(Qe.Keyboard,0,93)===1),o=i&&t.pollInput(Qe.Keyboard,0,16)===1;e.altKey=r,e.ctrlKey=s,e.metaKey=a,e.shiftKey=o}static _CreateEvent(e){let t={};return t.preventDefault=()=>{},t.target=e,t}}});var cA,XB=C(()=>{AC();Xh();cA=class{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,(r,s,a,o)=>{let l=fo.CreateDeviceEvent(r,s,a,o,this);i(r,s,l)}):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===Qe.Mouse||e===Qe.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}});var YB,KB,fA,jB=C(()=>{va();bi();AC();Xh();YB=255,KB=Object.keys(gt).length/2,fA=class{constructor(e,t,i,r){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=pe.IsSafari(),this._usingMacOs=wl()&&/(Mac|iPhone|iPod|iPad)/i.test(navigator.platform),this._keyboardDownEvent=s=>{},this._keyboardUpEvent=s=>{},this._keyboardBlurEvent=s=>{},this._pointerMoveEvent=s=>{},this._pointerDownEvent=s=>{},this._pointerUpEvent=s=>{},this._pointerCancelEvent=s=>{},this._pointerCancelTouch=s=>{},this._pointerLeaveEvent=s=>{},this._pointerWheelEvent=s=>{},this._pointerBlurEvent=s=>{},this._pointerMacOsChromeOutEvent=s=>{},this._eventsAttached=!1,this._mouseId=-1,this._isUsingFirefox=wl()&&navigator.userAgent&&navigator.userAgent.indexOf("Firefox")!==-1,this._isUsingChromium=wl()&&navigator.userAgent&&navigator.userAgent.indexOf("Chrome")!==-1,this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=s=>{},this._gamepadDisconnectedEvent=s=>{},this._eventPrefix=pe.GetPointerPrefix(e),this._engine=e,this._onDeviceConnected=t,this._onDeviceDisconnected=i,this._onInputChanged=r,this._mouseId=this._isUsingFirefox?0:1,this._enableEvents(),this._usingMacOs&&(this._metaKeys=[]),this._engine._onEngineViewChanged||(this._engine._onEngineViewChanged=()=>{this._enableEvents()})}pollInput(e,t,i){let r=this._inputs[e][t];if(!r)throw`Unable to find device ${Qe[e]}`;e>=Qe.DualShock&&e<=Qe.DualSense&&this._updateDevice(e,t,i);let s=r[i];if(s===void 0)throw`Unable to find input ${i} for device ${Qe[e]} in slot ${t}`;return i===gt.Move&&pe.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),s}isDeviceAvailable(e){return this._inputs[e]!==void 0}dispose(){this._onDeviceConnected=()=>{},this._onDeviceDisconnected=()=>{},this._onInputChanged=()=>{},delete this._engine._onEngineViewChanged,this._elementToAttachTo&&this._disableEvents()}_enableEvents(){let e=this==null?void 0:this._engine.getInputElement();if(e&&(!this._eventsAttached||this._elementToAttachTo!==e)){if(this._disableEvents(),this._inputs){for(let t of this._inputs)if(t)for(let i in t){let r=+i,s=t[r];if(s)for(let a=0;a{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(Qe.Keyboard,0,YB));let t=this._inputs[Qe.Keyboard][0];if(t){t[e.keyCode]=1;let i=e;i.inputIndex=e.keyCode,this._usingMacOs&&e.metaKey&&e.key!=="Meta"&&(this._metaKeys.includes(e.keyCode)||this._metaKeys.push(e.keyCode)),this._onInputChanged(Qe.Keyboard,0,i)}},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(Qe.Keyboard,0,YB));let t=this._inputs[Qe.Keyboard][0];if(t){t[e.keyCode]=0;let i=e;if(i.inputIndex=e.keyCode,this._usingMacOs&&e.key==="Meta"&&this._metaKeys.length>0){for(let r of this._metaKeys){let s=fo.CreateDeviceEvent(Qe.Keyboard,0,r,0,this,this._elementToAttachTo);t[r]=0,this._onInputChanged(Qe.Keyboard,0,s)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(Qe.Keyboard,0,i)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){let e=this._inputs[Qe.Keyboard][0];for(let t=0;t{let r=this._getPointerType(i),s=r===Qe.Mouse?0:this._activeTouchIds.indexOf(i.pointerId);if(r===Qe.Touch&&s===-1){let o=this._activeTouchIds.indexOf(-1);if(o>=0)s=o,this._activeTouchIds[o]=i.pointerId,this._onDeviceConnected(r,s);else{pe.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);return}}this._inputs[r]||(this._inputs[r]={}),this._inputs[r][s]||this._addPointerDevice(r,s,i.clientX,i.clientY);let a=this._inputs[r][s];if(a){let o=i;o.inputIndex=gt.Move,a[gt.Horizontal]=i.clientX,a[gt.Vertical]=i.clientY,r===Qe.Touch&&a[gt.LeftClick]===0&&(a[gt.LeftClick]=1),i.pointerId===void 0&&(i.pointerId=this._mouseId),this._onInputChanged(r,s,o),!this._usingSafari&&i.button!==-1&&(o.inputIndex=i.button+2,a[i.button+2]=a[i.button+2]?0:1,this._onInputChanged(r,s,o))}},this._pointerDownEvent=i=>{let r=this._getPointerType(i),s=r===Qe.Mouse?0:i.pointerId;if(r===Qe.Touch){let o=this._activeTouchIds.indexOf(i.pointerId);if(o===-1&&(o=this._activeTouchIds.indexOf(-1)),o>=0)s=o,this._activeTouchIds[o]=i.pointerId;else{pe.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);return}}this._inputs[r]||(this._inputs[r]={}),this._inputs[r][s]?r===Qe.Touch&&this._onDeviceConnected(r,s):this._addPointerDevice(r,s,i.clientX,i.clientY);let a=this._inputs[r][s];if(a){let o=a[gt.Horizontal],l=a[gt.Vertical];if(r===Qe.Mouse){if(i.pointerId===void 0&&(i.pointerId=this._mouseId),!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(this._mouseId)}catch(f){}}else if(i.pointerId&&!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(i.pointerId)}catch(f){}a[gt.Horizontal]=i.clientX,a[gt.Vertical]=i.clientY,a[i.button+2]=1;let c=i;c.inputIndex=i.button+2,this._onInputChanged(r,s,c),(o!==i.clientX||l!==i.clientY)&&(c.inputIndex=gt.Move,this._onInputChanged(r,s,c))}},this._pointerUpEvent=i=>{var c,f,h,d,u;let r=this._getPointerType(i),s=r===Qe.Mouse?0:this._activeTouchIds.indexOf(i.pointerId);if(r===Qe.Touch){if(s===-1)return;this._activeTouchIds[s]=-1}let a=(c=this._inputs[r])==null?void 0:c[s],o=i.button,l=a&&a[o+2]!==0;if(!l&&this._isUsingFirefox&&this._usingMacOs&&a&&(o=o===2?0:2,l=a[o+2]!==0),l){let m=a[gt.Horizontal],p=a[gt.Vertical];a[gt.Horizontal]=i.clientX,a[gt.Vertical]=i.clientY,a[o+2]=0;let _=i;i.pointerId===void 0&&(i.pointerId=this._mouseId),(m!==i.clientX||p!==i.clientY)&&(_.inputIndex=gt.Move,this._onInputChanged(r,s,_)),_.inputIndex=o+2,r===Qe.Mouse&&this._mouseId>=0&&((h=(f=this._elementToAttachTo).hasPointerCapture)!=null&&h.call(f,this._mouseId))?this._elementToAttachTo.releasePointerCapture(this._mouseId):i.pointerId&&((u=(d=this._elementToAttachTo).hasPointerCapture)!=null&&u.call(d,i.pointerId))&&this._elementToAttachTo.releasePointerCapture(i.pointerId),this._onInputChanged(r,s,_),r===Qe.Touch&&this._onDeviceDisconnected(r,s)}},this._pointerCancelTouch=i=>{var a,o;let r=this._activeTouchIds.indexOf(i);if(r===-1)return;(o=(a=this._elementToAttachTo).hasPointerCapture)!=null&&o.call(a,i)&&this._elementToAttachTo.releasePointerCapture(i),this._inputs[Qe.Touch][r][gt.LeftClick]=0;let s=fo.CreateDeviceEvent(Qe.Touch,r,gt.LeftClick,0,this,this._elementToAttachTo,i);this._onInputChanged(Qe.Touch,r,s),this._activeTouchIds[r]=-1,this._onDeviceDisconnected(Qe.Touch,r)},this._pointerCancelEvent=i=>{var r,s;if(i.pointerType==="mouse"){let a=this._inputs[Qe.Mouse][0];this._mouseId>=0&&((s=(r=this._elementToAttachTo).hasPointerCapture)!=null&&s.call(r,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let o=gt.LeftClick;o<=gt.BrowserForward;o++)if(a[o]===1){a[o]=0;let l=fo.CreateDeviceEvent(Qe.Mouse,0,o,0,this,this._elementToAttachTo);this._onInputChanged(Qe.Mouse,0,l)}}else this._pointerCancelTouch(i.pointerId)},this._pointerLeaveEvent=i=>{i.pointerType==="pen"&&this._pointerCancelTouch(i.pointerId)},this._wheelEventName="onwheel"in document.createElement("div")?"wheel":document.onmousewheel!==void 0?"mousewheel":"DOMMouseScroll";let e=!1,t=function(){};try{let i=Object.defineProperty({},"passive",{get:function(){e=!0}});this._elementToAttachTo.addEventListener("test",t,i),this._elementToAttachTo.removeEventListener("test",t,i)}catch(i){}this._pointerBlurEvent=()=>{var i,r,s,a,o;if(this.isDeviceAvailable(Qe.Mouse)){let l=this._inputs[Qe.Mouse][0];this._mouseId>=0&&((r=(i=this._elementToAttachTo).hasPointerCapture)!=null&&r.call(i,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let c=gt.LeftClick;c<=gt.BrowserForward;c++)if(l[c]===1){l[c]=0;let f=fo.CreateDeviceEvent(Qe.Mouse,0,c,0,this,this._elementToAttachTo);this._onInputChanged(Qe.Mouse,0,f)}}if(this.isDeviceAvailable(Qe.Touch)){let l=this._inputs[Qe.Touch];for(let c=0;c{let r=Qe.Mouse,s=0;this._inputs[r]||(this._inputs[r]=[]),this._inputs[r][s]||(this._pointerActive=!0,this._registerDevice(r,s,KB));let a=this._inputs[r][s];if(a){a[gt.MouseWheelX]=i.deltaX||0,a[gt.MouseWheelY]=i.deltaY||i.wheelDelta||0,a[gt.MouseWheelZ]=i.deltaZ||0;let o=i;i.pointerId===void 0&&(i.pointerId=this._mouseId),a[gt.MouseWheelX]!==0&&(o.inputIndex=gt.MouseWheelX,this._onInputChanged(r,s,o)),a[gt.MouseWheelY]!==0&&(o.inputIndex=gt.MouseWheelY,this._onInputChanged(r,s,o)),a[gt.MouseWheelZ]!==0&&(o.inputIndex=gt.MouseWheelZ,this._onInputChanged(r,s,o))}},this._usingMacOs&&this._isUsingChromium&&(this._pointerMacOsChromeOutEvent=i=>{i.buttons>1&&this._pointerCancelEvent(i)},this._elementToAttachTo.addEventListener("lostpointercapture",this._pointerMacOsChromeOutEvent)),this._elementToAttachTo.addEventListener(this._eventPrefix+"move",this._pointerMoveEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"down",this._pointerDownEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"up",this._pointerUpEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"cancel",this._pointerCancelEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"leave",this._pointerLeaveEvent),this._elementToAttachTo.addEventListener("blur",this._pointerBlurEvent),this._elementToAttachTo.addEventListener(this._wheelEventName,this._pointerWheelEvent,e?{passive:!1}:!1),this._pointerInputClearObserver=this._engine.onEndFrameObservable.add(()=>{if(this.isDeviceAvailable(Qe.Mouse)){let i=this._inputs[Qe.Mouse][0];i[gt.MouseWheelX]=0,i[gt.MouseWheelY]=0,i[gt.MouseWheelZ]=0}})}_handleGamepadActions(){this._gamepadConnectedEvent=e=>{this._addGamePad(e.gamepad)},this._gamepadDisconnectedEvent=e=>{if(this._gamepads){let t=this._getGamepadDeviceType(e.gamepad.id),i=e.gamepad.index;this._unregisterDevice(t,i),delete this._gamepads[i]}},window.addEventListener("gamepadconnected",this._gamepadConnectedEvent),window.addEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)}_updateDevice(e,t,i){let r=navigator.getGamepads()[t];if(r&&e===this._gamepads[t]){let s=this._inputs[e][t];i>=r.buttons.length?s[i]=r.axes[i-r.buttons.length].valueOf():s[i]=r.buttons[i].value}}_getGamepadDeviceType(e){return e.indexOf("054c")!==-1?e.indexOf("0ce6")!==-1?Qe.DualSense:Qe.DualShock:e.indexOf("Xbox One")!==-1||e.search("Xbox 360")!==-1||e.search("xinput")!==-1?Qe.Xbox:e.indexOf("057e")!==-1?Qe.Switch:Qe.Generic}_getPointerType(e){let t=Qe.Mouse;return(e.pointerType==="touch"||e.pointerType==="pen"||e.touches)&&(t=Qe.Touch),t}}});var tg,qB=C(()=>{hi();tg=class{constructor(e,t,i=0){this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new ie,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}}});var hA,ZB=C(()=>{Xh();XB();jB();qB();hA=class{constructor(e){this._registeredManagers=new Array,this._refCount=0,this.registerManager=a=>{for(let o=0;o{let o=this._registeredManagers.indexOf(a);o>-1&&this._registeredManagers.splice(o,1)};let t=Object.keys(Qe).length/2;this._devices=new Array(t);let i=(a,o)=>{this._devices[a]||(this._devices[a]=new Array),this._devices[a][o]||(this._devices[a][o]=o);for(let l of this._registeredManagers){let c=new tg(this._deviceInputSystem,a,o);l._addDevice(c)}},r=(a,o)=>{var l;(l=this._devices[a])!=null&&l[o]&&delete this._devices[a][o];for(let c of this._registeredManagers)c._removeDevice(a,o)},s=(a,o,l)=>{if(l)for(let c of this._registeredManagers)c._onInputChanged(a,o,l)};typeof _native!="undefined"?this._deviceInputSystem=new cA(i,r,s):this._deviceInputSystem=new fA(e,i,r,s)}dispose(){this._deviceInputSystem.dispose()}}});var dA,QB=C(()=>{Xh();hi();ZB();dA=class{getDeviceSource(e,t){if(t===void 0){if(this._firstDevice[e]===void 0)return null;t=this._firstDevice[e]}return!this._devices[e]||this._devices[e][t]===void 0?null:this._devices[e][t]}getDeviceSources(e){return this._devices[e]?this._devices[e].filter(t=>!!t):[]}constructor(e){let t=Object.keys(Qe).length/2;this._devices=new Array(t),this._firstDevice=new Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new hA(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new ie(i=>{for(let r of this._devices)if(r)for(let s of r)s&&this.onDeviceConnectedObservable.notifyObserver(i,s)}),this.onDeviceDisconnectedObservable=new ie,this._engine._deviceSourceManager.registerManager(this),this._onDisposeObserver=e.onDisposeObservable.add(()=>{this.dispose()})}dispose(){this.onDeviceConnectedObservable.clear(),this.onDeviceDisconnectedObservable.clear(),this._engine._deviceSourceManager&&(this._engine._deviceSourceManager.unregisterManager(this),--this._engine._deviceSourceManager._refCount<1&&(this._engine._deviceSourceManager.dispose(),delete this._engine._deviceSourceManager)),this._engine.onDisposeObservable.remove(this._onDisposeObserver)}_addDevice(e){this._devices[e.deviceType]||(this._devices[e.deviceType]=[]),this._devices[e.deviceType][e.deviceSlot]||(this._devices[e.deviceType][e.deviceSlot]=e,this._updateFirstDevices(e.deviceType)),this.onDeviceConnectedObservable.notifyObservers(e)}_removeDevice(e,t){var r,s;let i=(r=this._devices[e])==null?void 0:r[t];this.onDeviceDisconnectedObservable.notifyObservers(i),(s=this._devices[e])!=null&&s[t]&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){var r,s;(s=(r=this._devices[e])==null?void 0:r[t])==null||s.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case Qe.Keyboard:case Qe.Mouse:this._firstDevice[e]=0;break;case Qe.Touch:case Qe.DualSense:case Qe.DualShock:case Qe.Xbox:case Qe.Switch:case Qe.Generic:{delete this._firstDevice[e];let t=this._devices[e];if(t){for(let i=0;i{Yh=class{};Yh._IsPickingAvailable=!1});var uA,On,$B=C(()=>{oo();UB();Z_();Ve();vC();oA();Xh();QB();Pi();xC();uA=class{constructor(){this._singleClick=!1,this._doubleClick=!1,this._hasSwiped=!1,this._ignore=!1}get singleClick(){return this._singleClick}get doubleClick(){return this._doubleClick}get hasSwiped(){return this._hasSwiped}get ignore(){return this._ignore}set singleClick(e){this._singleClick=e}set doubleClick(e){this._doubleClick=e}set hasSwiped(e){this._hasSwiped=e}set ignore(e){this._ignore=e}},On=class n{constructor(e){this._alreadyAttached=!1,this._meshPickProceed=!1,this._currentPickResult=null,this._previousPickResult=null,this._activePointerIds=new Array,this._activePointerIdsCount=0,this._doubleClickOccured=!1,this._isSwiping=!1,this._swipeButtonPressed=-1,this._skipPointerTap=!1,this._isMultiTouchGesture=!1,this._pointerX=0,this._pointerY=0,this._startingPointerPosition=new we(0,0),this._previousStartingPointerPosition=new we(0,0),this._startingPointerTime=0,this._previousStartingPointerTime=0,this._pointerCaptures={},this._meshUnderPointerId={},this._movePointerInfo=null,this._cameraObserverCount=0,this._delayedClicks=[null,null,null,null,null],this._deviceSourceManager=null,this._scene=e||Le.LastCreatedScene,this._scene}get meshUnderPointer(){return this._movePointerInfo&&(this._movePointerInfo._generatePickInfo(),this._movePointerInfo=null),this._pointerOverMesh}getMeshUnderPointerByPointerId(e){return this._meshUnderPointerId[e]||null}get unTranslatedPointer(){return new we(this._unTranslatedPointerX,this._unTranslatedPointerY)}get pointerX(){return this._pointerX}set pointerX(e){this._pointerX=e}get pointerY(){return this._pointerY}set pointerY(e){this._pointerY=e}_updatePointerPosition(e){let t=this._scene.getEngine().getInputElementClientRect();t&&(this._pointerX=e.clientX-t.left,this._pointerY=e.clientY-t.top,this._unTranslatedPointerX=this._pointerX,this._unTranslatedPointerY=this._pointerY)}_processPointerMove(e,t){let i=this._scene,r=i.getEngine(),s=r.getInputElement();s&&(s.tabIndex=r.canvasTabIndex,i.doNotHandleCursors||(s.style.cursor=i.defaultCursor)),this._setCursorAndPointerOverMesh(e,t,i);for(let l of i._pointerMoveStage){e=e||this._pickMove(t);let c=!!(e!=null&&e.pickedMesh);e=l.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,c,s)}let a=t.inputIndex>=gt.MouseWheelX&&t.inputIndex<=gt.MouseWheelZ?st.POINTERWHEEL:st.POINTERMOVE;i.onPointerMove&&(e=e||this._pickMove(t),i.onPointerMove(t,e,a));let o;e?(o=new Ma(a,t,e),this._setRayOnPointerInfo(e,t)):(o=new Ma(a,t,null,this),this._movePointerInfo=o),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(o,a)}_setRayOnPointerInfo(e,t){let i=this._scene;e&&Yh._IsPickingAvailable&&(e.ray||(e.ray=i.createPickingRay(t.offsetX,t.offsetY,j.Identity(),i.activeCamera)))}_addCameraPointerObserver(e,t){return this._cameraObserverCount++,this._scene.onPointerObservable.add(e,t)}_removeCameraPointerObserver(e){return this._cameraObserverCount--,this._scene.onPointerObservable.remove(e)}_checkForPicking(){return!!(this._scene.onPointerObservable.observers.length>this._cameraObserverCount||this._scene.onPointerPick)}_checkPrePointerObservable(e,t,i){let r=this._scene,s=new aA(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(s.originalPickingInfo=e,s.ray=e.ray,t.pointerType==="xr-near"&&e.originMesh&&(s.nearInteractionPickingInfo=e)),r.onPrePointerObservable.notifyObservers(s,i),!!s.skipOnPointerObservable}_pickMove(e){let t=this._scene,i=t.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,t.pointerMovePredicate,t.pointerMoveFastCheck,t.cameraToUseForPointers,t.pointerMoveTrianglePredicate);return this._setCursorAndPointerOverMesh(i,e,t),i}_setCursorAndPointerOverMesh(e,t,i){let s=i.getEngine().getInputElement();if(e!=null&&e.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!i.doNotHandleCursors&&s&&this._pointerOverMesh){let a=this._pointerOverMesh._getActionManagerForTrigger();a&&a.hasPointerTriggers&&(s.style.cursor=a.hoverCursor||i.hoverCursor)}}else this.setPointerOverMesh(null,t.pointerId,e,t)}simulatePointerMove(e,t){let i=new PointerEvent("pointermove",t);i.inputIndex=gt.Move,!this._checkPrePointerObservable(e,i,st.POINTERMOVE)&&this._processPointerMove(e,i)}simulatePointerDown(e,t){let i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,!this._checkPrePointerObservable(e,i,st.POINTERDOWN)&&this._processPointerDown(e,i)}_processPointerDown(e,t){let i=this._scene;if(e!=null&&e.pickedMesh){this._pickedDownMesh=e.pickedMesh;let a=e.pickedMesh._getActionManagerForTrigger();if(a){if(a.hasPickTriggers)switch(a.processTrigger(5,new rn(e.pickedMesh,i.pointerX,i.pointerY,e.pickedMesh,t,e)),t.button){case 0:a.processTrigger(2,new rn(e.pickedMesh,i.pointerX,i.pointerY,e.pickedMesh,t,e));break;case 1:a.processTrigger(4,new rn(e.pickedMesh,i.pointerX,i.pointerY,e.pickedMesh,t,e));break;case 2:a.processTrigger(3,new rn(e.pickedMesh,i.pointerX,i.pointerY,e.pickedMesh,t,e));break}a.hasSpecificTrigger(8)&&window.setTimeout(()=>{let o=i.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,l=>l.isPickable&&l.isVisible&&l.isReady()&&l.actionManager&&l.actionManager.hasSpecificTrigger(8)&&l===this._pickedDownMesh,!1,i.cameraToUseForPointers);o!=null&&o.pickedMesh&&a&&this._activePointerIdsCount!==0&&Date.now()-this._startingPointerTime>n.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,a.processTrigger(8,rn.CreateNew(o.pickedMesh,t)))},n.LongPressDelay)}}else for(let a of i._pointerDownStage)e=a.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let r,s=st.POINTERDOWN;e?(i.onPointerDown&&i.onPointerDown(t,e,s),r=new Ma(s,t,e),this._setRayOnPointerInfo(e,t)):r=new Ma(s,t,null,this),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(r,s)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,i){let r=new PointerEvent("pointerup",t);r.inputIndex=gt.Move;let s=new uA;i?s.doubleClick=!0:s.singleClick=!0,!this._checkPrePointerObservable(e,r,st.POINTERUP)&&this._processPointerUp(e,r,s)}_processPointerUp(e,t,i){let r=this._scene;if(e!=null&&e.pickedMesh){if(this._pickedUpMesh=e.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(r.onPointerPick&&r.onPointerPick(t,e),i.singleClick&&!i.ignore&&r.onPointerObservable.observers.length>this._cameraObserverCount)){let a=st.POINTERPICK,o=new Ma(a,t,e);this._setRayOnPointerInfo(e,t),r.onPointerObservable.notifyObservers(o,a)}let s=e.pickedMesh._getActionManagerForTrigger();if(s&&!i.ignore){s.processTrigger(7,rn.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&s.processTrigger(1,rn.CreateNew(e.pickedMesh,t,e));let a=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&a&&a.processTrigger(6,rn.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(let s of r._pointerUpStage)e=s.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,i.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){let s=this._pickedDownMesh._getActionManagerForTrigger(16);s&&s.processTrigger(16,rn.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){let s=new Ma(st.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),r.onPointerObservable.notifyObservers(s,st.POINTERUP),r.onPointerUp&&r.onPointerUp(t,e,st.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let a=0;if(i.singleClick?a=st.POINTERTAP:i.doubleClick&&(a=st.POINTERDOUBLETAP),a){let o=new Ma(a,t,e);r.onPointerObservable.hasObservers()&&r.onPointerObservable.hasSpecificMask(a)&&r.onPointerObservable.notifyObservers(o,a)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,r=null){let s=this._scene,a=s.getEngine();r||(r=a.getInputElement()),this._alreadyAttached&&this.detachControl(),r&&(this._alreadyAttachedTo=r),this._deviceSourceManager=new dA(a),this._initActionManager=o=>{if(!this._meshPickProceed){let l=s.skipPointerUpPicking||s._registeredActions===0&&!this._checkForPicking()&&!s.onPointerUp?null:s.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,s.pointerUpPredicate,s.pointerUpFastCheck,s.cameraToUseForPointers,s.pointerUpTrianglePredicate);this._currentPickResult=l,l&&(o=l.hit&&l.pickedMesh?l.pickedMesh._getActionManagerForTrigger():null),this._meshPickProceed=!0}return o},this._delayedSimpleClick=(o,l,c)=>{if((Date.now()-this._previousStartingPointerTime>n.DoubleClickDelay&&!this._doubleClickOccured||o!==this._previousButtonPressed)&&(this._doubleClickOccured=!1,l.singleClick=!0,l.ignore=!1,this._delayedClicks[o])){let f=this._delayedClicks[o].evt,h=st.POINTERTAP,d=new Ma(h,f,this._currentPickResult);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(h)&&s.onPointerObservable.notifyObservers(d,h),this._delayedClicks[o]=null}},this._initClickEvent=(o,l,c,f)=>{var p,_;let h=new uA;this._currentPickResult=null;let d=null,u=o.hasSpecificMask(st.POINTERPICK)||l.hasSpecificMask(st.POINTERPICK)||o.hasSpecificMask(st.POINTERTAP)||l.hasSpecificMask(st.POINTERTAP)||o.hasSpecificMask(st.POINTERDOUBLETAP)||l.hasSpecificMask(st.POINTERDOUBLETAP);!u&&Ql&&(d=this._initActionManager(d,h),d&&(u=d.hasPickTriggers));let m=!1;if(u=u&&!this._isMultiTouchGesture,u){let g=c.button;if(h.hasSwiped=this._isPointerSwiping(),!h.hasSwiped){let v=!n.ExclusiveDoubleClickMode;if(v||(v=!o.hasSpecificMask(st.POINTERDOUBLETAP)&&!l.hasSpecificMask(st.POINTERDOUBLETAP),v&&!Ql.HasSpecificTrigger(6)&&(d=this._initActionManager(d,h),d&&(v=!d.hasSpecificTrigger(6)))),v)(Date.now()-this._previousStartingPointerTime>n.DoubleClickDelay||g!==this._previousButtonPressed)&&(h.singleClick=!0,f(h,this._currentPickResult),m=!0);else{let A={evt:c,clickInfo:h,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,g,h,f),n.DoubleClickDelay)};this._delayedClicks[g]=A}let x=o.hasSpecificMask(st.POINTERDOUBLETAP)||l.hasSpecificMask(st.POINTERDOUBLETAP);!x&&Ql.HasSpecificTrigger(6)&&(d=this._initActionManager(d,h),d&&(x=d.hasSpecificTrigger(6))),x&&(g===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime{if(this._updatePointerPosition(o),!this._isSwiping&&this._swipeButtonPressed!==-1&&(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>n.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>n.DragMovementThreshold),a.isPointerLock&&a._verifyPointerLock(),this._checkPrePointerObservable(null,o,o.inputIndex>=gt.MouseWheelX&&o.inputIndex<=gt.MouseWheelZ?st.POINTERWHEEL:st.POINTERMOVE)||!s.cameraToUseForPointers&&!s.activeCamera)return;if(s.skipPointerMovePicking){this._processPointerMove(new es,o);return}s.pointerMovePredicate||(s.pointerMovePredicate=c=>c.isPickable&&c.isVisible&&c.isReady()&&c.isEnabled()&&(c.enablePointerMoveEvents||s.constantlyUpdateMeshUnderPointer||c._getActionManagerForTrigger()!==null)&&(!s.cameraToUseForPointers||(s.cameraToUseForPointers.layerMask&c.layerMask)!==0));let l=s._registeredActions>0||s.constantlyUpdateMeshUnderPointer?this._pickMove(o):null;this._processPointerMove(l,o)},this._onPointerDown=o=>{var f;let l=this._activePointerIds.indexOf(-1);if(l===-1?this._activePointerIds.push(o.pointerId):this._activePointerIds[l]=o.pointerId,this._activePointerIdsCount++,this._pickedDownMesh=null,this._meshPickProceed=!1,n.ExclusiveDoubleClickMode){for(let h=0;hh.isPickable&&h.isVisible&&h.isReady()&&h.isEnabled()&&(!s.cameraToUseForPointers||(s.cameraToUseForPointers.layerMask&h.layerMask)!==0)),this._pickedDownMesh=null;let c;s.skipPointerDownPicking||s._registeredActions===0&&!this._checkForPicking()&&!s.onPointerDown?c=new es:c=s.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,s.pointerDownPredicate,s.pointerDownFastCheck,s.cameraToUseForPointers,s.pointerDownTrianglePredicate),this._processPointerDown(c,o)},this._onPointerUp=o=>{let l=this._activePointerIds.indexOf(o.pointerId);l!==-1&&(this._activePointerIds[l]=-1,this._activePointerIdsCount--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(o),s.preventDefaultOnPointerUp&&r&&(o.preventDefault(),r.focus()),this._initClickEvent(s.onPrePointerObservable,s.onPointerObservable,o,(c,f)=>{if(s.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!c.ignore)){if(this._checkPrePointerObservable(null,o,st.POINTERUP)){this._swipeButtonPressed===o.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1),o.buttons===0&&(this._pointerCaptures[o.pointerId]=!1);return}c.hasSwiped||(c.singleClick&&s.onPrePointerObservable.hasSpecificMask(st.POINTERTAP)&&this._checkPrePointerObservable(null,o,st.POINTERTAP)&&(this._skipPointerTap=!0),c.doubleClick&&s.onPrePointerObservable.hasSpecificMask(st.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,o,st.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}if(!this._pointerCaptures[o.pointerId]){this._swipeButtonPressed===o.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1);return}o.buttons===0&&(this._pointerCaptures[o.pointerId]=!1),!(!s.cameraToUseForPointers&&!s.activeCamera)&&(s.pointerUpPredicate||(s.pointerUpPredicate=h=>h.isPickable&&h.isVisible&&h.isReady()&&h.isEnabled()&&(!s.cameraToUseForPointers||(s.cameraToUseForPointers.layerMask&h.layerMask)!==0)),!this._meshPickProceed&&(Ql&&Ql.HasTriggers||this._checkForPicking()||s.onPointerUp)&&this._initActionManager(null,c),f||(f=this._currentPickResult),this._processPointerUp(f,o,c),this._previousPickResult=this._currentPickResult,this._swipeButtonPressed===o.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1))}))},this._onKeyDown=o=>{let l=lo.KEYDOWN;if(s.onPreKeyboardObservable.hasObservers()){let c=new eg(l,o);if(s.onPreKeyboardObservable.notifyObservers(c,l),c.skipOnKeyboardObservable)return}if(s.onKeyboardObservable.hasObservers()){let c=new lm(l,o);s.onKeyboardObservable.notifyObservers(c,l)}s.actionManager&&s.actionManager.processTrigger(14,rn.CreateNewFromScene(s,o))},this._onKeyUp=o=>{let l=lo.KEYUP;if(s.onPreKeyboardObservable.hasObservers()){let c=new eg(l,o);if(s.onPreKeyboardObservable.notifyObservers(c,l),c.skipOnKeyboardObservable)return}if(s.onKeyboardObservable.hasObservers()){let c=new lm(l,o);s.onKeyboardObservable.notifyObservers(c,l)}s.actionManager&&s.actionManager.processTrigger(15,rn.CreateNewFromScene(s,o))},this._deviceSourceManager.onDeviceConnectedObservable.add(o=>{o.deviceType===Qe.Mouse?o.onInputChangedObservable.add(l=>{this._originMouseEvent=l,l.inputIndex===gt.LeftClick||l.inputIndex===gt.MiddleClick||l.inputIndex===gt.RightClick||l.inputIndex===gt.BrowserBack||l.inputIndex===gt.BrowserForward?t&&o.getInput(l.inputIndex)===1?this._onPointerDown(l):e&&o.getInput(l.inputIndex)===0&&this._onPointerUp(l):i&&(l.inputIndex===gt.Move?this._onPointerMove(l):(l.inputIndex===gt.MouseWheelX||l.inputIndex===gt.MouseWheelY||l.inputIndex===gt.MouseWheelZ)&&this._onPointerMove(l))}):o.deviceType===Qe.Touch?o.onInputChangedObservable.add(l=>{l.inputIndex===gt.LeftClick&&(t&&o.getInput(l.inputIndex)===1?(this._onPointerDown(l),this._activePointerIdsCount>1&&(this._isMultiTouchGesture=!0)):e&&o.getInput(l.inputIndex)===0&&(this._onPointerUp(l),this._activePointerIdsCount===0&&(this._isMultiTouchGesture=!1))),i&&l.inputIndex===gt.Move&&this._onPointerMove(l)}):o.deviceType===Qe.Keyboard&&o.onInputChangedObservable.add(l=>{l.type==="keydown"?this._onKeyDown(l):l.type==="keyup"&&this._onKeyUp(l)})}),this._alreadyAttached=!0}detachControl(){this._alreadyAttached&&(this._deviceSourceManager.dispose(),this._deviceSourceManager=null,this._alreadyAttachedTo&&!this._scene.doNotHandleCursors&&(this._alreadyAttachedTo.style.cursor=this._scene.defaultCursor),this._alreadyAttached=!1,this._alreadyAttachedTo=null)}setPointerOverMesh(e,t=0,i,r){if(this._meshUnderPointerId[t]===e&&(!e||!e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting))return;let s=this._meshUnderPointerId[t],a;s&&(a=s._getActionManagerForTrigger(10),a&&a.processTrigger(10,new rn(s,this._pointerX,this._pointerY,e,r,{pointerId:t}))),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,a=e._getActionManagerForTrigger(9),a&&a.processTrigger(9,new rn(e,this._pointerX,this._pointerY,e,r,{pointerId:t,pickResult:i}))):(delete this._meshUnderPointerId[t],this._pointerOverMesh=null),this._scene.onMeshUnderPointerUpdatedObservable.hasObservers()&&this._scene.onMeshUnderPointerUpdatedObservable.notifyObservers({mesh:e,pointerId:t})}getPointerOverMesh(){return this.meshUnderPointer}_invalidateMesh(e){this._pointerOverMesh===e&&(this._pointerOverMesh=null),this._pickedDownMesh===e&&(this._pickedDownMesh=null),this._pickedUpMesh===e&&(this._pickedUpMesh=null);for(let t in this._meshUnderPointerId)this._meshUnderPointerId[t]===e&&delete this._meshUnderPointerId[t]}};On.DragMovementThreshold=10;On.LongPressDelay=500;On.DoubleClickDelay=300;On.ExclusiveDoubleClickMode=!1});var il,RC=C(()=>{Fl();il=class n{get min(){return this._min}get max(){return this._max}get average(){return this._average}get lastSecAverage(){return this._lastSecAverage}get current(){return this._current}get total(){return this._totalAccumulated}get count(){return this._totalValueCount}constructor(){this._startMonitoringTime=0,this._min=0,this._max=0,this._average=0,this._lastSecAverage=0,this._current=0,this._totalValueCount=0,this._totalAccumulated=0,this._lastSecAccumulated=0,this._lastSecTime=0,this._lastSecValueCount=0}fetchNewFrame(){this._totalValueCount++,this._current=0,this._lastSecValueCount++}addCount(e,t){n.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){n.Enabled&&(this._startMonitoringTime=mr.Now)}endMonitoring(e=!0){if(!n.Enabled)return;e&&this.fetchNewFrame();let t=mr.Now;this._current=t-this._startMonitoringTime,e&&this._fetchResult()}endFrame(){this._fetchResult()}_fetchResult(){this._totalAccumulated+=this._current,this._lastSecAccumulated+=this._current,this._min=Math.min(this._min,this._current),this._max=Math.max(this._max,this._current),this._average=this._totalAccumulated/this._totalValueCount;let e=mr.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}};il.Enabled=!0});var $l,mA=C(()=>{$l=class{static get UniqueId(){let e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}};$l._UniqueIdCounter=1});var pA,JB=C(()=>{pA=class{constructor(){this.pointerDownFastCheck=!1,this.pointerUpFastCheck=!1,this.pointerMoveFastCheck=!1,this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1}}});var $re,Jre,eU,$t,xs=C(()=>{bi();Fl();hi();so();RB();uf();Ve();q_();pf();Z_();vC();jT();J_();ZT();om();va();Pi();hn();$B();RC();zt();wT();mA();Hl();z_();Zo();JB();yt();Hi();jo();$re=new Ri,Jre=new Ri;(function(n){n[n.BackwardCompatible=0]="BackwardCompatible",n[n.Intermediate=1]="Intermediate",n[n.Aggressive=2]="Aggressive"})(eU||(eU={}));$t=class n{static DefaultMaterialFactory(e){throw Ze("StandardMaterial")}static CollisionCoordinatorFactory(){throw Ze("DefaultCollisionCoordinator")}get clearColor(){return this._clearColor}set clearColor(e){e!==this._clearColor&&(this._clearColor=e,this.onClearColorChangedObservable.notifyObservers(this._clearColor))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}get performancePriority(){return this._performancePriority}set performancePriority(e){if(e!==this._performancePriority){switch(this._performancePriority=e,e){case 0:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case 1:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case 2:this.skipFrustumClipping=!0,this._renderingManager.maintainStateBetweenFrames=!0,this.skipPointerMovePicking=!0,this.autoClear=!1;break}this.onScenePerformancePriorityChangedObservable.notifyObservers(e)}}set forceWireframe(e){this._forceWireframe!==e&&(this._forceWireframe=e,this.markAllMaterialsAsDirty(16))}get forceWireframe(){return this._forceWireframe}set skipFrustumClipping(e){this._skipFrustumClipping!==e&&(this._skipFrustumClipping=e)}get skipFrustumClipping(){return this._skipFrustumClipping}set forcePointsCloud(e){this._forcePointsCloud!==e&&(this._forcePointsCloud=e,this.markAllMaterialsAsDirty(16))}get forcePointsCloud(){return this._forcePointsCloud}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture!==e&&(this._environmentTexture=e,this.onEnvironmentTextureChangedObservable.notifyObservers(e),this.markAllMaterialsAsDirty(1))}getNodes(){let e=[];e=e.concat(this.meshes),e=e.concat(this.lights),e=e.concat(this.cameras),e=e.concat(this.transformNodes);for(let t of this.skeletons)e=e.concat(t.bones);return e}get animationPropertiesOverride(){return this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set beforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),e&&(this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e))}set afterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),e&&(this._onAfterRenderObserver=this.onAfterRenderObservable.add(e))}set beforeCameraRender(e){this._onBeforeCameraRenderObserver&&this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=this.onBeforeCameraRenderObservable.add(e)}set afterCameraRender(e){this._onAfterCameraRenderObserver&&this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=this.onAfterCameraRenderObservable.add(e)}get pointerDownPredicate(){return this._pointerPickingConfiguration.pointerDownPredicate}set pointerDownPredicate(e){this._pointerPickingConfiguration.pointerDownPredicate=e}get pointerUpPredicate(){return this._pointerPickingConfiguration.pointerUpPredicate}set pointerUpPredicate(e){this._pointerPickingConfiguration.pointerUpPredicate=e}get pointerMovePredicate(){return this._pointerPickingConfiguration.pointerMovePredicate}set pointerMovePredicate(e){this._pointerPickingConfiguration.pointerMovePredicate=e}get pointerDownFastCheck(){return this._pointerPickingConfiguration.pointerDownFastCheck}set pointerDownFastCheck(e){this._pointerPickingConfiguration.pointerDownFastCheck=e}get pointerUpFastCheck(){return this._pointerPickingConfiguration.pointerUpFastCheck}set pointerUpFastCheck(e){this._pointerPickingConfiguration.pointerUpFastCheck=e}get pointerMoveFastCheck(){return this._pointerPickingConfiguration.pointerMoveFastCheck}set pointerMoveFastCheck(e){this._pointerPickingConfiguration.pointerMoveFastCheck=e}get skipPointerMovePicking(){return this._pointerPickingConfiguration.skipPointerMovePicking}set skipPointerMovePicking(e){this._pointerPickingConfiguration.skipPointerMovePicking=e}get skipPointerDownPicking(){return this._pointerPickingConfiguration.skipPointerDownPicking}set skipPointerDownPicking(e){this._pointerPickingConfiguration.skipPointerDownPicking=e}get skipPointerUpPicking(){return this._pointerPickingConfiguration.skipPointerUpPicking}set skipPointerUpPicking(e){this._pointerPickingConfiguration.skipPointerUpPicking=e}get unTranslatedPointer(){return this._inputManager.unTranslatedPointer}static get DragMovementThreshold(){return On.DragMovementThreshold}static set DragMovementThreshold(e){On.DragMovementThreshold=e}static get LongPressDelay(){return On.LongPressDelay}static set LongPressDelay(e){On.LongPressDelay=e}static get DoubleClickDelay(){return On.DoubleClickDelay}static set DoubleClickDelay(e){On.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return On.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){On.ExclusiveDoubleClickMode=e}get _eyePosition(){var e,t,i;return(i=(t=this._forcedViewPosition)!=null?t:(e=this.activeCamera)==null?void 0:e.globalPosition)!=null?i:b.ZeroReadOnly}bindEyePosition(e,t="vEyePosition",i=!1){let r=this._eyePosition,s=this.useRightHandedSystem===(this._mirroredCameraPosition!=null),a=this.floatingOriginOffset,o=$re.set(r.x,r.y,r.z,s?-1:1),l=o.subtractFromFloatsToRef(a.x,a.y,a.z,0,Jre);return e&&(i?e.setFloat3(t,l.x,l.y,l.z):e.setVector4(t,l)),o}finalizeSceneUbo(){let e=this.getSceneUniformBuffer(),t=this.bindEyePosition(null),i=this.floatingOriginOffset;return e.updateFloat4("vEyePosition",t.x-i.x,t.y-i.y,t.z-i.z,t.w),e.update(),e}set useRightHandedSystem(e){this._useRightHandedSystem!==e&&(this._useRightHandedSystem=e,this.markAllMaterialsAsDirty(16))}get useRightHandedSystem(){return this._useRightHandedSystem}setStepId(e){this._currentStepId=e}getStepId(){return this._currentStepId}getInternalStep(){return this._currentInternalStep}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this.markAllMaterialsAsDirty(16))}get fogEnabled(){return this._fogEnabled}set fogMode(e){this._fogMode!==e&&(this._fogMode=e,this.markAllMaterialsAsDirty(16))}get fogMode(){return this._fogMode}get prePass(){return!!this.prePassRenderer&&this.prePassRenderer.defaultRT.enabled}set shadowsEnabled(e){this._shadowsEnabled!==e&&(this._shadowsEnabled=e,this.markAllMaterialsAsDirty(2))}get shadowsEnabled(){return this._shadowsEnabled}set lightsEnabled(e){this._lightsEnabled!==e&&(this._lightsEnabled=e,this.markAllMaterialsAsDirty(2))}get lightsEnabled(){return this._lightsEnabled}get activeCameras(){return this._activeCameras}set activeCameras(e){this._unObserveActiveCameras&&(this._unObserveActiveCameras(),this._unObserveActiveCameras=null),e&&(this._unObserveActiveCameras=OT(e,()=>{this.onActiveCamerasChanged.notifyObservers(this)})),this._activeCameras=e}get activeCamera(){return this._activeCamera}set activeCamera(e){e!==this._activeCamera&&(this._activeCamera=e,this.onActiveCameraChanged.notifyObservers(this))}get _hasDefaultMaterial(){return n.DefaultMaterialFactory!==n._OriginalDefaultMaterialFactory}get defaultMaterial(){return this._defaultMaterial||(this._defaultMaterial=n.DefaultMaterialFactory(this)),this._defaultMaterial}set defaultMaterial(e){this._defaultMaterial=e}set texturesEnabled(e){this._texturesEnabled!==e&&(this._texturesEnabled=e,this.markAllMaterialsAsDirty(1))}get texturesEnabled(){return this._texturesEnabled}get frameGraph(){return this._frameGraph}set frameGraph(e){if(this._frameGraph){this._frameGraph=e,e||(this.customRenderFunction=this._currentCustomRenderFunction);return}this._frameGraph=e,e&&(this._currentCustomRenderFunction=this.customRenderFunction,this.customRenderFunction=this._renderWithFrameGraph,this.activeCamera=null)}set skeletonsEnabled(e){this._skeletonsEnabled!==e&&(this._skeletonsEnabled=e,this.markAllMaterialsAsDirty(8))}get skeletonsEnabled(){return this._skeletonsEnabled}get collisionCoordinator(){return this._collisionCoordinator||(this._collisionCoordinator=n.CollisionCoordinatorFactory(),this._collisionCoordinator.init(this)),this._collisionCoordinator}get renderingManager(){return this._renderingManager}get frustumPlanes(){return this._frustumPlanes}_registerTransientComponents(){if(this._transientComponents.length>0){for(let e of this._transientComponents)e.register();this._transientComponents.length=0}}_addComponent(e){this._components.push(e),this._transientComponents.push(e);let t=e;t.addFromContainer&&t.serialize&&this._serializableComponents.push(t)}_getComponent(e){for(let t of this._components)if(t.name===e)return t;return null}get uniqueId(){return this._uniqueId}constructor(e,t){this._inputManager=new On(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this._clearColor=new lt(.2,.2,.3,1),this.onClearColorChangedObservable=new ie,this.ambientColor=new ge(0,0,0),this.environmentIntensity=1,this.iblIntensity=1,this._performancePriority=0,this.onScenePerformancePriorityChangedObservable=new ie,this._forceWireframe=!1,this._skipFrustumClipping=!1,this._forcePointsCloud=!1,this.rootNodes=[],this.cameras=[],this.lights=[],this.meshes=[],this.skeletons=[],this.particleSystems=[],this.animations=[],this.animationGroups=[],this.multiMaterials=[],this.materials=[],this.morphTargetManagers=[],this.geometries=[],this.transformNodes=[],this.actionManagers=[],this.objectRenderers=[],this.textures=[],this._environmentTexture=null,this.postProcesses=[],this.effectLayers=[],this.sounds=null,this.layers=[],this.lensFlareSystems=[],this.proceduralTextures=[],this.animationsEnabled=!0,this._animationPropertiesOverride=null,this.useConstantAnimationDeltaTime=!1,this.constantlyUpdateMeshUnderPointer=!1,this.hoverCursor="pointer",this.defaultCursor="",this.doNotHandleCursors=!1,this.preventDefaultOnPointerDown=!0,this.preventDefaultOnPointerUp=!0,this.metadata=null,this.reservedDataStore=null,this.disableOfflineSupportExceptionRules=[],this.onDisposeObservable=new ie,this._onDisposeObserver=null,this.onBeforeRenderObservable=new ie,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new ie,this.onAfterRenderCameraObservable=new ie,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new ie,this.onAfterAnimationsObservable=new ie,this.onBeforeDrawPhaseObservable=new ie,this.onAfterDrawPhaseObservable=new ie,this.onReadyObservable=new ie,this.onBeforeCameraRenderObservable=new ie,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new ie,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new ie,this.onAfterActiveMeshesEvaluationObservable=new ie,this.onBeforeParticlesRenderingObservable=new ie,this.onAfterParticlesRenderingObservable=new ie,this.onDataLoadedObservable=new ie,this.onNewCameraAddedObservable=new ie,this.onCameraRemovedObservable=new ie,this.onNewLightAddedObservable=new ie,this.onLightRemovedObservable=new ie,this.onNewGeometryAddedObservable=new ie,this.onGeometryRemovedObservable=new ie,this.onNewTransformNodeAddedObservable=new ie,this.onTransformNodeRemovedObservable=new ie,this.onNewMeshAddedObservable=new ie,this.onMeshRemovedObservable=new ie,this.onNewSkeletonAddedObservable=new ie,this.onSkeletonRemovedObservable=new ie,this.onNewParticleSystemAddedObservable=new ie,this.onParticleSystemRemovedObservable=new ie,this.onNewAnimationGroupAddedObservable=new ie,this.onAnimationGroupRemovedObservable=new ie,this.onNewMaterialAddedObservable=new ie,this.onNewMultiMaterialAddedObservable=new ie,this.onMaterialRemovedObservable=new ie,this.onMultiMaterialRemovedObservable=new ie,this.onNewTextureAddedObservable=new ie,this.onTextureRemovedObservable=new ie,this.onNewFrameGraphAddedObservable=new ie,this.onFrameGraphRemovedObservable=new ie,this.onNewObjectRendererAddedObservable=new ie,this.onObjectRendererRemovedObservable=new ie,this.onNewPostProcessAddedObservable=new ie,this.onPostProcessRemovedObservable=new ie,this.onNewEffectLayerAddedObservable=new ie,this.onEffectLayerRemovedObservable=new ie,this.onBeforeRenderTargetsRenderObservable=new ie,this.onAfterRenderTargetsRenderObservable=new ie,this.onBeforeStepObservable=new ie,this.onAfterStepObservable=new ie,this.onActiveCameraChanged=new ie,this.onActiveCamerasChanged=new ie,this.onBeforeRenderingGroupObservable=new ie,this.onAfterRenderingGroupObservable=new ie,this.onMeshImportedObservable=new ie,this.onAnimationFileImportedObservable=new ie,this.onEnvironmentTextureChangedObservable=new ie,this.onMeshUnderPointerUpdatedObservable=new ie,this._registeredForLateAnimationBindings=new no(256),this._pointerPickingConfiguration=new pA,this.onPrePointerObservable=new ie,this.onPointerObservable=new ie,this.onPreKeyboardObservable=new ie,this.onKeyboardObservable=new ie,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=n.FOGMODE_NONE,this.fogColor=new ge(.2,.2,.3),this.fogDensity=.1,this.fogStart=0,this.fogEnd=1e3,this.needsPreviousWorldMatrices=!1,this._shadowsEnabled=!0,this._lightsEnabled=!0,this._unObserveActiveCameras=null,this._texturesEnabled=!0,this._frameGraph=null,this.frameGraphs=[],this.physicsEnabled=!0,this.particlesEnabled=!0,this.spritesEnabled=!0,this._skeletonsEnabled=!0,this.lensFlaresEnabled=!0,this.collisionsEnabled=!0,this.gravity=new b(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=[],this.importedMeshesFiles=[],this.probesEnabled=!0,this._meshesForIntersections=new no(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new il,this._activeIndices=new il,this._activeParticles=new il,this._activeBones=new il,this._animationTime=0,this.animationTimeScale=1,this._renderId=0,this._frameId=0,this._executeWhenReadyTimeoutId=null,this._intermediateRendering=!1,this._defaultFrameBufferCleared=!1,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1,this._toBeDisposed=new Array(256),this._activeRequests=new Array,this._pendingData=[],this._isDisposed=!1,this._isReadyChecks=[],this.dispatchAllSubMeshesOfActiveMeshes=!1,this._activeMeshes=new wi(256),this._processedMaterials=new wi(256),this._renderTargets=new no(256),this._materialsRenderTargets=new no(256),this._activeParticleSystems=new wi(256),this._activeSkeletons=new no(32),this._softwareSkinnedMeshes=new no(32),this._activeAnimatables=new Array,this._transformMatrix=j.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=rr.Create(),this._beforeClearStage=rr.Create(),this._beforeRenderTargetClearStage=rr.Create(),this._gatherRenderTargetsStage=rr.Create(),this._gatherActiveCameraRenderTargetsStage=rr.Create(),this._isReadyForMeshStage=rr.Create(),this._beforeEvaluateActiveMeshStage=rr.Create(),this._evaluateSubMeshStage=rr.Create(),this._preActiveMeshStage=rr.Create(),this._cameraDrawRenderTargetStage=rr.Create(),this._beforeCameraDrawStage=rr.Create(),this._beforeRenderTargetDrawStage=rr.Create(),this._beforeRenderingGroupDrawStage=rr.Create(),this._beforeRenderingMeshStage=rr.Create(),this._afterRenderingMeshStage=rr.Create(),this._afterRenderingGroupDrawStage=rr.Create(),this._afterCameraDrawStage=rr.Create(),this._afterCameraPostProcessStage=rr.Create(),this._afterRenderTargetDrawStage=rr.Create(),this._afterRenderTargetPostProcessStage=rr.Create(),this._afterRenderStage=rr.Create(),this._pointerMoveStage=rr.Create(),this._pointerDownStage=rr.Create(),this._pointerUpStage=rr.Create(),this._geometriesByUniqueId=null,this._uniqueId=0,this._defaultMeshCandidates={data:[],length:0},this._defaultSubMeshCandidates={data:[],length:0},this.onReadyTimeoutObservable=new ie,this.onReadyTimeoutDuration=120*1e3,this._timeoutChecksStartTime=0,this._floatingOriginScene=void 0,this._preventFreeActiveMeshesAndRenderingGroups=!1,this._activeMeshesFrozen=!1,this._activeMeshesFrozenButKeepClipping=!1,this._skipEvaluateActiveMeshesCompletely=!1,this._freezeActiveMeshesCancel=null,this._useCurrentFrameBuffer=!1,this._allowPostProcessClearColor=!0,this.getDeterministicFrameTime=()=>this._engine.getTimeStep(),this._getFloatingOriginScene=()=>this._floatingOriginScene,this._registeredActions=0,this._blockMaterialDirtyMechanism=!1,this._perfCollector=null,this.activeCameras=[],this._uniqueId=this.getUniqueId();let i={useGeometryUniqueIdsMap:!0,useMaterialMeshMap:!0,useClonedMeshMap:!0,virtual:!1,defaultCameraLayerMask:268435455,defaultRenderableLayerMask:268435455,...t};this.defaultCameraLayerMask=i.defaultCameraLayerMask,this.defaultRenderableLayerMask=i.defaultRenderableLayerMask,e=this._engine=e||Le.LastCreatedEngine,i.virtual?e._virtualScenes.push(this):(Le._LastCreatedScene=this,e.scenes.push(this)),(e.getCreationOptions().useLargeWorldRendering||t!=null&&t.useFloatingOrigin)&&(BB(),this._floatingOriginScene=this,Ia.getScene=this._getFloatingOriginScene),this._uid=null,this._renderingManager=new Ta(this),Yl&&(this.postProcessManager=new Yl(this)),cr()&&this.attachControl(),this._createUbo(),kt&&(this._imageProcessingConfiguration=new kt),this.setDefaultCandidateProviders(),i.useGeometryUniqueIdsMap&&(this._geometriesByUniqueId={}),this.useMaterialMeshMap=i.useMaterialMeshMap,this.useClonedMeshMap=i.useClonedMeshMap,(!t||!t.virtual)&&e.onNewSceneAddedObservable.notifyObservers(this)}getClassName(){return"Scene"}_getDefaultMeshCandidates(){return this._defaultMeshCandidates.data=this.meshes,this._defaultMeshCandidates.length=this.meshes.length,this._defaultMeshCandidates}_getDefaultSubMeshCandidates(e){return this._defaultSubMeshCandidates.data=e.subMeshes,this._defaultSubMeshCandidates.length=e.subMeshes.length,this._defaultSubMeshCandidates}setDefaultCandidateProviders(){this.getActiveMeshCandidates=()=>this._getDefaultMeshCandidates(),this.getActiveSubMeshCandidates=e=>this._getDefaultSubMeshCandidates(e),this.getIntersectingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e),this.getCollidingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e)}get meshUnderPointer(){return this._inputManager.meshUnderPointer}get pointerX(){return this._inputManager.pointerX}set pointerX(e){this._inputManager.pointerX=e}get pointerY(){return this._inputManager.pointerY}set pointerY(e){this._inputManager.pointerY=e}getCachedMaterial(){return this._cachedMaterial}getCachedEffect(){return this._cachedEffect}getCachedVisibility(){return this._cachedVisibility}isCachedMaterialInvalid(e,t,i=1){return this._cachedEffect!==t||this._cachedMaterial!==e||this._cachedVisibility!==i}getEngine(){return this._engine}getTotalVertices(){return this._totalVertices.current}get totalVerticesPerfCounter(){return this._totalVertices}getActiveIndices(){return this._activeIndices.current}get totalActiveIndicesPerfCounter(){return this._activeIndices}getActiveParticles(){return this._activeParticles.current}get activeParticlesPerfCounter(){return this._activeParticles}getActiveBones(){return this._activeBones.current}get activeBonesPerfCounter(){return this._activeBones}getActiveMeshes(){return this._activeMeshes}getAnimationRatio(){return this._animationRatio!==void 0?this._animationRatio:1}getRenderId(){return this._renderId}getFrameId(){return this._frameId}incrementRenderId(){this._renderId++}_createUbo(){this.setSceneUniformBuffer(this.createSceneUniformBuffer())}simulatePointerMove(e,t){return this._inputManager.simulatePointerMove(e,t),this}simulatePointerDown(e,t){return this._inputManager.simulatePointerDown(e,t),this}simulatePointerUp(e,t,i){return this._inputManager.simulatePointerUp(e,t,i),this}isPointerCaptured(e=0){return this._inputManager.isPointerCaptured(e)}attachControl(e=!0,t=!0,i=!0){this._inputManager.attachControl(e,t,i)}detachControl(){this._inputManager.detachControl()}isReady(e=!0){var a,o,l;if(this._isDisposed)return!1;let t,i=this.getEngine(),r=i.currentRenderPassId;i.currentRenderPassId=(o=(a=this.activeCamera)==null?void 0:a.renderPassId)!=null?o:r;let s=!0;for(this._pendingData.length>0&&(s=!1),(l=this.prePassRenderer)==null||l.update(),this.useOrderIndependentTransparency&&this.depthPeelingRenderer&&s&&(s=this.depthPeelingRenderer.isReady()),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),t=0;t0;for(let d of this._isReadyForMeshStage)d.action(c,f)||(s=!1);if(!e)continue;let h=c.material||this.defaultMaterial;if(h)if(h._storeEffectOnSubMeshes)for(let d of c.subMeshes){let u=d.getMaterial();u&&u.hasRenderTargetTextures&&u.getRenderTargetTextures!=null&&this._processedMaterials.indexOf(u)===-1&&(this._processedMaterials.push(u),this._materialsRenderTargets.concatWithNoDuplicate(u.getRenderTargetTextures()))}else h.hasRenderTargetTextures&&h.getRenderTargetTextures!=null&&this._processedMaterials.indexOf(h)===-1&&(this._processedMaterials.push(h),this._materialsRenderTargets.concatWithNoDuplicate(h.getRenderTargetTextures()))}if(e){for(t=0;t0)for(let c of this.activeCameras)c.isReady(!0)||(s=!1);else this.activeCamera&&(this.activeCamera.isReady(!0)||(s=!1));for(let c of this.particleSystems)c.isReady()||(s=!1);if(this.proceduralTexturesEnabled)for(let c of this.proceduralTextures)c.isReady()||(s=!1);if(this.layers)for(let c of this.layers)c.isReady()||(s=!1);if(this.effectLayers)for(let c of this.effectLayers)c.isLayerReady()||(s=!1);for(let c of this._isReadyChecks)c.isReady()||(s=!1);return i.areAllEffectsReady()||(s=!1),i.currentRenderPassId=r,s}resetCachedMaterial(){this._cachedMaterial=null,this._cachedEffect=null,this._cachedVisibility=null}registerBeforeRender(e){this.onBeforeRenderObservable.add(e)}unregisterBeforeRender(e){this.onBeforeRenderObservable.removeCallback(e)}registerAfterRender(e){this.onAfterRenderObservable.add(e)}unregisterAfterRender(e){this.onAfterRenderObservable.removeCallback(e)}_executeOnceBeforeRender(e){let t=()=>{e(),setTimeout(()=>{this.unregisterBeforeRender(t)})};this.registerBeforeRender(t)}executeOnceBeforeRender(e,t){t!==void 0?setTimeout(()=>{this._executeOnceBeforeRender(e)},t):this._executeOnceBeforeRender(e)}addPendingData(e){this._pendingData.push(e)}removePendingData(e){let t=this.isLoading,i=this._pendingData.indexOf(e);i!==-1&&this._pendingData.splice(i,1),t&&!this.isLoading&&this.onDataLoadedObservable.notifyObservers(this)}getWaitingItemsCount(){return this._pendingData.length}get isLoading(){return this._pendingData.length>0}addIsReadyCheck(e){this._isReadyChecks.indexOf(e)===-1&&this._isReadyChecks.push(e)}removeIsReadyCheck(e){let t=this._isReadyChecks.indexOf(e);t!==-1&&this._isReadyChecks.splice(t,1)}executeWhenReady(e,t=!1){this.onReadyObservable.addOnce(e),this._executeWhenReadyTimeoutId===null&&this._checkIsReady(t)}async whenReadyAsync(e=!1){return await new Promise(t=>{this.executeWhenReady(()=>{t()},e)})}_clearReadynessChecksData(){this._timeoutChecksStartTime=0,this.onReadyTimeoutObservable.clear(),this.onReadyObservable.clear(),this._executeWhenReadyTimeoutId=null}_checkIsReady(e=!1){if(this._registerTransientComponents(),this._timeoutChecksStartTime===0)this._timeoutChecksStartTime=mr.Now;else if(this.onReadyTimeoutDuration>0&&mr.Now-this._timeoutChecksStartTime>this.onReadyTimeoutDuration){this.onReadyTimeoutObservable.notifyObservers(this),this._clearReadynessChecksData();return}if(this.isReady(e)){this.onReadyObservable.notifyObservers(this),this._clearReadynessChecksData();return}if(this._isDisposed){this._clearReadynessChecksData();return}this._executeWhenReadyTimeoutId=setTimeout(()=>{this.incrementRenderId(),this._checkIsReady(e)},100)}get animatables(){return this._activeAnimatables}resetLastAnimationTimeFrame(){this._animationTimeLast=mr.Now}getViewMatrix(){return this._viewMatrix}getProjectionMatrix(){return this._projectionMatrix}getInverseProjectionMatrix(){return this._inverseProjectionMatrix}getTransformMatrix(){return this._transformMatrix}setTransformMatrix(e,t,i,r){this._multiviewSceneUboIsActive=!!(i&&r&&this._multiviewSceneUbo),!(this._viewUpdateFlag===e.updateFlag&&this._projectionUpdateFlag===t.updateFlag)&&(this._viewUpdateFlag=e.updateFlag,this._projectionUpdateFlag=t.updateFlag,this._viewMatrix=e,this._projectionMatrix=t,this._inverseProjectionMatrix||(this._inverseProjectionMatrix=new j),this._projectionMatrix.invertToRef(this._inverseProjectionMatrix),this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._frustumPlanes?lf.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=lf.GetPlanes(this._transformMatrix),this._multiviewSceneUboIsActive&&this._multiviewSceneUbo.useUbo?this._updateMultiviewUbo(i,r):this._sceneUbo.useUbo&&(this._sceneUbo.updateMatrix("viewProjection",this._transformMatrix),this._sceneUbo.updateMatrix("view",this._viewMatrix),this._sceneUbo.updateMatrix("projection",this._projectionMatrix),this._sceneUbo.updateMatrix("inverseProjection",this._inverseProjectionMatrix)))}getSceneUniformBuffer(){return this._multiviewSceneUboIsActive&&this._multiviewSceneUbo?this._multiviewSceneUbo:this._sceneUbo}createSceneUniformBuffer(e,t){let i=typeof t=="boolean"?t:t==null?void 0:t.trackUBOsInFrame,r=new fr(this._engine,void 0,!1,e!=null?e:"scene",void 0,i);return r.addUniform("viewProjection",16),r.addUniform("view",16),r.addUniform("projection",16),r.addUniform("vEyePosition",4),r.addUniform("inverseProjection",16),r}setSceneUniformBuffer(e){this._sceneUbo=e,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1}get floatingOriginMode(){return this._floatingOriginScene!==void 0}get floatingOriginOffset(){return this.floatingOriginMode?this._eyePosition:b.ZeroReadOnly}getUniqueId(){return $l.UniqueId}addMesh(e,t=!1){if(!this._blockEntityCollection&&(this.meshes.push(e),e._resyncLightSources(),e.parent||e._addToSceneRootNodes(),pe.SetImmediate(()=>{this.onNewMeshAddedObservable.notifyObservers(e)}),t)){let i=e.getChildMeshes();for(let r of i)this.addMesh(r)}}removeMesh(e,t=!1){let i=this.meshes.indexOf(e);if(i!==-1&&(this.meshes.splice(i,1),e.parent||e._removeFromSceneRootNodes()),this._inputManager._invalidateMesh(e),this.onMeshRemovedObservable.notifyObservers(e),t){let r=e.getChildMeshes();for(let s of r)this.removeMesh(s)}return i}addTransformNode(e){this._blockEntityCollection||e.getScene()===this&&e._indexInSceneTransformNodesArray!==-1||(e._indexInSceneTransformNodesArray=this.transformNodes.length,this.transformNodes.push(e),e.parent||e._addToSceneRootNodes(),this.onNewTransformNodeAddedObservable.notifyObservers(e))}removeTransformNode(e){let t=e._indexInSceneTransformNodesArray;if(t!==-1){if(t!==this.transformNodes.length-1){let i=this.transformNodes[this.transformNodes.length-1];this.transformNodes[t]=i,i._indexInSceneTransformNodesArray=t}e._indexInSceneTransformNodesArray=-1,this.transformNodes.pop(),e.parent||e._removeFromSceneRootNodes()}return this.onTransformNodeRemovedObservable.notifyObservers(e),t}removeSkeleton(e){let t=this.skeletons.indexOf(e);return t!==-1&&(this.skeletons.splice(t,1),this.onSkeletonRemovedObservable.notifyObservers(e),this._executeActiveContainerCleanup(this._activeSkeletons)),t}removeMorphTargetManager(e){let t=this.morphTargetManagers.indexOf(e);return t!==-1&&this.morphTargetManagers.splice(t,1),t}removeLight(e){let t=this.lights.indexOf(e);if(t!==-1){for(let i of this.meshes)i._removeLightSource(e,!1);this.lights.splice(t,1),this.sortLightsByPriority(),e.parent||e._removeFromSceneRootNodes(),this.onLightRemovedObservable.notifyObservers(e)}return t}removeCamera(e){let t=this.cameras.indexOf(e);if(t!==-1&&(this.cameras.splice(t,1),e.parent||e._removeFromSceneRootNodes()),this.activeCameras){let i=this.activeCameras.indexOf(e);i!==-1&&this.activeCameras.splice(i,1)}return this.activeCamera===e&&(this.cameras.length>0?this.activeCamera=this.cameras[0]:this.activeCamera=null),this.onCameraRemovedObservable.notifyObservers(e),t}removeParticleSystem(e){let t=this.particleSystems.indexOf(e);return t!==-1&&(this.particleSystems.splice(t,1),this._executeActiveContainerCleanup(this._activeParticleSystems)),this.onParticleSystemRemovedObservable.notifyObservers(e),t}removeAnimation(e){let t=this.animations.indexOf(e);return t!==-1&&this.animations.splice(t,1),t}stopAnimation(e,t,i){}removeAnimationGroup(e){let t=this.animationGroups.indexOf(e);return t!==-1&&this.animationGroups.splice(t,1),this.onAnimationGroupRemovedObservable.notifyObservers(e),t}removeMultiMaterial(e){let t=this.multiMaterials.indexOf(e);return t!==-1&&this.multiMaterials.splice(t,1),this.onMultiMaterialRemovedObservable.notifyObservers(e),t}removeMaterial(e){let t=e._indexInSceneMaterialArray;if(t!==-1&&t{this.onNewLightAddedObservable.notifyObservers(e)})}}sortLightsByPriority(){this.requireLightSorting&&this.lights.sort(Yt.CompareLightsPriority)}addCamera(e){this._blockEntityCollection||(this.cameras.push(e),pe.SetImmediate(()=>{this.onNewCameraAddedObservable.notifyObservers(e)}),e.parent||e._addToSceneRootNodes())}addSkeleton(e){this._blockEntityCollection||(this.skeletons.push(e),pe.SetImmediate(()=>{this.onNewSkeletonAddedObservable.notifyObservers(e)}))}addParticleSystem(e){this._blockEntityCollection||(this.particleSystems.push(e),pe.SetImmediate(()=>{this.onNewParticleSystemAddedObservable.notifyObservers(e)}))}addAnimation(e){this._blockEntityCollection||this.animations.push(e)}addAnimationGroup(e){this._blockEntityCollection||(this.animationGroups.push(e),pe.SetImmediate(()=>{this.onNewAnimationGroupAddedObservable.notifyObservers(e)}))}addMultiMaterial(e){this._blockEntityCollection||(this.multiMaterials.push(e),pe.SetImmediate(()=>{this.onNewMultiMaterialAddedObservable.notifyObservers(e)}))}addMaterial(e){this._blockEntityCollection||e.getScene()===this&&e._indexInSceneMaterialArray!==-1||(e._indexInSceneMaterialArray=this.materials.length,this.materials.push(e),pe.SetImmediate(()=>{this.onNewMaterialAddedObservable.notifyObservers(e)}))}addMorphTargetManager(e){this._blockEntityCollection||this.morphTargetManagers.push(e)}addGeometry(e){this._blockEntityCollection||(this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=this.geometries.length),this.geometries.push(e))}addActionManager(e){this.actionManagers.push(e)}addTexture(e){this._blockEntityCollection||(this.textures.push(e),this.onNewTextureAddedObservable.notifyObservers(e))}addFrameGraph(e){this.frameGraphs.push(e),pe.SetImmediate(()=>{this.onNewFrameGraphAddedObservable.notifyObservers(e)})}addObjectRenderer(e){this.objectRenderers.push(e),pe.SetImmediate(()=>{this.onNewObjectRendererAddedObservable.notifyObservers(e)})}addPostProcess(e){this._blockEntityCollection||(this.postProcesses.push(e),pe.SetImmediate(()=>{this.onNewPostProcessAddedObservable.notifyObservers(e)}))}addEffectLayer(e){this._blockEntityCollection||(this.effectLayers.push(e),pe.SetImmediate(()=>{this.onNewEffectLayerAddedObservable.notifyObservers(e)}))}switchActiveCamera(e,t=!0){this._engine.getInputElement()&&(this.activeCamera&&this.activeCamera.detachControl(),this.activeCamera=e,t&&e.attachControl())}setActiveCameraById(e){let t=this.getCameraById(e);return t?(this.activeCamera=t,t):null}setActiveCameraByName(e){let t=this.getCameraByName(e);return t?(this.activeCamera=t,t):null}getAnimationGroupByName(e){for(let t=0;ti.uniqueId===e)}getMaterialById(e,t=!1){return this._getMaterial(t,i=>i.id===e)}getMaterialByName(e,t=!1){return this._getMaterial(t,i=>i.name===e)}getLastMaterialById(e,t=!1){for(let i=this.materials.length-1;i>=0;i--)if(this.materials[i].id===e)return this.materials[i];if(t){for(let i=this.multiMaterials.length-1;i>=0;i--)if(this.multiMaterials[i].id===e)return this.multiMaterials[i]}return null}getTextureByUniqueId(e){for(let t=0;t{this.onNewGeometryAddedObservable.notifyObservers(e)}),!0)}removeGeometry(e){let t;if(this._geometriesByUniqueId){if(t=this._geometriesByUniqueId[e.uniqueId],t===void 0)return!1}else if(t=this.geometries.indexOf(e),t<0)return!1;if(t!==this.geometries.length-1){let i=this.geometries[this.geometries.length-1];i&&(this.geometries[t]=i,this._geometriesByUniqueId&&(this._geometriesByUniqueId[i.uniqueId]=t))}return this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=void 0),this.geometries.pop(),this.onGeometryRemovedObservable.notifyObservers(e),!0}getGeometries(){return this.geometries}getMeshById(e){for(let t=0;t=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null}getLastTransformNodeById(e){for(let t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getLastEntryById(e){let t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];for(t=this.skeletons.length-1;t>=0;t--){let i=this.skeletons[t];for(let r=i.bones.length-1;r>=0;r--)if(i.bones[r].id===e)return i.bones[r]}return null}getNodeById(e){let t=this.getMeshById(e);if(t)return t;let i=this.getTransformNodeById(e);if(i)return i;let r=this.getLightById(e);if(r)return r;let s=this.getCameraById(e);if(s)return s;let a=this.getBoneById(e);return a||null}getNodeByName(e){let t=this.getMeshByName(e);if(t)return t;let i=this.getTransformNodeByName(e);if(i)return i;let r=this.getLightByName(e);if(r)return r;let s=this.getCameraByName(e);if(s)return s;let a=this.getBoneByName(e);return a||null}getMeshByName(e){for(let t=0;t=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByUniqueId(e){for(let t=0;t{let o=!0,l=!0;for(let c of a)o&&(o=c.objectRenderer._isFrozen),l&&(l=c.objectRenderer._freezeActiveMeshesCancel!==null);if(o)return!0;if(!l)throw new Error("Freezing active meshes was cancelled");return!1},()=>{this._freezeActiveMeshesCancel=null,this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=s,this._skipEvaluateActiveMeshesCompletely=e,t==null||t()},(o,l)=>{if(this._freezeActiveMeshesCancel=null,this.unfreezeActiveMeshes(),l){let c="Scene: Timeout while waiting for meshes to be frozen.";i?i(c):(te.Error(c),o&&te.Error(o))}else{let c="Scene: An unexpected error occurred while trying to freeze active meshes.";i?i(c):(te.Error(c),o&&(te.Error(o),o.stack&&te.Error(o.stack)))}}),this}return this.executeWhenReady(()=>{if(!this.activeCamera){i&&i("No active camera found");return}if(this._frustumPlanes||this.updateTransformMatrix(),this._evaluateActiveMeshes(),this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=s,this._skipEvaluateActiveMeshesCompletely=e,r)for(let a=0;ae.dispose())}_evaluateActiveMeshes(){var i;if(this._engine.snapshotRendering&&this._engine.snapshotRenderingMode===1){this._activeMeshes.length>0&&((i=this.activeCamera)==null||i._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset());return}if(this._activeMeshesFrozen&&this._activeMeshes.length){if(!this._skipEvaluateActiveMeshesCompletely){let r=this._activeMeshes.length;for(let s=0;s0&&(s.layerMask&this.activeCamera.layerMask)!==0&&(this._skipFrustumClipping||s.alwaysSelectAsActiveMesh||s.isInFrustum(this._frustumPlanes)))){this._activeMeshes.push(s),this.activeCamera._activeMeshes.push(s),o!==s&&o._activate(this._renderId,!1);for(let l of this._preActiveMeshStage)l.action(s);s._activate(this._renderId,!1)&&(s.isAnInstance?s._internalAbstractMeshDataInfo._actAsRegularMesh&&(o=s):o._internalAbstractMeshDataInfo._onlyForInstances=!1,o._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(s,o)),s._postActivate()}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(let r=0;r0){let r=this.getActiveSubMeshCandidates(t),s=r.length;i=i||s===1;for(let a=0;a0&&this._renderTargets.concatWithNoDuplicate(e.customRenderTargets),t&&t.customRenderTargets&&t.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(t.customRenderTargets),this.environmentTexture&&this.environmentTexture.isRenderTarget&&this._renderTargets.pushNoDuplicate(this.environmentTexture);for(let d of this._gatherActiveCameraRenderTargetsStage)d.action(this._renderTargets);let s=!1;if(this.renderTargetsEnabled){this._intermediateRendering=!0;let d;if(this._renderTargets.length>0){pe.StartPerformanceCounter("Render targets",this._renderTargets.length>0);let u=(f=this.getBoundingBoxRenderer)==null?void 0:f.call(this);for(let m=0;m0?u.renderList.data.slice():[],d.length=u.renderList.length),p.render(_,this.dumpNextRenderTargets),s=!0}}u&&d&&(u.renderList.data=d,u.renderList.length=d.length),pe.EndPerformanceCounter("Render targets",this._renderTargets.length>0),this._renderId++}if(this._cameraDrawRenderTargetStage.length>0){let u=(h=this.getBoundingBoxRenderer)==null?void 0:h.call(this);u&&!d&&(d=u.renderList.length>0?u.renderList.data.slice():[],d.length=u.renderList.length);for(let m of this._cameraDrawRenderTargetStage)s=m.action(this.activeCamera)||s;u&&d&&(u.renderList.data=d,u.renderList.length=d.length)}this._intermediateRendering=!1}s&&!this.prePass&&(this._bindFrameBuffer(this._activeCamera,!1),this.updateTransformMatrix()),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),this.postProcessManager&&!e._multiviewTexture&&!this.prePass&&this.postProcessManager._prepareFrame();for(let d of this._beforeCameraDrawStage)d.action(this.activeCamera);this.onBeforeDrawPhaseObservable.notifyObservers(this);let a=r.snapshotRendering&&r.snapshotRenderingMode===1;a&&this.finalizeSceneUbo(),this._renderingManager.render(null,null,!0,!a),this.onAfterDrawPhaseObservable.notifyObservers(this);for(let d of this._afterCameraDrawStage)d.action(this.activeCamera);if(this.postProcessManager&&!e._multiviewTexture){let d=e.outputRenderTarget?e.outputRenderTarget.renderTarget:void 0;this.postProcessManager._finalizeFrame(e.isIntermediate,d)}for(let d of this._afterCameraPostProcessStage)d.action(this.activeCamera);this._renderTargets.reset(),this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera)}_processSubCameras(e,t=!0){if(e.cameraRigMode===0||e._renderingMultiview){e._renderingMultiview&&!this._multiviewSceneUbo&&this._createMultiviewUbo(),this._renderForCamera(e,void 0,t),this.onAfterRenderCameraObservable.notifyObservers(e);return}if(e._useMultiviewToSingleView)this._renderMultiviewToSingleView(e);else{this.onBeforeCameraRenderObservable.notifyObservers(e);for(let i=0;i-1&&(r.trigger===13&&r._executeCurrent(rn.CreateNew(t,void 0,a)),(!t.actionManager.hasSpecificTrigger(13,c=>{let f=c.mesh?c.mesh:c;return a===f})||r.trigger===13)&&t._intersectionsInProgress.splice(l,1))}}}}_advancePhysicsEngineStep(e){}_animate(e){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(n.MinDeltaTime,Math.min(this._engine.getDeltaTime(),n.MaxDeltaTime))+this._timeAccumulator,t=this._engine.getTimeStep(),i=1e3/t/1e3,r=0,s=this._engine.getLockstepMaxSteps(),a=Math.floor(e/t);for(a=Math.min(a,s);e>0&&r0);for(let l=0;l0),this._renderId++}this.onAfterRenderTargetsRenderObservable.notifyObservers(this);for(let l of this._beforeClearStage)l.action();if(this._engine.snapshotRendering&&this._engine.snapshotRenderingMode===1)this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset();else{let l=this.getActiveMeshCandidates(),c=l.length;if(this._activeMeshesFrozen){if(!this._skipEvaluateActiveMeshesCompletely)for(let f=0;f0)for(let a=0;a0);for(let o=0;o0),this._renderId++}this._engine.currentRenderPassId=(s=a==null?void 0:a.renderPassId)!=null?s:0,this.activeCamera=a,this._activeCamera&&this._activeCamera.cameraRigMode!==22&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this);for(let o of this._beforeClearStage)o.action();this._clearFrameBuffer(this.activeCamera);for(let o of this._gatherRenderTargetsStage)o.action(this._renderTargets);if(this.activeCameras&&this.activeCameras.length>0)for(let o=0;o0);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera,!!this.activeCamera.outputRenderTarget)}}this._checkIntersections();for(let a of this._afterRenderStage)a.action();if(this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this),this._toBeDisposed.length){for(let a=0;as.dispose(!0)),this._disposeList(this.transformNodes,s=>s.dispose(!0));let i=this.cameras;this._disposeList(i),this._disposeList(this.particleSystems),this._disposeList(this.postProcesses),this._disposeList(this.textures),this._disposeList(this.morphTargetManagers),this._disposeList(this.frameGraphs),this._sceneUbo.dispose(),this._multiviewSceneUbo&&this._multiviewSceneUbo.dispose(),this.postProcessManager.dispose(),this._disposeList(this._components);let r=this._engine.scenes.indexOf(this);if(r>-1&&this._engine.scenes.splice(r,1),this._floatingOriginScene=void 0,this._engine.scenes.length===0&&FB(),Le._LastCreatedScene===this){Le._LastCreatedScene=null;let s=Le.Instances.length-1;for(;s>=0;){let a=Le.Instances[s];if(a.scenes.length>0){Le._LastCreatedScene=a.scenes[this._engine.scenes.length-1];break}s--}}r=this._engine._virtualScenes.indexOf(this),r>-1&&this._engine._virtualScenes.splice(r,1),this._engine.wipeCaches(!0),this.onDisposeObservable.clear(),this.onBeforeRenderObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderTargetsRenderObservable.clear(),this.onAfterRenderTargetsRenderObservable.clear(),this.onAfterStepObservable.clear(),this.onBeforeStepObservable.clear(),this.onBeforeActiveMeshesEvaluationObservable.clear(),this.onAfterActiveMeshesEvaluationObservable.clear(),this.onBeforeParticlesRenderingObservable.clear(),this.onAfterParticlesRenderingObservable.clear(),this.onBeforeDrawPhaseObservable.clear(),this.onAfterDrawPhaseObservable.clear(),this.onBeforeAnimationsObservable.clear(),this.onAfterAnimationsObservable.clear(),this.onDataLoadedObservable.clear(),this.onBeforeRenderingGroupObservable.clear(),this.onAfterRenderingGroupObservable.clear(),this.onMeshImportedObservable.clear(),this.onBeforeCameraRenderObservable.clear(),this.onAfterCameraRenderObservable.clear(),this.onAfterRenderCameraObservable.clear(),this.onReadyObservable.clear(),this.onNewCameraAddedObservable.clear(),this.onCameraRemovedObservable.clear(),this.onNewLightAddedObservable.clear(),this.onLightRemovedObservable.clear(),this.onNewGeometryAddedObservable.clear(),this.onGeometryRemovedObservable.clear(),this.onNewTransformNodeAddedObservable.clear(),this.onTransformNodeRemovedObservable.clear(),this.onNewMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onNewSkeletonAddedObservable.clear(),this.onSkeletonRemovedObservable.clear(),this.onNewMaterialAddedObservable.clear(),this.onNewMultiMaterialAddedObservable.clear(),this.onMaterialRemovedObservable.clear(),this.onMultiMaterialRemovedObservable.clear(),this.onNewTextureAddedObservable.clear(),this.onTextureRemovedObservable.clear(),this.onNewFrameGraphAddedObservable.clear(),this.onFrameGraphRemovedObservable.clear(),this.onNewObjectRendererAddedObservable.clear(),this.onObjectRendererRemovedObservable.clear(),this.onPrePointerObservable.clear(),this.onPointerObservable.clear(),this.onPreKeyboardObservable.clear(),this.onKeyboardObservable.clear(),this.onActiveCameraChanged.clear(),this.onScenePerformancePriorityChangedObservable.clear(),this.onClearColorChangedObservable.clear(),this.onEnvironmentTextureChangedObservable.clear(),this.onMeshUnderPointerUpdatedObservable.clear(),this._isDisposed=!0}_disposeList(e,t){let i=e.slice(0);t=t!=null?t:(r=>r.dispose());for(let r of i)t(r);e.length=0}get isDisposed(){return this._isDisposed}clearCachedVertexData(){for(let e=0;e!0);let r=this.meshes.filter(e);for(let s of r){if(s.computeWorldMatrix(!0),!s.subMeshes||s.subMeshes.length===0||s.infiniteDistance)continue;let a=s.getBoundingInfo(),o=a.boundingBox.minimumWorld,l=a.boundingBox.maximumWorld;b.CheckExtends(o,t,i),b.CheckExtends(l,t,i)}return t.x===Number.MAX_VALUE?{min:b.Zero(),max:b.Zero()}:{min:t,max:i}}createPickingRay(e,t,i,r,s=!1){throw Ze("Ray")}createPickingRayToRef(e,t,i,r,s,a=!1,o=!1){throw Ze("Ray")}createPickingRayInCameraSpace(e,t,i){throw Ze("Ray")}createPickingRayInCameraSpaceToRef(e,t,i,r){throw Ze("Ray")}pick(e,t,i,r,s,a){let o=Ze("Ray",!0);return o&&te.Warn(o),new es}pickWithBoundingInfo(e,t,i,r,s){let a=Ze("Ray",!0);return a&&te.Warn(a),new es}pickWithRay(e,t,i,r){throw Ze("Ray")}multiPick(e,t,i,r,s){throw Ze("Ray")}multiPickWithRay(e,t,i){throw Ze("Ray")}setPointerOverMesh(e,t,i){this._inputManager.setPointerOverMesh(e,t,i)}getPointerOverMesh(){return this._inputManager.getPointerOverMesh()}_rebuildGeometries(){for(let e of this.geometries)e._rebuild();for(let e of this.meshes)e._rebuild();this.postProcessManager&&this.postProcessManager._rebuild();for(let e of this._components)e.rebuild();for(let e of this.particleSystems)e.rebuild();if(this.spriteManagers)for(let e of this.spriteManagers)e.rebuild()}_rebuildTextures(){for(let e of this.textures)e._rebuild(!0);this.markAllMaterialsAsDirty(1)}_getByTags(e,t,i){if(t===void 0)return e;let r=[];for(let s in e){let a=e[s];qt&&qt.MatchesQuery(a,t)&&(!i||i(a))&&r.push(a)}return r}getMeshesByTags(e,t){return this._getByTags(this.meshes,e,t)}getCamerasByTags(e,t){return this._getByTags(this.cameras,e,t)}getLightsByTags(e,t){return this._getByTags(this.lights,e,t)}getMaterialByTags(e,t){return this._getByTags(this.materials,e,t).concat(this._getByTags(this.multiMaterials,e,t))}getTransformNodesByTags(e,t){return this._getByTags(this.transformNodes,e,t)}setRenderingOrder(e,t=null,i=null,r=null){this._renderingManager.setRenderingOrder(e,t,i,r)}setRenderingAutoClearDepthStencil(e,t,i=!0,r=!0){this._renderingManager.setRenderingAutoClearDepthStencil(e,t,i,r)}getAutoClearDepthStencilSetup(e){return this._renderingManager.getAutoClearDepthStencilSetup(e)}_forceBlockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism=e}get blockMaterialDirtyMechanism(){return this._blockMaterialDirtyMechanism}set blockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism!==e&&(this._blockMaterialDirtyMechanism=e,e||this.markAllMaterialsAsDirty(127))}markAllMaterialsAsDirty(e,t){if(!this._blockMaterialDirtyMechanism)for(let i of this.materials)t&&!t(i)||i.markAsDirty(e)}_loadFile(e,t,i,r,s,a,o){let l=el(e,t,i,r?this.offlineProvider:void 0,s,a,o);return this._activeRequests.push(l),l.onCompleteObservable.add(c=>{this._activeRequests.splice(this._activeRequests.indexOf(c),1)}),l}async _loadFileAsync(e,t,i,r,s){return await new Promise((a,o)=>{this._loadFile(e,l=>{a(l)},t,i,r,(l,c)=>{o(c)},s)})}_requestFile(e,t,i,r,s,a,o){let l=XT(e,t,i,r?this.offlineProvider:void 0,s,a,o);return this._activeRequests.push(l),l.onCompleteObservable.add(c=>{this._activeRequests.splice(this._activeRequests.indexOf(c),1)}),l}async _requestFileAsync(e,t,i,r,s){return await new Promise((a,o)=>{this._requestFile(e,l=>{a(l)},t,i,r,l=>{o(l)},s)})}_readFile(e,t,i,r,s){let a=Vh(e,t,i,r,s);return this._activeRequests.push(a),a.onCompleteObservable.add(o=>{this._activeRequests.splice(this._activeRequests.indexOf(o),1)}),a}async _readFileAsync(e,t,i){return await new Promise((r,s)=>{this._readFile(e,a=>{r(a)},t,i,a=>{s(a)})})}getPerfCollector(){throw Ze("performanceViewerSceneExtension")}setActiveCameraByID(e){return this.setActiveCameraById(e)}getMaterialByID(e){return this.getMaterialById(e)}getLastMaterialByID(e){return this.getLastMaterialById(e)}getTextureByUniqueID(e){return this.getTextureByUniqueId(e)}getCameraByID(e){return this.getCameraById(e)}getCameraByUniqueID(e){return this.getCameraByUniqueId(e)}getBoneByID(e){return this.getBoneById(e)}getLightByID(e){return this.getLightById(e)}getLightByUniqueID(e){return this.getLightByUniqueId(e)}getParticleSystemByID(e){return this.getParticleSystemById(e)}getGeometryByID(e){return this.getGeometryById(e)}getMeshByID(e){return this.getMeshById(e)}getMeshByUniqueID(e){return this.getMeshByUniqueId(e)}getLastMeshByID(e){return this.getLastMeshById(e)}getMeshesByID(e){return this.getMeshesById(e)}getTransformNodeByID(e){return this.getTransformNodeById(e)}getTransformNodeByUniqueID(e){return this.getTransformNodeByUniqueId(e)}getTransformNodesByID(e){return this.getTransformNodesById(e)}getNodeByID(e){return this.getNodeById(e)}getLastEntryByID(e){return this.getLastEntryById(e)}getLastSkeletonByID(e){return this.getLastSkeletonById(e)}};$t.FOGMODE_NONE=0;$t.FOGMODE_EXP=1;$t.FOGMODE_EXP2=2;$t.FOGMODE_LINEAR=3;$t.MinDeltaTime=1;$t.MaxDeltaTime=1e3;$t._OriginalDefaultMaterialFactory=$t.DefaultMaterialFactory;wt("BABYLON.Scene",$t)});var tU,ene,Ca=C(()=>{W();tU="helperFunctions",ene=`const PI: f32=3.141592653589793;const TWO_PI: f32=6.283185307179586;const HALF_PI: f32=1.5707963267948966;const RECIPROCAL_PI: f32=0.3183098861837907;const RECIPROCAL_PI2: f32=0.15915494309189535;const RECIPROCAL_PI4: f32=0.07957747154594767;const HALF_MIN: f32=5.96046448e-08; +}`;T.ShadersStore[nC]||(T.ShadersStore[nC]=oB);Yre={name:nC,shader:oB}});var Kl,K_,sC=C(()=>{kh();Di();Kl=class n extends zr{_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Promise.resolve().then(()=>(rB(),iB))]))):t.push(Promise.all([Promise.resolve().then(()=>($M(),QM))])),super._gatherImports(e,t)}constructor(e,t=null,i){let r={name:e,engine:t||Oe.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:n.FragmentUrl,...i};r.engine||(r.engine=Oe.LastCreatedEngine),super(r)}};Kl.FragmentUrl="pass";K_=class n extends zr{_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Promise.resolve().then(()=>(aB(),sB))]))):t.push(Promise.all([Promise.resolve().then(()=>(cB(),lB))])),super._gatherImports(e,t)}constructor(e,t=null,i){super({...i,name:e,engine:t||Oe.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:n.FragmentUrl,defines:"#define POSITIVEX"}),this._face=0}get face(){return this._face}set face(e){if(!(e<0||e>5))switch(this._face=e,this._face){case 0:this.updateEffect("#define POSITIVEX");break;case 1:this.updateEffect("#define NEGATIVEX");break;case 2:this.updateEffect("#define POSITIVEY");break;case 3:this.updateEffect("#define NEGATIVEY");break;case 4:this.updateEffect("#define POSITIVEZ");break;case 5:this.updateEffect("#define NEGATIVEZ");break}}};K_.FragmentUrl="passCube"});var Wh,aC,oC=C(()=>{Gt();Yl();wr();Hi();Tr();sC();Vt();Wh=class n extends Ri{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,r,s,a,o=0,l=!1){let c={size:typeof t=="number"?t:void 0,camera:i,samplingMode:r,engine:s,reusable:a,textureType:o,blockCompilation:l,...t};super(e,Kl.FragmentUrl,{effectWrapper:typeof t=="number"||!t.effectWrapper?new Kl(e,s,c):void 0,...c})}static _Parse(e,t,i,r){return it.Parse(()=>new n(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable),e,i,r)}};Ft("BABYLON.PassPostProcess",Wh);aC=class n extends Ri{get face(){return this._effectWrapper.face}set face(e){this._effectWrapper.face=e}getClassName(){return"PassCubePostProcess"}constructor(e,t,i=null,r,s,a,o=0,l=!1){let c={size:typeof t=="number"?t:void 0,camera:i,samplingMode:r,engine:s,reusable:a,textureType:o,blockCompilation:l,...t};super(e,Kl.FragmentUrl,{effectWrapper:typeof t=="number"||!t.effectWrapper?new K_(e,s,c):void 0,...c})}static _Parse(e,t,i,r){return it.Parse(()=>new n(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable),e,i,r)}};P([w()],aC.prototype,"face",null);Me._RescalePostProcessFactory=n=>new Wh("rescale",1,null,2,n,!1,0)});function hB(n,e,t,i,r,s,a,o){let l=e.getEngine();return e.isReady=!1,r=r!=null?r:e.samplingMode,i=i!=null?i:e.type,s=s!=null?s:e.format,a=a!=null?a:e.width,o=o!=null?o:e.height,i===-1&&(i=0),new Promise(c=>{let f=new Ri("postprocess",n,null,null,1,null,r,l,!1,void 0,i,void 0,null,!1,s);f.externalTextureSamplerBinding=!0;let h=l.createRenderTargetTexture({width:a,height:o},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:r,type:i,format:s});f.onEffectCreatedObservable.addOnce(d=>{d.executeWhenCompiled(()=>{f.onApply=u=>{u._bindTexture("textureSampler",e),u.setFloat2("scale",1,1)},t.postProcessManager.directRender([f],h,!0),l.restoreDefaultFramebuffer(),l._releaseTexture(e),f&&f.dispose(),h._swapAndDie(e),e.type=i,e.format=5,e.isReady=!0,c(e)})})})}function Hh(n){eA||(eA=new Float32Array(1),fB=new Int32Array(eA.buffer)),eA[0]=n;let e=fB[0],t=e>>16&32768,i=e>>12&2047,r=e>>23&255;return r<103?t:r>142?(t|=31744,t|=(r==255?0:1)&&e&8388607,t):r<113?(i|=2048,t|=(i>>114-r)+(i>>113-r&1),t):(t|=r-112<<10|i>>1,t+=i&1,t)}function jl(n){let e=(n&32768)>>15,t=(n&31744)>>10,i=n&1023;return t===0?(e?-1:1)*Math.pow(2,-14)*(i/Math.pow(2,10)):t==31?i?NaN:(e?-1:1)*(1/0):(e?-1:1)*Math.pow(2,t-15)*(1+i/Math.pow(2,10))}var eA,fB,lC=C(()=>{Fr();_f();oC();Yl();Ln()});function fC(n){return n.split(" ").filter(e=>e!=="").map(e=>parseFloat(e))}function cC(n,e,t){for(;t.length!==e;){let i=fC(n.lines[n.index++]);t.push(...i)}}function Kre(n,e,t){let i=0,r=0,s=0,a=0,o=0,l=0;for(let g=0;g0&&!i.lines[i.index].includes("TILT=");)i.index++;i.lines[i.index].includes("INCLUDE"),i.index++;let s=fC(i.lines[i.index++]);r.numberOfLights=s[0],r.lumensPerLamp=s[1],r.candelaMultiplier=s[2],r.numberOfVerticalAngles=s[3],r.numberOfHorizontalAngles=s[4],r.photometricType=s[5],r.unitsType=s[6],r.width=s[7],r.length=s[8],r.height=s[9];let a=fC(i.lines[i.index++]);r.ballastFactor=a[0],r.fileGenerationType=a[1],r.inputWatts=a[2];for(let m=0;m0)for(let m=0;m=u)&&(p%=u*2,p>u&&(p=u*2-p)),h[_+p*l]=Kre(r,_,p)}return{width:c/2,height:1,data:h}}var uB=C(()=>{Ln()});var mB={};tt(mB,{_IESTextureLoader:()=>hC});var hC,pB=C(()=>{uB();hC=class{constructor(){this.supportCascades=!1}loadCubeData(){throw".ies not supported in Cube."}loadData(e,t,i){let r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=dB(r);i(s.width,s.height,!!t.useMipMaps,!1,()=>{let a=t.getEngine();t.type=1,t.format=6,t._gammaSpace=!1,a._uploadDataToTextureDirectly(t,s.data)})}}});var _B={};tt(_B,{_DDSTextureLoader:()=>dC});var dC,gB=C(()=>{F_();uC();dC=class{constructor(){this.supportCascades=!0}loadCubeData(e,t,i,r){let s=t.getEngine(),a,o=!1,l=1e3;if(Array.isArray(e))for(let c=0;c1)&&t.generateMipMaps,s._unpackFlipY(a.isCompressed),ao.UploadDDSLevels(s,t,f,a,o,6,-1,c),!a.isFourCC&&a.mipmapCount===1?s.generateMipMapsForCubemap(t):l=a.mipmapCount-1}else{let c=e;a=ao.GetDDSInfo(c),t.width=a.width,t.height=a.height,i&&(a.sphericalPolynomial=new $o),o=(a.isRGB||a.isLuminance||a.mipmapCount>1)&&t.generateMipMaps,s._unpackFlipY(a.isCompressed),ao.UploadDDSLevels(s,t,c,a,o,6),!a.isFourCC&&a.mipmapCount===1?s.generateMipMapsForCubemap(t,!1):l=a.mipmapCount-1}s._setCubeMapTextureParams(t,o,l),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r({isDDS:!0,width:t.width,info:a,data:e,texture:t})}loadData(e,t,i){let r=ao.GetDDSInfo(e),s=(r.isRGB||r.isLuminance||r.mipmapCount>1)&&t.generateMipMaps&&Math.max(r.width,r.height)>>r.mipmapCount-1===1;i(r.width,r.height,s,r.isFourCC,()=>{ao.UploadDDSLevels(t.getEngine(),t,e,r,s,1)})}}});function vB(){let n={cTFETC1:0,cTFETC2:1,cTFBC1:2,cTFBC3:3,cTFBC4:4,cTFBC5:5,cTFBC7:6,cTFPVRTC1_4_RGB:8,cTFPVRTC1_4_RGBA:9,cTFASTC_4x4:10,cTFATC_RGB:11,cTFATC_RGBA_INTERPOLATED_ALPHA:12,cTFRGBA32:13,cTFRGB565:14,cTFBGR565:15,cTFRGBA4444:16,cTFFXT1_RGB:17,cTFPVRTC2_4_RGB:18,cTFPVRTC2_4_RGBA:19,cTFETC2_EAC_R11:20,cTFETC2_EAC_RG11:21},e=null;onmessage=a=>{if(a.data.action==="init"){if(a.data.url)try{importScripts(a.data.url)}catch(o){postMessage({action:"error",error:o})}e||(e=BASIS({wasmBinary:a.data.wasmBinary})),e!==null&&e.then(o=>{BASIS=o,o.initializeBasis(),postMessage({action:"init"})})}else if(a.data.action==="transcode"){let o=a.data.config,l=a.data.imageData,c=new BASIS.BasisFile(l),f=i(c),h=a.data.ignoreSupportedFormats?null:t(a.data.config,f),d=!1;h===null&&(d=!0,h=f.hasAlpha?n.cTFBC3:n.cTFBC1);let u=!0;c.startTranscoding()||(u=!1);let m=[];for(let p=0;p>2&3],h[x++]=f[v>>4&3],h[x]=f[v>>6&3]}}return h}}async function EB(n,e,t){return await new Promise((i,r)=>{let s=a=>{a.data.action==="init"?(n.removeEventListener("message",s),i(n)):a.data.action==="error"&&r(a.data.error||"error initializing worker")};n.addEventListener("message",s),n.postMessage({action:"init",url:t?_e.GetBabylonScriptURL(t):void 0,wasmBinary:e},[e])})}var SB=C(()=>{Ii()});var ql,gf,jre,mC,zh,qre,Zre,Qre,iA,tA,rA,pC,TB=C(()=>{Ii();Fr();vs();SB();(function(n){n[n.cTFETC1=0]="cTFETC1",n[n.cTFETC2=1]="cTFETC2",n[n.cTFBC1=2]="cTFBC1",n[n.cTFBC3=3]="cTFBC3",n[n.cTFBC4=4]="cTFBC4",n[n.cTFBC5=5]="cTFBC5",n[n.cTFBC7=6]="cTFBC7",n[n.cTFPVRTC1_4_RGB=8]="cTFPVRTC1_4_RGB",n[n.cTFPVRTC1_4_RGBA=9]="cTFPVRTC1_4_RGBA",n[n.cTFASTC_4x4=10]="cTFASTC_4x4",n[n.cTFATC_RGB=11]="cTFATC_RGB",n[n.cTFATC_RGBA_INTERPOLATED_ALPHA=12]="cTFATC_RGBA_INTERPOLATED_ALPHA",n[n.cTFRGBA32=13]="cTFRGBA32",n[n.cTFRGB565=14]="cTFRGB565",n[n.cTFBGR565=15]="cTFBGR565",n[n.cTFRGBA4444=16]="cTFRGBA4444",n[n.cTFFXT1_RGB=17]="cTFFXT1_RGB",n[n.cTFPVRTC2_4_RGB=18]="cTFPVRTC2_4_RGB",n[n.cTFPVRTC2_4_RGBA=19]="cTFPVRTC2_4_RGBA",n[n.cTFETC2_EAC_R11=20]="cTFETC2_EAC_R11",n[n.cTFETC2_EAC_RG11=21]="cTFETC2_EAC_RG11"})(ql||(ql={}));gf={JSModuleURL:`${_e._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.js`,WasmModuleURL:`${_e._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.wasm`},jre=(n,e)=>{let t;switch(n){case ql.cTFETC1:t=36196;break;case ql.cTFBC1:t=33776;break;case ql.cTFBC4:t=33779;break;case ql.cTFASTC_4x4:t=37808;break;case ql.cTFETC2:t=37496;break;case ql.cTFBC7:t=36492;break}if(t===void 0)throw"The chosen Basis transcoder format is not currently supported";return t},mC=null,zh=null,qre=0,Zre=!1,Qre=async()=>(mC||(mC=new Promise((n,e)=>{zh?n(zh):_e.LoadFileAsync(_e.GetBabylonScriptURL(gf.WasmModuleURL)).then(t=>{if(typeof URL!="function")return e("Basis transcoder requires an environment with a URL constructor");let i=URL.createObjectURL(new Blob([`(${vB})()`],{type:"application/javascript"}));zh=new Worker(i),EB(zh,t,gf.JSModuleURL).then(n,e)}).catch(e)})),await mC),iA=async(n,e)=>{let t=n instanceof ArrayBuffer?new Uint8Array(n):n;return await new Promise((i,r)=>{Qre().then(()=>{let s=qre++,a=l=>{l.data.action==="transcode"&&l.data.id===s&&(zh.removeEventListener("message",a),l.data.success?i(l.data):r("Transcode is not supported on this device"))};zh.addEventListener("message",a);let o=new Uint8Array(t.byteLength);o.set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),zh.postMessage({action:"transcode",id:s,imageData:o,config:e,ignoreSupportedFormats:Zre},[o.buffer])},s=>{r(s)})})},tA=(n,e)=>{var i,r;let t=(i=e._gl)==null?void 0:i.TEXTURE_2D;n.isCube&&(t=(r=e._gl)==null?void 0:r.TEXTURE_CUBE_MAP),e._bindTextureDirectly(t,n,!0)},rA=(n,e)=>{let t=n.getEngine();for(let i=0;i{t._releaseTexture(s),tA(n,t)})}else n._invertVScale=!n.invertY,n.width=r.width+3&-4,n.height=r.height+3&-4,n.samplingMode=2,tA(n,t),t._uploadDataToTextureDirectly(n,new Uint16Array(r.transcodedPixels.buffer),i,0,4,!0);else{n.width=r.width,n.height=r.height,n.generateMipMaps=e.fileInfo.images[i].levels.length>1;let s=pC.GetInternalFormatFromBasisFormat(e.format,t);n.format=s,tA(n,t);let a=e.fileInfo.images[i].levels;for(let o=0;o_C});var _C,xB=C(()=>{TB();Ii();_C=class{constructor(){this.supportCascades=!1}loadCubeData(e,t,i,r,s){if(Array.isArray(e))return;let a=t.getEngine().getCaps(),o={supportedCompressionFormats:{etc1:!!a.etc1,s3tc:!!a.s3tc,pvrtc:!!a.pvrtc,etc2:!!a.etc2,astc:!!a.astc,bc7:!!a.bptc}};iA(e,o).then(l=>{let c=l.fileInfo.images[0].levels.length>1&&t.generateMipMaps;rA(t,l),t.getEngine()._setCubeMapTextureParams(t,c),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()}).catch(l=>{_e.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),t.isReady=!0,s&&s(l)})}loadData(e,t,i){let r=t.getEngine().getCaps(),s={supportedCompressionFormats:{etc1:!!r.etc1,s3tc:!!r.s3tc,pvrtc:!!r.pvrtc,etc2:!!r.etc2,astc:!!r.astc,bc7:!!r.bptc}};iA(e,s).then(a=>{let o=a.fileInfo.images[0].levels[0],l=a.fileInfo.images[0].levels.length>1&&t.generateMipMaps;i(o.width,o.height,l,a.format!==-1,()=>{rA(t,a)})}).catch(a=>{_e.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),_e.Warn(`Failed to transcode Basis file: ${a}`),i(0,0,!1,!1,()=>{},!0)})}}});var j_,RB=C(()=>{j_=class{constructor(){this._count=0,this._data={}}copyFrom(e){this.clear(),e.forEach((t,i)=>this.add(t,i))}get(e){let t=this._data[e];if(t!==void 0)return t}getOrAddWithFactory(e,t){let i=this.get(e);return i!==void 0||(i=t(e),i&&this.add(e,i)),i}getOrAdd(e,t){let i=this.get(e);return i!==void 0?i:(this.add(e,t),t)}contains(e){return this._data[e]!==void 0}add(e,t){return this._data[e]!==void 0?!1:(this._data[e]=t,++this._count,!0)}set(e,t){return this._data[e]===void 0?!1:(this._data[e]=t,!0)}getAndRemove(e){let t=this.get(e);return t!==void 0?(delete this._data[e],--this._count,t):null}remove(e){return this.contains(e)?(delete this._data[e],--this._count,!0):!1}clear(){this._data={},this._count=0}get count(){return this._count}forEach(e){for(let t in this._data){let i=this._data[t];e(t,i)}}first(e){for(let t in this._data){let i=this._data[t],r=e(t,i);if(r)return r}return null}}});function nA(n){n.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")}var gC=C(()=>{});var tn,bB=C(()=>{Gt();Vt();zt();Tr();gC();tn=class n{constructor(){this._dirty=!0,this._tempColor=new lt(0,0,0,0),this._globalCurve=new lt(0,0,0,0),this._highlightsCurve=new lt(0,0,0,0),this._midtonesCurve=new lt(0,0,0,0),this._shadowsCurve=new lt(0,0,0,0),this._positiveCurve=new lt(0,0,0,0),this._negativeCurve=new lt(0,0,0,0),this._globalHue=30,this._globalDensity=0,this._globalSaturation=0,this._globalExposure=0,this._highlightsHue=30,this._highlightsDensity=0,this._highlightsSaturation=0,this._highlightsExposure=0,this._midtonesHue=30,this._midtonesDensity=0,this._midtonesSaturation=0,this._midtonesExposure=0,this._shadowsHue=30,this._shadowsDensity=0,this._shadowsSaturation=0,this._shadowsExposure=0}get globalHue(){return this._globalHue}set globalHue(e){this._globalHue=e,this._dirty=!0}get globalDensity(){return this._globalDensity}set globalDensity(e){this._globalDensity=e,this._dirty=!0}get globalSaturation(){return this._globalSaturation}set globalSaturation(e){this._globalSaturation=e,this._dirty=!0}get globalExposure(){return this._globalExposure}set globalExposure(e){this._globalExposure=e,this._dirty=!0}get highlightsHue(){return this._highlightsHue}set highlightsHue(e){this._highlightsHue=e,this._dirty=!0}get highlightsDensity(){return this._highlightsDensity}set highlightsDensity(e){this._highlightsDensity=e,this._dirty=!0}get highlightsSaturation(){return this._highlightsSaturation}set highlightsSaturation(e){this._highlightsSaturation=e,this._dirty=!0}get highlightsExposure(){return this._highlightsExposure}set highlightsExposure(e){this._highlightsExposure=e,this._dirty=!0}get midtonesHue(){return this._midtonesHue}set midtonesHue(e){this._midtonesHue=e,this._dirty=!0}get midtonesDensity(){return this._midtonesDensity}set midtonesDensity(e){this._midtonesDensity=e,this._dirty=!0}get midtonesSaturation(){return this._midtonesSaturation}set midtonesSaturation(e){this._midtonesSaturation=e,this._dirty=!0}get midtonesExposure(){return this._midtonesExposure}set midtonesExposure(e){this._midtonesExposure=e,this._dirty=!0}get shadowsHue(){return this._shadowsHue}set shadowsHue(e){this._shadowsHue=e,this._dirty=!0}get shadowsDensity(){return this._shadowsDensity}set shadowsDensity(e){this._shadowsDensity=e,this._dirty=!0}get shadowsSaturation(){return this._shadowsSaturation}set shadowsSaturation(e){this._shadowsSaturation=e,this._dirty=!0}get shadowsExposure(){return this._shadowsExposure}set shadowsExposure(e){this._shadowsExposure=e,this._dirty=!0}getClassName(){return"ColorCurves"}static Bind(e,t,i="vCameraColorCurvePositive",r="vCameraColorCurveNeutral",s="vCameraColorCurveNegative"){e._dirty&&(e._dirty=!1,e._getColorGradingDataToRef(e._globalHue,e._globalDensity,e._globalSaturation,e._globalExposure,e._globalCurve),e._getColorGradingDataToRef(e._highlightsHue,e._highlightsDensity,e._highlightsSaturation,e._highlightsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._highlightsCurve),e._getColorGradingDataToRef(e._midtonesHue,e._midtonesDensity,e._midtonesSaturation,e._midtonesExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._midtonesCurve),e._getColorGradingDataToRef(e._shadowsHue,e._shadowsDensity,e._shadowsSaturation,e._shadowsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._shadowsCurve),e._highlightsCurve.subtractToRef(e._midtonesCurve,e._positiveCurve),e._midtonesCurve.subtractToRef(e._shadowsCurve,e._negativeCurve)),t&&(t.setFloat4(i,e._positiveCurve.r,e._positiveCurve.g,e._positiveCurve.b,e._positiveCurve.a),t.setFloat4(r,e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4(s,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))}_getColorGradingDataToRef(e,t,i,r,s){e!=null&&(e=n._Clamp(e,0,360),t=n._Clamp(t,-100,100),i=n._Clamp(i,-100,100),r=n._Clamp(r,-100,100),t=n._ApplyColorGradingSliderNonlinear(t),t*=.5,r=n._ApplyColorGradingSliderNonlinear(r),t<0&&(t*=-1,e=(e+180)%360),n._FromHSBToRef(e,t,50+.25*r,s),s.scaleToRef(2,s),s.a=1+.01*i)}static _ApplyColorGradingSliderNonlinear(e){e/=100;let t=Math.abs(e);return t=Math.pow(t,2),e<0&&(t*=-1),t*=100,t}static _FromHSBToRef(e,t,i,r){let s=n._Clamp(e,0,360),a=n._Clamp(t/100,0,1),o=n._Clamp(i/100,0,1);if(a===0)r.r=o,r.g=o,r.b=o;else{s/=60;let l=Math.floor(s),c=s-l,f=o*(1-a),h=o*(1-a*c),d=o*(1-a*(1-c));switch(l){case 0:r.r=o,r.g=d,r.b=f;break;case 1:r.r=h,r.g=o,r.b=f;break;case 2:r.r=f,r.g=o,r.b=d;break;case 3:r.r=f,r.g=h,r.b=o;break;case 4:r.r=d,r.g=f,r.b=o;break;default:r.r=o,r.g=f,r.b=h;break}}r.a=1}static _Clamp(e,t,i){return Math.min(Math.max(e,t),i)}clone(){return it.Clone(()=>new n,this)}serialize(){return it.Serialize(this)}static Parse(e){return it.Parse(()=>new n,e,null,null)}};tn.PrepareUniforms=nA;P([w()],tn.prototype,"_globalHue",void 0);P([w()],tn.prototype,"_globalDensity",void 0);P([w()],tn.prototype,"_globalSaturation",void 0);P([w()],tn.prototype,"_globalExposure",void 0);P([w()],tn.prototype,"_highlightsHue",void 0);P([w()],tn.prototype,"_highlightsDensity",void 0);P([w()],tn.prototype,"_highlightsSaturation",void 0);P([w()],tn.prototype,"_highlightsExposure",void 0);P([w()],tn.prototype,"_midtonesHue",void 0);P([w()],tn.prototype,"_midtonesDensity",void 0);P([w()],tn.prototype,"_midtonesSaturation",void 0);P([w()],tn.prototype,"_midtonesExposure",void 0);it._ColorCurvesParser=tn.Parse});function IB(n,e){e.EXPOSURE&&n.push("exposureLinear"),e.CONTRAST&&n.push("contrast"),e.COLORGRADING&&n.push("colorTransformSettings"),(e.VIGNETTE||e.DITHER)&&n.push("vInverseScreenSize"),e.VIGNETTE&&(n.push("vignetteSettings1"),n.push("vignetteSettings2")),e.COLORCURVES&&nA(n),e.DITHER&&n.push("ditherIntensity")}function MB(n,e){e.COLORGRADING&&n.push("txColorTransform")}var CB=C(()=>{gC()});var kt,q_=C(()=>{Gt();Vt();di();zt();bB();$a();Tr();CB();Hi();kt=class n{constructor(){this.colorCurves=new tn,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=n.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new lt(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=n.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.outputTextureWidth=0,this.outputTextureHeight=0,this.onUpdateParameters=new ie}get colorCurvesEnabled(){return this._colorCurvesEnabled}set colorCurvesEnabled(e){this._colorCurvesEnabled!==e&&(this._colorCurvesEnabled=e,this._updateParameters())}get colorGradingTexture(){return this._colorGradingTexture}set colorGradingTexture(e){this._colorGradingTexture!==e&&(this._colorGradingTexture=e,this._updateParameters())}get colorGradingEnabled(){return this._colorGradingEnabled}set colorGradingEnabled(e){this._colorGradingEnabled!==e&&(this._colorGradingEnabled=e,this._updateParameters())}get colorGradingWithGreenDepth(){return this._colorGradingWithGreenDepth}set colorGradingWithGreenDepth(e){this._colorGradingWithGreenDepth!==e&&(this._colorGradingWithGreenDepth=e,this._updateParameters())}get colorGradingBGR(){return this._colorGradingBGR}set colorGradingBGR(e){this._colorGradingBGR!==e&&(this._colorGradingBGR=e,this._updateParameters())}get exposure(){return this._exposure}set exposure(e){this._exposure!==e&&(this._exposure=e,this._updateParameters())}get toneMappingEnabled(){return this._toneMappingEnabled}set toneMappingEnabled(e){this._toneMappingEnabled!==e&&(this._toneMappingEnabled=e,this._updateParameters())}get toneMappingType(){return this._toneMappingType}set toneMappingType(e){this._toneMappingType!==e&&(this._toneMappingType=e,this._updateParameters())}get contrast(){return this._contrast}set contrast(e){this._contrast!==e&&(this._contrast=e,this._updateParameters())}get vignetteCentreY(){return this.vignetteCenterY}set vignetteCentreY(e){this.vignetteCenterY=e}get vignetteCentreX(){return this.vignetteCenterX}set vignetteCentreX(e){this.vignetteCenterX=e}get vignetteBlendMode(){return this._vignetteBlendMode}set vignetteBlendMode(e){this._vignetteBlendMode!==e&&(this._vignetteBlendMode=e,this._updateParameters())}get vignetteEnabled(){return this._vignetteEnabled}set vignetteEnabled(e){this._vignetteEnabled!==e&&(this._vignetteEnabled=e,this._updateParameters())}get ditheringEnabled(){return this._ditheringEnabled}set ditheringEnabled(e){this._ditheringEnabled!==e&&(this._ditheringEnabled=e,this._updateParameters())}get ditheringIntensity(){return this._ditheringIntensity}set ditheringIntensity(e){this._ditheringIntensity!==e&&(this._ditheringIntensity=e,this._updateParameters())}get skipFinalColorClamp(){return this._skipFinalColorClamp}set skipFinalColorClamp(e){this._skipFinalColorClamp!==e&&(this._skipFinalColorClamp=e,this._updateParameters())}get applyByPostProcess(){return this._applyByPostProcess}set applyByPostProcess(e){this._applyByPostProcess!==e&&(this._applyByPostProcess=e,this._updateParameters())}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,this._updateParameters())}_updateParameters(){this.onUpdateParameters.notifyObservers(this)}getClassName(){return"ImageProcessingConfiguration"}prepareDefines(e,t=!1){if(t!==this.applyByPostProcess||!this._isEnabled){e.VIGNETTE=!1,e.TONEMAPPING=0,e.CONTRAST=!1,e.EXPOSURE=!1,e.COLORCURVES=!1,e.COLORGRADING=!1,e.COLORGRADING3D=!1,e.DITHER=!1,e.IMAGEPROCESSING=!1,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess&&this._isEnabled;return}if(e.VIGNETTE=this.vignetteEnabled,e.VIGNETTEBLENDMODEMULTIPLY=this.vignetteBlendMode===n._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,!this._toneMappingEnabled)e.TONEMAPPING=0;else switch(this._toneMappingType){case n.TONEMAPPING_KHR_PBR_NEUTRAL:e.TONEMAPPING=3;break;case n.TONEMAPPING_ACES:e.TONEMAPPING=2;break;default:e.TONEMAPPING=1;break}e.CONTRAST=this.contrast!==1,e.EXPOSURE=this.exposure!==1,e.COLORCURVES=this.colorCurvesEnabled&&!!this.colorCurves,e.COLORGRADING=this.colorGradingEnabled&&!!this.colorGradingTexture,e.COLORGRADING?e.COLORGRADING3D=this.colorGradingTexture.is3D:e.COLORGRADING3D=!1,e.SAMPLER3DGREENDEPTH=this.colorGradingWithGreenDepth,e.SAMPLER3DBGRMAP=this.colorGradingBGR,e.DITHER=this._ditheringEnabled,e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,e.IMAGEPROCESSING=e.VIGNETTE||!!e.TONEMAPPING||e.CONTRAST||e.EXPOSURE||e.COLORCURVES||e.COLORGRADING||e.DITHER}isReady(){return!this.colorGradingEnabled||!this.colorGradingTexture||this.colorGradingTexture.isReady()}bind(e,t){if(this._colorCurvesEnabled&&this.colorCurves&&tn.Bind(this.colorCurves,e),this._vignetteEnabled||this._ditheringEnabled){let i=1/(this.outputTextureWidth||e.getEngine().getRenderWidth()),r=1/(this.outputTextureHeight||e.getEngine().getRenderHeight());if(e.setFloat2("vInverseScreenSize",i,r),this._ditheringEnabled&&e.setFloat("ditherIntensity",.5*this._ditheringIntensity),this._vignetteEnabled){let s=t!=null?t:r/i,a=Math.tan(this.vignetteCameraFov*.5),o=a*s,l=Math.sqrt(o*a);o=L_(o,l,this.vignetteStretch),a=L_(a,l,this.vignetteStretch),e.setFloat4("vignetteSettings1",o,a,-o*this.vignetteCenterX,-a*this.vignetteCenterY);let c=-2*this.vignetteWeight;e.setFloat4("vignetteSettings2",this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b,c)}}if(e.setFloat("exposureLinear",this.exposure),e.setFloat("contrast",this.contrast),this.colorGradingTexture){e.setTexture("txColorTransform",this.colorGradingTexture);let i=this.colorGradingTexture.getSize().height;e.setFloat4("colorTransformSettings",(i-1)/i,.5/i,i,this.colorGradingTexture.level)}}clone(){return it.Clone(()=>new n,this)}serialize(){return it.Serialize(this)}static Parse(e){let t=it.Parse(()=>new n,e,null,null);return e.vignetteCentreX!==void 0&&(t.vignetteCenterX=e.vignetteCentreX),e.vignetteCentreY!==void 0&&(t.vignetteCenterY=e.vignetteCentreY),t}static get VIGNETTEMODE_MULTIPLY(){return this._VIGNETTEMODE_MULTIPLY}static get VIGNETTEMODE_OPAQUE(){return this._VIGNETTEMODE_OPAQUE}};kt.TONEMAPPING_STANDARD=0;kt.TONEMAPPING_ACES=1;kt.TONEMAPPING_KHR_PBR_NEUTRAL=2;kt.PrepareUniforms=IB;kt.PrepareSamplers=MB;kt._VIGNETTEMODE_MULTIPLY=0;kt._VIGNETTEMODE_OPAQUE=1;P([R2()],kt.prototype,"colorCurves",void 0);P([w()],kt.prototype,"_colorCurvesEnabled",void 0);P([Ut("colorGradingTexture")],kt.prototype,"_colorGradingTexture",void 0);P([w()],kt.prototype,"_colorGradingEnabled",void 0);P([w()],kt.prototype,"_colorGradingWithGreenDepth",void 0);P([w()],kt.prototype,"_colorGradingBGR",void 0);P([w()],kt.prototype,"_exposure",void 0);P([w()],kt.prototype,"_toneMappingEnabled",void 0);P([w()],kt.prototype,"_toneMappingType",void 0);P([w()],kt.prototype,"_contrast",void 0);P([w()],kt.prototype,"vignetteStretch",void 0);P([w()],kt.prototype,"vignetteCenterX",void 0);P([w()],kt.prototype,"vignetteCenterY",void 0);P([w()],kt.prototype,"vignetteWeight",void 0);P([tm()],kt.prototype,"vignetteColor",void 0);P([w()],kt.prototype,"vignetteCameraFov",void 0);P([w()],kt.prototype,"_vignetteBlendMode",void 0);P([w()],kt.prototype,"_vignetteEnabled",void 0);P([w()],kt.prototype,"_ditheringEnabled",void 0);P([w()],kt.prototype,"_ditheringIntensity",void 0);P([w()],kt.prototype,"_skipFinalColorClamp",void 0);P([w()],kt.prototype,"_applyByPostProcess",void 0);P([w()],kt.prototype,"_isEnabled",void 0);P([w()],kt.prototype,"outputTextureWidth",void 0);P([w()],kt.prototype,"outputTextureHeight",void 0);it._ImageProcessingConfigurationParser=kt.Parse;Ft("BABYLON.ImageProcessingConfiguration",kt)});var Jn,Z_=C(()=>{Ge();ki();Jn=class{constructor(){this.hit=!1,this.distance=0,this.pickedPoint=null,this.pickedMesh=null,this.bu=0,this.bv=0,this.faceId=-1,this.subMeshFaceId=-1,this.subMeshId=0,this.pickedSprite=null,this.thinInstanceIndex=-1,this.ray=null,this.originMesh=null,this.aimTransform=null,this.gripTransform=null}getNormal(e=!1,t=!0){if(!this.pickedMesh||t&&!this.pickedMesh.isVerticesDataPresent(L.NormalKind))return null;let i=this.pickedMesh.getIndices();(i==null?void 0:i.length)===0&&(i=null);let r,s=$.Vector3[0],a=$.Vector3[1],o=$.Vector3[2];if(t){let c=this.pickedMesh.getVerticesData(L.NormalKind),f=i?b.FromArrayToRef(c,i[this.faceId*3]*3,s):s.copyFromFloats(c[this.faceId*3*3],c[this.faceId*3*3+1],c[this.faceId*3*3+2]),h=i?b.FromArrayToRef(c,i[this.faceId*3+1]*3,a):a.copyFromFloats(c[(this.faceId*3+1)*3],c[(this.faceId*3+1)*3+1],c[(this.faceId*3+1)*3+2]),d=i?b.FromArrayToRef(c,i[this.faceId*3+2]*3,o):o.copyFromFloats(c[(this.faceId*3+2)*3],c[(this.faceId*3+2)*3+1],c[(this.faceId*3+2)*3+2]);f=f.scale(this.bu),h=h.scale(this.bv),d=d.scale(1-this.bu-this.bv),r=new b(f.x+h.x+d.x,f.y+h.y+d.y,f.z+h.z+d.z)}else{let c=this.pickedMesh.getVerticesData(L.PositionKind),f=i?b.FromArrayToRef(c,i[this.faceId*3]*3,s):s.copyFromFloats(c[this.faceId*3*3],c[this.faceId*3*3+1],c[this.faceId*3*3+2]),h=i?b.FromArrayToRef(c,i[this.faceId*3+1]*3,a):a.copyFromFloats(c[(this.faceId*3+1)*3],c[(this.faceId*3+1)*3+1],c[(this.faceId*3+1)*3+2]),d=i?b.FromArrayToRef(c,i[this.faceId*3+2]*3,o):o.copyFromFloats(c[(this.faceId*3+2)*3],c[(this.faceId*3+2)*3+1],c[(this.faceId*3+2)*3+2]),u=f.subtract(h),m=d.subtract(h);r=b.Cross(u,m)}let l=(c,f)=>{if(this.thinInstanceIndex!==-1){let d=c._thinInstanceDataStorage.matrixData,u=this.thinInstanceIndex<<4;if(d&&d.length>u){let m=$.Matrix[0];K.FromArrayToRef(d,u,m),b.TransformNormalToRef(f,m,f)}}let h=c.getWorldMatrix();c.nonUniformScaling&&($.Matrix[0].copyFrom(h),h=$.Matrix[0],h.setTranslationFromFloats(0,0,0),h.invert(),h.transposeToRef($.Matrix[1]),h=$.Matrix[1]),b.TransformNormalToRef(f,h,f)};if(e&&l(this.pickedMesh,r),this.ray){let c=$.Vector3[0].copyFrom(r);e||l(this.pickedMesh,c),b.Dot(c,this.ray.direction)>0&&r.negateInPlace()}return r.normalize(),r}getTextureCoordinates(e=L.UVKind){if(!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(e))return null;let t=this.pickedMesh.getIndices();if(!t)return null;let i=this.pickedMesh.getVerticesData(e);if(!i)return null;let r=we.FromArray(i,t[this.faceId*3]*2),s=we.FromArray(i,t[this.faceId*3+1]*2),a=we.FromArray(i,t[this.faceId*3+2]*2);return r=r.scale(this.bu),s=s.scale(this.bv),a=a.scale(1-this.bu-this.bv),new we(r.x+s.x+a.x,r.y+s.y+a.y)}}});var rn,vC=C(()=>{rn=class n{constructor(e,t,i,r,s,a){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=r,this.sourceEvent=s,this.additionalData=a}static CreateNew(e,t,i){let r=e.getScene();return new n(e,r.pointerX,r.pointerY,r.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,r){return new n(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,r)}static CreateNewFromScene(e,t){return new n(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,r){return new n(e,t.x,t.y,null,i,r)}}});function Q_(n,e,t){let i=t.asArray(),r=e.asArray();for(let s=0;s<16;s++)i[s]=r[s];return i[12]-=n.x,i[13]-=n.y,i[14]-=n.z,t.markAsUpdated(),t}function LB(n,e,t){return N_(e,xa),Q_(n,xa,Ra),N_(Ra,t),t}function sA(n,e,t){if(!ba.eyeAtCamera)return LB(n,e,t);let i=t.asArray(),r=e.asArray();for(let s=0;s<16;s++)i[s]=r[s];return i[12]=0,i[13]=0,i[14]=0,t.markAsUpdated(),t}function EC(n,e,t,i){return Oh(sA(n,e,i),t,i),i}function OB(n,e,t,i,r){for(let s=0;s{yh();Ge();NM();mf();Aa=new K,xa=new K,Ra=new K,ba={getScene:()=>{},eyeAtCamera:!0};$_=hr,SC=rr,NB=$_.prototype._updateMatrixForUniform,wB=rr.prototype.setMatrix});var et,sr,am=C(()=>{et=class{};et.NAME_EFFECTLAYER="EffectLayer";et.NAME_LAYER="Layer";et.NAME_LENSFLARESYSTEM="LensFlareSystem";et.NAME_BOUNDINGBOXRENDERER="BoundingBoxRenderer";et.NAME_PARTICLESYSTEM="ParticleSystem";et.NAME_GAMEPAD="Gamepad";et.NAME_SIMPLIFICATIONQUEUE="SimplificationQueue";et.NAME_GEOMETRYBUFFERRENDERER="GeometryBufferRenderer";et.NAME_PREPASSRENDERER="PrePassRenderer";et.NAME_DEPTHRENDERER="DepthRenderer";et.NAME_DEPTHPEELINGRENDERER="DepthPeelingRenderer";et.NAME_POSTPROCESSRENDERPIPELINEMANAGER="PostProcessRenderPipelineManager";et.NAME_SPRITE="Sprite";et.NAME_SUBSURFACE="SubSurface";et.NAME_OUTLINERENDERER="Outline";et.NAME_PROCEDURALTEXTURE="ProceduralTexture";et.NAME_SHADOWGENERATOR="ShadowGenerator";et.NAME_OCTREE="Octree";et.NAME_PHYSICSENGINE="PhysicsEngine";et.NAME_AUDIO="Audio";et.NAME_FLUIDRENDERER="FluidRenderer";et.NAME_IBLCDFGENERATOR="iblCDFGenerator";et.NAME_CLUSTEREDLIGHTING="ClusteredLighting";et.STEP_ISREADYFORMESH_EFFECTLAYER=0;et.STEP_ISREADYFORMESH_DEPTHRENDERER=1;et.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER=0;et.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER=0;et.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER=0;et.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER=1;et.STEP_BEFORECAMERADRAW_PREPASS=0;et.STEP_BEFORECAMERADRAW_EFFECTLAYER=1;et.STEP_BEFORECAMERADRAW_LAYER=2;et.STEP_BEFORERENDERTARGETDRAW_PREPASS=0;et.STEP_BEFORERENDERTARGETDRAW_LAYER=1;et.STEP_BEFORERENDERINGMESH_PREPASS=0;et.STEP_BEFORERENDERINGMESH_OUTLINE=1;et.STEP_AFTERRENDERINGMESH_PREPASS=0;et.STEP_AFTERRENDERINGMESH_OUTLINE=1;et.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW=0;et.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER=1;et.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE=0;et.STEP_BEFORECLEAR_PROCEDURALTEXTURE=0;et.STEP_BEFORECLEAR_PREPASS=1;et.STEP_BEFORERENDERTARGETCLEAR_PREPASS=0;et.STEP_AFTERRENDERTARGETDRAW_PREPASS=0;et.STEP_AFTERRENDERTARGETDRAW_LAYER=1;et.STEP_AFTERCAMERADRAW_PREPASS=0;et.STEP_AFTERCAMERADRAW_EFFECTLAYER=1;et.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM=2;et.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW=3;et.STEP_AFTERCAMERADRAW_LAYER=4;et.STEP_AFTERCAMERADRAW_FLUIDRENDERER=5;et.STEP_AFTERCAMERAPOSTPROCESS_LAYER=0;et.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER=0;et.STEP_AFTERRENDER_AUDIO=0;et.STEP_GATHERRENDERTARGETS_DEPTHRENDERER=0;et.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER=1;et.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR=2;et.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER=3;et.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER=0;et.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER=1;et.STEP_GATHERACTIVECAMERARENDERTARGETS_CLUSTEREDLIGHTING=2;et.STEP_POINTERMOVE_SPRITE=0;et.STEP_POINTERDOWN_SPRITE=0;et.STEP_POINTERUP_SPRITE=0;sr=class n extends Array{constructor(e){super(...e)}static Create(){return Object.create(n.prototype)}registerStep(e,t,i){let r=0,s;for(;r{Ge();st=class{};st.POINTERDOWN=1;st.POINTERUP=2;st.POINTERMOVE=4;st.POINTERWHEEL=8;st.POINTERPICK=16;st.POINTERTAP=32;st.POINTERDOUBLETAP=64;aA=class{constructor(e,t){this.type=e,this.event=t}},oA=class extends aA{constructor(e,t,i,r){super(e,t),this.ray=null,this.originalPickingInfo=null,this.skipOnPointerObservable=!1,this.localPosition=new we(i,r)}},Ia=class extends aA{get pickInfo(){return this._pickInfo||this._generatePickInfo(),this._pickInfo}constructor(e,t,i,r=null){super(e,t),this._pickInfo=i,this._inputManager=r}_generatePickInfo(){this._inputManager&&(this._pickInfo=this._inputManager._pickMove(this.event),this._inputManager._setRayOnPointerInfo(this._pickInfo,this.event),this._inputManager=null)}}});var Zl,UB=C(()=>{Zl=class n{constructor(){this.hoverCursor="",this.actions=[],this.isRecursive=!1,this.disposeWhenUnowned=!0}static get HasTriggers(){for(let e in n.Triggers)if(Object.prototype.hasOwnProperty.call(n.Triggers,e))return!0;return!1}static get HasPickTriggers(){for(let e in n.Triggers)if(Object.prototype.hasOwnProperty.call(n.Triggers,e)){let t=parseInt(e);if(t>=1&&t<=7)return!0}return!1}static HasSpecificTrigger(e){for(let t in n.Triggers)if(Object.prototype.hasOwnProperty.call(n.Triggers,t)&&parseInt(t)===e)return!0;return!1}};Zl.Triggers={}});var lo,om,eg,lA=C(()=>{lo=class{};lo.KEYDOWN=1;lo.KEYUP=2;om=class{constructor(e,t){this.type=e,this.event=t}},eg=class extends om{get skipOnPointerObservable(){return this.skipOnKeyboardObservable}set skipOnPointerObservable(e){this.skipOnKeyboardObservable=e}constructor(e,t){super(e,t),this.type=e,this.event=t,this.skipOnKeyboardObservable=!1}}});var Qe,vt,VB,GB,kB,WB,HB,Xh=C(()=>{(function(n){n[n.Generic=0]="Generic",n[n.Keyboard=1]="Keyboard",n[n.Mouse=2]="Mouse",n[n.Touch=3]="Touch",n[n.DualShock=4]="DualShock",n[n.Xbox=5]="Xbox",n[n.Switch=6]="Switch",n[n.DualSense=7]="DualSense"})(Qe||(Qe={}));(function(n){n[n.Horizontal=0]="Horizontal",n[n.Vertical=1]="Vertical",n[n.LeftClick=2]="LeftClick",n[n.MiddleClick=3]="MiddleClick",n[n.RightClick=4]="RightClick",n[n.BrowserBack=5]="BrowserBack",n[n.BrowserForward=6]="BrowserForward",n[n.MouseWheelX=7]="MouseWheelX",n[n.MouseWheelY=8]="MouseWheelY",n[n.MouseWheelZ=9]="MouseWheelZ",n[n.Move=12]="Move"})(vt||(vt={}));(function(n){n[n.Horizontal=0]="Horizontal",n[n.Vertical=1]="Vertical",n[n.LeftClick=2]="LeftClick",n[n.MiddleClick=3]="MiddleClick",n[n.RightClick=4]="RightClick",n[n.BrowserBack=5]="BrowserBack",n[n.BrowserForward=6]="BrowserForward",n[n.MouseWheelX=7]="MouseWheelX",n[n.MouseWheelY=8]="MouseWheelY",n[n.MouseWheelZ=9]="MouseWheelZ",n[n.DeltaHorizontal=10]="DeltaHorizontal",n[n.DeltaVertical=11]="DeltaVertical"})(VB||(VB={}));(function(n){n[n.Cross=0]="Cross",n[n.Circle=1]="Circle",n[n.Square=2]="Square",n[n.Triangle=3]="Triangle",n[n.L1=4]="L1",n[n.R1=5]="R1",n[n.L2=6]="L2",n[n.R2=7]="R2",n[n.Share=8]="Share",n[n.Options=9]="Options",n[n.L3=10]="L3",n[n.R3=11]="R3",n[n.DPadUp=12]="DPadUp",n[n.DPadDown=13]="DPadDown",n[n.DPadLeft=14]="DPadLeft",n[n.DPadRight=15]="DPadRight",n[n.Home=16]="Home",n[n.TouchPad=17]="TouchPad",n[n.LStickXAxis=18]="LStickXAxis",n[n.LStickYAxis=19]="LStickYAxis",n[n.RStickXAxis=20]="RStickXAxis",n[n.RStickYAxis=21]="RStickYAxis"})(GB||(GB={}));(function(n){n[n.Cross=0]="Cross",n[n.Circle=1]="Circle",n[n.Square=2]="Square",n[n.Triangle=3]="Triangle",n[n.L1=4]="L1",n[n.R1=5]="R1",n[n.L2=6]="L2",n[n.R2=7]="R2",n[n.Create=8]="Create",n[n.Options=9]="Options",n[n.L3=10]="L3",n[n.R3=11]="R3",n[n.DPadUp=12]="DPadUp",n[n.DPadDown=13]="DPadDown",n[n.DPadLeft=14]="DPadLeft",n[n.DPadRight=15]="DPadRight",n[n.Home=16]="Home",n[n.TouchPad=17]="TouchPad",n[n.LStickXAxis=18]="LStickXAxis",n[n.LStickYAxis=19]="LStickYAxis",n[n.RStickXAxis=20]="RStickXAxis",n[n.RStickYAxis=21]="RStickYAxis"})(kB||(kB={}));(function(n){n[n.A=0]="A",n[n.B=1]="B",n[n.X=2]="X",n[n.Y=3]="Y",n[n.LB=4]="LB",n[n.RB=5]="RB",n[n.LT=6]="LT",n[n.RT=7]="RT",n[n.Back=8]="Back",n[n.Start=9]="Start",n[n.LS=10]="LS",n[n.RS=11]="RS",n[n.DPadUp=12]="DPadUp",n[n.DPadDown=13]="DPadDown",n[n.DPadLeft=14]="DPadLeft",n[n.DPadRight=15]="DPadRight",n[n.Home=16]="Home",n[n.LStickXAxis=17]="LStickXAxis",n[n.LStickYAxis=18]="LStickYAxis",n[n.RStickXAxis=19]="RStickXAxis",n[n.RStickYAxis=20]="RStickYAxis"})(WB||(WB={}));(function(n){n[n.B=0]="B",n[n.A=1]="A",n[n.Y=2]="Y",n[n.X=3]="X",n[n.L=4]="L",n[n.R=5]="R",n[n.ZL=6]="ZL",n[n.ZR=7]="ZR",n[n.Minus=8]="Minus",n[n.Plus=9]="Plus",n[n.LS=10]="LS",n[n.RS=11]="RS",n[n.DPadUp=12]="DPadUp",n[n.DPadDown=13]="DPadDown",n[n.DPadLeft=14]="DPadLeft",n[n.DPadRight=15]="DPadRight",n[n.Home=16]="Home",n[n.Capture=17]="Capture",n[n.LStickXAxis=18]="LStickXAxis",n[n.LStickYAxis=19]="LStickYAxis",n[n.RStickXAxis=20]="RStickXAxis",n[n.RStickYAxis=21]="RStickYAxis"})(HB||(HB={}))});var zB,co,cA=C(()=>{(function(n){n[n.PointerMove=0]="PointerMove",n[n.PointerDown=1]="PointerDown",n[n.PointerUp=2]="PointerUp"})(zB||(zB={}));co=class{};co.DOM_DELTA_PIXEL=0;co.DOM_DELTA_LINE=1;co.DOM_DELTA_PAGE=2});var fo,AC=C(()=>{cA();Xh();fo=class{static CreateDeviceEvent(e,t,i,r,s,a,o){switch(e){case Qe.Keyboard:return this._CreateKeyboardEvent(i,r,s,a);case Qe.Mouse:if(i===vt.MouseWheelX||i===vt.MouseWheelY||i===vt.MouseWheelZ)return this._CreateWheelEvent(e,t,i,r,s,a);case Qe.Touch:return this._CreatePointerEvent(e,t,i,r,s,a,o);default:throw`Unable to generate event for device ${Qe[e]}`}}static _CreatePointerEvent(e,t,i,r,s,a,o){let l=this._CreateMouseEvent(e,t,i,r,s,a);e===Qe.Mouse?(l.deviceType=Qe.Mouse,l.pointerId=1,l.pointerType="mouse"):(l.deviceType=Qe.Touch,l.pointerId=o!=null?o:t,l.pointerType="touch");let c=0;return c+=s.pollInput(e,t,vt.LeftClick),c+=s.pollInput(e,t,vt.RightClick)*2,c+=s.pollInput(e,t,vt.MiddleClick)*4,l.buttons=c,i===vt.Move?l.type="pointermove":i>=vt.LeftClick&&i<=vt.RightClick&&(l.type=r===1?"pointerdown":"pointerup",l.button=i-2),l}static _CreateWheelEvent(e,t,i,r,s,a){let o=this._CreateMouseEvent(e,t,i,r,s,a);switch(o.pointerId=1,o.type="wheel",o.deltaMode=co.DOM_DELTA_PIXEL,o.deltaX=0,o.deltaY=0,o.deltaZ=0,i){case vt.MouseWheelX:o.deltaX=r;break;case vt.MouseWheelY:o.deltaY=r;break;case vt.MouseWheelZ:o.deltaZ=r;break}return o}static _CreateMouseEvent(e,t,i,r,s,a){let o=this._CreateEvent(a),l=s.pollInput(e,t,vt.Horizontal),c=s.pollInput(e,t,vt.Vertical);return a?(o.movementX=0,o.movementY=0,o.offsetX=o.movementX-a.getBoundingClientRect().x,o.offsetY=o.movementY-a.getBoundingClientRect().y):(o.movementX=s.pollInput(e,t,10),o.movementY=s.pollInput(e,t,11),o.offsetX=0,o.offsetY=0),this._CheckNonCharacterKeys(o,s),o.clientX=l,o.clientY=c,o.x=l,o.y=c,o.deviceType=e,o.deviceSlot=t,o.inputIndex=i,o}static _CreateKeyboardEvent(e,t,i,r){let s=this._CreateEvent(r);return this._CheckNonCharacterKeys(s,i),s.deviceType=Qe.Keyboard,s.deviceSlot=0,s.inputIndex=e,s.type=t===1?"keydown":"keyup",s.key=String.fromCharCode(e),s.keyCode=e,s}static _CheckNonCharacterKeys(e,t){let i=t.isDeviceAvailable(Qe.Keyboard),r=i&&t.pollInput(Qe.Keyboard,0,18)===1,s=i&&t.pollInput(Qe.Keyboard,0,17)===1,a=i&&(t.pollInput(Qe.Keyboard,0,91)===1||t.pollInput(Qe.Keyboard,0,92)===1||t.pollInput(Qe.Keyboard,0,93)===1),o=i&&t.pollInput(Qe.Keyboard,0,16)===1;e.altKey=r,e.ctrlKey=s,e.metaKey=a,e.shiftKey=o}static _CreateEvent(e){let t={};return t.preventDefault=()=>{},t.target=e,t}}});var fA,XB=C(()=>{AC();Xh();fA=class{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,(r,s,a,o)=>{let l=fo.CreateDeviceEvent(r,s,a,o,this);i(r,s,l)}):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===Qe.Mouse||e===Qe.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}});var YB,KB,hA,jB=C(()=>{ga();Ii();AC();Xh();YB=255,KB=Object.keys(vt).length/2,hA=class{constructor(e,t,i,r){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=_e.IsSafari(),this._usingMacOs=Nl()&&/(Mac|iPhone|iPod|iPad)/i.test(navigator.platform),this._keyboardDownEvent=s=>{},this._keyboardUpEvent=s=>{},this._keyboardBlurEvent=s=>{},this._pointerMoveEvent=s=>{},this._pointerDownEvent=s=>{},this._pointerUpEvent=s=>{},this._pointerCancelEvent=s=>{},this._pointerCancelTouch=s=>{},this._pointerLeaveEvent=s=>{},this._pointerWheelEvent=s=>{},this._pointerBlurEvent=s=>{},this._pointerMacOsChromeOutEvent=s=>{},this._eventsAttached=!1,this._mouseId=-1,this._isUsingFirefox=Nl()&&navigator.userAgent&&navigator.userAgent.indexOf("Firefox")!==-1,this._isUsingChromium=Nl()&&navigator.userAgent&&navigator.userAgent.indexOf("Chrome")!==-1,this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=s=>{},this._gamepadDisconnectedEvent=s=>{},this._eventPrefix=_e.GetPointerPrefix(e),this._engine=e,this._onDeviceConnected=t,this._onDeviceDisconnected=i,this._onInputChanged=r,this._mouseId=this._isUsingFirefox?0:1,this._enableEvents(),this._usingMacOs&&(this._metaKeys=[]),this._engine._onEngineViewChanged||(this._engine._onEngineViewChanged=()=>{this._enableEvents()})}pollInput(e,t,i){let r=this._inputs[e][t];if(!r)throw`Unable to find device ${Qe[e]}`;e>=Qe.DualShock&&e<=Qe.DualSense&&this._updateDevice(e,t,i);let s=r[i];if(s===void 0)throw`Unable to find input ${i} for device ${Qe[e]} in slot ${t}`;return i===vt.Move&&_e.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),s}isDeviceAvailable(e){return this._inputs[e]!==void 0}dispose(){this._onDeviceConnected=()=>{},this._onDeviceDisconnected=()=>{},this._onInputChanged=()=>{},delete this._engine._onEngineViewChanged,this._elementToAttachTo&&this._disableEvents()}_enableEvents(){let e=this==null?void 0:this._engine.getInputElement();if(e&&(!this._eventsAttached||this._elementToAttachTo!==e)){if(this._disableEvents(),this._inputs){for(let t of this._inputs)if(t)for(let i in t){let r=+i,s=t[r];if(s)for(let a=0;a{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(Qe.Keyboard,0,YB));let t=this._inputs[Qe.Keyboard][0];if(t){t[e.keyCode]=1;let i=e;i.inputIndex=e.keyCode,this._usingMacOs&&e.metaKey&&e.key!=="Meta"&&(this._metaKeys.includes(e.keyCode)||this._metaKeys.push(e.keyCode)),this._onInputChanged(Qe.Keyboard,0,i)}},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(Qe.Keyboard,0,YB));let t=this._inputs[Qe.Keyboard][0];if(t){t[e.keyCode]=0;let i=e;if(i.inputIndex=e.keyCode,this._usingMacOs&&e.key==="Meta"&&this._metaKeys.length>0){for(let r of this._metaKeys){let s=fo.CreateDeviceEvent(Qe.Keyboard,0,r,0,this,this._elementToAttachTo);t[r]=0,this._onInputChanged(Qe.Keyboard,0,s)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(Qe.Keyboard,0,i)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){let e=this._inputs[Qe.Keyboard][0];for(let t=0;t{let r=this._getPointerType(i),s=r===Qe.Mouse?0:this._activeTouchIds.indexOf(i.pointerId);if(r===Qe.Touch&&s===-1){let o=this._activeTouchIds.indexOf(-1);if(o>=0)s=o,this._activeTouchIds[o]=i.pointerId,this._onDeviceConnected(r,s);else{_e.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);return}}this._inputs[r]||(this._inputs[r]={}),this._inputs[r][s]||this._addPointerDevice(r,s,i.clientX,i.clientY);let a=this._inputs[r][s];if(a){let o=i;o.inputIndex=vt.Move,a[vt.Horizontal]=i.clientX,a[vt.Vertical]=i.clientY,r===Qe.Touch&&a[vt.LeftClick]===0&&(a[vt.LeftClick]=1),i.pointerId===void 0&&(i.pointerId=this._mouseId),this._onInputChanged(r,s,o),!this._usingSafari&&i.button!==-1&&(o.inputIndex=i.button+2,a[i.button+2]=a[i.button+2]?0:1,this._onInputChanged(r,s,o))}},this._pointerDownEvent=i=>{let r=this._getPointerType(i),s=r===Qe.Mouse?0:i.pointerId;if(r===Qe.Touch){let o=this._activeTouchIds.indexOf(i.pointerId);if(o===-1&&(o=this._activeTouchIds.indexOf(-1)),o>=0)s=o,this._activeTouchIds[o]=i.pointerId;else{_e.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);return}}this._inputs[r]||(this._inputs[r]={}),this._inputs[r][s]?r===Qe.Touch&&this._onDeviceConnected(r,s):this._addPointerDevice(r,s,i.clientX,i.clientY);let a=this._inputs[r][s];if(a){let o=a[vt.Horizontal],l=a[vt.Vertical];if(r===Qe.Mouse){if(i.pointerId===void 0&&(i.pointerId=this._mouseId),!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(this._mouseId)}catch(f){}}else if(i.pointerId&&!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(i.pointerId)}catch(f){}a[vt.Horizontal]=i.clientX,a[vt.Vertical]=i.clientY,a[i.button+2]=1;let c=i;c.inputIndex=i.button+2,this._onInputChanged(r,s,c),(o!==i.clientX||l!==i.clientY)&&(c.inputIndex=vt.Move,this._onInputChanged(r,s,c))}},this._pointerUpEvent=i=>{var c,f,h,d,u;let r=this._getPointerType(i),s=r===Qe.Mouse?0:this._activeTouchIds.indexOf(i.pointerId);if(r===Qe.Touch){if(s===-1)return;this._activeTouchIds[s]=-1}let a=(c=this._inputs[r])==null?void 0:c[s],o=i.button,l=a&&a[o+2]!==0;if(!l&&this._isUsingFirefox&&this._usingMacOs&&a&&(o=o===2?0:2,l=a[o+2]!==0),l){let m=a[vt.Horizontal],p=a[vt.Vertical];a[vt.Horizontal]=i.clientX,a[vt.Vertical]=i.clientY,a[o+2]=0;let _=i;i.pointerId===void 0&&(i.pointerId=this._mouseId),(m!==i.clientX||p!==i.clientY)&&(_.inputIndex=vt.Move,this._onInputChanged(r,s,_)),_.inputIndex=o+2,r===Qe.Mouse&&this._mouseId>=0&&((h=(f=this._elementToAttachTo).hasPointerCapture)!=null&&h.call(f,this._mouseId))?this._elementToAttachTo.releasePointerCapture(this._mouseId):i.pointerId&&((u=(d=this._elementToAttachTo).hasPointerCapture)!=null&&u.call(d,i.pointerId))&&this._elementToAttachTo.releasePointerCapture(i.pointerId),this._onInputChanged(r,s,_),r===Qe.Touch&&this._onDeviceDisconnected(r,s)}},this._pointerCancelTouch=i=>{var a,o;let r=this._activeTouchIds.indexOf(i);if(r===-1)return;(o=(a=this._elementToAttachTo).hasPointerCapture)!=null&&o.call(a,i)&&this._elementToAttachTo.releasePointerCapture(i),this._inputs[Qe.Touch][r][vt.LeftClick]=0;let s=fo.CreateDeviceEvent(Qe.Touch,r,vt.LeftClick,0,this,this._elementToAttachTo,i);this._onInputChanged(Qe.Touch,r,s),this._activeTouchIds[r]=-1,this._onDeviceDisconnected(Qe.Touch,r)},this._pointerCancelEvent=i=>{var r,s;if(i.pointerType==="mouse"){let a=this._inputs[Qe.Mouse][0];this._mouseId>=0&&((s=(r=this._elementToAttachTo).hasPointerCapture)!=null&&s.call(r,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let o=vt.LeftClick;o<=vt.BrowserForward;o++)if(a[o]===1){a[o]=0;let l=fo.CreateDeviceEvent(Qe.Mouse,0,o,0,this,this._elementToAttachTo);this._onInputChanged(Qe.Mouse,0,l)}}else this._pointerCancelTouch(i.pointerId)},this._pointerLeaveEvent=i=>{i.pointerType==="pen"&&this._pointerCancelTouch(i.pointerId)},this._wheelEventName="onwheel"in document.createElement("div")?"wheel":document.onmousewheel!==void 0?"mousewheel":"DOMMouseScroll";let e=!1,t=function(){};try{let i=Object.defineProperty({},"passive",{get:function(){e=!0}});this._elementToAttachTo.addEventListener("test",t,i),this._elementToAttachTo.removeEventListener("test",t,i)}catch(i){}this._pointerBlurEvent=()=>{var i,r,s,a,o;if(this.isDeviceAvailable(Qe.Mouse)){let l=this._inputs[Qe.Mouse][0];this._mouseId>=0&&((r=(i=this._elementToAttachTo).hasPointerCapture)!=null&&r.call(i,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let c=vt.LeftClick;c<=vt.BrowserForward;c++)if(l[c]===1){l[c]=0;let f=fo.CreateDeviceEvent(Qe.Mouse,0,c,0,this,this._elementToAttachTo);this._onInputChanged(Qe.Mouse,0,f)}}if(this.isDeviceAvailable(Qe.Touch)){let l=this._inputs[Qe.Touch];for(let c=0;c{let r=Qe.Mouse,s=0;this._inputs[r]||(this._inputs[r]=[]),this._inputs[r][s]||(this._pointerActive=!0,this._registerDevice(r,s,KB));let a=this._inputs[r][s];if(a){a[vt.MouseWheelX]=i.deltaX||0,a[vt.MouseWheelY]=i.deltaY||i.wheelDelta||0,a[vt.MouseWheelZ]=i.deltaZ||0;let o=i;i.pointerId===void 0&&(i.pointerId=this._mouseId),a[vt.MouseWheelX]!==0&&(o.inputIndex=vt.MouseWheelX,this._onInputChanged(r,s,o)),a[vt.MouseWheelY]!==0&&(o.inputIndex=vt.MouseWheelY,this._onInputChanged(r,s,o)),a[vt.MouseWheelZ]!==0&&(o.inputIndex=vt.MouseWheelZ,this._onInputChanged(r,s,o))}},this._usingMacOs&&this._isUsingChromium&&(this._pointerMacOsChromeOutEvent=i=>{i.buttons>1&&this._pointerCancelEvent(i)},this._elementToAttachTo.addEventListener("lostpointercapture",this._pointerMacOsChromeOutEvent)),this._elementToAttachTo.addEventListener(this._eventPrefix+"move",this._pointerMoveEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"down",this._pointerDownEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"up",this._pointerUpEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"cancel",this._pointerCancelEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"leave",this._pointerLeaveEvent),this._elementToAttachTo.addEventListener("blur",this._pointerBlurEvent),this._elementToAttachTo.addEventListener(this._wheelEventName,this._pointerWheelEvent,e?{passive:!1}:!1),this._pointerInputClearObserver=this._engine.onEndFrameObservable.add(()=>{if(this.isDeviceAvailable(Qe.Mouse)){let i=this._inputs[Qe.Mouse][0];i[vt.MouseWheelX]=0,i[vt.MouseWheelY]=0,i[vt.MouseWheelZ]=0}})}_handleGamepadActions(){this._gamepadConnectedEvent=e=>{this._addGamePad(e.gamepad)},this._gamepadDisconnectedEvent=e=>{if(this._gamepads){let t=this._getGamepadDeviceType(e.gamepad.id),i=e.gamepad.index;this._unregisterDevice(t,i),delete this._gamepads[i]}},window.addEventListener("gamepadconnected",this._gamepadConnectedEvent),window.addEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)}_updateDevice(e,t,i){let r=navigator.getGamepads()[t];if(r&&e===this._gamepads[t]){let s=this._inputs[e][t];i>=r.buttons.length?s[i]=r.axes[i-r.buttons.length].valueOf():s[i]=r.buttons[i].value}}_getGamepadDeviceType(e){return e.indexOf("054c")!==-1?e.indexOf("0ce6")!==-1?Qe.DualSense:Qe.DualShock:e.indexOf("Xbox One")!==-1||e.search("Xbox 360")!==-1||e.search("xinput")!==-1?Qe.Xbox:e.indexOf("057e")!==-1?Qe.Switch:Qe.Generic}_getPointerType(e){let t=Qe.Mouse;return(e.pointerType==="touch"||e.pointerType==="pen"||e.touches)&&(t=Qe.Touch),t}}});var tg,qB=C(()=>{di();tg=class{constructor(e,t,i=0){this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new ie,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}}});var dA,ZB=C(()=>{Xh();XB();jB();qB();dA=class{constructor(e){this._registeredManagers=new Array,this._refCount=0,this.registerManager=a=>{for(let o=0;o{let o=this._registeredManagers.indexOf(a);o>-1&&this._registeredManagers.splice(o,1)};let t=Object.keys(Qe).length/2;this._devices=new Array(t);let i=(a,o)=>{this._devices[a]||(this._devices[a]=new Array),this._devices[a][o]||(this._devices[a][o]=o);for(let l of this._registeredManagers){let c=new tg(this._deviceInputSystem,a,o);l._addDevice(c)}},r=(a,o)=>{var l;(l=this._devices[a])!=null&&l[o]&&delete this._devices[a][o];for(let c of this._registeredManagers)c._removeDevice(a,o)},s=(a,o,l)=>{if(l)for(let c of this._registeredManagers)c._onInputChanged(a,o,l)};typeof _native!="undefined"?this._deviceInputSystem=new fA(i,r,s):this._deviceInputSystem=new hA(e,i,r,s)}dispose(){this._deviceInputSystem.dispose()}}});var uA,QB=C(()=>{Xh();di();ZB();uA=class{getDeviceSource(e,t){if(t===void 0){if(this._firstDevice[e]===void 0)return null;t=this._firstDevice[e]}return!this._devices[e]||this._devices[e][t]===void 0?null:this._devices[e][t]}getDeviceSources(e){return this._devices[e]?this._devices[e].filter(t=>!!t):[]}constructor(e){let t=Object.keys(Qe).length/2;this._devices=new Array(t),this._firstDevice=new Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new dA(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new ie(i=>{for(let r of this._devices)if(r)for(let s of r)s&&this.onDeviceConnectedObservable.notifyObserver(i,s)}),this.onDeviceDisconnectedObservable=new ie,this._engine._deviceSourceManager.registerManager(this),this._onDisposeObserver=e.onDisposeObservable.add(()=>{this.dispose()})}dispose(){this.onDeviceConnectedObservable.clear(),this.onDeviceDisconnectedObservable.clear(),this._engine._deviceSourceManager&&(this._engine._deviceSourceManager.unregisterManager(this),--this._engine._deviceSourceManager._refCount<1&&(this._engine._deviceSourceManager.dispose(),delete this._engine._deviceSourceManager)),this._engine.onDisposeObservable.remove(this._onDisposeObserver)}_addDevice(e){this._devices[e.deviceType]||(this._devices[e.deviceType]=[]),this._devices[e.deviceType][e.deviceSlot]||(this._devices[e.deviceType][e.deviceSlot]=e,this._updateFirstDevices(e.deviceType)),this.onDeviceConnectedObservable.notifyObservers(e)}_removeDevice(e,t){var r,s;let i=(r=this._devices[e])==null?void 0:r[t];this.onDeviceDisconnectedObservable.notifyObservers(i),(s=this._devices[e])!=null&&s[t]&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){var r,s;(s=(r=this._devices[e])==null?void 0:r[t])==null||s.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case Qe.Keyboard:case Qe.Mouse:this._firstDevice[e]=0;break;case Qe.Touch:case Qe.DualSense:case Qe.DualShock:case Qe.Xbox:case Qe.Switch:case Qe.Generic:{delete this._firstDevice[e];let t=this._devices[e];if(t){for(let i=0;i{Yh=class{};Yh._IsPickingAvailable=!1});var mA,On,$B=C(()=>{oo();UB();Z_();Ge();vC();lA();Xh();QB();Di();xC();mA=class{constructor(){this._singleClick=!1,this._doubleClick=!1,this._hasSwiped=!1,this._ignore=!1}get singleClick(){return this._singleClick}get doubleClick(){return this._doubleClick}get hasSwiped(){return this._hasSwiped}get ignore(){return this._ignore}set singleClick(e){this._singleClick=e}set doubleClick(e){this._doubleClick=e}set hasSwiped(e){this._hasSwiped=e}set ignore(e){this._ignore=e}},On=class n{constructor(e){this._alreadyAttached=!1,this._meshPickProceed=!1,this._currentPickResult=null,this._previousPickResult=null,this._activePointerIds=new Array,this._activePointerIdsCount=0,this._doubleClickOccured=!1,this._isSwiping=!1,this._swipeButtonPressed=-1,this._skipPointerTap=!1,this._isMultiTouchGesture=!1,this._pointerX=0,this._pointerY=0,this._startingPointerPosition=new we(0,0),this._previousStartingPointerPosition=new we(0,0),this._startingPointerTime=0,this._previousStartingPointerTime=0,this._pointerCaptures={},this._meshUnderPointerId={},this._movePointerInfo=null,this._cameraObserverCount=0,this._delayedClicks=[null,null,null,null,null],this._deviceSourceManager=null,this._scene=e||Oe.LastCreatedScene,this._scene}get meshUnderPointer(){return this._movePointerInfo&&(this._movePointerInfo._generatePickInfo(),this._movePointerInfo=null),this._pointerOverMesh}getMeshUnderPointerByPointerId(e){return this._meshUnderPointerId[e]||null}get unTranslatedPointer(){return new we(this._unTranslatedPointerX,this._unTranslatedPointerY)}get pointerX(){return this._pointerX}set pointerX(e){this._pointerX=e}get pointerY(){return this._pointerY}set pointerY(e){this._pointerY=e}_updatePointerPosition(e){let t=this._scene.getEngine().getInputElementClientRect();t&&(this._pointerX=e.clientX-t.left,this._pointerY=e.clientY-t.top,this._unTranslatedPointerX=this._pointerX,this._unTranslatedPointerY=this._pointerY)}_processPointerMove(e,t){let i=this._scene,r=i.getEngine(),s=r.getInputElement();s&&(s.tabIndex=r.canvasTabIndex,i.doNotHandleCursors||(s.style.cursor=i.defaultCursor)),this._setCursorAndPointerOverMesh(e,t,i);for(let l of i._pointerMoveStage){e=e||this._pickMove(t);let c=!!(e!=null&&e.pickedMesh);e=l.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,c,s)}let a=t.inputIndex>=vt.MouseWheelX&&t.inputIndex<=vt.MouseWheelZ?st.POINTERWHEEL:st.POINTERMOVE;i.onPointerMove&&(e=e||this._pickMove(t),i.onPointerMove(t,e,a));let o;e?(o=new Ia(a,t,e),this._setRayOnPointerInfo(e,t)):(o=new Ia(a,t,null,this),this._movePointerInfo=o),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(o,a)}_setRayOnPointerInfo(e,t){let i=this._scene;e&&Yh._IsPickingAvailable&&(e.ray||(e.ray=i.createPickingRay(t.offsetX,t.offsetY,K.Identity(),i.activeCamera)))}_addCameraPointerObserver(e,t){return this._cameraObserverCount++,this._scene.onPointerObservable.add(e,t)}_removeCameraPointerObserver(e){return this._cameraObserverCount--,this._scene.onPointerObservable.remove(e)}_checkForPicking(){return!!(this._scene.onPointerObservable.observers.length>this._cameraObserverCount||this._scene.onPointerPick)}_checkPrePointerObservable(e,t,i){let r=this._scene,s=new oA(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(s.originalPickingInfo=e,s.ray=e.ray,t.pointerType==="xr-near"&&e.originMesh&&(s.nearInteractionPickingInfo=e)),r.onPrePointerObservable.notifyObservers(s,i),!!s.skipOnPointerObservable}_pickMove(e){let t=this._scene,i=t.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,t.pointerMovePredicate,t.pointerMoveFastCheck,t.cameraToUseForPointers,t.pointerMoveTrianglePredicate);return this._setCursorAndPointerOverMesh(i,e,t),i}_setCursorAndPointerOverMesh(e,t,i){let s=i.getEngine().getInputElement();if(e!=null&&e.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!i.doNotHandleCursors&&s&&this._pointerOverMesh){let a=this._pointerOverMesh._getActionManagerForTrigger();a&&a.hasPointerTriggers&&(s.style.cursor=a.hoverCursor||i.hoverCursor)}}else this.setPointerOverMesh(null,t.pointerId,e,t)}simulatePointerMove(e,t){let i=new PointerEvent("pointermove",t);i.inputIndex=vt.Move,!this._checkPrePointerObservable(e,i,st.POINTERMOVE)&&this._processPointerMove(e,i)}simulatePointerDown(e,t){let i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,!this._checkPrePointerObservable(e,i,st.POINTERDOWN)&&this._processPointerDown(e,i)}_processPointerDown(e,t){let i=this._scene;if(e!=null&&e.pickedMesh){this._pickedDownMesh=e.pickedMesh;let a=e.pickedMesh._getActionManagerForTrigger();if(a){if(a.hasPickTriggers)switch(a.processTrigger(5,new rn(e.pickedMesh,i.pointerX,i.pointerY,e.pickedMesh,t,e)),t.button){case 0:a.processTrigger(2,new rn(e.pickedMesh,i.pointerX,i.pointerY,e.pickedMesh,t,e));break;case 1:a.processTrigger(4,new rn(e.pickedMesh,i.pointerX,i.pointerY,e.pickedMesh,t,e));break;case 2:a.processTrigger(3,new rn(e.pickedMesh,i.pointerX,i.pointerY,e.pickedMesh,t,e));break}a.hasSpecificTrigger(8)&&window.setTimeout(()=>{let o=i.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,l=>l.isPickable&&l.isVisible&&l.isReady()&&l.actionManager&&l.actionManager.hasSpecificTrigger(8)&&l===this._pickedDownMesh,!1,i.cameraToUseForPointers);o!=null&&o.pickedMesh&&a&&this._activePointerIdsCount!==0&&Date.now()-this._startingPointerTime>n.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,a.processTrigger(8,rn.CreateNew(o.pickedMesh,t)))},n.LongPressDelay)}}else for(let a of i._pointerDownStage)e=a.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let r,s=st.POINTERDOWN;e?(i.onPointerDown&&i.onPointerDown(t,e,s),r=new Ia(s,t,e),this._setRayOnPointerInfo(e,t)):r=new Ia(s,t,null,this),i.onPointerObservable.hasObservers()&&i.onPointerObservable.notifyObservers(r,s)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,i){let r=new PointerEvent("pointerup",t);r.inputIndex=vt.Move;let s=new mA;i?s.doubleClick=!0:s.singleClick=!0,!this._checkPrePointerObservable(e,r,st.POINTERUP)&&this._processPointerUp(e,r,s)}_processPointerUp(e,t,i){let r=this._scene;if(e!=null&&e.pickedMesh){if(this._pickedUpMesh=e.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(r.onPointerPick&&r.onPointerPick(t,e),i.singleClick&&!i.ignore&&r.onPointerObservable.observers.length>this._cameraObserverCount)){let a=st.POINTERPICK,o=new Ia(a,t,e);this._setRayOnPointerInfo(e,t),r.onPointerObservable.notifyObservers(o,a)}let s=e.pickedMesh._getActionManagerForTrigger();if(s&&!i.ignore){s.processTrigger(7,rn.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&s.processTrigger(1,rn.CreateNew(e.pickedMesh,t,e));let a=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&a&&a.processTrigger(6,rn.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(let s of r._pointerUpStage)e=s.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,i.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){let s=this._pickedDownMesh._getActionManagerForTrigger(16);s&&s.processTrigger(16,rn.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){let s=new Ia(st.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),r.onPointerObservable.notifyObservers(s,st.POINTERUP),r.onPointerUp&&r.onPointerUp(t,e,st.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let a=0;if(i.singleClick?a=st.POINTERTAP:i.doubleClick&&(a=st.POINTERDOUBLETAP),a){let o=new Ia(a,t,e);r.onPointerObservable.hasObservers()&&r.onPointerObservable.hasSpecificMask(a)&&r.onPointerObservable.notifyObservers(o,a)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,r=null){let s=this._scene,a=s.getEngine();r||(r=a.getInputElement()),this._alreadyAttached&&this.detachControl(),r&&(this._alreadyAttachedTo=r),this._deviceSourceManager=new uA(a),this._initActionManager=o=>{if(!this._meshPickProceed){let l=s.skipPointerUpPicking||s._registeredActions===0&&!this._checkForPicking()&&!s.onPointerUp?null:s.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,s.pointerUpPredicate,s.pointerUpFastCheck,s.cameraToUseForPointers,s.pointerUpTrianglePredicate);this._currentPickResult=l,l&&(o=l.hit&&l.pickedMesh?l.pickedMesh._getActionManagerForTrigger():null),this._meshPickProceed=!0}return o},this._delayedSimpleClick=(o,l,c)=>{if((Date.now()-this._previousStartingPointerTime>n.DoubleClickDelay&&!this._doubleClickOccured||o!==this._previousButtonPressed)&&(this._doubleClickOccured=!1,l.singleClick=!0,l.ignore=!1,this._delayedClicks[o])){let f=this._delayedClicks[o].evt,h=st.POINTERTAP,d=new Ia(h,f,this._currentPickResult);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(h)&&s.onPointerObservable.notifyObservers(d,h),this._delayedClicks[o]=null}},this._initClickEvent=(o,l,c,f)=>{var p,_;let h=new mA;this._currentPickResult=null;let d=null,u=o.hasSpecificMask(st.POINTERPICK)||l.hasSpecificMask(st.POINTERPICK)||o.hasSpecificMask(st.POINTERTAP)||l.hasSpecificMask(st.POINTERTAP)||o.hasSpecificMask(st.POINTERDOUBLETAP)||l.hasSpecificMask(st.POINTERDOUBLETAP);!u&&Zl&&(d=this._initActionManager(d,h),d&&(u=d.hasPickTriggers));let m=!1;if(u=u&&!this._isMultiTouchGesture,u){let g=c.button;if(h.hasSwiped=this._isPointerSwiping(),!h.hasSwiped){let v=!n.ExclusiveDoubleClickMode;if(v||(v=!o.hasSpecificMask(st.POINTERDOUBLETAP)&&!l.hasSpecificMask(st.POINTERDOUBLETAP),v&&!Zl.HasSpecificTrigger(6)&&(d=this._initActionManager(d,h),d&&(v=!d.hasSpecificTrigger(6)))),v)(Date.now()-this._previousStartingPointerTime>n.DoubleClickDelay||g!==this._previousButtonPressed)&&(h.singleClick=!0,f(h,this._currentPickResult),m=!0);else{let A={evt:c,clickInfo:h,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,g,h,f),n.DoubleClickDelay)};this._delayedClicks[g]=A}let x=o.hasSpecificMask(st.POINTERDOUBLETAP)||l.hasSpecificMask(st.POINTERDOUBLETAP);!x&&Zl.HasSpecificTrigger(6)&&(d=this._initActionManager(d,h),d&&(x=d.hasSpecificTrigger(6))),x&&(g===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime{if(this._updatePointerPosition(o),!this._isSwiping&&this._swipeButtonPressed!==-1&&(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>n.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>n.DragMovementThreshold),a.isPointerLock&&a._verifyPointerLock(),this._checkPrePointerObservable(null,o,o.inputIndex>=vt.MouseWheelX&&o.inputIndex<=vt.MouseWheelZ?st.POINTERWHEEL:st.POINTERMOVE)||!s.cameraToUseForPointers&&!s.activeCamera)return;if(s.skipPointerMovePicking){this._processPointerMove(new Jn,o);return}s.pointerMovePredicate||(s.pointerMovePredicate=c=>c.isPickable&&c.isVisible&&c.isReady()&&c.isEnabled()&&(c.enablePointerMoveEvents||s.constantlyUpdateMeshUnderPointer||c._getActionManagerForTrigger()!==null)&&(!s.cameraToUseForPointers||(s.cameraToUseForPointers.layerMask&c.layerMask)!==0));let l=s._registeredActions>0||s.constantlyUpdateMeshUnderPointer?this._pickMove(o):null;this._processPointerMove(l,o)},this._onPointerDown=o=>{var f;let l=this._activePointerIds.indexOf(-1);if(l===-1?this._activePointerIds.push(o.pointerId):this._activePointerIds[l]=o.pointerId,this._activePointerIdsCount++,this._pickedDownMesh=null,this._meshPickProceed=!1,n.ExclusiveDoubleClickMode){for(let h=0;hh.isPickable&&h.isVisible&&h.isReady()&&h.isEnabled()&&(!s.cameraToUseForPointers||(s.cameraToUseForPointers.layerMask&h.layerMask)!==0)),this._pickedDownMesh=null;let c;s.skipPointerDownPicking||s._registeredActions===0&&!this._checkForPicking()&&!s.onPointerDown?c=new Jn:c=s.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,s.pointerDownPredicate,s.pointerDownFastCheck,s.cameraToUseForPointers,s.pointerDownTrianglePredicate),this._processPointerDown(c,o)},this._onPointerUp=o=>{let l=this._activePointerIds.indexOf(o.pointerId);l!==-1&&(this._activePointerIds[l]=-1,this._activePointerIdsCount--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(o),s.preventDefaultOnPointerUp&&r&&(o.preventDefault(),r.focus()),this._initClickEvent(s.onPrePointerObservable,s.onPointerObservable,o,(c,f)=>{if(s.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!c.ignore)){if(this._checkPrePointerObservable(null,o,st.POINTERUP)){this._swipeButtonPressed===o.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1),o.buttons===0&&(this._pointerCaptures[o.pointerId]=!1);return}c.hasSwiped||(c.singleClick&&s.onPrePointerObservable.hasSpecificMask(st.POINTERTAP)&&this._checkPrePointerObservable(null,o,st.POINTERTAP)&&(this._skipPointerTap=!0),c.doubleClick&&s.onPrePointerObservable.hasSpecificMask(st.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,o,st.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}if(!this._pointerCaptures[o.pointerId]){this._swipeButtonPressed===o.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1);return}o.buttons===0&&(this._pointerCaptures[o.pointerId]=!1),!(!s.cameraToUseForPointers&&!s.activeCamera)&&(s.pointerUpPredicate||(s.pointerUpPredicate=h=>h.isPickable&&h.isVisible&&h.isReady()&&h.isEnabled()&&(!s.cameraToUseForPointers||(s.cameraToUseForPointers.layerMask&h.layerMask)!==0)),!this._meshPickProceed&&(Zl&&Zl.HasTriggers||this._checkForPicking()||s.onPointerUp)&&this._initActionManager(null,c),f||(f=this._currentPickResult),this._processPointerUp(f,o,c),this._previousPickResult=this._currentPickResult,this._swipeButtonPressed===o.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1))}))},this._onKeyDown=o=>{let l=lo.KEYDOWN;if(s.onPreKeyboardObservable.hasObservers()){let c=new eg(l,o);if(s.onPreKeyboardObservable.notifyObservers(c,l),c.skipOnKeyboardObservable)return}if(s.onKeyboardObservable.hasObservers()){let c=new om(l,o);s.onKeyboardObservable.notifyObservers(c,l)}s.actionManager&&s.actionManager.processTrigger(14,rn.CreateNewFromScene(s,o))},this._onKeyUp=o=>{let l=lo.KEYUP;if(s.onPreKeyboardObservable.hasObservers()){let c=new eg(l,o);if(s.onPreKeyboardObservable.notifyObservers(c,l),c.skipOnKeyboardObservable)return}if(s.onKeyboardObservable.hasObservers()){let c=new om(l,o);s.onKeyboardObservable.notifyObservers(c,l)}s.actionManager&&s.actionManager.processTrigger(15,rn.CreateNewFromScene(s,o))},this._deviceSourceManager.onDeviceConnectedObservable.add(o=>{o.deviceType===Qe.Mouse?o.onInputChangedObservable.add(l=>{this._originMouseEvent=l,l.inputIndex===vt.LeftClick||l.inputIndex===vt.MiddleClick||l.inputIndex===vt.RightClick||l.inputIndex===vt.BrowserBack||l.inputIndex===vt.BrowserForward?t&&o.getInput(l.inputIndex)===1?this._onPointerDown(l):e&&o.getInput(l.inputIndex)===0&&this._onPointerUp(l):i&&(l.inputIndex===vt.Move?this._onPointerMove(l):(l.inputIndex===vt.MouseWheelX||l.inputIndex===vt.MouseWheelY||l.inputIndex===vt.MouseWheelZ)&&this._onPointerMove(l))}):o.deviceType===Qe.Touch?o.onInputChangedObservable.add(l=>{l.inputIndex===vt.LeftClick&&(t&&o.getInput(l.inputIndex)===1?(this._onPointerDown(l),this._activePointerIdsCount>1&&(this._isMultiTouchGesture=!0)):e&&o.getInput(l.inputIndex)===0&&(this._onPointerUp(l),this._activePointerIdsCount===0&&(this._isMultiTouchGesture=!1))),i&&l.inputIndex===vt.Move&&this._onPointerMove(l)}):o.deviceType===Qe.Keyboard&&o.onInputChangedObservable.add(l=>{l.type==="keydown"?this._onKeyDown(l):l.type==="keyup"&&this._onKeyUp(l)})}),this._alreadyAttached=!0}detachControl(){this._alreadyAttached&&(this._deviceSourceManager.dispose(),this._deviceSourceManager=null,this._alreadyAttachedTo&&!this._scene.doNotHandleCursors&&(this._alreadyAttachedTo.style.cursor=this._scene.defaultCursor),this._alreadyAttached=!1,this._alreadyAttachedTo=null)}setPointerOverMesh(e,t=0,i,r){if(this._meshUnderPointerId[t]===e&&(!e||!e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting))return;let s=this._meshUnderPointerId[t],a;s&&(a=s._getActionManagerForTrigger(10),a&&a.processTrigger(10,new rn(s,this._pointerX,this._pointerY,e,r,{pointerId:t}))),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,a=e._getActionManagerForTrigger(9),a&&a.processTrigger(9,new rn(e,this._pointerX,this._pointerY,e,r,{pointerId:t,pickResult:i}))):(delete this._meshUnderPointerId[t],this._pointerOverMesh=null),this._scene.onMeshUnderPointerUpdatedObservable.hasObservers()&&this._scene.onMeshUnderPointerUpdatedObservable.notifyObservers({mesh:e,pointerId:t})}getPointerOverMesh(){return this.meshUnderPointer}_invalidateMesh(e){this._pointerOverMesh===e&&(this._pointerOverMesh=null),this._pickedDownMesh===e&&(this._pickedDownMesh=null),this._pickedUpMesh===e&&(this._pickedUpMesh=null);for(let t in this._meshUnderPointerId)this._meshUnderPointerId[t]===e&&delete this._meshUnderPointerId[t]}};On.DragMovementThreshold=10;On.LongPressDelay=500;On.DoubleClickDelay=300;On.ExclusiveDoubleClickMode=!1});var il,RC=C(()=>{wl();il=class n{get min(){return this._min}get max(){return this._max}get average(){return this._average}get lastSecAverage(){return this._lastSecAverage}get current(){return this._current}get total(){return this._totalAccumulated}get count(){return this._totalValueCount}constructor(){this._startMonitoringTime=0,this._min=0,this._max=0,this._average=0,this._lastSecAverage=0,this._current=0,this._totalValueCount=0,this._totalAccumulated=0,this._lastSecAccumulated=0,this._lastSecTime=0,this._lastSecValueCount=0}fetchNewFrame(){this._totalValueCount++,this._current=0,this._lastSecValueCount++}addCount(e,t){n.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){n.Enabled&&(this._startMonitoringTime=pr.Now)}endMonitoring(e=!0){if(!n.Enabled)return;e&&this.fetchNewFrame();let t=pr.Now;this._current=t-this._startMonitoringTime,e&&this._fetchResult()}endFrame(){this._fetchResult()}_fetchResult(){this._totalAccumulated+=this._current,this._lastSecAccumulated+=this._current,this._min=Math.min(this._min,this._current),this._max=Math.max(this._max,this._current),this._average=this._totalAccumulated/this._totalValueCount;let e=pr.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}};il.Enabled=!0});var Ql,pA=C(()=>{Ql=class{static get UniqueId(){let e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}};Ql._UniqueIdCounter=1});var _A,JB=C(()=>{_A=class{constructor(){this.pointerDownFastCheck=!1,this.pointerUpFastCheck=!1,this.pointerMoveFastCheck=!1,this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1}}});var $re,Jre,eU,Jt,As=C(()=>{Ii();wl();di();so();RB();df();Ge();q_();mf();Z_();vC();qT();J_();QT();am();ga();Di();hn();$B();RC();zt();FT();pA();Wl();z_();Zo();JB();Pt();Hi();jo();$re=new bi,Jre=new bi;(function(n){n[n.BackwardCompatible=0]="BackwardCompatible",n[n.Intermediate=1]="Intermediate",n[n.Aggressive=2]="Aggressive"})(eU||(eU={}));Jt=class n{static DefaultMaterialFactory(e){throw qe("StandardMaterial")}static CollisionCoordinatorFactory(){throw qe("DefaultCollisionCoordinator")}get clearColor(){return this._clearColor}set clearColor(e){e!==this._clearColor&&(this._clearColor=e,this.onClearColorChangedObservable.notifyObservers(this._clearColor))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}get performancePriority(){return this._performancePriority}set performancePriority(e){if(e!==this._performancePriority){switch(this._performancePriority=e,e){case 0:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case 1:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case 2:this.skipFrustumClipping=!0,this._renderingManager.maintainStateBetweenFrames=!0,this.skipPointerMovePicking=!0,this.autoClear=!1;break}this.onScenePerformancePriorityChangedObservable.notifyObservers(e)}}set forceWireframe(e){this._forceWireframe!==e&&(this._forceWireframe=e,this.markAllMaterialsAsDirty(16))}get forceWireframe(){return this._forceWireframe}set skipFrustumClipping(e){this._skipFrustumClipping!==e&&(this._skipFrustumClipping=e)}get skipFrustumClipping(){return this._skipFrustumClipping}set forcePointsCloud(e){this._forcePointsCloud!==e&&(this._forcePointsCloud=e,this.markAllMaterialsAsDirty(16))}get forcePointsCloud(){return this._forcePointsCloud}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture!==e&&(this._environmentTexture=e,this.onEnvironmentTextureChangedObservable.notifyObservers(e),this.markAllMaterialsAsDirty(1))}getNodes(){let e=[];e=e.concat(this.meshes),e=e.concat(this.lights),e=e.concat(this.cameras),e=e.concat(this.transformNodes);for(let t of this.skeletons)e=e.concat(t.bones);return e}get animationPropertiesOverride(){return this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set beforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),e&&(this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e))}set afterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),e&&(this._onAfterRenderObserver=this.onAfterRenderObservable.add(e))}set beforeCameraRender(e){this._onBeforeCameraRenderObserver&&this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=this.onBeforeCameraRenderObservable.add(e)}set afterCameraRender(e){this._onAfterCameraRenderObserver&&this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=this.onAfterCameraRenderObservable.add(e)}get pointerDownPredicate(){return this._pointerPickingConfiguration.pointerDownPredicate}set pointerDownPredicate(e){this._pointerPickingConfiguration.pointerDownPredicate=e}get pointerUpPredicate(){return this._pointerPickingConfiguration.pointerUpPredicate}set pointerUpPredicate(e){this._pointerPickingConfiguration.pointerUpPredicate=e}get pointerMovePredicate(){return this._pointerPickingConfiguration.pointerMovePredicate}set pointerMovePredicate(e){this._pointerPickingConfiguration.pointerMovePredicate=e}get pointerDownFastCheck(){return this._pointerPickingConfiguration.pointerDownFastCheck}set pointerDownFastCheck(e){this._pointerPickingConfiguration.pointerDownFastCheck=e}get pointerUpFastCheck(){return this._pointerPickingConfiguration.pointerUpFastCheck}set pointerUpFastCheck(e){this._pointerPickingConfiguration.pointerUpFastCheck=e}get pointerMoveFastCheck(){return this._pointerPickingConfiguration.pointerMoveFastCheck}set pointerMoveFastCheck(e){this._pointerPickingConfiguration.pointerMoveFastCheck=e}get skipPointerMovePicking(){return this._pointerPickingConfiguration.skipPointerMovePicking}set skipPointerMovePicking(e){this._pointerPickingConfiguration.skipPointerMovePicking=e}get skipPointerDownPicking(){return this._pointerPickingConfiguration.skipPointerDownPicking}set skipPointerDownPicking(e){this._pointerPickingConfiguration.skipPointerDownPicking=e}get skipPointerUpPicking(){return this._pointerPickingConfiguration.skipPointerUpPicking}set skipPointerUpPicking(e){this._pointerPickingConfiguration.skipPointerUpPicking=e}get unTranslatedPointer(){return this._inputManager.unTranslatedPointer}static get DragMovementThreshold(){return On.DragMovementThreshold}static set DragMovementThreshold(e){On.DragMovementThreshold=e}static get LongPressDelay(){return On.LongPressDelay}static set LongPressDelay(e){On.LongPressDelay=e}static get DoubleClickDelay(){return On.DoubleClickDelay}static set DoubleClickDelay(e){On.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return On.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){On.ExclusiveDoubleClickMode=e}get _eyePosition(){var e,t,i;return(i=(t=this._forcedViewPosition)!=null?t:(e=this.activeCamera)==null?void 0:e.globalPosition)!=null?i:b.ZeroReadOnly}bindEyePosition(e,t="vEyePosition",i=!1){let r=this._eyePosition,s=this.useRightHandedSystem===(this._mirroredCameraPosition!=null),a=this.floatingOriginOffset,o=$re.set(r.x,r.y,r.z,s?-1:1),l=o.subtractFromFloatsToRef(a.x,a.y,a.z,0,Jre);return e&&(i?e.setFloat3(t,l.x,l.y,l.z):e.setVector4(t,l)),o}finalizeSceneUbo(){let e=this.getSceneUniformBuffer(),t=this.bindEyePosition(null),i=this.floatingOriginOffset;return e.updateFloat4("vEyePosition",t.x-i.x,t.y-i.y,t.z-i.z,t.w),e.update(),e}set useRightHandedSystem(e){this._useRightHandedSystem!==e&&(this._useRightHandedSystem=e,this.markAllMaterialsAsDirty(16))}get useRightHandedSystem(){return this._useRightHandedSystem}setStepId(e){this._currentStepId=e}getStepId(){return this._currentStepId}getInternalStep(){return this._currentInternalStep}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this.markAllMaterialsAsDirty(16))}get fogEnabled(){return this._fogEnabled}set fogMode(e){this._fogMode!==e&&(this._fogMode=e,this.markAllMaterialsAsDirty(16))}get fogMode(){return this._fogMode}get prePass(){return!!this.prePassRenderer&&this.prePassRenderer.defaultRT.enabled}set shadowsEnabled(e){this._shadowsEnabled!==e&&(this._shadowsEnabled=e,this.markAllMaterialsAsDirty(2))}get shadowsEnabled(){return this._shadowsEnabled}set lightsEnabled(e){this._lightsEnabled!==e&&(this._lightsEnabled=e,this.markAllMaterialsAsDirty(2))}get lightsEnabled(){return this._lightsEnabled}get activeCameras(){return this._activeCameras}set activeCameras(e){this._unObserveActiveCameras&&(this._unObserveActiveCameras(),this._unObserveActiveCameras=null),e&&(this._unObserveActiveCameras=NT(e,()=>{this.onActiveCamerasChanged.notifyObservers(this)})),this._activeCameras=e}get activeCamera(){return this._activeCamera}set activeCamera(e){e!==this._activeCamera&&(this._activeCamera=e,this.onActiveCameraChanged.notifyObservers(this))}get _hasDefaultMaterial(){return n.DefaultMaterialFactory!==n._OriginalDefaultMaterialFactory}get defaultMaterial(){return this._defaultMaterial||(this._defaultMaterial=n.DefaultMaterialFactory(this)),this._defaultMaterial}set defaultMaterial(e){this._defaultMaterial=e}set texturesEnabled(e){this._texturesEnabled!==e&&(this._texturesEnabled=e,this.markAllMaterialsAsDirty(1))}get texturesEnabled(){return this._texturesEnabled}get frameGraph(){return this._frameGraph}set frameGraph(e){if(this._frameGraph){this._frameGraph=e,e||(this.customRenderFunction=this._currentCustomRenderFunction);return}this._frameGraph=e,e&&(this._currentCustomRenderFunction=this.customRenderFunction,this.customRenderFunction=this._renderWithFrameGraph,this.activeCamera=null)}set skeletonsEnabled(e){this._skeletonsEnabled!==e&&(this._skeletonsEnabled=e,this.markAllMaterialsAsDirty(8))}get skeletonsEnabled(){return this._skeletonsEnabled}get collisionCoordinator(){return this._collisionCoordinator||(this._collisionCoordinator=n.CollisionCoordinatorFactory(),this._collisionCoordinator.init(this)),this._collisionCoordinator}get renderingManager(){return this._renderingManager}get frustumPlanes(){return this._frustumPlanes}_registerTransientComponents(){if(this._transientComponents.length>0){for(let e of this._transientComponents)e.register();this._transientComponents.length=0}}_addComponent(e){this._components.push(e),this._transientComponents.push(e);let t=e;t.addFromContainer&&t.serialize&&this._serializableComponents.push(t)}_getComponent(e){for(let t of this._components)if(t.name===e)return t;return null}get uniqueId(){return this._uniqueId}constructor(e,t){this._inputManager=new On(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this._clearColor=new lt(.2,.2,.3,1),this.onClearColorChangedObservable=new ie,this.ambientColor=new ve(0,0,0),this.environmentIntensity=1,this.iblIntensity=1,this._performancePriority=0,this.onScenePerformancePriorityChangedObservable=new ie,this._forceWireframe=!1,this._skipFrustumClipping=!1,this._forcePointsCloud=!1,this.rootNodes=[],this.cameras=[],this.lights=[],this.meshes=[],this.skeletons=[],this.particleSystems=[],this.animations=[],this.animationGroups=[],this.multiMaterials=[],this.materials=[],this.morphTargetManagers=[],this.geometries=[],this.transformNodes=[],this.actionManagers=[],this.objectRenderers=[],this.textures=[],this._environmentTexture=null,this.postProcesses=[],this.effectLayers=[],this.sounds=null,this.layers=[],this.lensFlareSystems=[],this.proceduralTextures=[],this.animationsEnabled=!0,this._animationPropertiesOverride=null,this.useConstantAnimationDeltaTime=!1,this.constantlyUpdateMeshUnderPointer=!1,this.hoverCursor="pointer",this.defaultCursor="",this.doNotHandleCursors=!1,this.preventDefaultOnPointerDown=!0,this.preventDefaultOnPointerUp=!0,this.metadata=null,this.reservedDataStore=null,this.disableOfflineSupportExceptionRules=[],this.onDisposeObservable=new ie,this._onDisposeObserver=null,this.onBeforeRenderObservable=new ie,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new ie,this.onAfterRenderCameraObservable=new ie,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new ie,this.onAfterAnimationsObservable=new ie,this.onBeforeDrawPhaseObservable=new ie,this.onAfterDrawPhaseObservable=new ie,this.onReadyObservable=new ie,this.onBeforeCameraRenderObservable=new ie,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new ie,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new ie,this.onAfterActiveMeshesEvaluationObservable=new ie,this.onBeforeParticlesRenderingObservable=new ie,this.onAfterParticlesRenderingObservable=new ie,this.onDataLoadedObservable=new ie,this.onNewCameraAddedObservable=new ie,this.onCameraRemovedObservable=new ie,this.onNewLightAddedObservable=new ie,this.onLightRemovedObservable=new ie,this.onNewGeometryAddedObservable=new ie,this.onGeometryRemovedObservable=new ie,this.onNewTransformNodeAddedObservable=new ie,this.onTransformNodeRemovedObservable=new ie,this.onNewMeshAddedObservable=new ie,this.onMeshRemovedObservable=new ie,this.onNewSkeletonAddedObservable=new ie,this.onSkeletonRemovedObservable=new ie,this.onNewParticleSystemAddedObservable=new ie,this.onParticleSystemRemovedObservable=new ie,this.onNewAnimationGroupAddedObservable=new ie,this.onAnimationGroupRemovedObservable=new ie,this.onNewMaterialAddedObservable=new ie,this.onNewMultiMaterialAddedObservable=new ie,this.onMaterialRemovedObservable=new ie,this.onMultiMaterialRemovedObservable=new ie,this.onNewTextureAddedObservable=new ie,this.onTextureRemovedObservable=new ie,this.onNewFrameGraphAddedObservable=new ie,this.onFrameGraphRemovedObservable=new ie,this.onNewObjectRendererAddedObservable=new ie,this.onObjectRendererRemovedObservable=new ie,this.onNewPostProcessAddedObservable=new ie,this.onPostProcessRemovedObservable=new ie,this.onNewEffectLayerAddedObservable=new ie,this.onEffectLayerRemovedObservable=new ie,this.onBeforeRenderTargetsRenderObservable=new ie,this.onAfterRenderTargetsRenderObservable=new ie,this.onBeforeStepObservable=new ie,this.onAfterStepObservable=new ie,this.onActiveCameraChanged=new ie,this.onActiveCamerasChanged=new ie,this.onBeforeRenderingGroupObservable=new ie,this.onAfterRenderingGroupObservable=new ie,this.onMeshImportedObservable=new ie,this.onAnimationFileImportedObservable=new ie,this.onEnvironmentTextureChangedObservable=new ie,this.onMeshUnderPointerUpdatedObservable=new ie,this._registeredForLateAnimationBindings=new no(256),this._pointerPickingConfiguration=new _A,this.onPrePointerObservable=new ie,this.onPointerObservable=new ie,this.onPreKeyboardObservable=new ie,this.onKeyboardObservable=new ie,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=n.FOGMODE_NONE,this.fogColor=new ve(.2,.2,.3),this.fogDensity=.1,this.fogStart=0,this.fogEnd=1e3,this.needsPreviousWorldMatrices=!1,this._shadowsEnabled=!0,this._lightsEnabled=!0,this._unObserveActiveCameras=null,this._texturesEnabled=!0,this._frameGraph=null,this.frameGraphs=[],this.physicsEnabled=!0,this.particlesEnabled=!0,this.spritesEnabled=!0,this._skeletonsEnabled=!0,this.lensFlaresEnabled=!0,this.collisionsEnabled=!0,this.gravity=new b(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=[],this.importedMeshesFiles=[],this.probesEnabled=!0,this._meshesForIntersections=new no(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new il,this._activeIndices=new il,this._activeParticles=new il,this._activeBones=new il,this._animationTime=0,this.animationTimeScale=1,this._renderId=0,this._frameId=0,this._executeWhenReadyTimeoutId=null,this._intermediateRendering=!1,this._defaultFrameBufferCleared=!1,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1,this._toBeDisposed=new Array(256),this._activeRequests=new Array,this._pendingData=[],this._isDisposed=!1,this._isReadyChecks=[],this.dispatchAllSubMeshesOfActiveMeshes=!1,this._activeMeshes=new Bi(256),this._processedMaterials=new Bi(256),this._renderTargets=new no(256),this._materialsRenderTargets=new no(256),this._activeParticleSystems=new Bi(256),this._activeSkeletons=new no(32),this._softwareSkinnedMeshes=new no(32),this._activeAnimatables=new Array,this._transformMatrix=K.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=sr.Create(),this._beforeClearStage=sr.Create(),this._beforeRenderTargetClearStage=sr.Create(),this._gatherRenderTargetsStage=sr.Create(),this._gatherActiveCameraRenderTargetsStage=sr.Create(),this._isReadyForMeshStage=sr.Create(),this._beforeEvaluateActiveMeshStage=sr.Create(),this._evaluateSubMeshStage=sr.Create(),this._preActiveMeshStage=sr.Create(),this._cameraDrawRenderTargetStage=sr.Create(),this._beforeCameraDrawStage=sr.Create(),this._beforeRenderTargetDrawStage=sr.Create(),this._beforeRenderingGroupDrawStage=sr.Create(),this._beforeRenderingMeshStage=sr.Create(),this._afterRenderingMeshStage=sr.Create(),this._afterRenderingGroupDrawStage=sr.Create(),this._afterCameraDrawStage=sr.Create(),this._afterCameraPostProcessStage=sr.Create(),this._afterRenderTargetDrawStage=sr.Create(),this._afterRenderTargetPostProcessStage=sr.Create(),this._afterRenderStage=sr.Create(),this._pointerMoveStage=sr.Create(),this._pointerDownStage=sr.Create(),this._pointerUpStage=sr.Create(),this._geometriesByUniqueId=null,this._uniqueId=0,this._defaultMeshCandidates={data:[],length:0},this._defaultSubMeshCandidates={data:[],length:0},this.onReadyTimeoutObservable=new ie,this.onReadyTimeoutDuration=120*1e3,this._timeoutChecksStartTime=0,this._floatingOriginScene=void 0,this._preventFreeActiveMeshesAndRenderingGroups=!1,this._activeMeshesFrozen=!1,this._activeMeshesFrozenButKeepClipping=!1,this._skipEvaluateActiveMeshesCompletely=!1,this._freezeActiveMeshesCancel=null,this._useCurrentFrameBuffer=!1,this._allowPostProcessClearColor=!0,this.getDeterministicFrameTime=()=>this._engine.getTimeStep(),this._getFloatingOriginScene=()=>this._floatingOriginScene,this._registeredActions=0,this._blockMaterialDirtyMechanism=!1,this._perfCollector=null,this.activeCameras=[],this._uniqueId=this.getUniqueId();let i={useGeometryUniqueIdsMap:!0,useMaterialMeshMap:!0,useClonedMeshMap:!0,virtual:!1,defaultCameraLayerMask:268435455,defaultRenderableLayerMask:268435455,...t};this.defaultCameraLayerMask=i.defaultCameraLayerMask,this.defaultRenderableLayerMask=i.defaultRenderableLayerMask,e=this._engine=e||Oe.LastCreatedEngine,i.virtual?e._virtualScenes.push(this):(Oe._LastCreatedScene=this,e.scenes.push(this)),(e.getCreationOptions().useLargeWorldRendering||t!=null&&t.useFloatingOrigin)&&(BB(),this._floatingOriginScene=this,ba.getScene=this._getFloatingOriginScene),this._uid=null,this._renderingManager=new Sa(this),Xl&&(this.postProcessManager=new Xl(this)),fr()&&this.attachControl(),this._createUbo(),kt&&(this._imageProcessingConfiguration=new kt),this.setDefaultCandidateProviders(),i.useGeometryUniqueIdsMap&&(this._geometriesByUniqueId={}),this.useMaterialMeshMap=i.useMaterialMeshMap,this.useClonedMeshMap=i.useClonedMeshMap,(!t||!t.virtual)&&e.onNewSceneAddedObservable.notifyObservers(this)}getClassName(){return"Scene"}_getDefaultMeshCandidates(){return this._defaultMeshCandidates.data=this.meshes,this._defaultMeshCandidates.length=this.meshes.length,this._defaultMeshCandidates}_getDefaultSubMeshCandidates(e){return this._defaultSubMeshCandidates.data=e.subMeshes,this._defaultSubMeshCandidates.length=e.subMeshes.length,this._defaultSubMeshCandidates}setDefaultCandidateProviders(){this.getActiveMeshCandidates=()=>this._getDefaultMeshCandidates(),this.getActiveSubMeshCandidates=e=>this._getDefaultSubMeshCandidates(e),this.getIntersectingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e),this.getCollidingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e)}get meshUnderPointer(){return this._inputManager.meshUnderPointer}get pointerX(){return this._inputManager.pointerX}set pointerX(e){this._inputManager.pointerX=e}get pointerY(){return this._inputManager.pointerY}set pointerY(e){this._inputManager.pointerY=e}getCachedMaterial(){return this._cachedMaterial}getCachedEffect(){return this._cachedEffect}getCachedVisibility(){return this._cachedVisibility}isCachedMaterialInvalid(e,t,i=1){return this._cachedEffect!==t||this._cachedMaterial!==e||this._cachedVisibility!==i}getEngine(){return this._engine}getTotalVertices(){return this._totalVertices.current}get totalVerticesPerfCounter(){return this._totalVertices}getActiveIndices(){return this._activeIndices.current}get totalActiveIndicesPerfCounter(){return this._activeIndices}getActiveParticles(){return this._activeParticles.current}get activeParticlesPerfCounter(){return this._activeParticles}getActiveBones(){return this._activeBones.current}get activeBonesPerfCounter(){return this._activeBones}getActiveMeshes(){return this._activeMeshes}getAnimationRatio(){return this._animationRatio!==void 0?this._animationRatio:1}getRenderId(){return this._renderId}getFrameId(){return this._frameId}incrementRenderId(){this._renderId++}_createUbo(){this.setSceneUniformBuffer(this.createSceneUniformBuffer())}simulatePointerMove(e,t){return this._inputManager.simulatePointerMove(e,t),this}simulatePointerDown(e,t){return this._inputManager.simulatePointerDown(e,t),this}simulatePointerUp(e,t,i){return this._inputManager.simulatePointerUp(e,t,i),this}isPointerCaptured(e=0){return this._inputManager.isPointerCaptured(e)}attachControl(e=!0,t=!0,i=!0){this._inputManager.attachControl(e,t,i)}detachControl(){this._inputManager.detachControl()}isReady(e=!0){var a,o,l;if(this._isDisposed)return!1;let t,i=this.getEngine(),r=i.currentRenderPassId;i.currentRenderPassId=(o=(a=this.activeCamera)==null?void 0:a.renderPassId)!=null?o:r;let s=!0;for(this._pendingData.length>0&&(s=!1),(l=this.prePassRenderer)==null||l.update(),this.useOrderIndependentTransparency&&this.depthPeelingRenderer&&s&&(s=this.depthPeelingRenderer.isReady()),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),t=0;t0;for(let d of this._isReadyForMeshStage)d.action(c,f)||(s=!1);if(!e)continue;let h=c.material||this.defaultMaterial;if(h)if(h._storeEffectOnSubMeshes)for(let d of c.subMeshes){let u=d.getMaterial();u&&u.hasRenderTargetTextures&&u.getRenderTargetTextures!=null&&this._processedMaterials.indexOf(u)===-1&&(this._processedMaterials.push(u),this._materialsRenderTargets.concatWithNoDuplicate(u.getRenderTargetTextures()))}else h.hasRenderTargetTextures&&h.getRenderTargetTextures!=null&&this._processedMaterials.indexOf(h)===-1&&(this._processedMaterials.push(h),this._materialsRenderTargets.concatWithNoDuplicate(h.getRenderTargetTextures()))}if(e){for(t=0;t0)for(let c of this.activeCameras)c.isReady(!0)||(s=!1);else this.activeCamera&&(this.activeCamera.isReady(!0)||(s=!1));for(let c of this.particleSystems)c.isReady()||(s=!1);if(this.proceduralTexturesEnabled)for(let c of this.proceduralTextures)c.isReady()||(s=!1);if(this.layers)for(let c of this.layers)c.isReady()||(s=!1);if(this.effectLayers)for(let c of this.effectLayers)c.isLayerReady()||(s=!1);for(let c of this._isReadyChecks)c.isReady()||(s=!1);return i.areAllEffectsReady()||(s=!1),i.currentRenderPassId=r,s}resetCachedMaterial(){this._cachedMaterial=null,this._cachedEffect=null,this._cachedVisibility=null}registerBeforeRender(e){this.onBeforeRenderObservable.add(e)}unregisterBeforeRender(e){this.onBeforeRenderObservable.removeCallback(e)}registerAfterRender(e){this.onAfterRenderObservable.add(e)}unregisterAfterRender(e){this.onAfterRenderObservable.removeCallback(e)}_executeOnceBeforeRender(e){let t=()=>{e(),setTimeout(()=>{this.unregisterBeforeRender(t)})};this.registerBeforeRender(t)}executeOnceBeforeRender(e,t){t!==void 0?setTimeout(()=>{this._executeOnceBeforeRender(e)},t):this._executeOnceBeforeRender(e)}addPendingData(e){this._pendingData.push(e)}removePendingData(e){let t=this.isLoading,i=this._pendingData.indexOf(e);i!==-1&&this._pendingData.splice(i,1),t&&!this.isLoading&&this.onDataLoadedObservable.notifyObservers(this)}getWaitingItemsCount(){return this._pendingData.length}get isLoading(){return this._pendingData.length>0}addIsReadyCheck(e){this._isReadyChecks.indexOf(e)===-1&&this._isReadyChecks.push(e)}removeIsReadyCheck(e){let t=this._isReadyChecks.indexOf(e);t!==-1&&this._isReadyChecks.splice(t,1)}executeWhenReady(e,t=!1){this.onReadyObservable.addOnce(e),this._executeWhenReadyTimeoutId===null&&this._checkIsReady(t)}async whenReadyAsync(e=!1){return await new Promise(t=>{this.executeWhenReady(()=>{t()},e)})}_clearReadynessChecksData(){this._timeoutChecksStartTime=0,this.onReadyTimeoutObservable.clear(),this.onReadyObservable.clear(),this._executeWhenReadyTimeoutId=null}_checkIsReady(e=!1){if(this._registerTransientComponents(),this._timeoutChecksStartTime===0)this._timeoutChecksStartTime=pr.Now;else if(this.onReadyTimeoutDuration>0&&pr.Now-this._timeoutChecksStartTime>this.onReadyTimeoutDuration){this.onReadyTimeoutObservable.notifyObservers(this),this._clearReadynessChecksData();return}if(this.isReady(e)){this.onReadyObservable.notifyObservers(this),this._clearReadynessChecksData();return}if(this._isDisposed){this._clearReadynessChecksData();return}this._executeWhenReadyTimeoutId=setTimeout(()=>{this.incrementRenderId(),this._checkIsReady(e)},100)}get animatables(){return this._activeAnimatables}resetLastAnimationTimeFrame(){this._animationTimeLast=pr.Now}getViewMatrix(){return this._viewMatrix}getProjectionMatrix(){return this._projectionMatrix}getInverseProjectionMatrix(){return this._inverseProjectionMatrix}getTransformMatrix(){return this._transformMatrix}setTransformMatrix(e,t,i,r){this._multiviewSceneUboIsActive=!!(i&&r&&this._multiviewSceneUbo),!(this._viewUpdateFlag===e.updateFlag&&this._projectionUpdateFlag===t.updateFlag)&&(this._viewUpdateFlag=e.updateFlag,this._projectionUpdateFlag=t.updateFlag,this._viewMatrix=e,this._projectionMatrix=t,this._inverseProjectionMatrix||(this._inverseProjectionMatrix=new K),this._projectionMatrix.invertToRef(this._inverseProjectionMatrix),this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._frustumPlanes?of.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=of.GetPlanes(this._transformMatrix),this._multiviewSceneUboIsActive&&this._multiviewSceneUbo.useUbo?this._updateMultiviewUbo(i,r):this._sceneUbo.useUbo&&(this._sceneUbo.updateMatrix("viewProjection",this._transformMatrix),this._sceneUbo.updateMatrix("view",this._viewMatrix),this._sceneUbo.updateMatrix("projection",this._projectionMatrix),this._sceneUbo.updateMatrix("inverseProjection",this._inverseProjectionMatrix)))}getSceneUniformBuffer(){return this._multiviewSceneUboIsActive&&this._multiviewSceneUbo?this._multiviewSceneUbo:this._sceneUbo}createSceneUniformBuffer(e,t){let i=typeof t=="boolean"?t:t==null?void 0:t.trackUBOsInFrame,r=new hr(this._engine,void 0,!1,e!=null?e:"scene",void 0,i);return r.addUniform("viewProjection",16),r.addUniform("view",16),r.addUniform("projection",16),r.addUniform("vEyePosition",4),r.addUniform("inverseProjection",16),r}setSceneUniformBuffer(e){this._sceneUbo=e,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1}get floatingOriginMode(){return this._floatingOriginScene!==void 0}get floatingOriginOffset(){return this.floatingOriginMode?this._eyePosition:b.ZeroReadOnly}getUniqueId(){return Ql.UniqueId}addMesh(e,t=!1){if(!this._blockEntityCollection&&(this.meshes.push(e),e._resyncLightSources(),e.parent||e._addToSceneRootNodes(),_e.SetImmediate(()=>{this.onNewMeshAddedObservable.notifyObservers(e)}),t)){let i=e.getChildMeshes();for(let r of i)this.addMesh(r)}}removeMesh(e,t=!1){let i=this.meshes.indexOf(e);if(i!==-1&&(this.meshes.splice(i,1),e.parent||e._removeFromSceneRootNodes()),this._inputManager._invalidateMesh(e),this.onMeshRemovedObservable.notifyObservers(e),t){let r=e.getChildMeshes();for(let s of r)this.removeMesh(s)}return i}addTransformNode(e){this._blockEntityCollection||e.getScene()===this&&e._indexInSceneTransformNodesArray!==-1||(e._indexInSceneTransformNodesArray=this.transformNodes.length,this.transformNodes.push(e),e.parent||e._addToSceneRootNodes(),this.onNewTransformNodeAddedObservable.notifyObservers(e))}removeTransformNode(e){let t=e._indexInSceneTransformNodesArray;if(t!==-1){if(t!==this.transformNodes.length-1){let i=this.transformNodes[this.transformNodes.length-1];this.transformNodes[t]=i,i._indexInSceneTransformNodesArray=t}e._indexInSceneTransformNodesArray=-1,this.transformNodes.pop(),e.parent||e._removeFromSceneRootNodes()}return this.onTransformNodeRemovedObservable.notifyObservers(e),t}removeSkeleton(e){let t=this.skeletons.indexOf(e);return t!==-1&&(this.skeletons.splice(t,1),this.onSkeletonRemovedObservable.notifyObservers(e),this._executeActiveContainerCleanup(this._activeSkeletons)),t}removeMorphTargetManager(e){let t=this.morphTargetManagers.indexOf(e);return t!==-1&&this.morphTargetManagers.splice(t,1),t}removeLight(e){let t=this.lights.indexOf(e);if(t!==-1){for(let i of this.meshes)i._removeLightSource(e,!1);this.lights.splice(t,1),this.sortLightsByPriority(),e.parent||e._removeFromSceneRootNodes(),this.onLightRemovedObservable.notifyObservers(e)}return t}removeCamera(e){let t=this.cameras.indexOf(e);if(t!==-1&&(this.cameras.splice(t,1),e.parent||e._removeFromSceneRootNodes()),this.activeCameras){let i=this.activeCameras.indexOf(e);i!==-1&&this.activeCameras.splice(i,1)}return this.activeCamera===e&&(this.cameras.length>0?this.activeCamera=this.cameras[0]:this.activeCamera=null),this.onCameraRemovedObservable.notifyObservers(e),t}removeParticleSystem(e){let t=this.particleSystems.indexOf(e);return t!==-1&&(this.particleSystems.splice(t,1),this._executeActiveContainerCleanup(this._activeParticleSystems)),this.onParticleSystemRemovedObservable.notifyObservers(e),t}removeAnimation(e){let t=this.animations.indexOf(e);return t!==-1&&this.animations.splice(t,1),t}stopAnimation(e,t,i){}removeAnimationGroup(e){let t=this.animationGroups.indexOf(e);return t!==-1&&this.animationGroups.splice(t,1),this.onAnimationGroupRemovedObservable.notifyObservers(e),t}removeMultiMaterial(e){let t=this.multiMaterials.indexOf(e);return t!==-1&&this.multiMaterials.splice(t,1),this.onMultiMaterialRemovedObservable.notifyObservers(e),t}removeMaterial(e){let t=e._indexInSceneMaterialArray;if(t!==-1&&t{this.onNewLightAddedObservable.notifyObservers(e)})}}sortLightsByPriority(){this.requireLightSorting&&this.lights.sort(Yt.CompareLightsPriority)}addCamera(e){this._blockEntityCollection||(this.cameras.push(e),_e.SetImmediate(()=>{this.onNewCameraAddedObservable.notifyObservers(e)}),e.parent||e._addToSceneRootNodes())}addSkeleton(e){this._blockEntityCollection||(this.skeletons.push(e),_e.SetImmediate(()=>{this.onNewSkeletonAddedObservable.notifyObservers(e)}))}addParticleSystem(e){this._blockEntityCollection||(this.particleSystems.push(e),_e.SetImmediate(()=>{this.onNewParticleSystemAddedObservable.notifyObservers(e)}))}addAnimation(e){this._blockEntityCollection||this.animations.push(e)}addAnimationGroup(e){this._blockEntityCollection||(this.animationGroups.push(e),_e.SetImmediate(()=>{this.onNewAnimationGroupAddedObservable.notifyObservers(e)}))}addMultiMaterial(e){this._blockEntityCollection||(this.multiMaterials.push(e),_e.SetImmediate(()=>{this.onNewMultiMaterialAddedObservable.notifyObservers(e)}))}addMaterial(e){this._blockEntityCollection||e.getScene()===this&&e._indexInSceneMaterialArray!==-1||(e._indexInSceneMaterialArray=this.materials.length,this.materials.push(e),_e.SetImmediate(()=>{this.onNewMaterialAddedObservable.notifyObservers(e)}))}addMorphTargetManager(e){this._blockEntityCollection||this.morphTargetManagers.push(e)}addGeometry(e){this._blockEntityCollection||(this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=this.geometries.length),this.geometries.push(e))}addActionManager(e){this.actionManagers.push(e)}addTexture(e){this._blockEntityCollection||(this.textures.push(e),this.onNewTextureAddedObservable.notifyObservers(e))}addFrameGraph(e){this.frameGraphs.push(e),_e.SetImmediate(()=>{this.onNewFrameGraphAddedObservable.notifyObservers(e)})}addObjectRenderer(e){this.objectRenderers.push(e),_e.SetImmediate(()=>{this.onNewObjectRendererAddedObservable.notifyObservers(e)})}addPostProcess(e){this._blockEntityCollection||(this.postProcesses.push(e),_e.SetImmediate(()=>{this.onNewPostProcessAddedObservable.notifyObservers(e)}))}addEffectLayer(e){this._blockEntityCollection||(this.effectLayers.push(e),_e.SetImmediate(()=>{this.onNewEffectLayerAddedObservable.notifyObservers(e)}))}switchActiveCamera(e,t=!0){this._engine.getInputElement()&&(this.activeCamera&&this.activeCamera.detachControl(),this.activeCamera=e,t&&e.attachControl())}setActiveCameraById(e){let t=this.getCameraById(e);return t?(this.activeCamera=t,t):null}setActiveCameraByName(e){let t=this.getCameraByName(e);return t?(this.activeCamera=t,t):null}getAnimationGroupByName(e){for(let t=0;ti.uniqueId===e)}getMaterialById(e,t=!1){return this._getMaterial(t,i=>i.id===e)}getMaterialByName(e,t=!1){return this._getMaterial(t,i=>i.name===e)}getLastMaterialById(e,t=!1){for(let i=this.materials.length-1;i>=0;i--)if(this.materials[i].id===e)return this.materials[i];if(t){for(let i=this.multiMaterials.length-1;i>=0;i--)if(this.multiMaterials[i].id===e)return this.multiMaterials[i]}return null}getTextureByUniqueId(e){for(let t=0;t{this.onNewGeometryAddedObservable.notifyObservers(e)}),!0)}removeGeometry(e){let t;if(this._geometriesByUniqueId){if(t=this._geometriesByUniqueId[e.uniqueId],t===void 0)return!1}else if(t=this.geometries.indexOf(e),t<0)return!1;if(t!==this.geometries.length-1){let i=this.geometries[this.geometries.length-1];i&&(this.geometries[t]=i,this._geometriesByUniqueId&&(this._geometriesByUniqueId[i.uniqueId]=t))}return this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=void 0),this.geometries.pop(),this.onGeometryRemovedObservable.notifyObservers(e),!0}getGeometries(){return this.geometries}getMeshById(e){for(let t=0;t=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null}getLastTransformNodeById(e){for(let t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getLastEntryById(e){let t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];for(t=this.skeletons.length-1;t>=0;t--){let i=this.skeletons[t];for(let r=i.bones.length-1;r>=0;r--)if(i.bones[r].id===e)return i.bones[r]}return null}getNodeById(e){let t=this.getMeshById(e);if(t)return t;let i=this.getTransformNodeById(e);if(i)return i;let r=this.getLightById(e);if(r)return r;let s=this.getCameraById(e);if(s)return s;let a=this.getBoneById(e);return a||null}getNodeByName(e){let t=this.getMeshByName(e);if(t)return t;let i=this.getTransformNodeByName(e);if(i)return i;let r=this.getLightByName(e);if(r)return r;let s=this.getCameraByName(e);if(s)return s;let a=this.getBoneByName(e);return a||null}getMeshByName(e){for(let t=0;t=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByUniqueId(e){for(let t=0;t{let o=!0,l=!0;for(let c of a)o&&(o=c.objectRenderer._isFrozen),l&&(l=c.objectRenderer._freezeActiveMeshesCancel!==null);if(o)return!0;if(!l)throw new Error("Freezing active meshes was cancelled");return!1},()=>{this._freezeActiveMeshesCancel=null,this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=s,this._skipEvaluateActiveMeshesCompletely=e,t==null||t()},(o,l)=>{if(this._freezeActiveMeshesCancel=null,this.unfreezeActiveMeshes(),l){let c="Scene: Timeout while waiting for meshes to be frozen.";i?i(c):(te.Error(c),o&&te.Error(o))}else{let c="Scene: An unexpected error occurred while trying to freeze active meshes.";i?i(c):(te.Error(c),o&&(te.Error(o),o.stack&&te.Error(o.stack)))}}),this}return this.executeWhenReady(()=>{if(!this.activeCamera){i&&i("No active camera found");return}if(this._frustumPlanes||this.updateTransformMatrix(),this._evaluateActiveMeshes(),this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=s,this._skipEvaluateActiveMeshesCompletely=e,r)for(let a=0;ae.dispose())}_evaluateActiveMeshes(){var i;if(this._engine.snapshotRendering&&this._engine.snapshotRenderingMode===1){this._activeMeshes.length>0&&((i=this.activeCamera)==null||i._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset());return}if(this._activeMeshesFrozen&&this._activeMeshes.length){if(!this._skipEvaluateActiveMeshesCompletely){let r=this._activeMeshes.length;for(let s=0;s0&&(s.layerMask&this.activeCamera.layerMask)!==0&&(this._skipFrustumClipping||s.alwaysSelectAsActiveMesh||s.isInFrustum(this._frustumPlanes)))){this._activeMeshes.push(s),this.activeCamera._activeMeshes.push(s),o!==s&&o._activate(this._renderId,!1);for(let l of this._preActiveMeshStage)l.action(s);s._activate(this._renderId,!1)&&(s.isAnInstance?s._internalAbstractMeshDataInfo._actAsRegularMesh&&(o=s):o._internalAbstractMeshDataInfo._onlyForInstances=!1,o._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(s,o)),s._postActivate()}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(let r=0;r0){let r=this.getActiveSubMeshCandidates(t),s=r.length;i=i||s===1;for(let a=0;a0&&this._renderTargets.concatWithNoDuplicate(e.customRenderTargets),t&&t.customRenderTargets&&t.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(t.customRenderTargets),this.environmentTexture&&this.environmentTexture.isRenderTarget&&this._renderTargets.pushNoDuplicate(this.environmentTexture);for(let d of this._gatherActiveCameraRenderTargetsStage)d.action(this._renderTargets);let s=!1;if(this.renderTargetsEnabled){this._intermediateRendering=!0;let d;if(this._renderTargets.length>0){_e.StartPerformanceCounter("Render targets",this._renderTargets.length>0);let u=(f=this.getBoundingBoxRenderer)==null?void 0:f.call(this);for(let m=0;m0?u.renderList.data.slice():[],d.length=u.renderList.length),p.render(_,this.dumpNextRenderTargets),s=!0}}u&&d&&(u.renderList.data=d,u.renderList.length=d.length),_e.EndPerformanceCounter("Render targets",this._renderTargets.length>0),this._renderId++}if(this._cameraDrawRenderTargetStage.length>0){let u=(h=this.getBoundingBoxRenderer)==null?void 0:h.call(this);u&&!d&&(d=u.renderList.length>0?u.renderList.data.slice():[],d.length=u.renderList.length);for(let m of this._cameraDrawRenderTargetStage)s=m.action(this.activeCamera)||s;u&&d&&(u.renderList.data=d,u.renderList.length=d.length)}this._intermediateRendering=!1}s&&!this.prePass&&(this._bindFrameBuffer(this._activeCamera,!1),this.updateTransformMatrix()),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),this.postProcessManager&&!e._multiviewTexture&&!this.prePass&&this.postProcessManager._prepareFrame();for(let d of this._beforeCameraDrawStage)d.action(this.activeCamera);this.onBeforeDrawPhaseObservable.notifyObservers(this);let a=r.snapshotRendering&&r.snapshotRenderingMode===1;a&&this.finalizeSceneUbo(),this._renderingManager.render(null,null,!0,!a),this.onAfterDrawPhaseObservable.notifyObservers(this);for(let d of this._afterCameraDrawStage)d.action(this.activeCamera);if(this.postProcessManager&&!e._multiviewTexture){let d=e.outputRenderTarget?e.outputRenderTarget.renderTarget:void 0;this.postProcessManager._finalizeFrame(e.isIntermediate,d)}for(let d of this._afterCameraPostProcessStage)d.action(this.activeCamera);this._renderTargets.reset(),this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera)}_processSubCameras(e,t=!0){if(e.cameraRigMode===0||e._renderingMultiview){e._renderingMultiview&&!this._multiviewSceneUbo&&this._createMultiviewUbo(),this._renderForCamera(e,void 0,t),this.onAfterRenderCameraObservable.notifyObservers(e);return}if(e._useMultiviewToSingleView)this._renderMultiviewToSingleView(e);else{this.onBeforeCameraRenderObservable.notifyObservers(e);for(let i=0;i-1&&(r.trigger===13&&r._executeCurrent(rn.CreateNew(t,void 0,a)),(!t.actionManager.hasSpecificTrigger(13,c=>{let f=c.mesh?c.mesh:c;return a===f})||r.trigger===13)&&t._intersectionsInProgress.splice(l,1))}}}}_advancePhysicsEngineStep(e){}_animate(e){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(n.MinDeltaTime,Math.min(this._engine.getDeltaTime(),n.MaxDeltaTime))+this._timeAccumulator,t=this._engine.getTimeStep(),i=1e3/t/1e3,r=0,s=this._engine.getLockstepMaxSteps(),a=Math.floor(e/t);for(a=Math.min(a,s);e>0&&r0);for(let l=0;l0),this._renderId++}this.onAfterRenderTargetsRenderObservable.notifyObservers(this);for(let l of this._beforeClearStage)l.action();if(this._engine.snapshotRendering&&this._engine.snapshotRenderingMode===1)this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset();else{let l=this.getActiveMeshCandidates(),c=l.length;if(this._activeMeshesFrozen){if(!this._skipEvaluateActiveMeshesCompletely)for(let f=0;f0)for(let a=0;a0);for(let o=0;o0),this._renderId++}this._engine.currentRenderPassId=(s=a==null?void 0:a.renderPassId)!=null?s:0,this.activeCamera=a,this._activeCamera&&this._activeCamera.cameraRigMode!==22&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this);for(let o of this._beforeClearStage)o.action();this._clearFrameBuffer(this.activeCamera);for(let o of this._gatherRenderTargetsStage)o.action(this._renderTargets);if(this.activeCameras&&this.activeCameras.length>0)for(let o=0;o0);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera,!!this.activeCamera.outputRenderTarget)}}this._checkIntersections();for(let a of this._afterRenderStage)a.action();if(this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this),this._toBeDisposed.length){for(let a=0;as.dispose(!0)),this._disposeList(this.transformNodes,s=>s.dispose(!0));let i=this.cameras;this._disposeList(i),this._disposeList(this.particleSystems),this._disposeList(this.postProcesses),this._disposeList(this.textures),this._disposeList(this.morphTargetManagers),this._disposeList(this.frameGraphs),this._sceneUbo.dispose(),this._multiviewSceneUbo&&this._multiviewSceneUbo.dispose(),this.postProcessManager.dispose(),this._disposeList(this._components);let r=this._engine.scenes.indexOf(this);if(r>-1&&this._engine.scenes.splice(r,1),this._floatingOriginScene=void 0,this._engine.scenes.length===0&&FB(),Oe._LastCreatedScene===this){Oe._LastCreatedScene=null;let s=Oe.Instances.length-1;for(;s>=0;){let a=Oe.Instances[s];if(a.scenes.length>0){Oe._LastCreatedScene=a.scenes[this._engine.scenes.length-1];break}s--}}r=this._engine._virtualScenes.indexOf(this),r>-1&&this._engine._virtualScenes.splice(r,1),this._engine.wipeCaches(!0),this.onDisposeObservable.clear(),this.onBeforeRenderObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderTargetsRenderObservable.clear(),this.onAfterRenderTargetsRenderObservable.clear(),this.onAfterStepObservable.clear(),this.onBeforeStepObservable.clear(),this.onBeforeActiveMeshesEvaluationObservable.clear(),this.onAfterActiveMeshesEvaluationObservable.clear(),this.onBeforeParticlesRenderingObservable.clear(),this.onAfterParticlesRenderingObservable.clear(),this.onBeforeDrawPhaseObservable.clear(),this.onAfterDrawPhaseObservable.clear(),this.onBeforeAnimationsObservable.clear(),this.onAfterAnimationsObservable.clear(),this.onDataLoadedObservable.clear(),this.onBeforeRenderingGroupObservable.clear(),this.onAfterRenderingGroupObservable.clear(),this.onMeshImportedObservable.clear(),this.onBeforeCameraRenderObservable.clear(),this.onAfterCameraRenderObservable.clear(),this.onAfterRenderCameraObservable.clear(),this.onReadyObservable.clear(),this.onNewCameraAddedObservable.clear(),this.onCameraRemovedObservable.clear(),this.onNewLightAddedObservable.clear(),this.onLightRemovedObservable.clear(),this.onNewGeometryAddedObservable.clear(),this.onGeometryRemovedObservable.clear(),this.onNewTransformNodeAddedObservable.clear(),this.onTransformNodeRemovedObservable.clear(),this.onNewMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onNewSkeletonAddedObservable.clear(),this.onSkeletonRemovedObservable.clear(),this.onNewMaterialAddedObservable.clear(),this.onNewMultiMaterialAddedObservable.clear(),this.onMaterialRemovedObservable.clear(),this.onMultiMaterialRemovedObservable.clear(),this.onNewTextureAddedObservable.clear(),this.onTextureRemovedObservable.clear(),this.onNewFrameGraphAddedObservable.clear(),this.onFrameGraphRemovedObservable.clear(),this.onNewObjectRendererAddedObservable.clear(),this.onObjectRendererRemovedObservable.clear(),this.onPrePointerObservable.clear(),this.onPointerObservable.clear(),this.onPreKeyboardObservable.clear(),this.onKeyboardObservable.clear(),this.onActiveCameraChanged.clear(),this.onScenePerformancePriorityChangedObservable.clear(),this.onClearColorChangedObservable.clear(),this.onEnvironmentTextureChangedObservable.clear(),this.onMeshUnderPointerUpdatedObservable.clear(),this._isDisposed=!0}_disposeList(e,t){let i=e.slice(0);t=t!=null?t:(r=>r.dispose());for(let r of i)t(r);e.length=0}get isDisposed(){return this._isDisposed}clearCachedVertexData(){for(let e=0;e!0);let r=this.meshes.filter(e);for(let s of r){if(s.computeWorldMatrix(!0),!s.subMeshes||s.subMeshes.length===0||s.infiniteDistance)continue;let a=s.getBoundingInfo(),o=a.boundingBox.minimumWorld,l=a.boundingBox.maximumWorld;b.CheckExtends(o,t,i),b.CheckExtends(l,t,i)}return t.x===Number.MAX_VALUE?{min:b.Zero(),max:b.Zero()}:{min:t,max:i}}createPickingRay(e,t,i,r,s=!1){throw qe("Ray")}createPickingRayToRef(e,t,i,r,s,a=!1,o=!1){throw qe("Ray")}createPickingRayInCameraSpace(e,t,i){throw qe("Ray")}createPickingRayInCameraSpaceToRef(e,t,i,r){throw qe("Ray")}pick(e,t,i,r,s,a){let o=qe("Ray",!0);return o&&te.Warn(o),new Jn}pickWithBoundingInfo(e,t,i,r,s){let a=qe("Ray",!0);return a&&te.Warn(a),new Jn}pickWithRay(e,t,i,r){throw qe("Ray")}multiPick(e,t,i,r,s){throw qe("Ray")}multiPickWithRay(e,t,i){throw qe("Ray")}setPointerOverMesh(e,t,i){this._inputManager.setPointerOverMesh(e,t,i)}getPointerOverMesh(){return this._inputManager.getPointerOverMesh()}_rebuildGeometries(){for(let e of this.geometries)e._rebuild();for(let e of this.meshes)e._rebuild();this.postProcessManager&&this.postProcessManager._rebuild();for(let e of this._components)e.rebuild();for(let e of this.particleSystems)e.rebuild();if(this.spriteManagers)for(let e of this.spriteManagers)e.rebuild()}_rebuildTextures(){for(let e of this.textures)e._rebuild(!0);this.markAllMaterialsAsDirty(1)}_getByTags(e,t,i){if(t===void 0)return e;let r=[];for(let s in e){let a=e[s];Zt&&Zt.MatchesQuery(a,t)&&(!i||i(a))&&r.push(a)}return r}getMeshesByTags(e,t){return this._getByTags(this.meshes,e,t)}getCamerasByTags(e,t){return this._getByTags(this.cameras,e,t)}getLightsByTags(e,t){return this._getByTags(this.lights,e,t)}getMaterialByTags(e,t){return this._getByTags(this.materials,e,t).concat(this._getByTags(this.multiMaterials,e,t))}getTransformNodesByTags(e,t){return this._getByTags(this.transformNodes,e,t)}setRenderingOrder(e,t=null,i=null,r=null){this._renderingManager.setRenderingOrder(e,t,i,r)}setRenderingAutoClearDepthStencil(e,t,i=!0,r=!0){this._renderingManager.setRenderingAutoClearDepthStencil(e,t,i,r)}getAutoClearDepthStencilSetup(e){return this._renderingManager.getAutoClearDepthStencilSetup(e)}_forceBlockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism=e}get blockMaterialDirtyMechanism(){return this._blockMaterialDirtyMechanism}set blockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism!==e&&(this._blockMaterialDirtyMechanism=e,e||this.markAllMaterialsAsDirty(127))}markAllMaterialsAsDirty(e,t){if(!this._blockMaterialDirtyMechanism)for(let i of this.materials)t&&!t(i)||i.markAsDirty(e)}_loadFile(e,t,i,r,s,a,o){let l=el(e,t,i,r?this.offlineProvider:void 0,s,a,o);return this._activeRequests.push(l),l.onCompleteObservable.add(c=>{this._activeRequests.splice(this._activeRequests.indexOf(c),1)}),l}async _loadFileAsync(e,t,i,r,s){return await new Promise((a,o)=>{this._loadFile(e,l=>{a(l)},t,i,r,(l,c)=>{o(c)},s)})}_requestFile(e,t,i,r,s,a,o){let l=YT(e,t,i,r?this.offlineProvider:void 0,s,a,o);return this._activeRequests.push(l),l.onCompleteObservable.add(c=>{this._activeRequests.splice(this._activeRequests.indexOf(c),1)}),l}async _requestFileAsync(e,t,i,r,s){return await new Promise((a,o)=>{this._requestFile(e,l=>{a(l)},t,i,r,l=>{o(l)},s)})}_readFile(e,t,i,r,s){let a=Vh(e,t,i,r,s);return this._activeRequests.push(a),a.onCompleteObservable.add(o=>{this._activeRequests.splice(this._activeRequests.indexOf(o),1)}),a}async _readFileAsync(e,t,i){return await new Promise((r,s)=>{this._readFile(e,a=>{r(a)},t,i,a=>{s(a)})})}getPerfCollector(){throw qe("performanceViewerSceneExtension")}setActiveCameraByID(e){return this.setActiveCameraById(e)}getMaterialByID(e){return this.getMaterialById(e)}getLastMaterialByID(e){return this.getLastMaterialById(e)}getTextureByUniqueID(e){return this.getTextureByUniqueId(e)}getCameraByID(e){return this.getCameraById(e)}getCameraByUniqueID(e){return this.getCameraByUniqueId(e)}getBoneByID(e){return this.getBoneById(e)}getLightByID(e){return this.getLightById(e)}getLightByUniqueID(e){return this.getLightByUniqueId(e)}getParticleSystemByID(e){return this.getParticleSystemById(e)}getGeometryByID(e){return this.getGeometryById(e)}getMeshByID(e){return this.getMeshById(e)}getMeshByUniqueID(e){return this.getMeshByUniqueId(e)}getLastMeshByID(e){return this.getLastMeshById(e)}getMeshesByID(e){return this.getMeshesById(e)}getTransformNodeByID(e){return this.getTransformNodeById(e)}getTransformNodeByUniqueID(e){return this.getTransformNodeByUniqueId(e)}getTransformNodesByID(e){return this.getTransformNodesById(e)}getNodeByID(e){return this.getNodeById(e)}getLastEntryByID(e){return this.getLastEntryById(e)}getLastSkeletonByID(e){return this.getLastSkeletonById(e)}};Jt.FOGMODE_NONE=0;Jt.FOGMODE_EXP=1;Jt.FOGMODE_EXP2=2;Jt.FOGMODE_LINEAR=3;Jt.MinDeltaTime=1;Jt.MaxDeltaTime=1e3;Jt._OriginalDefaultMaterialFactory=Jt.DefaultMaterialFactory;Ft("BABYLON.Scene",Jt)});var tU,ene,Ma=C(()=>{k();tU="helperFunctions",ene=`const PI: f32=3.141592653589793;const TWO_PI: f32=6.283185307179586;const HALF_PI: f32=1.5707963267948966;const RECIPROCAL_PI: f32=0.3183098861837907;const RECIPROCAL_PI2: f32=0.15915494309189535;const RECIPROCAL_PI4: f32=0.07957747154594767;const HALF_MIN: f32=5.96046448e-08; const LinearEncodePowerApprox: f32=2.2;const GammaEncodePowerApprox: f32=1.0/LinearEncodePowerApprox;const LuminanceEncodeApprox: vec3f=vec3f(0.2126,0.7152,0.0722);const Epsilon:f32=0.0000001;fn square(x: f32)->f32 {return x*x;} fn saturate(x: f32)->f32 {return clamp(x,0.0,1.0);} fn saturateVec3(x: vec3f)->vec3f {return clamp(x,vec3f(),vec3f(1.0));} @@ -4295,11 +4295,11 @@ fn max3(v: vec3f)->f32 {return max(v.x,max(v.y,v.z));} fn uint2float(i: u32)->f32 {return bitcast(0x3F800000u | (i>>9u))-1.0;} fn plasticSequence(rstate: u32)->vec2f {return vec2f(uint2float(rstate*3242174889u), uint2float(rstate*2447445414u));} -`;T.IncludesShadersStoreWGSL[tU]||(T.IncludesShadersStoreWGSL[tU]=ene)});var IC={};tt(IC,{rgbdDecodePixelShaderWGSL:()=>tne});var bC,iU,tne,MC=C(()=>{W();Ca();bC="rgbdDecodePixelShader",iU=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d; +`;T.IncludesShadersStoreWGSL[tU]||(T.IncludesShadersStoreWGSL[tU]=ene)});var IC={};tt(IC,{rgbdDecodePixelShaderWGSL:()=>tne});var bC,iU,tne,MC=C(()=>{k();Ma();bC="rgbdDecodePixelShader",iU=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d; #include #define CUSTOM_FRAGMENT_DEFINITIONS @fragment -fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=vec4f(fromRGBD(textureSample(textureSampler,textureSamplerSampler,input.vUV)),1.0);}`;T.ShadersStoreWGSL[bC]||(T.ShadersStoreWGSL[bC]=iU);tne={name:bC,shader:iU}});var rU,ine,ya=C(()=>{W();rU="helperFunctions",ine=`const float PI=3.141592653589793;const float TWO_PI=6.283185307179586;const float HALF_PI=1.5707963267948966;const float RECIPROCAL_PI=0.3183098861837907;const float RECIPROCAL_PI2=0.15915494309189535;const float RECIPROCAL_PI4=0.07957747154594767;const float HALF_MIN=5.96046448e-08; +fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=vec4f(fromRGBD(textureSample(textureSampler,textureSamplerSampler,input.vUV)),1.0);}`;T.ShadersStoreWGSL[bC]||(T.ShadersStoreWGSL[bC]=iU);tne={name:bC,shader:iU}});var rU,ine,Ca=C(()=>{k();rU="helperFunctions",ine=`const float PI=3.141592653589793;const float TWO_PI=6.283185307179586;const float HALF_PI=1.5707963267948966;const float RECIPROCAL_PI=0.3183098861837907;const float RECIPROCAL_PI2=0.15915494309189535;const float RECIPROCAL_PI4=0.07957747154594767;const float HALF_MIN=5.96046448e-08; const float LinearEncodePowerApprox=2.2;const float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;const vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);const float Epsilon=0.0000001; #define saturate(x) clamp(x,0.0,1.0) #define absEps(x) abs(x)+Epsilon @@ -4417,28 +4417,28 @@ float uint2float(uint i) {return uintBitsToFloat(0x3F800000u | (i>>9u))-1.0;} vec2 plasticSequence(const uint rstate) {return vec2(uint2float(rstate*3242174889u), uint2float(rstate*2447445414u));} #endif -`;T.IncludesShadersStore[rU]||(T.IncludesShadersStore[rU]=ine)});var yC={};tt(yC,{rgbdDecodePixelShader:()=>rne});var CC,nU,rne,PC=C(()=>{W();ya();CC="rgbdDecodePixelShader",nU=`varying vec2 vUV;uniform sampler2D textureSampler; +`;T.IncludesShadersStore[rU]||(T.IncludesShadersStore[rU]=ine)});var yC={};tt(yC,{rgbdDecodePixelShader:()=>rne});var CC,nU,rne,PC=C(()=>{k();Ca();CC="rgbdDecodePixelShader",nU=`varying vec2 vUV;uniform sampler2D textureSampler; #include #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) -{gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);}`;T.ShadersStore[CC]||(T.ShadersStore[CC]=nU);rne={name:CC,shader:nU}});var aU={};tt(aU,{rgbdEncodePixelShader:()=>nne});var DC,sU,nne,oU=C(()=>{W();ya();DC="rgbdEncodePixelShader",sU=`varying vec2 vUV;uniform sampler2D textureSampler; +{gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);}`;T.ShadersStore[CC]||(T.ShadersStore[CC]=nU);rne={name:CC,shader:nU}});var aU={};tt(aU,{rgbdEncodePixelShader:()=>nne});var DC,sU,nne,oU=C(()=>{k();Ca();DC="rgbdEncodePixelShader",sU=`varying vec2 vUV;uniform sampler2D textureSampler; #include #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) -{gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);}`;T.ShadersStore[DC]||(T.ShadersStore[DC]=sU);nne={name:DC,shader:sU}});var cU={};tt(cU,{rgbdEncodePixelShaderWGSL:()=>sne});var LC,lU,sne,fU=C(()=>{W();Ca();LC="rgbdEncodePixelShader",lU=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d; +{gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);}`;T.ShadersStore[DC]||(T.ShadersStore[DC]=sU);nne={name:DC,shader:sU}});var cU={};tt(cU,{rgbdEncodePixelShaderWGSL:()=>sne});var LC,lU,sne,fU=C(()=>{k();Ma();LC="rgbdEncodePixelShader",lU=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d; #include #define CUSTOM_FRAGMENT_DEFINITIONS @fragment -fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=toRGBD(textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb);}`;T.ShadersStoreWGSL[LC]||(T.ShadersStoreWGSL[LC]=lU);sne={name:LC,shader:lU}});var cm,OC=C(()=>{Kl();lC();cm=class{static ExpandRGBDTexture(e){let t=e._texture;if(!t||!e.isRGBD)return;let i=t.getEngine(),r=i.getCaps(),s=t.isReady,a=!1;r.textureHalfFloatRender&&r.textureHalfFloatLinearFiltering?(a=!0,t.type=2):r.textureFloatRender&&r.textureFloatLinearFiltering&&(a=!0,t.type=1),a&&(t.isReady=!1,t._isRGBD=!1,t.invertY=!1);let o=async()=>{let l=i.isWebGPU,c=l?1:0;t.isReady=!1,l?await Promise.resolve().then(()=>(MC(),IC)):await Promise.resolve().then(()=>(PC(),yC));let f=new xi("rgbdDecode","rgbdDecode",null,null,1,null,3,i,!1,void 0,t.type,void 0,null,!1,void 0,c);f.externalTextureSamplerBinding=!0;let h=i.createRenderTargetTexture(t.width,{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:t.samplingMode,type:t.type,format:5});f.onEffectCreatedObservable.addOnce(d=>{d.executeWhenCompiled(()=>{f.onApply=u=>{u._bindTexture("textureSampler",t),u.setFloat2("scale",1,1)},e.getScene().postProcessManager.directRender([f],h,!0),i.restoreDefaultFramebuffer(),i._releaseTexture(t),f&&f.dispose(),h._swapAndDie(t),t.isReady=!0})})};a&&(s?o():e.onLoadObservable.addOnce(o))}static async EncodeTextureToRGBD(e,t,i=0){return t.getEngine().isWebGPU?await Promise.resolve().then(()=>(fU(),cU)):await Promise.resolve().then(()=>(oU(),aU)),await hB("rgbdEncode",e,t,i,1,5)}}});var NC=C(()=>{kM();k_();pi.prototype._sphericalPolynomialTargetSize=0;pi.prototype.forceSphericalPolynomialsRecompute=function(){this._texture&&(this._texture._sphericalPolynomial=null,this._texture._sphericalPolynomialPromise=null,this._texture._sphericalPolynomialComputed=!1)};Object.defineProperty(pi.prototype,"sphericalPolynomial",{get:function(){if(this._texture){if(this._texture._sphericalPolynomial||this._texture._sphericalPolynomialComputed)return this._texture._sphericalPolynomial;if(this._texture.isReady)return this._texture._sphericalPolynomialPromise||(this._texture._sphericalPolynomialPromise=zl.ConvertCubeMapTextureToSphericalPolynomial(this),this._texture._sphericalPolynomialPromise===null?this._texture._sphericalPolynomialComputed=!0:this._texture._sphericalPolynomialPromise.then(n=>{this._texture._sphericalPolynomial=n,this._texture._sphericalPolynomialComputed=!0})),null}return null},set:function(n){this._texture&&(this._texture._sphericalPolynomial=n)},enumerable:!0,configurable:!0})});function mU(n){let e=new DataView(n.buffer,n.byteOffset,n.byteLength),t=0;for(let a=0;ahU)throw new Error(`Unsupported babylon environment map version "${n.version}". Latest supported version is "${hU}".`);return n.version===2||(n={...n,version:2,imageType:_A}),n}function ane(n,e){e=ig(e);let t=e.specular,i=Math.log2(e.width);if(i=Math.round(i)+1,t.mipmaps.length!==6*i)throw new Error(`Unsupported specular mipmaps number "${t.mipmaps.length}"`);let r=new Array(i);for(let s=0;s{if(t){let u=e.createTexture(null,!0,!0,null,1,null,m=>{d(m)},n);i==null||i.onEffectCreatedObservable.addOnce(m=>{m.executeWhenCompiled(()=>{i.externalTextureSamplerBinding=!0,i.onApply=p=>{p._bindTexture("textureSampler",u),p.setFloat2("scale",1,e._features.needsInvertingBitmap&&n instanceof ImageBitmap?-1:1)},e.scenes.length&&(e.scenes[0].postProcessManager.directRender([i],c,!0,s,a),e.restoreDefaultFramebuffer(),u.dispose(),URL.revokeObjectURL(r),h())})})}else{if(e._uploadImageToTexture(f,n,s,a),o){let u=l[a];u&&e._uploadImageToTexture(u._texture,n,s,0)}h()}})}async function lne(n,e,t=_A){let i=n.getEngine();n.format=5,n.type=0,n.generateMipMaps=!0,n._cachedAnisotropicFilteringLevel=null,i.updateTextureSamplingMode(3,n),await _U(n,e,!0,t),n.isReady=!0}async function cne(n,e,t,i=_A,r=null){let s=n.getEngine(),a=new yi(s,5),o=new pi(s,a);n._irradianceTexture=o,o._dominantDirection=r,a.isCube=!0,a.format=5,a.type=0,a.generateMipMaps=!0,a._cachedAnisotropicFilteringLevel=null,a.generateMipMaps=!0,a.width=t,a.height=t,s.updateTextureSamplingMode(3,a),await _U(a,[e],!1,i),s.generateMipMapsForCubemap(a),a.isReady=!0}async function _U(n,e,t,i=_A){if(!pe.IsExponentOfTwo(n.width))throw new Error("Texture size must be a power of two");let r=p2(n.width)+1,s=n.getEngine(),a=!1,o=!1,l=null,c=null,f=null,h=s.getCaps();h.textureLOD?s._features.supportRenderAndCopyToLodForFloatTextures?h.textureHalfFloatRender&&h.textureHalfFloatLinearFiltering?(a=!0,n.type=2):h.textureFloatRender&&h.textureFloatLinearFiltering&&(a=!0,n.type=1):a=!1:(a=!1,o=t);let d=0;if(a)s.isWebGPU?(d=1,await Promise.resolve().then(()=>(MC(),IC))):await Promise.resolve().then(()=>(PC(),yC)),l=new xi("rgbdDecode","rgbdDecode",null,null,1,null,3,s,!1,void 0,n.type,void 0,null,!1,void 0,d),n._isRGBD=!1,n.invertY=!1,c=s.createRenderTargetCubeTexture(n.width,{generateDepthBuffer:!1,generateMipMaps:!0,generateStencilBuffer:!1,samplingMode:3,type:n.type,format:5});else if(n._isRGBD=!0,n.invertY=!0,o){f={};let p=n._lodGenerationScale,_=n._lodGenerationOffset;for(let g=0;g<3;g++){let x=1-g/2,A=_,S=(r-1)*p+_,E=A+(S-A)*x,R=Math.round(Math.min(Math.max(E,0),S)),I=new yi(s,2);I.isCube=!0,I.invertY=!0,I.generateMipMaps=!1,s.updateTextureSamplingMode(2,I);let y=new pi(null);switch(y._isCube=!0,y._texture=I,f[R]=y,g){case 0:n._lodTextureLow=y;break;case 1:n._lodTextureMid=y;break;case 2:n._lodTextureHigh=y;break}}}let u=[];for(let m=0;mawait uU(S,s,a,l,x,p,m,o,f,c,n));else{let S=new Image;S.src=x,A=new Promise((E,R)=>{S.onload=()=>{uU(S,s,a,l,x,p,m,o,f,c,n).then(()=>E()).catch(I=>{R(I)})},S.onerror=I=>{R(I)}})}u.push(A)}if(await Promise.all(u),e.length{bi();Ve();Ln();F_();Es();k_();xs();Kl();yt();OC();tC();NC();nm();_A="image/png",hU=2,dU=[134,22,135,150,246,214,150,54]});var EU={};tt(EU,{_ENVTextureLoader:()=>wC});var wC,SU=C(()=>{vU();wC=class{constructor(){this.supportCascades=!1}loadCubeData(e,t,i,r,s){if(Array.isArray(e))return;let a=mU(e);if(a){t.width=a.width,t.height=a.width;try{gU(t,a),pU(t,e,a).then(()=>{t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()},o=>{s==null||s("Can not upload environment levels",o)})}catch(o){s==null||s("Can not upload environment file",o)}}else s&&s("Can not parse the environment file",null)}loadData(){throw".env not supported in 2d."}}});var Jl,TU=C(()=>{Ve();Jl=class{static ConvertPanoramaToCubemap(e,t,i,r,s=!1,a=!0){if(!e)throw"ConvertPanoramaToCubemap: input cannot be null";let o;if(e.length!=t*i*3){if(e.length!=t*i*4)throw"ConvertPanoramaToCubemap: input size is wrong";o=4}else o=3;let l=this.CreateCubemapTexture(r,this.FACE_FRONT,e,t,i,s,a,o),c=this.CreateCubemapTexture(r,this.FACE_BACK,e,t,i,s,a,o),f=this.CreateCubemapTexture(r,this.FACE_LEFT,e,t,i,s,a,o),h=this.CreateCubemapTexture(r,this.FACE_RIGHT,e,t,i,s,a,o),d=this.CreateCubemapTexture(r,this.FACE_UP,e,t,i,s,a,o),u=this.CreateCubemapTexture(r,this.FACE_DOWN,e,t,i,s,a,o);return{front:l,back:c,left:f,right:h,up:d,down:u,size:r,type:1,format:4,gammaSpace:!1}}static CreateCubemapTexture(e,t,i,r,s,a,o,l){let c=new ArrayBuffer(e*e*4*3),f=new Float32Array(c),h=a?Math.max(1,Math.round(r/4/e)):1,d=1/h,u=d*d,m=t[1].subtract(t[0]).scale(d/e),p=t[3].subtract(t[2]).scale(d/e),_=1/e,g=0;for(let v=0;vMath.PI;)o-=2*Math.PI;let c=o/Math.PI,f=l/Math.PI;c=c*.5+.5;let h=Math.round(c*i);h<0?h=0:h>=i&&(h=i-1);let d=Math.round(f*r);d<0?d=0:d>=r&&(d=r-1);let u=a?r-d-1:d,m=t[u*i*s+h*s+0],p=t[u*i*s+h*s+1],_=t[u*i*s+h*s+2];return{r:m,g:p,b:_}}};Jl.FACE_LEFT=[new b(-1,-1,-1),new b(1,-1,-1),new b(-1,1,-1),new b(1,1,-1)];Jl.FACE_RIGHT=[new b(1,-1,1),new b(-1,-1,1),new b(1,1,1),new b(-1,1,1)];Jl.FACE_FRONT=[new b(1,-1,-1),new b(1,-1,1),new b(1,1,-1),new b(1,1,1)];Jl.FACE_BACK=[new b(-1,-1,1),new b(-1,-1,-1),new b(-1,1,1),new b(-1,1,-1)];Jl.FACE_DOWN=[new b(1,1,-1),new b(1,1,1),new b(-1,1,-1),new b(-1,1,1)];Jl.FACE_UP=[new b(-1,-1,-1),new b(-1,-1,1),new b(1,-1,-1),new b(1,-1,1)]});function fne(n,e){return e>1023?n*Math.pow(2,1023)*Math.pow(2,e-1023):e<-1074?n*Math.pow(2,-1074)*Math.pow(2,e+1074):n*Math.pow(2,e)}function AU(n,e,t,i,r,s){r>0?(r=fne(1,r-136),n[s+0]=e*r,n[s+1]=t*r,n[s+2]=i*r):(n[s+0]=0,n[s+1]=0,n[s+2]=0)}function FC(n,e){let t="",i;for(let r=e;r32767)throw"HDR Bad header format, unsupported size";return r+=e.length+1,{height:l,width:o,dataPosition:r}}function RU(n,e){return hne(n,e)}function hne(n,e){let t=e.height,i=e.width,r,s,a,o,l,c=e.dataPosition,f,h,d,u=new ArrayBuffer(i*4),m=new Uint8Array(u),p=new ArrayBuffer(e.width*e.height*4*3),_=new Float32Array(p);for(;t>0;){if(r=n[c++],s=n[c++],a=n[c++],o=n[c++],r!=2||s!=2||a&128||e.width<8||e.width>32767)return dne(n,e);if((a<<8|o)!=i)throw"HDR Bad header format, wrong scan line width";for(f=0,d=0;d<4;d++)for(h=(d+1)*i;f128){if(l=r-128,l==0||l>h-f)throw"HDR Bad Format, bad scanline data (run)";for(;l-- >0;)m[f++]=s}else{if(l=r,l==0||l>h-f)throw"HDR Bad Format, bad scanline data (non-run)";if(m[f++]=s,--l>0)for(let g=0;g0;){for(l=0;l{TU()});var IU={};tt(IU,{_HDRTextureLoader:()=>BC});var BC,MU=C(()=>{bU();BC=class{constructor(){this.supportCascades=!1}loadCubeData(){throw".hdr not supported in Cube."}loadData(e,t,i){let r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=xU(r),a=RU(r,s),o=s.width*s.height,l=new Float32Array(o*4);for(let c=0;c{let c=t.getEngine();t.type=1,t.format=5,t._gammaSpace=!1,c._uploadDataToTextureDirectly(t,l)})}}});var ho,CU=C(()=>{yt();ho=class n{constructor(e,t){if(this.data=e,this.isInvalid=!1,!n.IsValid(e)){this.isInvalid=!0,te.Error("texture missing KTX identifier");return}let i=Uint32Array.BYTES_PER_ELEMENT,r=new DataView(this.data.buffer,this.data.byteOffset+12,13*i),a=r.getUint32(0,!0)===67305985;if(this.glType=r.getUint32(1*i,a),this.glTypeSize=r.getUint32(2*i,a),this.glFormat=r.getUint32(3*i,a),this.glInternalFormat=r.getUint32(4*i,a),this.glBaseInternalFormat=r.getUint32(5*i,a),this.pixelWidth=r.getUint32(6*i,a),this.pixelHeight=r.getUint32(7*i,a),this.pixelDepth=r.getUint32(8*i,a),this.numberOfArrayElements=r.getUint32(9*i,a),this.numberOfFaces=r.getUint32(10*i,a),this.numberOfMipmapLevels=r.getUint32(11*i,a),this.bytesOfKeyValueData=r.getUint32(12*i,a),this.glType!==0){te.Error("only compressed formats currently supported"),this.isInvalid=!0;return}else this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels);if(this.pixelHeight===0||this.pixelDepth!==0){te.Error("only 2D textures currently supported"),this.isInvalid=!0;return}if(this.numberOfArrayElements!==0){te.Error("texture arrays not currently supported"),this.isInvalid=!0;return}if(this.numberOfFaces!==t){te.Error("number of faces expected"+t+", but found "+this.numberOfFaces),this.isInvalid=!0;return}this.loadType=n.COMPRESSED_2D}uploadLevels(e,t){switch(this.loadType){case n.COMPRESSED_2D:this._upload2DCompressedLevels(e,t);break;case n.TEX_2D:case n.COMPRESSED_3D:case n.TEX_3D:}}_upload2DCompressedLevels(e,t){let i=n.HEADER_LEN+this.bytesOfKeyValueData,r=this.pixelWidth,s=this.pixelHeight,a=t?this.numberOfMipmapLevels:1;for(let o=0;o=12){let t=new Uint8Array(e.buffer,e.byteOffset,12);if(t[0]===171&&t[1]===75&&t[2]===84&&t[3]===88&&t[4]===32&&t[5]===49&&t[6]===49&&t[7]===187&&t[8]===13&&t[9]===10&&t[10]===26&&t[11]===10)return!0}return!1}};ho.HEADER_LEN=64;ho.COMPRESSED_2D=0;ho.COMPRESSED_3D=1;ho.TEX_2D=2;ho.TEX_3D=3});var UC,rg,yU=C(()=>{UC=class{constructor(e){this._pendingActions=new Array,this._workerInfos=e.map(t=>({workerPromise:Promise.resolve(t),idle:!0}))}dispose(){for(let e of this._workerInfos)e.workerPromise.then(t=>{t.terminate()});this._workerInfos.length=0,this._pendingActions.length=0}push(e){this._executeOnIdleWorker(e)||this._pendingActions.push(e)}_executeOnIdleWorker(e){for(let t of this._workerInfos)if(t.idle)return this._execute(t,e),!0;return!1}_execute(e,t){e.idle=!1,e.workerPromise.then(i=>{t(i,()=>{let r=this._pendingActions.shift();r?this._execute(e,r):e.idle=!0})})}},rg=class n extends UC{constructor(e,t,i=n.DefaultOptions){super([]),this._maxWorkers=e,this._createWorkerAsync=t,this._options=i}push(e){if(!this._executeOnIdleWorker(e))if(this._workerInfos.length{t(i,()=>{r(),e.idle&&(e.timeoutId=setTimeout(()=>{e.workerPromise.then(a=>{a.terminate()});let s=this._workerInfos.indexOf(e);s!==-1&&this._workerInfos.splice(s,1)},this._options.idleTimeElapsedBeforeRelease))})})}};rg.DefaultOptions={idleTimeElapsedBeforeRelease:1e3}});var PU,fm,DU,LU=C(()=>{(function(n){n[n.ETC1S=0]="ETC1S",n[n.UASTC4x4=1]="UASTC4x4"})(PU||(PU={}));(function(n){n[n.ASTC_4X4_RGBA=0]="ASTC_4X4_RGBA",n[n.ASTC_4x4_RGBA=0]="ASTC_4x4_RGBA",n[n.BC7_RGBA=1]="BC7_RGBA",n[n.BC3_RGBA=2]="BC3_RGBA",n[n.BC1_RGB=3]="BC1_RGB",n[n.PVRTC1_4_RGBA=4]="PVRTC1_4_RGBA",n[n.PVRTC1_4_RGB=5]="PVRTC1_4_RGB",n[n.ETC2_RGBA=6]="ETC2_RGBA",n[n.ETC1_RGB=7]="ETC1_RGB",n[n.RGBA32=8]="RGBA32",n[n.R8=9]="R8",n[n.RG8=10]="RG8"})(fm||(fm={}));(function(n){n[n.COMPRESSED_RGBA_BPTC_UNORM_EXT=36492]="COMPRESSED_RGBA_BPTC_UNORM_EXT",n[n.COMPRESSED_RGBA_ASTC_4X4_KHR=37808]="COMPRESSED_RGBA_ASTC_4X4_KHR",n[n.COMPRESSED_RGB_S3TC_DXT1_EXT=33776]="COMPRESSED_RGB_S3TC_DXT1_EXT",n[n.COMPRESSED_RGBA_S3TC_DXT5_EXT=33779]="COMPRESSED_RGBA_S3TC_DXT5_EXT",n[n.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=35842]="COMPRESSED_RGBA_PVRTC_4BPPV1_IMG",n[n.COMPRESSED_RGB_PVRTC_4BPPV1_IMG=35840]="COMPRESSED_RGB_PVRTC_4BPPV1_IMG",n[n.COMPRESSED_RGBA8_ETC2_EAC=37496]="COMPRESSED_RGBA8_ETC2_EAC",n[n.COMPRESSED_RGB8_ETC2=37492]="COMPRESSED_RGB8_ETC2",n[n.COMPRESSED_RGB_ETC1_WEBGL=36196]="COMPRESSED_RGB_ETC1_WEBGL",n[n.RGBA8Format=32856]="RGBA8Format",n[n.R8Format=33321]="R8Format",n[n.RG8Format=33323]="RG8Format"})(DU||(DU={}))});function ng(n,e){let t=(e==null?void 0:e.jsDecoderModule)||KTX2DECODER;n&&(n.wasmBaseUrl&&(t.Transcoder.WasmBaseUrl=n.wasmBaseUrl),n.wasmUASTCToASTC&&(t.LiteTranscoder_UASTC_ASTC.WasmModuleURL=n.wasmUASTCToASTC),n.wasmUASTCToBC7&&(t.LiteTranscoder_UASTC_BC7.WasmModuleURL=n.wasmUASTCToBC7),n.wasmUASTCToRGBA_UNORM&&(t.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL=n.wasmUASTCToRGBA_UNORM),n.wasmUASTCToRGBA_SRGB&&(t.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL=n.wasmUASTCToRGBA_SRGB),n.wasmUASTCToR8_UNORM&&(t.LiteTranscoder_UASTC_R8_UNORM.WasmModuleURL=n.wasmUASTCToR8_UNORM),n.wasmUASTCToRG8_UNORM&&(t.LiteTranscoder_UASTC_RG8_UNORM.WasmModuleURL=n.wasmUASTCToRG8_UNORM),n.jsMSCTranscoder&&(t.MSCTranscoder.JSModuleURL=n.jsMSCTranscoder),n.wasmMSCTranscoder&&(t.MSCTranscoder.WasmModuleURL=n.wasmMSCTranscoder),n.wasmZSTDDecoder&&(t.ZSTDDecoder.WasmModuleURL=n.wasmZSTDDecoder)),e&&(e.wasmUASTCToASTC&&(t.LiteTranscoder_UASTC_ASTC.WasmBinary=e.wasmUASTCToASTC),e.wasmUASTCToBC7&&(t.LiteTranscoder_UASTC_BC7.WasmBinary=e.wasmUASTCToBC7),e.wasmUASTCToRGBA_UNORM&&(t.LiteTranscoder_UASTC_RGBA_UNORM.WasmBinary=e.wasmUASTCToRGBA_UNORM),e.wasmUASTCToRGBA_SRGB&&(t.LiteTranscoder_UASTC_RGBA_SRGB.WasmBinary=e.wasmUASTCToRGBA_SRGB),e.wasmUASTCToR8_UNORM&&(t.LiteTranscoder_UASTC_R8_UNORM.WasmBinary=e.wasmUASTCToR8_UNORM),e.wasmUASTCToRG8_UNORM&&(t.LiteTranscoder_UASTC_RG8_UNORM.WasmBinary=e.wasmUASTCToRG8_UNORM),e.jsMSCTranscoder&&(t.MSCTranscoder.JSModule=e.jsMSCTranscoder),e.wasmMSCTranscoder&&(t.MSCTranscoder.WasmBinary=e.wasmMSCTranscoder),e.wasmZSTDDecoder&&(t.ZSTDDecoder.WasmBinary=e.wasmZSTDDecoder))}function OU(n){typeof n=="undefined"&&typeof KTX2DECODER!="undefined"&&(n=KTX2DECODER);let e;onmessage=t=>{if(t.data)switch(t.data.action){case"init":{let i=t.data.urls;i&&(i.jsDecoderModule&&typeof n=="undefined"&&(importScripts(i.jsDecoderModule),n=KTX2DECODER),ng(i)),t.data.wasmBinaries&&ng(void 0,{...t.data.wasmBinaries,jsDecoderModule:n}),e=new n.KTX2Decoder,postMessage({action:"init"});break}case"setDefaultDecoderOptions":{n.KTX2Decoder.DefaultDecoderOptions=t.data.options;break}case"decode":e.decode(t.data.data,t.data.caps,t.data.options).then(i=>{let r=[];for(let s=0;s{postMessage({action:"decoded",success:!1,msg:i})});break}}}async function NU(n,e,t){return await new Promise((i,r)=>{let s=o=>{n.removeEventListener("error",s),n.removeEventListener("message",a),r(o)},a=o=>{o.data.action==="init"&&(n.removeEventListener("error",s),n.removeEventListener("message",a),i(n))};n.addEventListener("error",s),n.addEventListener("message",a),n.postMessage({action:"init",urls:t,wasmBinaries:e})})}var wU=C(()=>{});var VC,ec,FU=C(()=>{yU();bi();LU();wU();VC=class{constructor(){this._isDirty=!0,this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC=!0,this._ktx2DecoderOptions={}}get isDirty(){return this._isDirty}get useRGBAIfASTCBC7NotAvailableWhenUASTC(){return this._useRGBAIfASTCBC7NotAvailableWhenUASTC}set useRGBAIfASTCBC7NotAvailableWhenUASTC(e){this._useRGBAIfASTCBC7NotAvailableWhenUASTC!==e&&(this._useRGBAIfASTCBC7NotAvailableWhenUASTC=e,this._isDirty=!0)}get useRGBAIfOnlyBC1BC3AvailableWhenUASTC(){return this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC}set useRGBAIfOnlyBC1BC3AvailableWhenUASTC(e){this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC!==e&&(this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC=e,this._isDirty=!0)}get forceRGBA(){return this._forceRGBA}set forceRGBA(e){this._forceRGBA!==e&&(this._forceRGBA=e,this._isDirty=!0)}get forceR8(){return this._forceR8}set forceR8(e){this._forceR8!==e&&(this._forceR8=e,this._isDirty=!0)}get forceRG8(){return this._forceRG8}set forceRG8(e){this._forceRG8!==e&&(this._forceRG8=e,this._isDirty=!0)}get bypassTranscoders(){return this._bypassTranscoders}set bypassTranscoders(e){this._bypassTranscoders!==e&&(this._bypassTranscoders=e,this._isDirty=!0)}_getKTX2DecoderOptions(){if(!this._isDirty)return this._ktx2DecoderOptions;this._isDirty=!1;let e={};return this._useRGBAIfASTCBC7NotAvailableWhenUASTC!==void 0&&(e.useRGBAIfASTCBC7NotAvailableWhenUASTC=this._useRGBAIfASTCBC7NotAvailableWhenUASTC),this._forceRGBA!==void 0&&(e.forceRGBA=this._forceRGBA),this._forceR8!==void 0&&(e.forceR8=this._forceR8),this._forceRG8!==void 0&&(e.forceRG8=this._forceRG8),this._bypassTranscoders!==void 0&&(e.bypassTranscoders=this._bypassTranscoders),this.useRGBAIfOnlyBC1BC3AvailableWhenUASTC&&(e.transcodeFormatDecisionTree={UASTC:{transcodeFormat:[fm.BC1_RGB,fm.BC3_RGBA],yes:{transcodeFormat:fm.RGBA32,engineFormat:32856,roundToMultiple4:!1}}}),this._ktx2DecoderOptions=e,e}},ec=class n{static GetDefaultNumWorkers(){return typeof navigator!="object"||!navigator.hardwareConcurrency?1:Math.min(Math.floor(navigator.hardwareConcurrency*.5),4)}static _Initialize(e){if(n._WorkerPoolPromise||n._DecoderModulePromise)return;let t={wasmBaseUrl:pe.ScriptBaseUrl,jsDecoderModule:pe.GetBabylonScriptURL(this.URLConfig.jsDecoderModule,!0),wasmUASTCToASTC:pe.GetBabylonScriptURL(this.URLConfig.wasmUASTCToASTC,!0),wasmUASTCToBC7:pe.GetBabylonScriptURL(this.URLConfig.wasmUASTCToBC7,!0),wasmUASTCToRGBA_UNORM:pe.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_UNORM,!0),wasmUASTCToRGBA_SRGB:pe.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_SRGB,!0),wasmUASTCToR8_UNORM:pe.GetBabylonScriptURL(this.URLConfig.wasmUASTCToR8_UNORM,!0),wasmUASTCToRG8_UNORM:pe.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRG8_UNORM,!0),jsMSCTranscoder:pe.GetBabylonScriptURL(this.URLConfig.jsMSCTranscoder,!0),wasmMSCTranscoder:pe.GetBabylonScriptURL(this.URLConfig.wasmMSCTranscoder,!0),wasmZSTDDecoder:pe.GetBabylonScriptURL(this.URLConfig.wasmZSTDDecoder,!0)};e&&typeof Worker=="function"&&typeof URL!="undefined"?n._WorkerPoolPromise=new Promise(i=>{let r=`${ng}(${OU})()`,s=URL.createObjectURL(new Blob([r],{type:"application/javascript"}));i(new rg(e,async()=>await NU(new Worker(s),void 0,t)))}):typeof n._KTX2DecoderModule=="undefined"?n._DecoderModulePromise=pe.LoadBabylonScriptAsync(t.jsDecoderModule).then(()=>(n._KTX2DecoderModule=KTX2DECODER,n._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread=!1,n._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,ng(t,n._KTX2DecoderModule),new n._KTX2DecoderModule.KTX2Decoder)):(n._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread=!1,n._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,n._DecoderModulePromise=Promise.resolve(new n._KTX2DecoderModule.KTX2Decoder))}constructor(e,t=n.DefaultNumWorkers){var r,s;this._engine=e;let i=typeof t=="object"&&t.workerPool||n.WorkerPool;if(i)n._WorkerPoolPromise=Promise.resolve(i);else{typeof t=="object"?n._KTX2DecoderModule=(r=t==null?void 0:t.binariesAndModulesContainer)==null?void 0:r.jsDecoderModule:typeof KTX2DECODER!="undefined"&&(n._KTX2DecoderModule=KTX2DECODER);let a=typeof t=="number"?t:(s=t.numWorkers)!=null?s:n.DefaultNumWorkers;n._Initialize(a)}}async _uploadAsync(e,t,i){let r=this._engine.getCaps(),s={astc:!!r.astc,bptc:!!r.bptc,s3tc:!!r.s3tc,pvrtc:!!r.pvrtc,etc2:!!r.etc2,etc1:!!r.etc1};if(n._WorkerPoolPromise){let a=await n._WorkerPoolPromise;return await new Promise((o,l)=>{a.push((c,f)=>{let h=m=>{c.removeEventListener("error",h),c.removeEventListener("message",d),l(m),f()},d=m=>{if(m.data.action==="decoded"){if(c.removeEventListener("error",h),c.removeEventListener("message",d),!m.data.success)l({message:m.data.msg});else try{this._createTexture(m.data.decodedData,t,i),o()}catch(p){l({message:p})}f()}};c.addEventListener("error",h),c.addEventListener("message",d),c.postMessage({action:"setDefaultDecoderOptions",options:n.DefaultDecoderOptions._getKTX2DecoderOptions()});let u=new Uint8Array(e.byteLength);u.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),c.postMessage({action:"decode",data:u,caps:s,options:i},[u.buffer])})})}else if(n._DecoderModulePromise){let a=await n._DecoderModulePromise;return n.DefaultDecoderOptions.isDirty&&(n._KTX2DecoderModule.KTX2Decoder.DefaultDecoderOptions=n.DefaultDecoderOptions._getKTX2DecoderOptions()),await new Promise((o,l)=>{a.decode(e,r).then(c=>{this._createTexture(c,t),o()}).catch(c=>{l({message:c})})})}throw new Error("KTX2 decoder module is not available")}_createTexture(e,t,i){this._engine._bindTextureDirectly(3553,t),i&&(i.transcodedFormat=e.transcodedFormat,i.isInGammaSpace=e.isInGammaSpace,i.hasAlpha=e.hasAlpha,i.transcoderName=e.transcoderName);let s=!0;switch(e.transcodedFormat){case 32856:t.type=0,t.format=5;break;case 33321:t.type=0,t.format=6;break;case 33323:t.type=0,t.format=7;break;default:t.format=e.transcodedFormat,s=!1;break}if(t._gammaSpace=e.isInGammaSpace,t.generateMipMaps=e.mipmaps.length>1,t.width=e.mipmaps[0].width,t.height=e.mipmaps[0].height,e.errors)throw new Error("KTX2 container - could not transcode the data. "+e.errors);for(let a=0;a=12){let t=new Uint8Array(e.buffer,e.byteOffset,12);if(t[0]===171&&t[1]===75&&t[2]===84&&t[3]===88&&t[4]===32&&t[5]===50&&t[6]===48&&t[7]===187&&t[8]===13&&t[9]===10&&t[10]===26&&t[11]===10)return!0}return!1}};ec.URLConfig={jsDecoderModule:"https://cdn.babylonjs.com/babylon.ktx2Decoder.js",wasmUASTCToASTC:null,wasmUASTCToBC7:null,wasmUASTCToRGBA_UNORM:null,wasmUASTCToRGBA_SRGB:null,wasmUASTCToR8_UNORM:null,wasmUASTCToRG8_UNORM:null,jsMSCTranscoder:null,wasmMSCTranscoder:null,wasmZSTDDecoder:null};ec.DefaultNumWorkers=ec.GetDefaultNumWorkers();ec.DefaultDecoderOptions=new VC});var kC={};tt(kC,{_KTXTextureLoader:()=>GC});function une(n){switch(n){case 35916:return 33776;case 35918:return 33778;case 35919:return 33779;case 37493:return 37492;case 37497:return 37496;case 37495:return 37494;case 37840:return 37808;case 37841:return 37809;case 37842:return 37810;case 37843:return 37811;case 37844:return 37812;case 37845:return 37813;case 37846:return 37814;case 37847:return 37815;case 37848:return 37816;case 37849:return 37817;case 37850:return 37818;case 37851:return 37819;case 37852:return 37820;case 37853:return 37821;case 36493:return 36492}return null}var GC,WC=C(()=>{CU();FU();yt();GC=class{constructor(){this.supportCascades=!1}loadCubeData(e,t,i,r){if(Array.isArray(e))return;t._invertVScale=!t.invertY;let s=t.getEngine(),a=new ho(e,6),o=a.numberOfMipmapLevels>1&&t.generateMipMaps;s._unpackFlipY(!0),a.uploadLevels(t,t.generateMipMaps),t.width=a.pixelWidth,t.height=a.pixelHeight,s._setCubeMapTextureParams(t,o,a.numberOfMipmapLevels-1),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()}loadData(e,t,i,r){if(ho.IsValid(e)){t._invertVScale=!t.invertY;let s=new ho(e,1),a=une(s.glInternalFormat);a?(t.format=a,t._useSRGBBuffer=t.getEngine()._getUseSRGBBuffer(!0,t.generateMipMaps),t._gammaSpace=!0):t.format=s.glInternalFormat,i(s.pixelWidth,s.pixelHeight,t.generateMipMaps,!0,()=>{s.uploadLevels(t,t.generateMipMaps)},s.isInvalid)}else ec.IsValid(e)?new ec(t.getEngine())._uploadAsync(e,t,r).then(()=>{i(t.width,t.height,t.generateMipMaps,!0,()=>{},!1)},a=>{te.Warn(`Failed to load KTX2 texture data: ${a.message}`),i(0,0,!1,!1,()=>{},!0)}):(te.Error("texture missing KTX identifier"),i(0,0,!1,!1,()=>{},!0))}}});function gA(n){let e=0;return{id_length:n[e++],colormap_type:n[e++],image_type:n[e++],colormap_index:n[e++]|n[e++]<<8,colormap_length:n[e++]|n[e++]<<8,colormap_size:n[e++],origin:[n[e++]|n[e++]<<8,n[e++]|n[e++]<<8],width:n[e++]|n[e++]<<8,height:n[e++]|n[e++]<<8,pixel_size:n[e++],flags:n[e]}}function HC(n,e){if(e.length<19){te.Error("Unable to load TGA file - Not enough data to contain header");return}let t=18,i=gA(e);if(i.id_length+t>e.length){te.Error("Unable to load TGA file - Not enough data");return}t+=i.id_length;let r=!1,s=!1,a=!1;switch(i.image_type){case gne:r=!0;case mne:s=!0;break;case vne:r=!0;case pne:break;case Ene:r=!0;case _ne:a=!0;break}let o,l=i.pixel_size>>3,c=i.width*i.height*l,f;if(s&&(f=e.subarray(t,t+=i.colormap_length*(i.colormap_size>>3))),r){o=new Uint8Array(c);let A,S,E,R=0,I=new Uint8Array(l);for(;t>Tne){default:case Rne:h=0,u=1,_=i.width,d=0,m=1,p=i.height;break;case Ane:h=0,u=1,_=i.width,d=i.height-1,m=-1,p=-1;break;case bne:h=i.width-1,u=-1,_=-1,d=0,m=1,p=i.height;break;case xne:h=i.width-1,u=-1,_=-1,d=i.height-1,m=-1,p=-1;break}let g="_getImageData"+(a?"Grey":"")+i.pixel_size+"bits",v=Lne[g](i,f,o,d,m,p,h,u,_);n.getEngine()._uploadDataToTextureDirectly(n,v)}function Ine(n,e,t,i,r,s,a,o,l){let c=t,f=e,h=n.width,d=n.height,u,m=0,p,_,g=new Uint8Array(h*d*4);for(_=i;_!==s;_+=r)for(p=a;p!==l;p+=o,m++)u=c[m],g[(p+h*_)*4+3]=255,g[(p+h*_)*4+2]=f[u*3+0],g[(p+h*_)*4+1]=f[u*3+1],g[(p+h*_)*4+0]=f[u*3+2];return g}function Mne(n,e,t,i,r,s,a,o,l){let c=t,f=n.width,h=n.height,d,u=0,m,p,_=new Uint8Array(f*h*4);for(p=i;p!==s;p+=r)for(m=a;m!==l;m+=o,u+=2){d=c[u+0]+(c[u+1]<<8);let g=((d&31744)>>10)*255/31|0,v=((d&992)>>5)*255/31|0,x=(d&31)*255/31|0;_[(m+f*p)*4+0]=g,_[(m+f*p)*4+1]=v,_[(m+f*p)*4+2]=x,_[(m+f*p)*4+3]=d&32768?0:255}return _}function Cne(n,e,t,i,r,s,a,o,l){let c=t,f=n.width,h=n.height,d=0,u,m,p=new Uint8Array(f*h*4);for(m=i;m!==s;m+=r)for(u=a;u!==l;u+=o,d+=3)p[(u+f*m)*4+3]=255,p[(u+f*m)*4+2]=c[d+0],p[(u+f*m)*4+1]=c[d+1],p[(u+f*m)*4+0]=c[d+2];return p}function yne(n,e,t,i,r,s,a,o,l){let c=t,f=n.width,h=n.height,d=0,u,m,p=new Uint8Array(f*h*4);for(m=i;m!==s;m+=r)for(u=a;u!==l;u+=o,d+=4)p[(u+f*m)*4+2]=c[d+0],p[(u+f*m)*4+1]=c[d+1],p[(u+f*m)*4+0]=c[d+2],p[(u+f*m)*4+3]=c[d+3];return p}function Pne(n,e,t,i,r,s,a,o,l){let c=t,f=n.width,h=n.height,d,u=0,m,p,_=new Uint8Array(f*h*4);for(p=i;p!==s;p+=r)for(m=a;m!==l;m+=o,u++)d=c[u],_[(m+f*p)*4+0]=d,_[(m+f*p)*4+1]=d,_[(m+f*p)*4+2]=d,_[(m+f*p)*4+3]=255;return _}function Dne(n,e,t,i,r,s,a,o,l){let c=t,f=n.width,h=n.height,d=0,u,m,p=new Uint8Array(f*h*4);for(m=i;m!==s;m+=r)for(u=a;u!==l;u+=o,d+=2)p[(u+f*m)*4+0]=c[d+0],p[(u+f*m)*4+1]=c[d+0],p[(u+f*m)*4+2]=c[d+0],p[(u+f*m)*4+3]=c[d+1];return p}var mne,pne,_ne,gne,vne,Ene,Sne,Tne,Ane,xne,Rne,bne,Lne,BU=C(()=>{yt();mne=1,pne=2,_ne=3,gne=9,vne=10,Ene=11,Sne=48,Tne=4,Ane=0,xne=1,Rne=2,bne=3;Lne={GetTGAHeader:gA,UploadContent:HC,_getImageData8bits:Ine,_getImageData16bits:Mne,_getImageData24bits:Cne,_getImageData32bits:yne,_getImageDataGrey8bits:Pne,_getImageDataGrey16bits:Dne}});var UU={};tt(UU,{_TGATextureLoader:()=>zC});var zC,VU=C(()=>{BU();zC=class{constructor(){this.supportCascades=!1}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){let r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=gA(r);i(s.width,s.height,t.generateMipMaps,!1,()=>{HC(t,r)})}}});var sg=C(()=>{});function Nne(){let n=new ArrayBuffer(4),e=new Float32Array(n),t=new Uint32Array(n),i=new Uint32Array(512),r=new Uint32Array(512);for(let l=0;l<256;++l){let c=l-127;c<-27?(i[l]=0,i[l|256]=32768,r[l]=24,r[l|256]=24):c<-14?(i[l]=1024>>-c-14,i[l|256]=1024>>-c-14|32768,r[l]=-c-1,r[l|256]=-c-1):c<=15?(i[l]=c+15<<10,i[l|256]=c+15<<10|32768,r[l]=13,r[l|256]=13):c<128?(i[l]=31744,i[l|256]=64512,r[l]=24,r[l|256]=24):(i[l]=31744,i[l|256]=64512,r[l]=13,r[l|256]=13)}let s=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let l=1;l<1024;++l){let c=l<<13,f=0;for(;(c&8388608)===0;)c<<=1,f-=8388608;c&=-8388609,f+=947912704,s[l]=c|f}for(let l=1024;l<2048;++l)s[l]=939524096+(l-1024<<13);for(let l=1;l<31;++l)a[l]=l<<23;a[31]=1199570944,a[32]=2147483648;for(let l=33;l<63;++l)a[l]=2147483648+(l-32<<23);a[63]=3347054592;for(let l=1;l<64;++l)l!==32&&(o[l]=1024);return{floatView:e,uint32View:t,baseTable:i,shiftTable:r,mantissaTable:s,exponentTable:a,offsetTable:o}}function SA(n,e){let t=new Uint8Array(n),i=0;for(;t[e.value+i]!=0;)i+=1;let r=new TextDecoder().decode(t.slice(e.value,e.value+i));return e.value=e.value+i+1,r}function uo(n,e){let t=n.getInt32(e.value,!0);return e.value+=4,t}function js(n,e){let t=n.getUint32(e.value,!0);return e.value+=4,t}function ag(n,e){let t=n.getUint8(e.value);return e.value+=1,t}function hm(n,e){let t=n.getUint16(e.value,!0);return e.value+=2,t}function YC(n,e){let t=n[e.value];return e.value+=1,t}function WU(n,e){let t;return"getBigInt64"in DataView.prototype?t=Number(n.getBigInt64(e.value,!0)):t=n.getUint32(e.value+4,!0)+Number(n.getUint32(e.value,!0)<<32),e.value+=8,t}function Sn(n,e){let t=n.getFloat32(e.value,!0);return e.value+=4,t}function HU(n,e){return wne(hm(n,e))}function wne(n){let e=(n&31744)>>10,t=n&1023;return(n>>15?-1:1)*(e?e===31?t?NaN:1/0:Math.pow(2,e-15)*(1+t/1024):6103515625e-14*(t/1024))}function Fne(n){if(Math.abs(n)>65504)throw new Error("Value out of range.Consider using float instead of half-float.");n=Nt(n,-65504,65504),vA.floatView[0]=n;let e=vA.uint32View[0],t=e>>23&511;return vA.baseTable[t]+((e&8388607)>>vA.shiftTable[t])}function zU(n,e){return Fne(Sn(n,e))}function Bne(n,e,t){let i=new TextDecoder().decode(new Uint8Array(n).slice(e.value,e.value+t));return e.value=e.value+t,i}function Une(n,e){let t=uo(n,e),i=js(n,e);return[t,i]}function Vne(n,e){let t=js(n,e),i=js(n,e);return[t,i]}function Gne(n,e){let t=Sn(n,e),i=Sn(n,e);return[t,i]}function kne(n,e){let t=Sn(n,e),i=Sn(n,e),r=Sn(n,e);return[t,i,r]}function Wne(n,e,t){let i=e.value,r=[];for(;e.values||(e[r++]=n[t++],r>s));)e[r++]=n[i++]}var rl,XC,vA,og=C(()=>{Ln();sg();(function(n){n[n.NO_COMPRESSION=0]="NO_COMPRESSION",n[n.RLE_COMPRESSION=1]="RLE_COMPRESSION",n[n.ZIPS_COMPRESSION=2]="ZIPS_COMPRESSION",n[n.ZIP_COMPRESSION=3]="ZIP_COMPRESSION",n[n.PIZ_COMPRESSION=4]="PIZ_COMPRESSION",n[n.PXR24_COMPRESSION=5]="PXR24_COMPRESSION"})(rl||(rl={}));(function(n){n[n.INCREASING_Y=0]="INCREASING_Y",n[n.DECREASING_Y=1]="DECREASING_Y"})(XC||(XC={}));vA=Nne()});function qC(n,e){if(n.getUint32(0,!0)!=Kne)throw new Error("Incorrect OpenEXR format");let t=n.getUint8(4),i=n.getUint8(5),r={singleTile:!!(i&2),longName:!!(i&4),deepFormat:!!(i&8),multiPart:!!(i&16)};e.value=8;let s={},a=!0;for(;a;){let o=SA(n.buffer,e);if(!o)a=!1;else{let l=SA(n.buffer,e),c=js(n,e),f=XU(n,e,l,c);f===void 0?te.Warn(`Unknown header attribute type ${l}'.`):s[o]=f}}if((i&-5)!=0)throw new Error("Unsupported file format");return{version:t,spec:r,...s}}var Kne,YU=C(()=>{yt();og();Kne=20000630});function eV(n,e){let t=0;for(let r=0;r<65536;++r)(r==0||n[r>>3]&1<<(r&7))&&(e[t++]=r);let i=t-1;for(;t<65536;)e[t++]=0;return i}function Qne(n){for(let e=0;e<16384;e++)n[e]={},n[e].len=0,n[e].lit=0,n[e].p=null}function ZU(n,e,t,i,r){for(;t>t&(1<>i;if(c=new Uint8Array([c])[0],o.value+c>l)return null;let f=a[o.value-1];for(;c-- >0;)a[o.value++]=f}else if(o.value0;--t){let i=e+lg[t]>>1;lg[t]=e,e=i}for(let t=0;t<65537;++t){let i=n[t];i>0&&(n[t]=i|lg[i]++<<6)}}function Jne(n,e,t,i,r,s){let a=e,o=0,l=0;for(;i<=r;i++){if(a.value-e.value>t)return;let c=ZU(6,o,l,n,a),f=c.l;if(o=c.c,l=c.lc,s[i]=f,f==63){if(a.value-e.value>t)throw new Error("Error in HufUnpackEncTable");c=ZU(8,o,l,n,a);let h=c.l+6;if(o=c.c,l=c.lc,i+h>r+1)throw new Error("Error in HufUnpackEncTable");for(;h--;)s[i++]=0;i--}else if(f>=59){let h=f-59+2;if(i+h>r+1)throw new Error("Error in HufUnpackEncTable");for(;h--;)s[i++]=0;i--}}$ne(s)}function tV(n){return n&63}function iV(n){return n>>6}function ese(n,e,t,i){for(;e<=t;e++){let r=iV(n[e]),s=tV(n[e]);if(r>>s)throw new Error("Invalid table entry");if(s>14){let a=i[r>>s-14];if(a.len)throw new Error("Invalid table entry");if(a.lit++,a.p){let o=a.p;a.p=new Array(a.lit);for(let l=0;l0;o--){let l=i[(r<<14-s)+a];if(l.len||l.p)throw new Error("Invalid table entry");l.len=s,l.lit=e,a++}}}return!0}function tse(n,e,t,i,r,s,a,o,l){let c=0,f=0,h=a,d=Math.trunc(i.value+(r+7)/8);for(;i.value=14;){let p=c>>f-14&16383,_=e[p];if(_.len){f-=_.len;let g=ZC(_.lit,s,c,f,t,i,o,l,h);g&&(c=g.c,f=g.lc)}else{if(!_.p)throw new Error("hufDecode issues");let g;for(g=0;g<_.lit;g++){let v=tV(n[_.p[g]]);for(;f=v&&iV(n[_.p[g]])==(c>>f-v&(1<>=u,f-=u;f>0;){let m=e[c<<14-f&16383];if(m.len){f-=m.len;let p=ZC(m.lit,s,c,f,t,i,o,l,h);p&&(c=p.c,f=p.lc)}else throw new Error("HufDecode issues")}return!0}function rV(n,e,t,i,r,s){let a={value:0},o=t.value,l=js(e,t),c=js(e,t);t.value+=4;let f=js(e,t);if(t.value+=4,l<0||l>=65537||c<0||c>=65537)throw new Error("Wrong HUF_ENCSIZE");let h=new Array(65537),d=new Array(16384);Qne(d);let u=i-(t.value-o);if(Jne(n,t,u,l,c,h),f>8*(i-(t.value-o)))throw new Error("Wrong hufUncompress");ese(h,l,c,d),tse(h,d,n,t,f,c,s,r,a)}function $C(n){return n&65535}function QU(n){let e=$C(n);return e>32767?e-65536:e}function dm(n,e){let t=QU(n),r=QU(e),s=t+(r&1)+(r>>1),a=s,o=s-r;return{a,b:o}}function um(n,e){let t=$C(n),i=$C(e),r=t-(i>>1)&qU;return{a:i+r-Zne&qU,b:r}}function nV(n,e,t,i,r,s,a){let o=a<16384,l=t>r?r:t,c=1,f,h;for(;c<=l;)c<<=1;for(c>>=1,f=c,c>>=1;c>=1;){h=0;let d=h+s*(r-f),u=s*c,m=s*f,p=i*c,_=i*f,g,v,x,A;for(;h<=d;h+=m){let S=h,E=h+i*(t-f);for(;S<=E;S+=_){let R=S+p,I=S+u,y=I+p;if(o){let M=dm(n[S+e],n[I+e]);g=M.a,x=M.b,M=dm(n[R+e],n[y+e]),v=M.a,A=M.b,M=dm(g,v),n[S+e]=M.a,n[R+e]=M.b,M=dm(x,A),n[I+e]=M.a,n[y+e]=M.b}else{let M=um(n[S+e],n[I+e]);g=M.a,x=M.b,M=um(n[R+e],n[y+e]),v=M.a,A=M.b,M=um(g,v),n[S+e]=M.a,n[R+e]=M.b,M=um(x,A),n[I+e]=M.a,n[y+e]=M.b}}if(t&c){let R=S+u,I;o?I=dm(n[S+e],n[R+e]):I=um(n[S+e],n[R+e]),g=I.a,n[R+e]=I.b,n[S+e]=g}}if(r&c){let S=h,E=h+i*(t-f);for(;S<=E;S+=_){let R=S+p,I;o?I=dm(n[S+e],n[R+e]):I=um(n[S+e],n[R+e]),g=I.a,n[R+e]=I.b,n[S+e]=g}}f=c,c>>=1}return h}function sV(n,e,t){for(let i=0;i{og();sg();JU=16,Zne=1<0;){let s=r.getInt8(i++);if(s<0){let a=-s;e-=a+1;for(let o=0;o{});function JC(n){return new DataView(n.array.buffer,n.offset.value,n.size)}function fV(n){let e=n.viewer.buffer.slice(n.offset.value,n.offset.value+n.size),t=new Uint8Array(oV(e)),i=new Uint8Array(t.length);return KC(t),jC(t,i),new DataView(i.buffer)}function ey(n){let e=n.array.slice(n.offset.value,n.offset.value+n.size),t=fflate.unzlibSync(e),i=new Uint8Array(t.length);return KC(t),jC(t,i),new DataView(i.buffer)}function hV(n){let e=n.array.slice(n.offset.value,n.offset.value+n.size),t=fflate.unzlibSync(e),i=n.lines*n.channels*n.width,r=n.type==1?new Uint16Array(i):new Uint32Array(i),s=0,a=0,o=new Array(4);for(let l=0;l=8192)throw new Error("Wrong PIZ_COMPRESSION BITMAP_SIZE");if(o<=l)for(let m=0;m{aV();lV();og();sg()});var Pa,nl,ty=C(()=>{(function(n){n[n.Float=0]="Float",n[n.HalfFloat=1]="HalfFloat"})(Pa||(Pa={}));nl=class{};nl.DefaultOutputType=Pa.HalfFloat;nl.FFLATEUrl="https://unpkg.com/fflate@0.8.2"});async function iy(n,e,t,i){let r={size:0,viewer:e,array:new Uint8Array(e.buffer),offset:t,width:n.dataWindow.xMax-n.dataWindow.xMin+1,height:n.dataWindow.yMax-n.dataWindow.yMin+1,channels:n.channels.length,channelLineOffsets:{},scanOrder:()=>0,bytesPerLine:0,outLineWidth:0,lines:0,scanlineBlockSize:0,inputSize:null,type:0,uncompress:null,getter:()=>0,format:5,outputChannels:0,decodeChannels:{},blockCount:null,byteArray:null,linearSpace:!1,textureType:0};switch(n.compression){case rl.NO_COMPRESSION:r.lines=1,r.uncompress=JC;break;case rl.RLE_COMPRESSION:r.lines=1,r.uncompress=fV;break;case rl.ZIPS_COMPRESSION:r.lines=1,r.uncompress=ey,await pe.LoadScriptAsync(nl.FFLATEUrl);break;case rl.ZIP_COMPRESSION:r.lines=16,r.uncompress=ey,await pe.LoadScriptAsync(nl.FFLATEUrl);break;case rl.PIZ_COMPRESSION:r.lines=32,r.uncompress=dV;break;case rl.PXR24_COMPRESSION:r.lines=16,r.uncompress=hV,await pe.LoadScriptAsync(nl.FFLATEUrl);break;default:throw new Error(rl[n.compression]+" is unsupported")}r.scanlineBlockSize=r.lines;let s={};for(let c of n.channels)switch(c.name){case"R":case"G":case"B":case"A":s[c.name]=!0,r.type=c.pixelType;break;case"Y":s[c.name]=!0,r.type=c.pixelType;break;default:break}let a=!1;if(s.R&&s.G&&s.B&&s.A)r.outputChannels=4,r.decodeChannels={R:0,G:1,B:2,A:3};else if(s.R&&s.G&&s.B)a=!0,r.outputChannels=4,r.decodeChannels={R:0,G:1,B:2,A:3};else if(s.R&&s.G)r.outputChannels=2,r.decodeChannels={R:0,G:1};else if(s.R)r.outputChannels=1,r.decodeChannels={R:0};else if(s.Y)r.outputChannels=1,r.decodeChannels={Y:0};else throw new Error("EXRLoader.parse: file contains unsupported data channels.");if(r.type===1)switch(i){case Pa.Float:r.getter=HU,r.inputSize=2;break;case Pa.HalfFloat:r.getter=hm,r.inputSize=2;break}else if(r.type===2)switch(i){case Pa.Float:r.getter=Sn,r.inputSize=4;break;case Pa.HalfFloat:r.getter=zU,r.inputSize=4}else throw new Error("Unsupported pixelType "+r.type+" for "+n.compression);r.blockCount=r.height/r.scanlineBlockSize;for(let c=0;cc:r.scanOrder=c=>r.height-1-c,r.outputChannels==4?(r.format=5,r.linearSpace=!0):(r.format=6,r.linearSpace=!1),r}function ry(n,e,t,i){let r={value:0};for(let s=0;sn.height?n.height-a:n.scanlineBlockSize;let l=n.size=n.height)continue;let d=c*n.bytesPerLine,u=(n.height-1-h)*n.outLineWidth;for(let m=0;m{og();uV();sg();bi();ty()});var pV={};tt(pV,{ReadExrDataAsync:()=>ise,_ExrTextureLoader:()=>ny});async function ise(n){let e=new DataView(n),t={value:0},i=qC(e,t);try{let r=await iy(i,e,t,Pa.Float);return ry(r,i,e,t),r.byteArray?{width:i.dataWindow.xMax-i.dataWindow.xMin+1,height:i.dataWindow.yMax-i.dataWindow.yMin+1,data:new Float32Array(r.byteArray)}:(te.Error("Failed to decode EXR data: No byte array available."),{width:0,height:0,data:null})}catch(r){te.Error("Failed to load EXR data: ",r)}return{width:0,height:0,data:null}}var ny,_V=C(()=>{YU();mV();ty();yt();ny=class{constructor(){this.supportCascades=!1}loadCubeData(e,t,i,r,s){throw".exr not supported in Cube."}loadData(e,t,i){let r=new DataView(e.buffer),s={value:0},a=qC(r,s);iy(a,r,s,nl.DefaultOutputType).then(o=>{ry(o,a,r,s);let l=a.dataWindow.xMax-a.dataWindow.xMin+1,c=a.dataWindow.yMax-a.dataWindow.yMin+1;i(l,c,t.generateMipMaps,!1,()=>{let f=t.getEngine();t.format=a.format,t.type=o.textureType,t.invertY=!1,t._gammaSpace=!a.linearSpace,o.byteArray&&f._uploadDataToTextureDirectly(t,o.byteArray,0,0,void 0,!0)})}).catch(o=>{te.Error("Failed to load EXR texture: ",o)})}}});function tc(n,e){rse(n)&&te.Warn(`Extension with the name '${n}' already exists`),AA.set(n,e)}function rse(n){return AA.delete(n)}function xA(n,e){(e==="image/ktx"||e==="image/ktx2")&&(n=".ktx"),AA.has(n)||(n.endsWith(".ies")&&tc(".ies",async()=>await Promise.resolve().then(()=>(pB(),mB)).then(i=>new i._IESTextureLoader)),n.endsWith(".dds")&&tc(".dds",async()=>await Promise.resolve().then(()=>(gB(),_B)).then(i=>new i._DDSTextureLoader)),n.endsWith(".basis")&&tc(".basis",async()=>await Promise.resolve().then(()=>(xB(),AB)).then(i=>new i._BasisTextureLoader)),n.endsWith(".env")&&tc(".env",async()=>await Promise.resolve().then(()=>(SU(),EU)).then(i=>new i._ENVTextureLoader)),n.endsWith(".hdr")&&tc(".hdr",async()=>await Promise.resolve().then(()=>(MU(),IU)).then(i=>new i._HDRTextureLoader)),(n.endsWith(".ktx")||n.endsWith(".ktx2"))&&(tc(".ktx",async()=>await Promise.resolve().then(()=>(WC(),kC)).then(i=>new i._KTXTextureLoader)),tc(".ktx2",async()=>await Promise.resolve().then(()=>(WC(),kC)).then(i=>new i._KTXTextureLoader))),n.endsWith(".tga")&&tc(".tga",async()=>await Promise.resolve().then(()=>(VU(),UU)).then(i=>new i._TGATextureLoader)),n.endsWith(".exr")&&tc(".exr",async()=>await Promise.resolve().then(()=>(_V(),pV)).then(i=>new i._ExrTextureLoader)));let t=AA.get(n);return t?Promise.resolve(t(e)):null}var AA,sy=C(()=>{yt();AA=new Map});function gV(n){let e=n.split("?")[0],t=e.lastIndexOf(".");return t>-1?e.substring(t).toLowerCase():""}var vV=C(()=>{});var EV=C(()=>{Es();yt();Hl();B_();wr();sy();vV();Ie.prototype._partialLoadFile=function(n,e,t,i,r=null){let s=o=>{t[e]=o,t._internalCount++,t._internalCount===6&&i(t)},a=(o,l)=>{r&&o&&r(o.status+" "+o.statusText,l)};this._loadFile(n,s,void 0,void 0,!0,a)};Ie.prototype._cascadeLoadFiles=function(n,e,t,i=null){let r=[];r._internalCount=0;for(let s=0;s<6;s++)this._partialLoadFile(t[s],s,r,e,i)};Ie.prototype._cascadeLoadImgs=function(n,e,t,i,r=null,s){let a=[];a._internalCount=0;for(let o=0;o<6;o++)this._partialLoadImg(i[o],o,a,n,e,t,r,s)};Ie.prototype._partialLoadImg=function(n,e,t,i,r,s,a=null,o){let l=cf();am(n,h=>{t[e]=h,t._internalCount++,i&&i.removePendingData(l),t._internalCount===6&&s&&s(r,t)},(h,d)=>{i&&i.removePendingData(l),a&&a(h,d)},i?i.offlineProvider:null,o),i&&i.addPendingData(l)};Ie.prototype.createCubeTextureBase=function(n,e,t,i,r=null,s=null,a,o=null,l=!1,c=0,f=0,h=null,d=null,u=null,m=!1,p=null){let _=h||new yi(this,7);_.isCube=!0,_.url=n,_.generateMipMaps=!i,_._lodGenerationScale=c,_._lodGenerationOffset=f,_._useSRGBBuffer=!!m&&this._caps.supportSRGBBuffers&&(this.version>1||this.isWebGPU||!!i),_!==h&&(_.label=n.substring(0,60)),this._doNotHandleContextLost||(_._extension=o,_._files=t,_._buffer=p);let g=n;this._transformTextureUrl&&!h&&(n=this._transformTextureUrl(n));let v=o!=null?o:gV(n),x=xA(v),A=(E,R)=>{_.dispose(),s?s(E,R):E&&te.Warn(E)},S=(E,R)=>{n===g?E&&A(E.status+" "+E.statusText,R):(te.Warn(`Failed to load ${n}, falling back to the ${g}`),this.createCubeTextureBase(g,e,t,!!i,r,A,a,o,l,c,f,_,d,u,m,p))};if(x)x.then(E=>{let R=I=>{d&&d(_,I),E.loadCubeData(I,_,l,r,(y,M)=>{A(y,M)})};p?R(p):t&&t.length===6?E.supportCascades?this._cascadeLoadFiles(e,I=>R(I.map(y=>new Uint8Array(y))),t,A):A("Textures type does not support cascades."):this._loadFile(n,I=>R(new Uint8Array(I)),void 0,e?e.offlineProvider||null:void 0,!0,S)});else{if(!t||t.length===0)throw new Error("Cannot load cubemap because files were not defined, or the correct loader was not found.");this._cascadeLoadImgs(e,_,(E,R)=>{u&&u(E,R)},t,A)}return this._internalTexturesCache.push(_),_}});var FV={};tt(FV,{DDSTools:()=>ao});function RA(n){return n.charCodeAt(0)+(n.charCodeAt(1)<<8)+(n.charCodeAt(2)<<16)+(n.charCodeAt(3)<<24)}function sse(n){return String.fromCharCode(n&255,n>>8&255,n>>16&255,n>>24&255)}var nse,SV,TV,AV,xV,RV,bV,IV,MV,ay,CV,yV,PV,DV,ase,oy,ose,lse,LV,OV,ly,NV,cy,wV,cse,fse,hse,dse,use,mse,pse,ao,uC=C(()=>{Ln();yt();kM();lC();EV();nse=542327876,SV=131072,TV=512,AV=4,xV=64,RV=131072;bV=RA("DXT1"),IV=RA("DXT3"),MV=RA("DXT5"),ay=RA("DX10"),CV=113,yV=116,PV=2,DV=10,ase=88,oy=31,ose=0,lse=1,LV=2,OV=3,ly=4,NV=7,cy=20,wV=21,cse=22,fse=23,hse=24,dse=25,use=26,mse=28,pse=32,ao=class n{static GetDDSInfo(e){let t=new Int32Array(e.buffer,e.byteOffset,oy),i=new Int32Array(e.buffer,e.byteOffset,oy+4),r=1;t[LV]&SV&&(r=Math.max(1,t[NV]));let s=t[wV],a=s===ay?i[pse]:0,o=0;switch(s){case CV:o=2;break;case yV:o=1;break;case ay:if(a===DV){o=2;break}if(a===PV){o=1;break}}return{width:t[ly],height:t[OV],mipmapCount:r,isFourCC:(t[cy]&AV)===AV,isRGB:(t[cy]&xV)===xV,isLuminance:(t[cy]&RV)===RV,isCube:(t[mse]&TV)===TV,isCompressed:s===bV||s===IV||s===MV,dxgiFormat:a,textureType:o}}static _GetHalfFloatAsFloatRGBAArrayBuffer(e,t,i,r,s,a){let o=new Float32Array(r),l=new Uint16Array(s,i),c=0;for(let f=0;f>8)}static _GetRGBArrayBuffer(e,t,i,r,s,a,o,l){let c=new Uint8Array(r),f=new Uint8Array(s,i),h=0;for(let d=0;d0?r.sphericalPolynomial=zl.ConvertCubeMapToSphericalPolynomial({size:d[ly],right:f[0],left:f[1],up:f[2],down:f[3],front:f[4],back:f[5],format:5,type:1,gammaSpace:!1}):r.sphericalPolynomial=void 0}};ao.StoreLODInAlphaChannel=!1});var BV=C(()=>{Qn();Es();yt();F_();k_();Rt.prototype.createPrefilteredCubeTexture=function(n,e,t,i,r=null,s=null,a,o=null,l=!0){let c=async f=>{var g;if(!f){r&&r(null);return}let h=f.texture;if(l?f.info.sphericalPolynomial&&(h._sphericalPolynomial=f.info.sphericalPolynomial):h._sphericalPolynomial=(g=h._sphericalPolynomial)!=null?g:new $o,h._source=9,this.getCaps().textureLOD){r&&r(h);return}let d=3,u=this._gl,m=f.width;if(!m)return;let{DDSTools:p}=await Promise.resolve().then(()=>(uC(),FV)),_=[];for(let v=0;v{Qn();CT();Rt.prototype.createUniformBuffer=function(n,e){let t=this._gl.createBuffer();if(!t)throw new Error("Unable to create uniform buffer");let i=new qo(t);return this.bindUniformBuffer(i),n instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,n,this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(n),this._gl.STATIC_DRAW),this.bindUniformBuffer(null),i.references=1,i};Rt.prototype.createDynamicUniformBuffer=function(n,e){let t=this._gl.createBuffer();if(!t)throw new Error("Unable to create dynamic uniform buffer");let i=new qo(t);return this.bindUniformBuffer(i),n instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,n,this._gl.DYNAMIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(n),this._gl.DYNAMIC_DRAW),this.bindUniformBuffer(null),i.references=1,i};Rt.prototype.updateUniformBuffer=function(n,e,t,i){this.bindUniformBuffer(n),t===void 0&&(t=0),i===void 0?e instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,t,e):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,t,new Float32Array(e)):e instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,e.subarray(t,t+i)):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,new Float32Array(e).subarray(t,t+i)),this.bindUniformBuffer(null)};Rt.prototype.bindUniformBuffer=function(n){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,n?n.underlyingResource:null)};Rt.prototype.bindUniformBufferBase=function(n,e,t){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,e,n?n.underlyingResource:null)};Rt.prototype.bindUniformBlock=function(n,e,t){let i=n.program,r=this._gl.getUniformBlockIndex(i,e);r!==4294967295&&this._gl.uniformBlockBinding(i,r,t)}});var VV=C(()=>{va();wr();Ie.prototype.displayLoadingUI=function(){if(!cr())return;let n=this.loadingScreen;n&&n.displayLoadingUI()};Ie.prototype.hideLoadingUI=function(){if(!cr())return;let n=this._loadingScreen;n&&n.hideLoadingUI()};Object.defineProperty(Ie.prototype,"loadingScreen",{get:function(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=Ie.DefaultLoadingScreenFactory(this._renderingCanvas)),this._loadingScreen},set:function(n){this._loadingScreen=n},enumerable:!0,configurable:!0});Object.defineProperty(Ie.prototype,"loadingUIText",{set:function(n){this.loadingScreen.loadingUIText=n},enumerable:!0,configurable:!0});Object.defineProperty(Ie.prototype,"loadingUIBackgroundColor",{set:function(n){this.loadingScreen.loadingUIBackgroundColor=n},enumerable:!0,configurable:!0})});var GV=C(()=>{wr();Ie.prototype.getInputElement=function(){return this._renderingCanvas};Ie.prototype.getRenderingCanvasClientRect=function(){return this._renderingCanvas?this._renderingCanvas.getBoundingClientRect():null};Ie.prototype.getInputElementClientRect=function(){return this._renderingCanvas?this.getInputElement().getBoundingClientRect():null};Ie.prototype.getAspectRatio=function(n,e=!1){let t=n.viewport;return this.getRenderWidth(e)*t.width/(this.getRenderHeight(e)*t.height)};Ie.prototype.getScreenAspectRatio=function(){return this.getRenderWidth(!0)/this.getRenderHeight(!0)};Ie.prototype._verifyPointerLock=function(){var n;(n=this._onPointerLockChange)==null||n.call(this)}});var fy=C(()=>{wr();Ie.prototype.setAlphaEquation=function(n,e=0){if(this._alphaEquation[e]!==n){switch(n){case 0:this._alphaState.setAlphaEquationParameters(32774,32774,e);break;case 1:this._alphaState.setAlphaEquationParameters(32778,32778,e);break;case 2:this._alphaState.setAlphaEquationParameters(32779,32779,e);break;case 3:this._alphaState.setAlphaEquationParameters(32776,32776,e);break;case 4:this._alphaState.setAlphaEquationParameters(32775,32775,e);break;case 5:this._alphaState.setAlphaEquationParameters(32775,32774,e);break}this._alphaEquation[e]=n}}});var kV=C(()=>{wr();fy();Ie.prototype.getInputElement=function(){return this._renderingCanvas};Ie.prototype.getDepthFunction=function(){return this._depthCullingState.depthFunc};Ie.prototype.setDepthFunction=function(n){this._depthCullingState.depthFunc=n};Ie.prototype.setDepthFunctionToGreater=function(){this.setDepthFunction(516)};Ie.prototype.setDepthFunctionToGreaterOrEqual=function(){this.setDepthFunction(518)};Ie.prototype.setDepthFunctionToLess=function(){this.setDepthFunction(513)};Ie.prototype.setDepthFunctionToLessOrEqual=function(){this.setDepthFunction(515)};Ie.prototype.getDepthWrite=function(){return this._depthCullingState.depthMask};Ie.prototype.setDepthWrite=function(n){this._depthCullingState.depthMask=n};Ie.prototype.setAlphaConstants=function(n,e,t,i){this._alphaState.setAlphaBlendConstants(n,e,t,i)};Ie.prototype.getAlphaMode=function(n=0){return this._alphaMode[n]};Ie.prototype.getAlphaEquation=function(n=0){return this._alphaEquation[n]}});var WV=C(()=>{wr();fy();Ie.prototype.getStencilBuffer=function(){return this._stencilState.stencilTest};Ie.prototype.setStencilBuffer=function(n){this._stencilState.stencilTest=n};Ie.prototype.getStencilMask=function(){return this._stencilState.stencilMask};Ie.prototype.setStencilMask=function(n){this._stencilState.stencilMask=n};Ie.prototype.getStencilFunction=function(){return this._stencilState.stencilFunc};Ie.prototype.getStencilBackFunction=function(){return this._stencilState.stencilBackFunc};Ie.prototype.getStencilFunctionReference=function(){return this._stencilState.stencilFuncRef};Ie.prototype.getStencilFunctionMask=function(){return this._stencilState.stencilFuncMask};Ie.prototype.setStencilFunction=function(n){this._stencilState.stencilFunc=n};Ie.prototype.setStencilBackFunction=function(n){this._stencilState.stencilBackFunc=n};Ie.prototype.setStencilFunctionReference=function(n){this._stencilState.stencilFuncRef=n};Ie.prototype.setStencilFunctionMask=function(n){this._stencilState.stencilFuncMask=n};Ie.prototype.getStencilOperationFail=function(){return this._stencilState.stencilOpStencilFail};Ie.prototype.getStencilBackOperationFail=function(){return this._stencilState.stencilBackOpStencilFail};Ie.prototype.getStencilOperationDepthFail=function(){return this._stencilState.stencilOpDepthFail};Ie.prototype.getStencilBackOperationDepthFail=function(){return this._stencilState.stencilBackOpDepthFail};Ie.prototype.getStencilOperationPass=function(){return this._stencilState.stencilOpStencilDepthPass};Ie.prototype.getStencilBackOperationPass=function(){return this._stencilState.stencilBackOpStencilDepthPass};Ie.prototype.setStencilOperationFail=function(n){this._stencilState.stencilOpStencilFail=n};Ie.prototype.setStencilBackOperationFail=function(n){this._stencilState.stencilBackOpStencilFail=n};Ie.prototype.setStencilOperationDepthFail=function(n){this._stencilState.stencilOpDepthFail=n};Ie.prototype.setStencilBackOperationDepthFail=function(n){this._stencilState.stencilBackOpDepthFail=n};Ie.prototype.setStencilOperationPass=function(n){this._stencilState.stencilOpStencilDepthPass=n};Ie.prototype.setStencilBackOperationPass=function(n){this._stencilState.stencilBackOpStencilDepthPass=n};Ie.prototype.cacheStencilState=function(){this._cachedStencilBuffer=this.getStencilBuffer(),this._cachedStencilFunction=this.getStencilFunction(),this._cachedStencilMask=this.getStencilMask(),this._cachedStencilOperationPass=this.getStencilOperationPass(),this._cachedStencilOperationFail=this.getStencilOperationFail(),this._cachedStencilOperationDepthFail=this.getStencilOperationDepthFail(),this._cachedStencilReference=this.getStencilFunctionReference()};Ie.prototype.restoreStencilState=function(){this.setStencilFunction(this._cachedStencilFunction),this.setStencilMask(this._cachedStencilMask),this.setStencilBuffer(this._cachedStencilBuffer),this.setStencilOperationPass(this._cachedStencilOperationPass),this.setStencilOperationFail(this._cachedStencilOperationFail),this.setStencilOperationDepthFail(this._cachedStencilOperationDepthFail),this.setStencilFunctionReference(this._cachedStencilReference)}});var HV=C(()=>{wr();Ie.prototype.getRenderPassNames=function(){return this._renderPassNames};Ie.prototype.getCurrentRenderPassName=function(){return this._renderPassNames[this.currentRenderPassId]};Ie.prototype.createRenderPassId=function(n){let e=++Ie._RenderPassIdCounter;return this._renderPassNames[e]=n!=null?n:"NONAME",e};Ie.prototype.releaseRenderPassId=function(n){this._renderPassNames[n]=void 0;for(let e=0;e{wr();Ie.prototype._loadFileAsync=async function(n,e,t){return await new Promise((i,r)=>{this._loadFile(n,s=>{i(s)},void 0,e,t,(s,a)=>{r(a)})})}});var XV=C(()=>{sy();wr();Ie.GetCompatibleTextureLoader=xA});function _se(n){!n||!n.setAttribute||(n.setAttribute("touch-action","none"),n.style.touchAction="none",n.style.webkitTapHighlightColor="transparent")}function YV(n,e,t){n._onCanvasFocus=()=>{n.onCanvasFocusObservable.notifyObservers(n)},n._onCanvasBlur=()=>{n.onCanvasBlurObservable.notifyObservers(n)},n._onCanvasContextMenu=r=>{n.disableContextMenu&&r.preventDefault()},e.addEventListener("focus",n._onCanvasFocus),e.addEventListener("blur",n._onCanvasBlur),e.addEventListener("contextmenu",n._onCanvasContextMenu),n._onBlur=()=>{n.disablePerformanceMonitorInBackground&&n.performanceMonitor.disable(),n._windowIsBackground=!0},n._onFocus=()=>{n.disablePerformanceMonitorInBackground&&n.performanceMonitor.enable(),n._windowIsBackground=!1},n._onCanvasPointerOut=r=>{document.elementFromPoint(r.clientX,r.clientY)!==e&&n.onCanvasPointerOutObservable.notifyObservers(r)};let i=n.getHostWindow();i&&typeof i.addEventListener=="function"&&(i.addEventListener("blur",n._onBlur),i.addEventListener("focus",n._onFocus)),e.addEventListener("pointerout",n._onCanvasPointerOut),t.doNotHandleTouchAction||_se(e),!Ie.audioEngine&&t.audioEngine&&Ie.AudioEngineFactory&&(Ie.audioEngine=Ie.AudioEngineFactory(n.getRenderingCanvas(),n.getAudioContext(),n.getAudioDestination())),af()&&(n._onFullscreenChange=()=>{n.isFullscreen=!!document.fullscreenElement,n.isFullscreen&&n._pointerLockRequested&&e&&hy(e)},document.addEventListener("fullscreenchange",n._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",n._onFullscreenChange,!1),n._onPointerLockChange=()=>{n.isPointerLock=document.pointerLockElement===e},document.addEventListener("pointerlockchange",n._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",n._onPointerLockChange,!1)),n.enableOfflineSupport=Ie.OfflineProviderFactory!==void 0,n._deterministicLockstep=!!t.deterministicLockstep,n._lockstepMaxSteps=t.lockstepMaxSteps||0,n._timeStep=t.timeStep||1/60}function KV(n,e){Le.Instances.length===1&&Ie.audioEngine&&(Ie.audioEngine.dispose(),Ie.audioEngine=null);let t=n.getHostWindow();t&&typeof t.removeEventListener=="function"&&(t.removeEventListener("blur",n._onBlur),t.removeEventListener("focus",n._onFocus)),e&&(e.removeEventListener("focus",n._onCanvasFocus),e.removeEventListener("blur",n._onCanvasBlur),e.removeEventListener("pointerout",n._onCanvasPointerOut),e.removeEventListener("contextmenu",n._onCanvasContextMenu)),af()&&(document.removeEventListener("fullscreenchange",n._onFullscreenChange),document.removeEventListener("mozfullscreenchange",n._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",n._onFullscreenChange),document.removeEventListener("msfullscreenchange",n._onFullscreenChange),document.removeEventListener("pointerlockchange",n._onPointerLockChange),document.removeEventListener("mspointerlockchange",n._onPointerLockChange),document.removeEventListener("mozpointerlockchange",n._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",n._onPointerLockChange))}function jV(n){let e=document.createElement("span");e.textContent="Hg",e.style.font=n;let t=document.createElement("div");t.style.display="inline-block",t.style.width="1px",t.style.height="0px",t.style.verticalAlign="bottom";let i=document.createElement("div");i.style.whiteSpace="nowrap",i.appendChild(e),i.appendChild(t),document.body.appendChild(i);let r,s;try{s=t.getBoundingClientRect().top-e.getBoundingClientRect().top,t.style.verticalAlign="baseline",r=t.getBoundingClientRect().top-e.getBoundingClientRect().top}finally{document.body.removeChild(i)}return{ascent:r,height:s,descent:s-r}}async function qV(n,e,t){return await new Promise((i,r)=>{let s=new Image;s.onload=()=>{s.decode().then(()=>{n.createImageBitmap(s,t).then(a=>{i(a)})})},s.onerror=()=>{r(`Error loading image ${s.src}`)},s.src=e})}function ZV(n,e,t,i){let s=n.createCanvas(t,i).getContext("2d");if(!s)throw new Error("Unable to get 2d context for resizeImageBitmap");return s.drawImage(e,0,0),s.getImageData(0,0,t,i).data}function QV(n){let e=n.requestFullscreen||n.webkitRequestFullscreen;e&&e.call(n)}function $V(){let n=document;document.exitFullscreen?document.exitFullscreen():n.webkitCancelFullScreen&&n.webkitCancelFullScreen()}function hy(n){if(n.requestPointerLock){let e=n.requestPointerLock();e instanceof Promise?e.then(()=>{n.focus()}).catch(()=>{}):n.focus()}}function JV(){document.exitPointerLock&&document.exitPointerLock()}var eG=C(()=>{va();wr();Pi()});var Ue,dy=C(()=>{Es();Pi();Qn();Q3();CT();yt();MM();$3();i2();r2();n2();s2();l2();c2();f2();BV();UV();VV();GV();kV();WV();HV();DM();zV();XV();wr();eG();RC();jo();Ue=class n extends Rt{static get NpmPackage(){return Ie.NpmPackage}static get Version(){return Ie.Version}static get Instances(){return Le.Instances}static get LastCreatedEngine(){return Le.LastCreatedEngine}static get LastCreatedScene(){return Le.LastCreatedScene}static DefaultLoadingScreenFactory(e){return Ie.DefaultLoadingScreenFactory(e)}get _supportsHardwareTextureRescaling(){return!!n._RescalePostProcessFactory}_measureFps(){this._performanceMonitor.sampleFrame(),this._fps=this._performanceMonitor.averageFPS,this._deltaTime=this._performanceMonitor.instantaneousFrameTime||0}get performanceMonitor(){return this._performanceMonitor}constructor(e,t,i,r=!1){super(e,t,i,r),this.customAnimationFrameRequester=null,this._performanceMonitor=new PT,this._drawCalls=new il,e&&(this._features.supportRenderPasses=!0)}_initGLContext(){super._initGLContext(),this._rescalePostProcess=null}_sharedInit(e){super._sharedInit(e),YV(this,e,this._creationOptions)}resizeImageBitmap(e,t,i){return ZV(this,e,t,i)}async _createImageBitmapFromSource(e,t){return await qV(this,e,t)}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&QV(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&$V()}setDitheringState(e){e?this._gl.enable(this._gl.DITHER):this._gl.disable(this._gl.DITHER)}setRasterizerState(e){e?this._gl.disable(this._gl.RASTERIZER_DISCARD):this._gl.enable(this._gl.RASTERIZER_DISCARD)}setDirectViewport(e,t,i,r){let s=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,r),s}scissorClear(e,t,i,r,s){this.enableScissor(e,t,i,r),this.clear(s,!0,!0,!0),this.disableScissor()}enableScissor(e,t,i,r){let s=this._gl;s.enable(s.SCISSOR_TEST),s.scissor(e,t,i,r)}disableScissor(){let e=this._gl;e.disable(e.SCISSOR_TEST)}getVertexShaderSource(e){let t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[0]):null}getFragmentShaderSource(e){let t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[1]):null}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e,this._framebufferDimensionsObject&&this.onResizeObservable.notifyObservers(this)}_rebuildBuffers(){for(let e of this.scenes)e.resetCachedMaterial(),e._rebuildGeometries();for(let e of this._virtualScenes)e.resetCachedMaterial(),e._rebuildGeometries();super._rebuildBuffers()}getFontOffset(e){return jV(e)}_cancelFrame(){if(this.customAnimationFrameRequester){if(this._frameHandler!==0){this._frameHandler=0;let{cancelAnimationFrame:e}=this.customAnimationFrameRequester;e&&e(this.customAnimationFrameRequester.requestID)}}else super._cancelFrame()}_renderLoop(e){this._processFrame(e),this._activeRenderLoops.length>0&&this._frameHandler===0&&(this.customAnimationFrameRequester?(this.customAnimationFrameRequester.requestID=this._queueNewFrame(this.customAnimationFrameRequester.renderFunction||this._boundRenderFunction,this.customAnimationFrameRequester),this._frameHandler=this.customAnimationFrameRequester.requestID):this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()))}enterPointerlock(){this._renderingCanvas&&hy(this._renderingCanvas)}exitPointerlock(){JV()}beginFrame(){this._measureFps(),super.beginFrame()}_deletePipelineContext(e){let t=e;t&&t.program&&t.transformFeedback&&(this.deleteTransformFeedback(t.transformFeedback),t.transformFeedback=null),super._deletePipelineContext(e)}createShaderProgram(e,t,i,r,s,a=null){s=s||this._gl,this.onBeforeShaderCompilationObservable.notifyObservers(this);let o=super.createShaderProgram(e,t,i,r,s,a);return this.onAfterShaderCompilationObservable.notifyObservers(this),o}_createShaderProgram(e,t,i,r,s=null){let a=r.createProgram();if(e.program=a,!a)throw new Error("Unable to create program");if(r.attachShader(a,t),r.attachShader(a,i),this.webGLVersion>1&&s){let o=this.createTransformFeedback();this.bindTransformFeedback(o),this.setTranformFeedbackVaryings(a,s),e.transformFeedback=o}return r.linkProgram(a),this.webGLVersion>1&&s&&this.bindTransformFeedback(null),e.context=r,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),a}_releaseTexture(e){super._releaseTexture(e)}_releaseRenderTargetWrapper(e){super._releaseRenderTargetWrapper(e);for(let t of this.scenes){for(let i of t.postProcesses)i._outputTexture===e&&(i._outputTexture=null);for(let i of t.cameras)for(let r of i._postProcesses)r&&r._outputTexture===e&&(r._outputTexture=null)}}_rescaleTexture(e,t,i,r,s){this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._gl.CLAMP_TO_EDGE),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._gl.CLAMP_TO_EDGE);let a=this.createRenderTargetTexture({width:t.width,height:t.height},{generateMipMaps:!1,type:0,samplingMode:2,generateDepthBuffer:!1,generateStencilBuffer:!1});if(!this._rescalePostProcess&&n._RescalePostProcessFactory&&(this._rescalePostProcess=n._RescalePostProcessFactory(this)),this._rescalePostProcess){this._rescalePostProcess.externalTextureSamplerBinding=!0;let o=()=>{this._rescalePostProcess.onApply=function(f){f._bindTexture("textureSampler",e)};let c=i;c||(c=this.scenes[this.scenes.length-1]),c.postProcessManager.directRender([this._rescalePostProcess],a,!0),this._bindTextureDirectly(this._gl.TEXTURE_2D,t,!0),this._gl.copyTexImage2D(this._gl.TEXTURE_2D,0,r,0,0,t.width,t.height,0),this.unBindFramebuffer(a),a.dispose(),s&&s()},l=this._rescalePostProcess.getEffect();l?l.executeWhenCompiled(o):this._rescalePostProcess.onEffectCreatedObservable.addOnce(c=>{c.executeWhenCompiled(o)})}}wrapWebGLTexture(e,t=!1,i=3,r=0,s=0){let a=new Wu(e,this._gl),o=new yi(this,0,!0);return o._hardwareTexture=a,o.baseWidth=r,o.baseHeight=s,o.width=r,o.height=s,o.isReady=!0,o.useMipMaps=t,this.updateTextureSamplingMode(i,o),o}_uploadImageToTexture(e,t,i=0,r=0){let s=this._gl,a=this._getWebGLTextureType(e.type),o=this._getInternalFormat(e.format),l=this._getRGBABufferInternalSizedFormat(e.type,o),c=e.isCube?s.TEXTURE_CUBE_MAP:s.TEXTURE_2D;this._bindTextureDirectly(c,e,!0),this._unpackFlipY(e.invertY);let f=s.TEXTURE_2D;e.isCube&&(f=s.TEXTURE_CUBE_MAP_POSITIVE_X+i),s.texImage2D(f,r,l,o,a,t),this._bindTextureDirectly(c,null,!0)}updateTextureComparisonFunction(e,t){if(this.webGLVersion===1){te.Error("WebGL 1 does not support texture comparison.");return}let i=this._gl;e.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,e,!0),t===0?(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):(this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),t===0?(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)),e._comparisonFunction=t}createInstancesBuffer(e){let t=this._gl.createBuffer();if(!t)throw new Error("Unable to create instance buffer");let i=new qo(t);return i.capacity=e,this.bindArrayBuffer(i),this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW),i.references=1,i}deleteInstancesBuffer(e){this._gl.deleteBuffer(e)}async _clientWaitAsync(e,t=0,i=10){let r=this._gl;return await new Promise((s,a)=>{Ko(()=>{let o=r.clientWaitSync(e,t,0);if(o==r.WAIT_FAILED)throw new Error("clientWaitSync failed");return o!=r.TIMEOUT_EXPIRED},s,a,i)})}_readPixelsAsync(e,t,i,r,s,a,o){if(this._webGLVersion<2)throw new Error("_readPixelsAsync only work on WebGL2+");let l=this._gl,c=l.createBuffer();l.bindBuffer(l.PIXEL_PACK_BUFFER,c),l.bufferData(l.PIXEL_PACK_BUFFER,o.byteLength,l.STREAM_READ),l.readPixels(e,t,i,r,s,a,0),l.bindBuffer(l.PIXEL_PACK_BUFFER,null);let f=l.fenceSync(l.SYNC_GPU_COMMANDS_COMPLETE,0);return f?(l.flush(),this._clientWaitAsync(f,0,10).then(()=>(l.deleteSync(f),l.bindBuffer(l.PIXEL_PACK_BUFFER,c),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,o),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),l.deleteBuffer(c),o))):null}dispose(){this.hideLoadingUI(),this._rescalePostProcess&&this._rescalePostProcess.dispose(),KV(this,this._renderingCanvas),super.dispose()}};Ue.ALPHA_DISABLE=0;Ue.ALPHA_ADD=1;Ue.ALPHA_COMBINE=2;Ue.ALPHA_SUBTRACT=3;Ue.ALPHA_MULTIPLY=4;Ue.ALPHA_MAXIMIZED=5;Ue.ALPHA_ONEONE=6;Ue.ALPHA_PREMULTIPLIED=7;Ue.ALPHA_PREMULTIPLIED_PORTERDUFF=8;Ue.ALPHA_INTERPOLATE=9;Ue.ALPHA_SCREENMODE=10;Ue.DELAYLOADSTATE_NONE=0;Ue.DELAYLOADSTATE_LOADED=1;Ue.DELAYLOADSTATE_LOADING=2;Ue.DELAYLOADSTATE_NOTLOADED=4;Ue.NEVER=512;Ue.ALWAYS=519;Ue.LESS=513;Ue.EQUAL=514;Ue.LEQUAL=515;Ue.GREATER=516;Ue.GEQUAL=518;Ue.NOTEQUAL=517;Ue.KEEP=7680;Ue.REPLACE=7681;Ue.INCR=7682;Ue.DECR=7683;Ue.INVERT=5386;Ue.INCR_WRAP=34055;Ue.DECR_WRAP=34056;Ue.TEXTURE_CLAMP_ADDRESSMODE=0;Ue.TEXTURE_WRAP_ADDRESSMODE=1;Ue.TEXTURE_MIRROR_ADDRESSMODE=2;Ue.TEXTUREFORMAT_ALPHA=0;Ue.TEXTUREFORMAT_LUMINANCE=1;Ue.TEXTUREFORMAT_LUMINANCE_ALPHA=2;Ue.TEXTUREFORMAT_RGB=4;Ue.TEXTUREFORMAT_RGBA=5;Ue.TEXTUREFORMAT_RED=6;Ue.TEXTUREFORMAT_R=6;Ue.TEXTUREFORMAT_R16_UNORM=33322;Ue.TEXTUREFORMAT_RG16_UNORM=33324;Ue.TEXTUREFORMAT_RGB16_UNORM=32852;Ue.TEXTUREFORMAT_RGBA16_UNORM=32859;Ue.TEXTUREFORMAT_R16_SNORM=36760;Ue.TEXTUREFORMAT_RG16_SNORM=36761;Ue.TEXTUREFORMAT_RGB16_SNORM=36762;Ue.TEXTUREFORMAT_RGBA16_SNORM=36763;Ue.TEXTUREFORMAT_RG=7;Ue.TEXTUREFORMAT_RED_INTEGER=8;Ue.TEXTUREFORMAT_R_INTEGER=8;Ue.TEXTUREFORMAT_RG_INTEGER=9;Ue.TEXTUREFORMAT_RGB_INTEGER=10;Ue.TEXTUREFORMAT_RGBA_INTEGER=11;Ue.TEXTURETYPE_UNSIGNED_BYTE=0;Ue.TEXTURETYPE_UNSIGNED_INT=0;Ue.TEXTURETYPE_FLOAT=1;Ue.TEXTURETYPE_HALF_FLOAT=2;Ue.TEXTURETYPE_BYTE=3;Ue.TEXTURETYPE_SHORT=4;Ue.TEXTURETYPE_UNSIGNED_SHORT=5;Ue.TEXTURETYPE_INT=6;Ue.TEXTURETYPE_UNSIGNED_INTEGER=7;Ue.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8;Ue.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9;Ue.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10;Ue.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11;Ue.TEXTURETYPE_UNSIGNED_INT_24_8=12;Ue.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13;Ue.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14;Ue.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15;Ue.TEXTURE_NEAREST_SAMPLINGMODE=1;Ue.TEXTURE_BILINEAR_SAMPLINGMODE=2;Ue.TEXTURE_TRILINEAR_SAMPLINGMODE=3;Ue.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8;Ue.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11;Ue.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3;Ue.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4;Ue.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5;Ue.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6;Ue.TEXTURE_NEAREST_LINEAR=7;Ue.TEXTURE_NEAREST_NEAREST=1;Ue.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9;Ue.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10;Ue.TEXTURE_LINEAR_LINEAR=2;Ue.TEXTURE_LINEAR_NEAREST=12;Ue.TEXTURE_EXPLICIT_MODE=0;Ue.TEXTURE_SPHERICAL_MODE=1;Ue.TEXTURE_PLANAR_MODE=2;Ue.TEXTURE_CUBIC_MODE=3;Ue.TEXTURE_PROJECTION_MODE=4;Ue.TEXTURE_SKYBOX_MODE=5;Ue.TEXTURE_INVCUBIC_MODE=6;Ue.TEXTURE_EQUIRECTANGULAR_MODE=7;Ue.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8;Ue.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;Ue.SCALEMODE_FLOOR=1;Ue.SCALEMODE_NEAREST=2;Ue.SCALEMODE_CEILING=3});var uy,_i,qs=C(()=>{Gt();Ve();Ut();hi();Pi();hn();Tr();uy=class{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new ie,this._onClonedObservable=new ie,this._inheritVisibility=!1,this._isVisible=!0}},_i=class n{static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,i,r){let s=this._NodeConstructors[e];return s?s(t,i,r):null}set accessibilityTag(e){this._accessibilityTag=e,this.onAccessibilityTagChangedObservable.notifyObservers(e)}get accessibilityTag(){return this._accessibilityTag}get doNotSerialize(){return this._nodeDataStorage._doNotSerialize?!0:this._parentNode?this._parentNode.doNotSerialize:!1}set doNotSerialize(e){this._nodeDataStorage._doNotSerialize=e}isDisposed(){return this._nodeDataStorage._isDisposed}set parent(e){if(this._parentNode===e)return;let t=this._parentNode;if(this._parentNode&&this._parentNode._children!==void 0&&this._parentNode._children!==null){let i=this._parentNode._children.indexOf(this);i!==-1&&this._parentNode._children.splice(i,1),!e&&!this._nodeDataStorage._isDisposed&&this._addToSceneRootNodes()}this._parentNode=e,this._isDirty=!0,this._parentNode&&((this._parentNode._children===void 0||this._parentNode._children===null)&&(this._parentNode._children=new Array),this._parentNode._children.push(this),t||this._removeFromSceneRootNodes()),this._syncParentEnabledState()}get parent(){return this._parentNode}get inheritVisibility(){return this._nodeDataStorage._inheritVisibility}set inheritVisibility(e){this._nodeDataStorage._inheritVisibility=e}get isVisible(){return this.inheritVisibility&&this._parentNode&&!this._parentNode.isVisible?!1:this._nodeDataStorage._isVisible}set isVisible(e){this._nodeDataStorage._isVisible=e}_serializeAsParent(e){e.parentId=this.uniqueId}_addToSceneRootNodes(){this._nodeDataStorage._sceneRootNodesIndex===-1&&(this._nodeDataStorage._sceneRootNodesIndex=this._scene.rootNodes.length,this._scene.rootNodes.push(this))}_removeFromSceneRootNodes(){if(this._nodeDataStorage._sceneRootNodesIndex!==-1){let e=this._scene.rootNodes,t=e.length-1;e[this._nodeDataStorage._sceneRootNodesIndex]=e[t],e[this._nodeDataStorage._sceneRootNodesIndex]._nodeDataStorage._sceneRootNodesIndex=this._nodeDataStorage._sceneRootNodesIndex,this._scene.rootNodes.pop(),this._nodeDataStorage._sceneRootNodesIndex=-1}}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}getClassName(){return"Node"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get onEnabledStateChangedObservable(){return this._nodeDataStorage._onEnabledStateChangedObservable}get onClonedObservable(){return this._nodeDataStorage._onClonedObservable}constructor(e,t=null,i=!0){this._isDirty=!1,this._nodeDataStorage=new uy,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new ie,this._parentContainer=null,this.animations=[],this._ranges={},this.onReady=null,this._currentRenderId=-1,this._parentUpdateId=-1,this._childUpdateId=-1,this._waitingParentId=null,this._waitingParentInstanceIndex=null,this._waitingParsedUniqueId=null,this._cache={},this._parentNode=null,this._children=null,this._worldMatrix=j.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new ie,this._onDisposeObserver=null,this._behaviors=new Array,this.name=e,this.id=e,this._scene=t||Le.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache(),i&&this._addToSceneRootNodes()}getScene(){return this._scene}getEngine(){return this._scene.getEngine()}addBehavior(e,t=!1){return this._behaviors.indexOf(e)!==-1?this:(e.init(),this._scene.isLoading&&!t?this._scene.onDataLoadedObservable.addOnce(()=>{this._behaviors.includes(e)&&e.attach(this)}):e.attach(this),this._behaviors.push(e),this)}removeBehavior(e){let t=this._behaviors.indexOf(e);return t===-1?this:(this._behaviors[t].detach(),this._behaviors.splice(t,1),this)}get behaviors(){return this._behaviors}getBehaviorByName(e){for(let t of this._behaviors)if(t.name===e)return t;return null}getWorldMatrix(){return this._currentRenderId!==this._scene.getRenderId()&&this.computeWorldMatrix(),this._worldMatrix}_getWorldMatrixDeterminant(){return this._worldMatrixDeterminantIsDirty&&(this._worldMatrixDeterminantIsDirty=!1,this._worldMatrixDeterminant=this._worldMatrix.determinant()),this._worldMatrixDeterminant}get worldMatrixFromCache(){return this._worldMatrix}_initCache(){this._cache={}}updateCache(e){!e&&this.isSynchronized()||this._updateCache()}_getActionManagerForTrigger(e,t=!0){return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_updateCache(e){}_isSynchronized(){return!0}_markSyncedWithParent(){this._parentNode&&(this._parentUpdateId=this._parentNode._childUpdateId)}isSynchronizedWithParent(){return this._parentNode?this._parentNode._isDirty||this._parentUpdateId!==this._parentNode._childUpdateId?!1:this._parentNode.isSynchronized():!0}isSynchronized(){return this._parentNode&&!this.isSynchronizedWithParent()?!1:this._isSynchronized()}isReady(e=!1){return this._nodeDataStorage._isReady}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}isEnabled(e=!0){return e===!1?this._nodeDataStorage._isEnabled:this._nodeDataStorage._isEnabled?this._nodeDataStorage._isParentEnabled:!1}_syncParentEnabledState(){if(this._nodeDataStorage._isParentEnabled=this._parentNode?this._parentNode.isEnabled():!0,this._children)for(let e of this._children)e._syncParentEnabledState()}setEnabled(e){this._nodeDataStorage._isEnabled!==e&&(this._nodeDataStorage._isEnabled=e,this._syncParentEnabledState(),this._nodeDataStorage._onEnabledStateChangedObservable.notifyObservers(e))}isDescendantOf(e){return this.parent?this.parent===e?!0:this.parent.isDescendantOf(e):!1}_getDescendants(e,t=!1,i){if(this._children)for(let r=0;r(!t||t(r))&&r.cullingStrategy!==void 0),i}getChildren(e,t=!0){return this.getDescendants(t,e)}_setReady(e){if(e!==this._nodeDataStorage._isReady){if(!e){this._nodeDataStorage._isReady=!1;return}this.onReady&&this.onReady(this),this._nodeDataStorage._isReady=!0}}getAnimationByName(e){for(let t=0;tnew n(e,this.getScene()),this);if(t&&(r.parent=t),!i){let s=this.getDescendants(!0);for(let a=0;a{throw Ze("AnimationRange")};_i._NodeConstructors={};P([w()],_i.prototype,"name",void 0);P([w()],_i.prototype,"id",void 0);P([w()],_i.prototype,"uniqueId",void 0);P([w()],_i.prototype,"state",void 0);P([w()],_i.prototype,"metadata",void 0)});function my(n,e,t){try{let i=n.next();i.done?e(i):i.value?i.value.then(()=>{i.value=void 0,e(i)},t):e(i)}catch(i){t(i)}}function tG(n=25){let e;return(t,i,r)=>{let s=performance.now();e===void 0||s-e>n?(e=s,setTimeout(()=>{my(t,i,r)},0)):my(t,i,r)}}function iG(n,e,t,i,r){let s=()=>{let a,o=l=>{l.done?t(l.value):a===void 0?a=!0:s()};do a=void 0,!r||!r.aborted?e(n,o,i):i(new Error("Aborted")),a===void 0&&(a=!1);while(a)};s()}function fg(n,e){let t;return iG(n,my,i=>t=i,i=>{throw i},e),t}async function rG(n,e,t){return await new Promise((i,r)=>{iG(n,e,i,r,t)})}function nG(n,e){return(...t)=>fg(n(...t),e)}var py=C(()=>{});var ut,sl=C(()=>{Gt();Ut();so();bi();hi();Ve();qs();yt();Hi();hn();Ju();wT();Tr();ut=class n extends _i{get position(){return this._position}set position(e){this._position=e}set upVector(e){this._upVector=e}get upVector(){return this._upVector}get screenArea(){var i,r,s,a;let e,t;if(this.mode===n.PERSPECTIVE_CAMERA)this.fovMode===n.FOVMODE_VERTICAL_FIXED?(t=this.minZ*2*Math.tan(this.fov/2),e=this.getEngine().getAspectRatio(this)*t):(e=this.minZ*2*Math.tan(this.fov/2),t=e/this.getEngine().getAspectRatio(this));else{let o=this.getEngine().getRenderWidth()/2,l=this.getEngine().getRenderHeight()/2;e=((i=this.orthoRight)!=null?i:o)-((r=this.orthoLeft)!=null?r:-o),t=((s=this.orthoTop)!=null?s:l)-((a=this.orthoBottom)!=null?a:-l)}return e*t}set orthoLeft(e){this._orthoLeft=e;for(let t of this._rigCameras)t.orthoLeft=e}get orthoLeft(){return this._orthoLeft}set orthoRight(e){this._orthoRight=e;for(let t of this._rigCameras)t.orthoRight=e}get orthoRight(){return this._orthoRight}set orthoBottom(e){this._orthoBottom=e;for(let t of this._rigCameras)t.orthoBottom=e}get orthoBottom(){return this._orthoBottom}set orthoTop(e){this._orthoTop=e;for(let t of this._rigCameras)t.orthoTop=e}get orthoTop(){return this._orthoTop}setFocalLength(e,t=36){this.fov=2*Math.atan(t/(2*e))}set mode(e){this._mode=e;for(let t of this._rigCameras)t.mode=e}get mode(){return this._mode}get hasMoved(){return this._hasMoved}constructor(e,t,i,r=!0){super(e,i,!1),this._position=b.Zero(),this._upVector=b.Up(),this.oblique=null,this._orthoLeft=null,this._orthoRight=null,this._orthoBottom=null,this._orthoTop=null,this.fov=.8,this.projectionPlaneTilt=0,this.minZ=1,this.maxZ=1e4,this.inertia=.9,this._mode=n.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new io(0,0,1,1),this.layerMask=268435455,this.fovMode=n.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=n.RIG_MODE_NONE,this.ignoreCameraMaxZ=!1,this.customRenderTargets=[],this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new ie,this.onProjectionMatrixChangedObservable=new ie,this.onAfterCheckInputsObservable=new ie,this.onRestoreStateObservable=new ie,this.isRigCamera=!1,this._hasMoved=!1,this._rigCameras=new Array,this._skipRendering=!1,this._projectionMatrix=new j,this._postProcesses=new Array,this._activeMeshes=new wi(256),this._globalPosition=b.Zero(),this._computedViewMatrix=j.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=j.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=Ye.Identity(),this._isCamera=!0,this._isLeftCamera=!1,this._isRightCamera=!1,this.layerMask=this.getScene().defaultCameraLayerMask,this.getScene().addCamera(this),r&&!this.getScene().activeCamera&&(this.getScene().activeCamera=this),this.position=t,this.renderPassId=this.getScene().getEngine().createRenderPassId(`Camera ${e}`)}storeState(){return this._stateStored=!0,this._storedFov=this.fov,this}hasStateStored(){return!!this._stateStored}_restoreStateValues(){return this._stateStored?(this.fov=this._storedFov,!0):!1}restoreState(){return this._restoreStateValues()?(this.onRestoreStateObservable.notifyObservers(this),!0):!1}getClassName(){return"Camera"}toString(e){let t="Name: "+this.name;if(t+=", type: "+this.getClassName(),this.animations)for(let i=0;i-1?(te.Error("You're trying to reuse a post process not defined as reusable."),0):(t==null||t<0?this._postProcesses.push(e):this._postProcesses[t]===null?this._postProcesses[t]=e:this._postProcesses.splice(t,0,e),this._cascadePostProcessesToRigCams(),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._postProcesses.indexOf(e))}detachPostProcess(e){let t=this._postProcesses.indexOf(e);t!==-1&&(this._postProcesses[t]=null),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._cascadePostProcessesToRigCams()}getWorldMatrix(){return this._isSynchronizedViewMatrix()?this._worldMatrix:(this.getViewMatrix(),this._worldMatrix)}_getViewMatrix(){return j.Identity()}getViewMatrix(e){return!e&&this._isSynchronizedViewMatrix()?this._computedViewMatrix:(this._hasMoved=!0,this.updateCache(),this._computedViewMatrix=this._getViewMatrix(),this._currentRenderId=this.getScene().getRenderId(),this._childUpdateId++,this._refreshFrustumPlanes=!0,this._cameraRigParams&&this._cameraRigParams.vrPreViewMatrix&&this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix,this._computedViewMatrix),this.parent&&this.parent.onViewMatrixChangedObservable&&this.parent.onViewMatrixChangedObservable.notifyObservers(this.parent),this.onViewMatrixChangedObservable.notifyObservers(this),this._computedViewMatrix.invertToRef(this._worldMatrix),this._worldMatrix.getTranslationToRef(this._globalPosition),this._computedViewMatrix)}freezeProjectionMatrix(e){this._doNotComputeProjectionMatrix=!0,e!==void 0&&(this._projectionMatrix=e)}unfreezeProjectionMatrix(){this._doNotComputeProjectionMatrix=!1}getProjectionMatrix(e){var a,o,l,c,f,h,d,u,m,p,_,g,v,x,A,S,E,R,I;if(this._doNotComputeProjectionMatrix||!e&&this._isSynchronizedProjectionMatrix())return this._projectionMatrix;let t=this.ignoreCameraMaxZ?0:this.maxZ;this._cache.mode=this.mode,this._cache.minZ=this.minZ,this._cache.maxZ=t,this._refreshFrustumPlanes=!0;let i=this.getEngine(),r=this.getScene(),s=i.useReverseDepthBuffer;if(this.mode===n.PERSPECTIVE_CAMERA){this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=i.getAspectRatio(this),this._cache.projectionPlaneTilt=this.projectionPlaneTilt,this.minZ<=0&&(this.minZ=.1);let y;r.useRightHandedSystem?y=j.PerspectiveFovRHToRef:y=j.PerspectiveFovLHToRef,y(this.fov,i.getAspectRatio(this),s?t:this.minZ,s?this.minZ:t,this._projectionMatrix,this.fovMode===n.FOVMODE_VERTICAL_FIXED,i.isNDCHalfZRange,this.projectionPlaneTilt,s)}else{let y=i.getRenderWidth()/2,M=i.getRenderHeight()/2;r.useRightHandedSystem?this.oblique?j.ObliqueOffCenterRHToRef((a=this.orthoLeft)!=null?a:-y,(o=this.orthoRight)!=null?o:y,(l=this.orthoBottom)!=null?l:-M,(c=this.orthoTop)!=null?c:M,s?t:this.minZ,s?this.minZ:t,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,i.isNDCHalfZRange):j.OrthoOffCenterRHToRef((f=this.orthoLeft)!=null?f:-y,(h=this.orthoRight)!=null?h:y,(d=this.orthoBottom)!=null?d:-M,(u=this.orthoTop)!=null?u:M,s?t:this.minZ,s?this.minZ:t,this._projectionMatrix,i.isNDCHalfZRange):this.oblique?j.ObliqueOffCenterLHToRef((m=this.orthoLeft)!=null?m:-y,(p=this.orthoRight)!=null?p:y,(_=this.orthoBottom)!=null?_:-M,(g=this.orthoTop)!=null?g:M,s?t:this.minZ,s?this.minZ:t,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,i.isNDCHalfZRange):j.OrthoOffCenterLHToRef((v=this.orthoLeft)!=null?v:-y,(x=this.orthoRight)!=null?x:y,(A=this.orthoBottom)!=null?A:-M,(S=this.orthoTop)!=null?S:M,s?t:this.minZ,s?this.minZ:t,this._projectionMatrix,i.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.obliqueAngle=(E=this.oblique)==null?void 0:E.angle,this._cache.obliqueLength=(R=this.oblique)==null?void 0:R.length,this._cache.obliqueOffset=(I=this.oblique)==null?void 0:I.offset,this._cache.renderWidth=i.getRenderWidth(),this._cache.renderHeight=i.getRenderHeight()}return this.onProjectionMatrixChangedObservable.notifyObservers(this),this._projectionMatrix}getTransformationMatrix(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix}_computeObliqueDistance(e){let t=this,i=this;return(t.radius||(i.target?b.Distance(this.position,i.target):this.position.length()))+e}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?lf.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=lf.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)}isInFrustum(e,t=!1){if(this._updateFrustumPlanes(),t&&this.rigCameras.length>0){let i=!1;for(let r of this.rigCameras)r._updateFrustumPlanes(),i=i||e.isInFrustum(r._frustumPlanes);return i}else return e.isInFrustum(this._frustumPlanes)}isCompletelyInFrustum(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)}getForwardRay(e=100,t,i){throw Ze("Ray")}getForwardRayToRef(e,t=100,i,r){throw Ze("Ray")}dispose(e,t=!1){for(this.onViewMatrixChangedObservable.clear(),this.onProjectionMatrixChangedObservable.clear(),this.onAfterCheckInputsObservable.clear(),this.onRestoreStateObservable.clear(),this.inputs&&this.inputs.clear(),this.getScene().stopAnimation(this),this.getScene().removeCamera(this);this._rigCameras.length>0;){let r=this._rigCameras.pop();r&&r.dispose()}if(this._parentContainer){let r=this._parentContainer.cameras.indexOf(this);r>-1&&this._parentContainer.cameras.splice(r,1),this._parentContainer=null}if(this._rigPostProcess)this._rigPostProcess.dispose(this),this._rigPostProcess=null,this._postProcesses.length=0;else if(this.cameraRigMode!==n.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses.length=0;else{let r=this._postProcesses.length;for(;--r>=0;){let s=this._postProcesses[r];s&&s.dispose(this)}}let i=this.customRenderTargets.length;for(;--i>=0;)this.customRenderTargets[i].dispose();this.customRenderTargets.length=0,this._activeMeshes.dispose(),this.getScene().getEngine().releaseRenderPassId(this.renderPassId),super.dispose(e,t)}get isLeftCamera(){return this._isLeftCamera}get isRightCamera(){return this._isRightCamera}get leftCamera(){return this._rigCameras.length<1?null:this._rigCameras[0]}get rightCamera(){return this._rigCameras.length<2?null:this._rigCameras[1]}getLeftTarget(){return this._rigCameras.length<1?null:this._rigCameras[0].getTarget()}getRightTarget(){return this._rigCameras.length<2?null:this._rigCameras[1].getTarget()}setCameraRigMode(e,t){if(this.cameraRigMode!==e){for(;this._rigCameras.length>0;){let i=this._rigCameras.pop();i&&i.dispose()}if(this.cameraRigMode=e,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=t.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=pe.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==n.RIG_MODE_NONE){let i=this.createRigCamera(this.name+"_L",0);i&&(i._isLeftCamera=!0);let r=this.createRigCamera(this.name+"_R",1);r&&(r._isRightCamera=!0),i&&r&&(this._rigCameras.push(i),this._rigCameras.push(r))}this._setRigMode(t),this._cascadePostProcessesToRigCams(),this.update()}}_setRigMode(e){}_getVRProjectionMatrix(){return j.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov,this._cameraRigParams.vrMetrics.aspectRatio,this.minZ,this.ignoreCameraMaxZ?0:this.maxZ,this._cameraRigParams.vrWorkMatrix,!0,this.getEngine().isNDCHalfZRange),this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix,this._projectionMatrix),this._projectionMatrix}setCameraRigParameter(e,t){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[e]=t,e==="interaxialDistance"&&(this._cameraRigParams.stereoHalfAngle=pe.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;en._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){let i=e.type,r=n.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),s=it.Parse(r,e,t);if(e.parentId!==void 0&&(s._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),s.inputs&&(s.inputs.parse(e),s._setupInputs()),e.upVector&&(s.upVector=b.FromArray(e.upVector)),s.setPosition&&(s.position.copyFromFloats(0,0,0),s.setPosition(b.FromArray(e.position))),e.target&&s.setTarget&&s.setTarget(b.FromArray(e.target)),e.cameraRigMode){let a=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};s.setCameraRigMode(e.cameraRigMode,a)}if(e.animations){for(let a=0;a{throw Ze("UniversalCamera")};ut.PERSPECTIVE_CAMERA=0;ut.ORTHOGRAPHIC_CAMERA=1;ut.FOVMODE_VERTICAL_FIXED=0;ut.FOVMODE_HORIZONTAL_FIXED=1;ut.RIG_MODE_NONE=0;ut.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10;ut.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11;ut.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12;ut.RIG_MODE_STEREOSCOPIC_OVERUNDER=13;ut.RIG_MODE_STEREOSCOPIC_INTERLACED=14;ut.RIG_MODE_VR=20;ut.RIG_MODE_CUSTOM=22;ut.ForceAttachControlToAlwaysPreventDefault=!1;P([Hr("position")],ut.prototype,"_position",void 0);P([Hr("upVector")],ut.prototype,"_upVector",void 0);P([w()],ut.prototype,"orthoLeft",null);P([w()],ut.prototype,"orthoRight",null);P([w()],ut.prototype,"orthoBottom",null);P([w()],ut.prototype,"orthoTop",null);P([w()],ut.prototype,"fov",void 0);P([w()],ut.prototype,"projectionPlaneTilt",void 0);P([w()],ut.prototype,"minZ",void 0);P([w()],ut.prototype,"maxZ",void 0);P([w()],ut.prototype,"inertia",void 0);P([w()],ut.prototype,"mode",null);P([w()],ut.prototype,"layerMask",void 0);P([w()],ut.prototype,"fovMode",void 0);P([w()],ut.prototype,"cameraRigMode",void 0);P([w()],ut.prototype,"interaxialDistance",void 0);P([w()],ut.prototype,"isStereoscopicSideBySide",void 0);P([w()],ut.prototype,"ignoreCameraMaxZ",void 0)});var jh,_y=C(()=>{jh=class{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0,this._internalSubMeshId=0}}});var Sf,gy=C(()=>{Zo();Ve();Dn();Sf=class n{constructor(e,t,i){this.vectors=dn(8,b.Zero),this.center=b.Zero(),this.centerWorld=b.Zero(),this.extendSize=b.Zero(),this.extendSizeWorld=b.Zero(),this.directions=dn(3,b.Zero),this.vectorsWorld=dn(8,b.Zero),this.minimumWorld=b.Zero(),this.maximumWorld=b.Zero(),this.minimum=b.Zero(),this.maximum=b.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}reConstruct(e,t,i){let r=e.x,s=e.y,a=e.z,o=t.x,l=t.y,c=t.z,f=this.vectors;this.minimum.copyFromFloats(r,s,a),this.maximum.copyFromFloats(o,l,c),f[0].copyFromFloats(r,s,a),f[1].copyFromFloats(o,l,c),f[2].copyFromFloats(o,s,a),f[3].copyFromFloats(r,l,a),f[4].copyFromFloats(r,s,c),f[5].copyFromFloats(o,l,a),f[6].copyFromFloats(r,l,c),f[7].copyFromFloats(o,s,c),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||j.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){let t=n._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),r=i.length();i.normalizeFromLength(r);let s=r*e,a=i.scaleInPlace(s*.5),o=this.center.subtractToRef(a,t[1]),l=this.center.addToRef(a,t[2]);return this.reConstruct(o,l,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){let t=this.minimumWorld,i=this.maximumWorld,r=this.directions,s=this.vectorsWorld,a=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let o=0;o<8;++o)s[o].copyFrom(a[o]);this.extendSizeWorld.copyFrom(this.extendSize),this.centerWorld.copyFrom(this.center)}else{t.setAll(Number.MAX_VALUE),i.setAll(-Number.MAX_VALUE);for(let o=0;o<8;++o){let l=s[o];b.TransformCoordinatesToRef(a[o],e,l),t.minimizeInPlace(l),i.maximizeInPlace(l)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}b.FromArrayToRef(e.m,0,r[0]),b.FromArrayToRef(e.m,4,r[1]),b.FromArrayToRef(e.m,8,r[2]),this._worldMatrix=e}isInFrustum(e){return n.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return n.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){let t=this.minimumWorld,i=this.maximumWorld,r=t.x,s=t.y,a=t.z,o=i.x,l=i.y,c=i.z,f=e.x,h=e.y,d=e.z,u=-Ot;return!(o-ff-r||l-hh-s||c-dd-a)}intersectsSphere(e){return n.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){let i=this.minimumWorld,r=this.maximumWorld,s=i.x,a=i.y,o=i.z,l=r.x,c=r.y,f=r.z,h=e.x,d=e.y,u=e.z,m=t.x,p=t.y,_=t.z;return!(lm||cp||f_)}dispose(){var e,t;(e=this._drawWrapperFront)==null||e.dispose(),(t=this._drawWrapperBack)==null||t.dispose()}static Intersects(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)}static IntersectsSphere(e,t,i,r){let s=n._TmpVector3[0];return b.ClampToRef(i,e,t,s),b.DistanceSquared(i,s)<=r*r}static IsCompletelyInFrustum(e,t){for(let i=0;i<6;++i){let r=t[i];for(let s=0;s<8;++s)if(r.dotCoordinate(e[s])<0)return!1}return!0}static IsInFrustum(e,t){for(let i=0;i<6;++i){let r=!0,s=t[i];for(let a=0;a<8;++a)if(s.dotCoordinate(e[a])>=0){r=!1;break}if(r)return!1}return!0}};Sf._TmpVector3=dn(3,b.Zero)});var mm,sG=C(()=>{Zo();Ve();mm=class n{constructor(e,t,i){this.center=b.Zero(),this.centerWorld=b.Zero(),this.minimum=b.Zero(),this.maximum=b.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);let r=b.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=r*.5,this._update(i||j.IdentityReadOnly)}scale(e){let t=this.radius*e,i=n._TmpVector3,r=i[0].setAll(t),s=this.center.subtractToRef(r,i[1]),a=this.center.addToRef(r,i[2]);return this.reConstruct(s,a,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{b.TransformCoordinatesToRef(this.center,e,this.centerWorld);let t=n._TmpVector3[0];b.TransformNormalFromFloatsToRef(1,1,1,e,t),this.radiusWorld=Math.max(Math.abs(t.x),Math.abs(t.y),Math.abs(t.z))*this.radius}}isInFrustum(e){let t=this.centerWorld,i=this.radiusWorld;for(let r=0;r<6;r++)if(e[r].dotCoordinate(t)<=-i)return!1;return!0}isCenterInFrustum(e){let t=this.centerWorld;for(let i=0;i<6;i++)if(e[i].dotCoordinate(t)<0)return!1;return!0}intersectsPoint(e){let t=b.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld{Zo();Ve();gy();sG();vy={min:0,max:0},Ey={min:0,max:0},aG=(n,e,t)=>{let i=b.Dot(e.centerWorld,n),r=Math.abs(b.Dot(e.directions[0],n))*e.extendSize.x,s=Math.abs(b.Dot(e.directions[1],n))*e.extendSize.y,a=Math.abs(b.Dot(e.directions[2],n))*e.extendSize.z,o=r+s+a;t.min=i-o,t.max=i+o},ts=(n,e,t)=>(aG(n,e,vy),aG(n,t,Ey),!(vy.min>Ey.max||Ey.min>vy.max)),un=class n{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new Sf(e,t,i),this.boundingSphere=new mm(e,t,i)}reConstruct(e,t,i){this.boundingBox.reConstruct(e,t,i),this.boundingSphere.reConstruct(e,t,i)}get minimum(){return this.boundingBox.minimum}get maximum(){return this.boundingBox.maximum}get isLocked(){return this._isLocked}set isLocked(e){this._isLocked=e}update(e){this._isLocked||(this.boundingBox._update(e),this.boundingSphere._update(e))}centerOn(e,t){let i=n._TmpVector3[0].copyFrom(e).subtractInPlace(t),r=n._TmpVector3[1].copyFrom(e).addInPlace(t);return this.boundingBox.reConstruct(i,r,this.boundingBox.getWorldMatrix()),this.boundingSphere.reConstruct(i,r,this.boundingBox.getWorldMatrix()),this}encapsulate(e){let t=b.Minimize(this.minimum,e),i=b.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){let t=$.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);let i=$.Vector3[0];return b.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,i),this.encapsulate(i),b.TransformCoordinatesToRef(e.boundingBox.maximumWorld,t,i),this.encapsulate(i),this}scale(e){return this.boundingBox.scale(e),this.boundingSphere.scale(e),this}isInFrustum(e,t=0){return(t===2||t===3)&&this.boundingSphere.isCenterInFrustum(e)?!0:this.boundingSphere.isInFrustum(e)?t===1||t===3?!0:this.boundingBox.isInFrustum(e):!1}get diagonalLength(){let e=this.boundingBox;return e.maximumWorld.subtractToRef(e.minimumWorld,n._TmpVector3[0]).length()}isCompletelyInFrustum(e){return this.boundingBox.isCompletelyInFrustum(e)}_checkCollision(e){return e._canDoCollision(this.boundingSphere.centerWorld,this.boundingSphere.radiusWorld,this.boundingBox.minimumWorld,this.boundingBox.maximumWorld)}intersectsPoint(e){return!(!this.boundingSphere.centerWorld||!this.boundingSphere.intersectsPoint(e)||!this.boundingBox.intersectsPoint(e))}intersects(e,t){if(!mm.Intersects(this.boundingSphere,e.boundingSphere)||!Sf.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;let i=this.boundingBox,r=e.boundingBox;return!(!ts(i.directions[0],i,r)||!ts(i.directions[1],i,r)||!ts(i.directions[2],i,r)||!ts(r.directions[0],i,r)||!ts(r.directions[1],i,r)||!ts(r.directions[2],i,r)||!ts(b.Cross(i.directions[0],r.directions[0]),i,r)||!ts(b.Cross(i.directions[0],r.directions[1]),i,r)||!ts(b.Cross(i.directions[0],r.directions[2]),i,r)||!ts(b.Cross(i.directions[1],r.directions[0]),i,r)||!ts(b.Cross(i.directions[1],r.directions[1]),i,r)||!ts(b.Cross(i.directions[1],r.directions[2]),i,r)||!ts(b.Cross(i.directions[2],r.directions[0]),i,r)||!ts(b.Cross(i.directions[2],r.directions[1]),i,r)||!ts(b.Cross(i.directions[2],r.directions[2]),i,r))}};un._TmpVector3=dn(2,b.Zero)});function oG(n,e,t,i,r=null){let s=new b(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new b(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return _m.extractMinAndMaxIndexed(n,e,t,i,s,a),r&&(s.x-=s.x*r.x+r.y,s.y-=s.y*r.x+r.y,s.z-=s.z*r.x+r.y,a.x+=a.x*r.x+r.y,a.y+=a.y*r.x+r.y,a.z+=a.z*r.x+r.y),{minimum:s,maximum:a}}function bA(n,e,t,i=null,r){let s=new b(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new b(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return r||(r=3),_m.extractMinAndMax(n,e,t,r,s,a),i&&(s.x-=s.x*i.x+i.y,s.y-=s.y*i.x+i.y,s.z-=s.z*i.x+i.y,a.x+=a.x*i.x+i.y,a.y+=a.y*i.x+i.y,a.z+=a.z*i.x+i.y),{minimum:s,maximum:a}}var _m,IA=C(()=>{Gt();Ve();Ut();_m=class{static extractMinAndMaxIndexed(e,t,i,r,s,a){for(let o=i;o!Array.isArray(n[0])&&!Array.isArray(n[1]))],_m,"extractMinAndMaxIndexed",null);P([Ts.filter((...n)=>!Array.isArray(n[0]))],_m,"extractMinAndMax",null)});var Rs,hg=C(()=>{Gi();_y();pm();IA();Gh();Rs=class n{get materialDefines(){var t;let e=this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.defines:(t=this._getDrawWrapper())==null?void 0:t.defines;return typeof e=="string"?null:e}set materialDefines(e){var i;let t=(i=this._mainDrawWrapperOverride)!=null?i:this._getDrawWrapper(void 0,!0);t.defines=e}_getDrawWrapper(e,t=!1){e=e!=null?e:this._engine.currentRenderPassId;let i=this._drawWrappers[e];return!i&&t&&(this._drawWrappers[e]=i=new Jn(this._mesh.getScene().getEngine())),i}_removeDrawWrapper(e,t=!0,i=!1){var r;t&&((r=this._drawWrappers[e])==null||r.dispose(i)),this._drawWrappers[e]=void 0}get effect(){var e,t;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.effect:(t=(e=this._getDrawWrapper())==null?void 0:e.effect)!=null?t:null}get _drawWrapper(){var e;return(e=this._mainDrawWrapperOverride)!=null?e:this._getDrawWrapper(void 0,!0)}get _drawWrapperOverride(){return this._mainDrawWrapperOverride}_setMainDrawWrapperOverride(e){this._mainDrawWrapperOverride=e}setEffect(e,t=null,i,r=!0){let s=this._drawWrapper;s.setEffect(e,t,r),i!==void 0&&(s.materialContext=i),e||(s.defines=null,s.materialContext=void 0)}resetDrawCache(e,t=!1){if(this._drawWrappers)if(e!==void 0){this._removeDrawWrapper(e,!0,t);return}else for(let i of this._drawWrappers)i==null||i.dispose(t);this._drawWrappers=[]}static AddToMesh(e,t,i,r,s,a,o,l=!0){return new n(e,t,i,r,s,a,o,l)}constructor(e,t,i,r,s,a,o,l=!0,c=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=r,this.indexCount=s,this._mainDrawWrapperOverride=null,this._linesIndexCount=0,this._linesIndexBuffer=null,this._lastColliderWorldVertices=null,this._lastColliderTransformMatrix=null,this._wasDispatched=!1,this._renderId=0,this._alphaIndex=0,this._distanceToCamera=0,this._currentMaterial=null,this._mesh=a,this._renderingMesh=o||a,c&&a.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=a.subMeshes.length-1,l&&(this.refreshBoundingInfo(),a.computeWorldMatrix(!0))}get IsGlobal(){return this.verticesStart===0&&this.verticesCount===this._mesh.getTotalVertices()&&this.indexStart===0&&this.indexCount===this._mesh.getTotalIndices()}getBoundingInfo(){return this.IsGlobal||this._mesh.hasThinInstances?this._mesh.getBoundingInfo():this._boundingInfo}setBoundingInfo(e){return this._boundingInfo=e,this}getMesh(){return this._mesh}getRenderingMesh(){return this._renderingMesh}getReplacementMesh(){return this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null}getEffectiveMesh(){let e=this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null;return e||this._renderingMesh}getMaterial(e=!0){var i;let t=(i=this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId))!=null?i:this._renderingMesh.material;if(t){if(this._isMultiMaterial(t)){let r=t.getSubMaterial(this.materialIndex);return this._currentMaterial!==r&&(this._currentMaterial=r,this.resetDrawCache()),r}}else return e&&this._mesh.getScene()._hasDefaultMaterial?this._mesh.getScene().defaultMaterial:null;return t}_isMultiMaterial(e){return e.getSubMaterial!==void 0}refreshBoundingInfo(e=null){if(this._lastColliderWorldVertices=null,this.IsGlobal||!this._renderingMesh||!this._renderingMesh.geometry)return this;if(e||(e=this._renderingMesh.getVerticesData(L.PositionKind)),!e)return this._boundingInfo=this._mesh.getBoundingInfo(),this;let t=this._renderingMesh.getIndices(),i;if(this.indexStart===0&&this.indexCount===t.length){let r=this._renderingMesh.getBoundingInfo();i={minimum:r.minimum.clone(),maximum:r.maximum.clone()}}else i=oG(e,t,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new un(i.minimum,i.maximum),this}_checkCollision(e){return this.getBoundingInfo()._checkCollision(e)}updateBoundingInfo(e){let t=this.getBoundingInfo();return t||(this.refreshBoundingInfo(),t=this.getBoundingInfo()),t&&t.update(e),this}isInFrustum(e){let t=this.getBoundingInfo();return t?t.isInFrustum(e,this._mesh.cullingStrategy):!1}isCompletelyInFrustum(e){let t=this.getBoundingInfo();return t?t.isCompletelyInFrustum(e):!1}render(e){return this._renderingMesh.render(this,e,this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:void 0),this}_getLinesIndexBuffer(e,t){if(!this._linesIndexBuffer){let i=Math.floor(this.indexCount/3)*6,s=this.verticesStart+this.verticesCount>65535?new Uint32Array(i):new Uint16Array(i),a=0;if(e.length===0)for(let o=this.indexStart;ol&&(l=d)}return new n(e,o,l-o+1,t,i,r,s,a)}}});var dg,Me,hr=C(()=>{Gt();Ve();Gi();hn();zt();yt();Ut();py();U_();hg();dg=class{},Me=class n{constructor(){this.uniqueId=0,this.metadata={},this._applyTo=nG(this._applyToCoroutine.bind(this)),this.uniqueId=n._UniqueIdGenerator,n._UniqueIdGenerator++}set(e,t){switch(e.length||te.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case L.PositionKind:this.positions=e;break;case L.NormalKind:this.normals=e;break;case L.TangentKind:this.tangents=e;break;case L.UVKind:this.uvs=e;break;case L.UV2Kind:this.uvs2=e;break;case L.UV3Kind:this.uvs3=e;break;case L.UV4Kind:this.uvs4=e;break;case L.UV5Kind:this.uvs5=e;break;case L.UV6Kind:this.uvs6=e;break;case L.ColorKind:this.colors=e;break;case L.MatricesIndicesKind:this.matricesIndices=e;break;case L.MatricesWeightsKind:this.matricesWeights=e;break;case L.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case L.MatricesWeightsExtraKind:this.matricesWeightsExtra=e;break}}applyToMesh(e,t){return this._applyTo(e,t,!1),this}applyToGeometry(e,t){return this._applyTo(e,t,!1),this}updateMesh(e){return this._update(e),this}updateGeometry(e){return this._update(e),this}*_applyToCoroutine(e,t=!1,i){if(this.positions&&(e.setVerticesData(L.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(L.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(L.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(L.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(L.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(L.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(L.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(L.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(L.UV6Kind,this.uvs6,t),i&&(yield)),this.colors){let r=this.positions&&this.colors.length===this.positions.length?3:4;e.setVerticesData(L.ColorKind,this.colors,t,r),this.hasVertexAlpha&&e.hasVertexAlpha!==void 0&&(e.hasVertexAlpha=!0),i&&(yield)}if(this.matricesIndices&&(e.setVerticesData(L.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(L.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(L.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(L.MatricesWeightsExtraKind,this.matricesWeightsExtra,t),i&&(yield)),this.indices?(e.setIndices(this.indices,null,t),i&&(yield)):e.setIndices([],null),e.subMeshes&&this.materialInfos&&this.materialInfos.length>1){let r=e;r.subMeshes=[];for(let s of this.materialInfos)new Rs(s.materialIndex,s.verticesStart,s.verticesCount,s.indexStart,s.indexCount,r)}return this}_update(e,t,i){return this.positions&&e.updateVerticesData(L.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(L.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(L.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(L.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(L.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(L.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(L.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(L.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(L.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(L.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(L.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(L.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(L.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(L.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,r=e.length){let s=$.Vector3[0],a=$.Vector3[1];for(let o=i;o({vertexData:o})):[{vertexData:e}];return fg(this._mergeCoroutine(void 0,a,t,!1,i,r,s))}*_mergeCoroutine(e,t,i=!1,r,s,a=!1,o=!1){var u,m,p,_;this._validate();let l=t.map(g=>g.vertexData),c=this;if(o)for(let g of l)g&&(g._validate(),!this.normals&&g.normals&&(this.normals=new Float32Array(this.positions.length)),!this.tangents&&g.tangents&&(this.tangents=new Float32Array(this.positions.length/3*4)),!this.uvs&&g.uvs&&(this.uvs=new Float32Array(this.positions.length/3*2)),!this.uvs2&&g.uvs2&&(this.uvs2=new Float32Array(this.positions.length/3*2)),!this.uvs3&&g.uvs3&&(this.uvs3=new Float32Array(this.positions.length/3*2)),!this.uvs4&&g.uvs4&&(this.uvs4=new Float32Array(this.positions.length/3*2)),!this.uvs5&&g.uvs5&&(this.uvs5=new Float32Array(this.positions.length/3*2)),!this.uvs6&&g.uvs6&&(this.uvs6=new Float32Array(this.positions.length/3*2)),!this.colors&&g.colors&&(this.colors=new Float32Array(this.positions.length/3*4),this.colors.fill(1)),!this.matricesIndices&&g.matricesIndices&&(this.matricesIndices=new Float32Array(this.positions.length/3*4)),!this.matricesWeights&&g.matricesWeights&&(this.matricesWeights=new Float32Array(this.positions.length/3*4)),!this.matricesIndicesExtra&&g.matricesIndicesExtra&&(this.matricesIndicesExtra=new Float32Array(this.positions.length/3*4)),!this.matricesWeightsExtra&&g.matricesWeightsExtra&&(this.matricesWeightsExtra=new Float32Array(this.positions.length/3*4)));for(let g of l)if(g){if(o)this.normals&&!g.normals&&(g.normals=new Float32Array(g.positions.length)),this.tangents&&!g.tangents&&(g.tangents=new Float32Array(g.positions.length/3*4)),this.uvs&&!g.uvs&&(g.uvs=new Float32Array(g.positions.length/3*2)),this.uvs2&&!g.uvs2&&(g.uvs2=new Float32Array(g.positions.length/3*2)),this.uvs3&&!g.uvs3&&(g.uvs3=new Float32Array(g.positions.length/3*2)),this.uvs4&&!g.uvs4&&(g.uvs4=new Float32Array(g.positions.length/3*2)),this.uvs5&&!g.uvs5&&(g.uvs5=new Float32Array(g.positions.length/3*2)),this.uvs6&&!g.uvs6&&(g.uvs6=new Float32Array(g.positions.length/3*2)),this.colors&&!g.colors&&(g.colors=new Float32Array(g.positions.length/3*4),g.colors.fill(1)),this.matricesIndices&&!g.matricesIndices&&(g.matricesIndices=new Float32Array(g.positions.length/3*4)),this.matricesWeights&&!g.matricesWeights&&(g.matricesWeights=new Float32Array(g.positions.length/3*4)),this.matricesIndicesExtra&&!g.matricesIndicesExtra&&(g.matricesIndicesExtra=new Float32Array(g.positions.length/3*4)),this.matricesWeightsExtra&&!g.matricesWeightsExtra&&(g.matricesWeightsExtra=new Float32Array(g.positions.length/3*4));else if(g._validate(),!this.normals!=!g.normals||!this.tangents!=!g.tangents||!this.uvs!=!g.uvs||!this.uvs2!=!g.uvs2||!this.uvs3!=!g.uvs3||!this.uvs4!=!g.uvs4||!this.uvs5!=!g.uvs5||!this.uvs6!=!g.uvs6||!this.colors!=!g.colors||!this.matricesIndices!=!g.matricesIndices||!this.matricesWeights!=!g.matricesWeights||!this.matricesIndicesExtra!=!g.matricesIndicesExtra||!this.matricesWeightsExtra!=!g.matricesWeightsExtra)throw new Error("Cannot merge vertex data that do not have the same set of attributes")}if(a){let g,v=0,x=0,A=[],S=null,E=[];for(let I of this.splitBasedOnMaterialID())E.push({vertexData:I,transform:e});for(let I of t)if(I.vertexData)for(let y of I.vertexData.splitBasedOnMaterialID())E.push({vertexData:y,transform:I.transform});E.sort((I,y)=>{let M=I.vertexData.materialInfos?I.vertexData.materialInfos[0].materialIndex:0,D=y.vertexData.materialInfos?y.vertexData.materialInfos[0].materialIndex:0;return M>D?1:M===D?0:-1});for(let I of E){let y=I.vertexData;if(y.materialInfos?g=y.materialInfos[0].materialIndex:g=0,S&&S.materialIndex===g)S.indexCount+=y.indices.length,S.verticesCount+=y.positions.length/3;else{let M=new dg;M.materialIndex=g,M.indexStart=v,M.indexCount=y.indices.length,M.verticesStart=x,M.verticesCount=y.positions.length/3,A.push(M),S=M}v+=y.indices.length,x+=y.positions.length/3}let R=E.splice(0,1)[0];c=R.vertexData,e=R.transform,l=E.map(I=>I.vertexData),t=E,this.materialInfos=A}let f=l.reduce((g,v)=>{var x,A;return g+((A=(x=v.indices)==null?void 0:x.length)!=null?A:0)},(m=(u=c.indices)==null?void 0:u.length)!=null?m:0),d=s||l.some(g=>g.indices===c.indices)?(p=c.indices)==null?void 0:p.slice():c.indices;if(f>0){let g=(_=d==null?void 0:d.length)!=null?_:0;if(d||(d=new Array(f)),d.length!==f){if(Array.isArray(d))d.length=f;else{let x=i||d instanceof Uint32Array?new Uint32Array(f):new Uint16Array(f);x.set(d),d=x}e&&e.determinant()<0&&n._FlipFaces(d,0,g)}let v=c.positions?c.positions.length/3:0;for(let{vertexData:x,transform:A}of t)if(x.indices){for(let S=0;S[g.vertexData.positions,g.transform])),r&&(yield),c.normals&&(this.normals=n._MergeElement(L.NormalKind,c.normals,e,t.map(g=>[g.vertexData.normals,g.transform])),r&&(yield)),c.tangents&&(this.tangents=n._MergeElement(L.TangentKind,c.tangents,e,t.map(g=>[g.vertexData.tangents,g.transform])),r&&(yield)),c.uvs&&(this.uvs=n._MergeElement(L.UVKind,c.uvs,e,t.map(g=>[g.vertexData.uvs,g.transform])),r&&(yield)),c.uvs2&&(this.uvs2=n._MergeElement(L.UV2Kind,c.uvs2,e,t.map(g=>[g.vertexData.uvs2,g.transform])),r&&(yield)),c.uvs3&&(this.uvs3=n._MergeElement(L.UV3Kind,c.uvs3,e,t.map(g=>[g.vertexData.uvs3,g.transform])),r&&(yield)),c.uvs4&&(this.uvs4=n._MergeElement(L.UV4Kind,c.uvs4,e,t.map(g=>[g.vertexData.uvs4,g.transform])),r&&(yield)),c.uvs5&&(this.uvs5=n._MergeElement(L.UV5Kind,c.uvs5,e,t.map(g=>[g.vertexData.uvs5,g.transform])),r&&(yield)),c.uvs6&&(this.uvs6=n._MergeElement(L.UV6Kind,c.uvs6,e,t.map(g=>[g.vertexData.uvs6,g.transform])),r&&(yield)),c.colors&&(this.colors=n._MergeElement(L.ColorKind,c.colors,e,t.map(g=>[g.vertexData.colors,g.transform])),(c.hasVertexAlpha!==void 0||t.some(g=>g.vertexData.hasVertexAlpha!==void 0))&&(this.hasVertexAlpha=c.hasVertexAlpha||t.some(g=>g.vertexData.hasVertexAlpha)),r&&(yield)),c.matricesIndices&&(this.matricesIndices=n._MergeElement(L.MatricesIndicesKind,c.matricesIndices,e,t.map(g=>[g.vertexData.matricesIndices,g.transform])),r&&(yield)),c.matricesWeights&&(this.matricesWeights=n._MergeElement(L.MatricesWeightsKind,c.matricesWeights,e,t.map(g=>[g.vertexData.matricesWeights,g.transform])),r&&(yield)),c.matricesIndicesExtra&&(this.matricesIndicesExtra=n._MergeElement(L.MatricesIndicesExtraKind,c.matricesIndicesExtra,e,t.map(g=>[g.vertexData.matricesIndicesExtra,g.transform])),r&&(yield)),c.matricesWeightsExtra&&(this.matricesWeightsExtra=n._MergeElement(L.MatricesWeightsExtraKind,c.matricesWeightsExtra,e,t.map(g=>[g.vertexData.matricesWeightsExtra,g.transform]))),this}static _MergeElement(e,t,i,r){let s=r.filter(l=>l[0]!==null&&l[0]!==void 0);if(!t&&s.length==0)return t;if(!t)return this._MergeElement(e,s[0][0],s[0][1],s.slice(1));let a=s.reduce((l,c)=>l+c[0].length,t.length),o=e===L.PositionKind?n._TransformVector3Coordinates:e===L.NormalKind?n._TransformVector3Normals:e===L.TangentKind?n._TransformVector4Normals:()=>{};if(t instanceof Float32Array){let l=new Float32Array(a);l.set(t),i&&o(l,i,0,t.length);let c=t.length;for(let[f,h]of s)l.set(f,c),h&&o(l,h,c,f.length),c+=f.length;return l}else{let l=new Array(a);for(let f=0;f{let a=L.DeduceStride(r);if(s.length%a!==0)throw new Error("The "+r+"s array count must be a multiple of "+a);return s.length/a},t=e(L.PositionKind,this.positions),i=(r,s)=>{let a=e(r,s);if(a!==t)throw new Error("The "+r+"s element count ("+a+") does not match the positions count ("+t+")")};this.normals&&i(L.NormalKind,this.normals),this.tangents&&i(L.TangentKind,this.tangents),this.uvs&&i(L.UVKind,this.uvs),this.uvs2&&i(L.UV2Kind,this.uvs2),this.uvs3&&i(L.UV3Kind,this.uvs3),this.uvs4&&i(L.UV4Kind,this.uvs4),this.uvs5&&i(L.UV5Kind,this.uvs5),this.uvs6&&i(L.UV6Kind,this.uvs6),this.colors&&i(L.ColorKind,this.colors),this.matricesIndices&&i(L.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&i(L.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&i(L.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&i(L.MatricesWeightsExtraKind,this.matricesWeightsExtra)}clone(){let e=this.serialize();return n.Parse(e)}serialize(){let e={};if(this.positions&&(e.positions=Array.from(this.positions)),this.normals&&(e.normals=Array.from(this.normals)),this.tangents&&(e.tangents=Array.from(this.tangents)),this.uvs&&(e.uvs=Array.from(this.uvs)),this.uvs2&&(e.uvs2=Array.from(this.uvs2)),this.uvs3&&(e.uvs3=Array.from(this.uvs3)),this.uvs4&&(e.uvs4=Array.from(this.uvs4)),this.uvs5&&(e.uvs5=Array.from(this.uvs5)),this.uvs6&&(e.uvs6=Array.from(this.uvs6)),this.colors&&(e.colors=Array.from(this.colors),e.hasVertexAlpha=this.hasVertexAlpha),this.matricesIndices&&(e.matricesIndices=Array.from(this.matricesIndices),e.matricesIndicesExpanded=!0),this.matricesWeights&&(e.matricesWeights=Array.from(this.matricesWeights)),this.matricesIndicesExtra&&(e.matricesIndicesExtra=Array.from(this.matricesIndicesExtra),e.matricesIndicesExtraExpanded=!0),this.matricesWeightsExtra&&(e.matricesWeightsExtra=Array.from(this.matricesWeightsExtra)),e.indices=this.indices?Array.from(this.indices):[],this.materialInfos){e.materialInfos=[];for(let t of this.materialInfos){let i={indexStart:t.indexStart,indexCount:t.indexCount,materialIndex:t.materialIndex,verticesStart:t.verticesStart,verticesCount:t.verticesCount};e.materialInfos.push(i)}}return e}static ExtractFromMesh(e,t,i){return n._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return n._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){let r=new n;if(e.isVerticesDataPresent(L.PositionKind)&&(r.positions=e.getVerticesData(L.PositionKind,t,i)),e.isVerticesDataPresent(L.NormalKind)&&(r.normals=e.getVerticesData(L.NormalKind,t,i)),e.isVerticesDataPresent(L.TangentKind)&&(r.tangents=e.getVerticesData(L.TangentKind,t,i)),e.isVerticesDataPresent(L.UVKind)&&(r.uvs=e.getVerticesData(L.UVKind,t,i)),e.isVerticesDataPresent(L.UV2Kind)&&(r.uvs2=e.getVerticesData(L.UV2Kind,t,i)),e.isVerticesDataPresent(L.UV3Kind)&&(r.uvs3=e.getVerticesData(L.UV3Kind,t,i)),e.isVerticesDataPresent(L.UV4Kind)&&(r.uvs4=e.getVerticesData(L.UV4Kind,t,i)),e.isVerticesDataPresent(L.UV5Kind)&&(r.uvs5=e.getVerticesData(L.UV5Kind,t,i)),e.isVerticesDataPresent(L.UV6Kind)&&(r.uvs6=e.getVerticesData(L.UV6Kind,t,i)),e.isVerticesDataPresent(L.ColorKind)){let s=e.geometry||e,a=s.getVertexBuffer(L.ColorKind),o=s.getVerticesData(L.ColorKind,t,i);if(a.getSize()===3){let l=new Float32Array(o.length*4/3);for(let c=0,f=0;c!Array.isArray(n[0]))],Me,"_TransformVector3Coordinates",null);P([Ts.filter((...n)=>!Array.isArray(n[0]))],Me,"_TransformVector3Normals",null);P([Ts.filter((...n)=>!Array.isArray(n[0]))],Me,"_TransformVector4Normals",null);P([Ts.filter((...n)=>!Array.isArray(n[0]))],Me,"_FlipFaces",null)});var Xr,MA=C(()=>{Xr=class n{static get ForceFullSceneLoadingForIncremental(){return n._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){n._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return n._ShowLoadingScreen}static set ShowLoadingScreen(e){n._ShowLoadingScreen=e}static get loggingLevel(){return n._LoggingLevel}static set loggingLevel(e){n._LoggingLevel=e}static get CleanBoneMatrixWeights(){return n._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){n._CleanBoneMatrixWeights=e}};Xr._ForceFullSceneLoadingForIncremental=!1;Xr._ShowLoadingScreen=!0;Xr._CleanBoneMatrixWeights=!1;Xr._LoggingLevel=0});var mn,CA=C(()=>{Ve();zt();hr();Gi();hg();MA();pm();bi();uf();IA();Pi();en();nm();mn=class n{get boundingBias(){return this._boundingBias}set boundingBias(e){this._boundingBias?this._boundingBias.copyFrom(e):this._boundingBias=e.clone(),this._updateBoundingInfo(!0,null)}static CreateGeometryForMesh(e){let t=new n(n.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,i,r=!1,s=null,a=null){this.delayLoadState=0,this._totalVertices=0,this._isDisposed=!1,this._extend={minimum:new b(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),maximum:new b(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)},this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this._scene=t||Le.LastCreatedScene,this._scene&&(this.id=e,this.uniqueId=this._scene.getUniqueId(),this._engine=this._scene.getEngine(),this._meshes=[],this._vertexBuffers={},this._indices=[],this._updatable=r,a!==null&&(this._totalVertices=a),i?this.setAllVerticesData(i,r):a===null&&(this._totalVertices=0),this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),s&&(this.applyToMesh(s),s.computeWorldMatrix(!0)))}get extend(){return this._extend}getScene(){return this._scene}getEngine(){return this._engine}isReady(){return this.delayLoadState===1||this.delayLoadState===0}get doNotSerialize(){for(let e=0;e{t._rebuild()})}setAllVerticesData(e,t){e.applyToGeometry(this,t),this._notifyUpdate()}setVerticesData(e,t,i=!1,r){i&&Array.isArray(t)&&(t=new Float32Array(t));let s=new L(this._engine,t,e,{updatable:i,postponeInternalCreation:this._meshes.length===0,stride:r,label:"Geometry_"+this.id+"_"+e});this.setVerticesBuffer(s)}removeVerticesData(e){this._vertexBuffers[e]&&(this._vertexBuffers[e].dispose(),delete this._vertexBuffers[e]),this._vertexArrayObjects&&this._disposeVertexArrayObjects()}setVerticesBuffer(e,t=null,i=!0){let r=e.getKind();this._vertexBuffers[r]&&i&&this._vertexBuffers[r].dispose(),e._buffer&&e._ownsBuffer&&e._buffer._increaseReferences(),this._vertexBuffers[r]=e;let s=this._meshes,a=s.length;if(r===L.PositionKind){this._totalVertices=t!=null?t:e._maxVerticesCount,this._updateExtend(this.useBoundingInfoFromGeometry&&this._boundingInfo?null:e.getFloatData(this._totalVertices)),this._resetPointsArrayCache();let o=this._extend&&this._extend.minimum||new b(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),l=this._extend&&this._extend.maximum||new b(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE);for(let c=0;c65535:e.is32Bits=r;for(let s of this._meshes)s._createGlobalSubMesh(!0),s.synchronizeInstances();this._notifyUpdate()}setIndices(e,t=null,i=!1,r=!1){this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indices=e,this._indexBufferIsUpdatable=i,this._meshes.length!==0&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,i,"Geometry_"+this.id+"_IndexBuffer")),t!=null&&(this._totalVertices=t);for(let s of this._meshes)s._createGlobalSubMesh(!r),s.synchronizeInstances();this._notifyUpdate()}getTotalIndices(){return this.isReady()?this._totalIndices!==void 0?this._totalIndices:this._indices.length:0}getIndices(e,t){if(!this.isReady())return null;let i=this._indices;return!t&&(!e||this._meshes.length===1)?i:i.slice()}getIndexBuffer(){return this.isReady()?this._indexBuffer:null}_releaseVertexArrayObject(e=null){!e||!this._vertexArrayObjects||this._vertexArrayObjects[e.key]&&(this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e.key]),delete this._vertexArrayObjects[e.key])}releaseForMesh(e,t){let i=this._meshes,r=i.indexOf(e);r!==-1&&(i.splice(r,1),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject(),e._geometry=null,i.length===0&&t&&this.dispose())}applyToMesh(e){if(e._geometry===this)return;let t=e._geometry;t&&t.releaseForMesh(e),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject();let i=this._meshes;e._geometry=this,e._internalAbstractMeshDataInfo._positions=null,this._scene.pushGeometry(this),i.push(e),this.isReady()?this._applyToMesh(e):this._boundingInfo&&e.setBoundingInfo(this._boundingInfo)}_updateExtend(e=null){if(this.useBoundingInfoFromGeometry&&this._boundingInfo)this._extend={minimum:this._boundingInfo.minimum.clone(),maximum:this._boundingInfo.maximum.clone()};else{if(!e&&(e=this.getVerticesData(L.PositionKind),!e))return;this._extend=bA(e,0,this._totalVertices,this.boundingBias,3)}}_applyToMesh(e){for(let t in this._vertexBuffers){let i=this._vertexBuffers[t];i._buffer.getBuffer()||i.create(),t===L.PositionKind&&(this._extend||this._updateExtend(),e.buildBoundingInfo(this._extend.minimum,this._extend.maximum),e._createGlobalSubMesh(e.isUnIndexed),e._updateBoundingInfo())}!this._indexBuffer&&this._indices&&this._indices.length>0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable,"Geometry_"+this.id+"_IndexBuffer")),e._syncGeometryWithMorphTargetManager(),e.synchronizeInstances()}_notifyUpdate(e){this.onGeometryUpdated&&this.onGeometryUpdated(this,e),this._vertexArrayObjects&&this._disposeVertexArrayObjects();for(let t of this._meshes)t._markSubMeshesAsAttributesDirty()}load(e,t){if(this.delayLoadState!==2){if(this.isReady()){t&&t();return}this.delayLoadState=2,this._queueLoad(e,t)}}_queueLoad(e,t){this.delayLoadingFile&&(e.addPendingData(this),e._loadFile(this.delayLoadingFile,i=>{if(!this._delayLoadingFunction)return;this._delayLoadingFunction(JSON.parse(i),this),this.delayLoadState=1,this._delayInfo=[],e.removePendingData(this);let r=this._meshes,s=r.length;for(let a=0;a0){for(let r=0;r0){for(let r=0;r0){for(let r=0;r-1&&this._parentContainer.geometries.splice(r,1),this._parentContainer=null}this._isDisposed=!0}copy(e){let t=new n(e,this._scene),i=this.getIndices(void 0,!0);i&&t.setIndices(i);let r=!1,s;for(s in this._vertexBuffers){let a=this.getVertexBuffer(s),o=a.getData();if(!o)continue;let l=a.isUpdatable(),c=a.getSize(),{type:f,byteOffset:h,byteStride:d,normalized:u}=a;r=r||l;let m=this._totalVertices;if(a.getIsInstanced()){let g;o instanceof Array?g=o.length*4:g=o.byteLength,m=g/d}let p=L2(o,c,f,h,d,m,!0),_=new L(this._engine,p,s,{updatable:l,useBytes:!1,stride:c,size:c,offset:0,type:f,normalized:u,takeBufferOwnership:!0,instanced:a.getIsInstanced()});t.setVerticesBuffer(_,m)}t._updatable=r,t.delayLoadState=this.delayLoadState,t.delayLoadingFile=this.delayLoadingFile,t._delayLoadingFunction=this._delayLoadingFunction;for(s in this._delayInfo)t._delayInfo=t._delayInfo||[],t._delayInfo.push(s);return t._boundingInfo=new un(this._extend.minimum,this._extend.maximum),t}serialize(){let e={};return e.id=this.id,e.uniqueId=this.uniqueId,e.updatable=this._updatable,qt&&qt.HasTags(this)&&(e.tags=qt.GetTags(this)),e}_toNumberArray(e){return Array.isArray(e)?e:Array.prototype.slice.call(e)}clearCachedData(){this._totalIndices=this._indices.length,this._indices=[],this._resetPointsArrayCache();for(let e in this._vertexBuffers)Object.prototype.hasOwnProperty.call(this._vertexBuffers,e)&&(this._vertexBuffers[e]._buffer._data=null)}serializeVerticeData(){let e=this.serialize();return this.isVerticesDataPresent(L.PositionKind)&&(e.positions=this._toNumberArray(this.getVerticesData(L.PositionKind)),this.isVertexBufferUpdatable(L.PositionKind)&&(e.positionsUpdatable=!0)),this.isVerticesDataPresent(L.NormalKind)&&(e.normals=this._toNumberArray(this.getVerticesData(L.NormalKind)),this.isVertexBufferUpdatable(L.NormalKind)&&(e.normalsUpdatable=!0)),this.isVerticesDataPresent(L.TangentKind)&&(e.tangents=this._toNumberArray(this.getVerticesData(L.TangentKind)),this.isVertexBufferUpdatable(L.TangentKind)&&(e.tangentsUpdatable=!0)),this.isVerticesDataPresent(L.UVKind)&&(e.uvs=this._toNumberArray(this.getVerticesData(L.UVKind)),this.isVertexBufferUpdatable(L.UVKind)&&(e.uvsUpdatable=!0)),this.isVerticesDataPresent(L.UV2Kind)&&(e.uvs2=this._toNumberArray(this.getVerticesData(L.UV2Kind)),this.isVertexBufferUpdatable(L.UV2Kind)&&(e.uvs2Updatable=!0)),this.isVerticesDataPresent(L.UV3Kind)&&(e.uvs3=this._toNumberArray(this.getVerticesData(L.UV3Kind)),this.isVertexBufferUpdatable(L.UV3Kind)&&(e.uvs3Updatable=!0)),this.isVerticesDataPresent(L.UV4Kind)&&(e.uvs4=this._toNumberArray(this.getVerticesData(L.UV4Kind)),this.isVertexBufferUpdatable(L.UV4Kind)&&(e.uvs4Updatable=!0)),this.isVerticesDataPresent(L.UV5Kind)&&(e.uvs5=this._toNumberArray(this.getVerticesData(L.UV5Kind)),this.isVertexBufferUpdatable(L.UV5Kind)&&(e.uvs5Updatable=!0)),this.isVerticesDataPresent(L.UV6Kind)&&(e.uvs6=this._toNumberArray(this.getVerticesData(L.UV6Kind)),this.isVertexBufferUpdatable(L.UV6Kind)&&(e.uvs6Updatable=!0)),this.isVerticesDataPresent(L.ColorKind)&&(e.colors=this._toNumberArray(this.getVerticesData(L.ColorKind)),this.isVertexBufferUpdatable(L.ColorKind)&&(e.colorsUpdatable=!0)),this.isVerticesDataPresent(L.MatricesIndicesKind)&&(e.matricesIndices=this._toNumberArray(this.getVerticesData(L.MatricesIndicesKind)),e.matricesIndicesExpanded=!0,this.isVertexBufferUpdatable(L.MatricesIndicesKind)&&(e.matricesIndicesUpdatable=!0)),this.isVerticesDataPresent(L.MatricesWeightsKind)&&(e.matricesWeights=this._toNumberArray(this.getVerticesData(L.MatricesWeightsKind)),this.isVertexBufferUpdatable(L.MatricesWeightsKind)&&(e.matricesWeightsUpdatable=!0)),e.indices=this._toNumberArray(this.getIndices()),e}static ExtractFromMesh(e,t){let i=e._geometry;return i?i.copy(t):null}static RandomId(){return pe.RandomId()}static _GetGeometryByLoadedUniqueId(e,t){for(let i=0;i0){let o=new Float32Array(e,a.positionsAttrDesc.offset,a.positionsAttrDesc.count);t.setVerticesData(L.PositionKind,o,!1)}if(a.normalsAttrDesc&&a.normalsAttrDesc.count>0){let o=new Float32Array(e,a.normalsAttrDesc.offset,a.normalsAttrDesc.count);t.setVerticesData(L.NormalKind,o,!1)}if(a.tangetsAttrDesc&&a.tangetsAttrDesc.count>0){let o=new Float32Array(e,a.tangetsAttrDesc.offset,a.tangetsAttrDesc.count);t.setVerticesData(L.TangentKind,o,!1)}if(a.uvsAttrDesc&&a.uvsAttrDesc.count>0){let o=new Float32Array(e,a.uvsAttrDesc.offset,a.uvsAttrDesc.count);if(It)for(let l=1;l0){let o=new Float32Array(e,a.uvs2AttrDesc.offset,a.uvs2AttrDesc.count);if(It)for(let l=1;l0){let o=new Float32Array(e,a.uvs3AttrDesc.offset,a.uvs3AttrDesc.count);if(It)for(let l=1;l0){let o=new Float32Array(e,a.uvs4AttrDesc.offset,a.uvs4AttrDesc.count);if(It)for(let l=1;l0){let o=new Float32Array(e,a.uvs5AttrDesc.offset,a.uvs5AttrDesc.count);if(It)for(let l=1;l0){let o=new Float32Array(e,a.uvs6AttrDesc.offset,a.uvs6AttrDesc.count);if(It)for(let l=1;l0){let o=new Float32Array(e,a.colorsAttrDesc.offset,a.colorsAttrDesc.count);t.setVerticesData(L.ColorKind,o,!1,a.colorsAttrDesc.stride)}if(a.matricesIndicesAttrDesc&&a.matricesIndicesAttrDesc.count>0){let o=new Int32Array(e,a.matricesIndicesAttrDesc.offset,a.matricesIndicesAttrDesc.count),l=[];for(let c=0;c>8),l.push((f&16711680)>>16),l.push(f>>24&255)}t.setVerticesData(L.MatricesIndicesKind,l,!1)}if(a.matricesIndicesExtraAttrDesc&&a.matricesIndicesExtraAttrDesc.count>0){let o=new Int32Array(e,a.matricesIndicesExtraAttrDesc.offset,a.matricesIndicesExtraAttrDesc.count),l=[];for(let c=0;c>8),l.push((f&16711680)>>16),l.push(f>>24&255)}t.setVerticesData(L.MatricesIndicesExtraKind,l,!1)}if(a.matricesWeightsAttrDesc&&a.matricesWeightsAttrDesc.count>0){let o=new Float32Array(e,a.matricesWeightsAttrDesc.offset,a.matricesWeightsAttrDesc.count);t.setVerticesData(L.MatricesWeightsKind,o,!1)}if(a.indicesAttrDesc&&a.indicesAttrDesc.count>0){let o=new Int32Array(e,a.indicesAttrDesc.offset,a.indicesAttrDesc.count);t.setIndices(o,null)}if(a.subMeshesAttrDesc&&a.subMeshesAttrDesc.count>0){let o=new Int32Array(e,a.subMeshesAttrDesc.offset,a.subMeshesAttrDesc.count*5);t.subMeshes=[];for(let l=0;l>8),a.push((l&16711680)>>16),a.push(l>>24&255)}t.setVerticesData(L.MatricesIndicesKind,a,e.matricesIndices._updatable||e.matricesIndicesUpdatable)}else delete e.matricesIndices._isExpanded,delete e.matricesIndicesExpanded,t.setVerticesData(L.MatricesIndicesKind,e.matricesIndices,e.matricesIndices._updatable||e.matricesIndicesUpdatable);if(e.matricesIndicesExtra)if(e.matricesIndicesExtraExpanded||e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,delete e.matricesIndicesExtraExpanded,t.setVerticesData(L.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable||e.matricesIndicesExtraUpdatable);else{let a=[];for(let o=0;o>8),a.push((l&16711680)>>16),a.push(l>>24&255)}t.setVerticesData(L.MatricesIndicesExtraKind,a,e.matricesIndicesExtra._updatable||e.matricesIndicesExtraUpdatable)}e.matricesWeights&&(n._CleanMatricesWeights(e,t),t.setVerticesData(L.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(L.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let a=0;a-1){let h=t.getScene().getLastSkeletonById(e.skeletonId);if(!h)return;r=h.bones.length}else return;let s=t.getVerticesData(L.MatricesIndicesKind),a=t.getVerticesData(L.MatricesIndicesExtraKind),o=e.matricesWeights,l=e.matricesWeightsExtra,c=e.numBoneInfluencer,f=o.length;for(let h=0;hc-1)&&(u=c-1),d>.001){let m=1/d;for(let p=0;p<4;p++)o[h+p]*=m;if(l)for(let p=0;p<4;p++)l[h+p]*=m}else u>=4?(l[h+u-4]=1-d,a[h+u-4]=r):(o[h+u]=1-d,s[h+u]=r)}t.setVerticesData(L.MatricesIndicesKind,s),e.matricesWeightsExtra&&t.setVerticesData(L.MatricesIndicesExtraKind,a)}static Parse(e,t,i){let r=new n(e.id,t,void 0,e.updatable);return r._loadedUniqueId=e.uniqueId,qt&&qt.AddTagsTo(r,e.tags),e.delayLoadingFile?(r.delayLoadState=4,r.delayLoadingFile=i+e.delayLoadingFile,r._boundingInfo=new un(b.FromArray(e.boundingBoxMinimum),b.FromArray(e.boundingBoxMaximum)),r._delayInfo=[],e.hasUVs&&r._delayInfo.push(L.UVKind),e.hasUVs2&&r._delayInfo.push(L.UV2Kind),e.hasUVs3&&r._delayInfo.push(L.UV3Kind),e.hasUVs4&&r._delayInfo.push(L.UV4Kind),e.hasUVs5&&r._delayInfo.push(L.UV5Kind),e.hasUVs6&&r._delayInfo.push(L.UV6Kind),e.hasColors&&r._delayInfo.push(L.ColorKind),e.hasMatricesIndices&&r._delayInfo.push(L.MatricesIndicesKind),e.hasMatricesWeights&&r._delayInfo.push(L.MatricesWeightsKind),r._delayLoadingFunction=Me.ImportVertexData):Me.ImportVertexData(e,r),t.pushGeometry(r,!0),r}}});var Jt,qh=C(()=>{Gt();Ut();Tr();hi();Ve();qs();Hi();Jt=class n extends _i{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=(this._billboardMode&n.BILLBOARDMODE_USE_POSITION)!==0)}get infiniteDistance(){return this._infiniteDistance}set infiniteDistance(e){this._infiniteDistance!==e&&(this._infiniteDistance=e)}constructor(e,t=null,i=!0){super(e,t,!1),this._forward=new b(0,0,1),this._up=new b(0,1,0),this._right=new b(1,0,0),this._position=b.Zero(),this._rotation=b.Zero(),this._rotationQuaternion=null,this._scaling=b.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=n.BILLBOARDMODE_NONE,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=j.Zero(),this._usePivotMatrix=!1,this._absolutePosition=b.Zero(),this._absoluteScaling=b.Zero(),this._absoluteRotationQuaternion=Ye.Identity(),this._pivotMatrix=j.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new ie,this._nonUniformScaling=!1,i&&this.getScene().addTransformNode(this)}getClassName(){return"TransformNode"}get position(){return this._position}set position(e){this._position=e,this._markAsDirtyInternal()}isUsingPivotMatrix(){return this._usePivotMatrix}isUsingPostMultiplyPivotMatrix(){return this._postMultiplyPivotMatrix}get rotation(){return this._rotation}set rotation(e){this._rotation=e,this._rotationQuaternion=null,this._markAsDirtyInternal()}get scaling(){return this._scaling}set scaling(e){this._scaling=e,this._markAsDirtyInternal()}get rotationQuaternion(){return this._rotationQuaternion}set rotationQuaternion(e){this._rotationQuaternion=e,e&&this._rotation.setAll(0),this._markAsDirtyInternal()}_markAsDirtyInternal(){this._isDirty||(this._isDirty=!0,this.customMarkAsDirty&&this.customMarkAsDirty())}get forward(){return b.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return b.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return b.TransformNormalFromFloatsToRef(this.getScene().useRightHandedSystem?-1:1,0,0,this.getWorldMatrix(),this._right),this._right.normalize()}updatePoseMatrix(e){return this._poseMatrix?(this._poseMatrix.copyFrom(e),this):(this._poseMatrix=e.clone(),this)}getPoseMatrix(){return this._poseMatrix||(this._poseMatrix=j.Identity()),this._poseMatrix}_isSynchronized(){let e=this._cache;return!(this._billboardMode!==e.billboardMode||this._billboardMode!==n.BILLBOARDMODE_NONE||e.pivotMatrixUpdated||this._infiniteDistance||this._position._isDirty||this._scaling._isDirty||this._rotationQuaternion&&this._rotationQuaternion._isDirty||this._rotation._isDirty)}_initCache(){super._initCache();let e=this._cache;e.localMatrixUpdated=!1,e.billboardMode=-1,e.infiniteDistance=!1,e.useBillboardPosition=!1}get absolutePosition(){return this.getAbsolutePosition()}get absoluteScaling(){return this._syncAbsoluteScalingAndRotation(),this._absoluteScaling}get absoluteRotationQuaternion(){return this._syncAbsoluteScalingAndRotation(),this._absoluteRotationQuaternion}setPreTransformMatrix(e){return this.setPivotMatrix(e,!1)}setPivotMatrix(e,t=!0){return this._pivotMatrix.copyFrom(e),this._usePivotMatrix=!this._pivotMatrix.isIdentity(),this._cache.pivotMatrixUpdated=!0,this._postMultiplyPivotMatrix=t,this._postMultiplyPivotMatrix&&(this._pivotMatrixInverse?this._pivotMatrix.invertToRef(this._pivotMatrixInverse):this._pivotMatrixInverse=j.Invert(this._pivotMatrix)),this}getPivotMatrix(){return this._pivotMatrix}instantiateHierarchy(e=null,t,i){let r=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);r&&i&&i(this,r);for(let s of this.getChildTransformNodes(!0))s.instantiateHierarchy(r,t,i);return r}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||Ye.Identity(),e.decompose(this._scaling,this._rotationQuaternion,this._position),this.computeWorldMatrix(!0)):(this._worldMatrix=e,this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._afterComputeWorldMatrix()):(this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0)),this._isDirty=!1,this._isWorldMatrixFrozen=!0,this}unfreezeWorldMatrix(){return this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0),this}get isWorldMatrixFrozen(){return this._isWorldMatrixFrozen}getAbsolutePosition(){return this.computeWorldMatrix(),this._absolutePosition}setAbsolutePosition(e){if(!e)return this;let t,i,r;if(e.x===void 0){if(arguments.length<3)return this;t=arguments[0],i=arguments[1],r=arguments[2]}else t=e.x,i=e.y,r=e.z;if(this.parent){let s=$.Matrix[0];this.parent.getWorldMatrix().invertToRef(s),b.TransformCoordinatesFromFloatsToRef(t,i,r,s,this.position)}else this.position.x=t,this.position.y=i,this.position.z=r;return this._absolutePosition.copyFrom(e),this}setPositionWithLocalVector(e){return this.computeWorldMatrix(),this.position=b.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();let e=$.Matrix[0];return this._localMatrix.invertToRef(e),b.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=b.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,r=0,s=0){let a=n._LookAtVectorCache,o=s===0?this.position:this.getAbsolutePosition();if(e.subtractToRef(o,a),this.setDirection(a,t,i,r),s===1&&this.parent)if(this.rotationQuaternion){let l=$.Matrix[0];this.rotationQuaternion.toRotationMatrix(l);let c=$.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(c),c.invert(),l.multiplyToRef(c,l),this.rotationQuaternion.fromRotationMatrix(l)}else{let l=$.Quaternion[0];Ye.FromEulerVectorToRef(this.rotation,l);let c=$.Matrix[0];l.toRotationMatrix(c);let f=$.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(f),f.invert(),c.multiplyToRef(f,c),l.fromRotationMatrix(c),l.toEulerAnglesToRef(this.rotation)}return this}getDirection(e){let t=b.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return b.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,r=0){let s=-Math.atan2(e.z,e.x)+Math.PI/2,a=Math.sqrt(e.x*e.x+e.z*e.z),o=-Math.atan2(e.y,a);return this.rotationQuaternion?Ye.RotationYawPitchRollToRef(s+t,o+i,r,this.rotationQuaternion):(this.rotation.x=o+i,this.rotation.y=s+t,this.rotation.z=r),this}setPivotPoint(e,t=0){this.getScene().getRenderId()==0&&this.computeWorldMatrix(!0);let i=this.getWorldMatrix();if(t==1){let r=$.Matrix[0];i.invertToRef(r),e=b.TransformCoordinates(e,r)}return this.setPivotMatrix(j.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){let e=b.Zero();return this.getPivotPointToRef(e),e}getPivotPointToRef(e){return e.x=-this._pivotMatrix.m[12],e.y=-this._pivotMatrix.m[13],e.z=-this._pivotMatrix.m[14],this}getAbsolutePivotPoint(){let e=b.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),b.TransformCoordinatesToRef(e,this.getWorldMatrix(),e),this}markAsDirty(e){if(this._isDirty)return this;if(this._children)for(let t of this._children)t.markAsDirty(e);return super.markAsDirty(e)}setParent(e,t=!1,i=!1){if(!e&&!this.parent)return this;let r=$.Quaternion[0],s=$.Vector3[0],a=$.Vector3[1],o=$.Matrix[1];j.IdentityToRef(o);let l=$.Matrix[0];this.computeWorldMatrix(!0);let c=this.rotationQuaternion;return c||(c=n._TmpRotation,Ye.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,c)),j.ComposeToRef(this.scaling,c,this.position,l),this.parent&&l.multiplyToRef(this.parent.computeWorldMatrix(!0),l),e&&(e.computeWorldMatrix(!0).invertToRef(o),l.multiplyToRef(o,l)),l.decompose(a,r,s,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(r):r.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(a),this.position.copyFrom(s),this.parent=e,i&&this.setPivotMatrix(j.Identity()),this}addChild(e,t=!1){return e.setParent(this,t),this}removeChild(e,t=!1){return e.parent!==this?this:(e.setParent(null,t),this)}get nonUniformScaling(){return this._nonUniformScaling}_updateNonUniformScalingState(e){return this._nonUniformScaling===e?!1:(this._nonUniformScaling=e,!0)}attachToBone(e,t){return this._currentParentWhenAttachingToBone=this.parent,this._transformToBoneReferal=t,this.parent=e,e.getSkeleton().prepare(!0),e.getFinalMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this}detachFromBone(e=!1){return this.parent?(this.parent.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this._transformToBoneReferal=null,e?this.parent=this._currentParentWhenAttachingToBone:this.parent=null,this):(e&&(this.parent=this._currentParentWhenAttachingToBone),this)}rotate(e,t,i){e.normalize(),this.rotationQuaternion||(this.rotationQuaternion=this.rotation.toQuaternion(),this.rotation.setAll(0));let r;if(!i||i===0)r=Ye.RotationAxisToRef(e,t,n._RotationAxisCache),this.rotationQuaternion.multiplyToRef(r,this.rotationQuaternion);else{if(this.parent){let s=this.parent.getWorldMatrix(),a=$.Matrix[0];s.invertToRef(a),e=b.TransformNormal(e,a),s.determinant()<0&&(t*=-1)}r=Ye.RotationAxisToRef(e,t,n._RotationAxisCache),r.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=Ye.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));let r=$.Vector3[0],s=$.Vector3[1],a=$.Vector3[2],o=$.Quaternion[0],l=$.Matrix[0],c=$.Matrix[1],f=$.Matrix[2],h=$.Matrix[3];return e.subtractToRef(this.position,r),j.TranslationToRef(r.x,r.y,r.z,l),j.TranslationToRef(-r.x,-r.y,-r.z,c),j.RotationAxisToRef(t,i,f),c.multiplyToRef(f,h),h.multiplyToRef(l,h),h.decompose(s,o,a),this.position.addInPlace(a),o.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){let r=e.scale(t);if(!i||i===0){let s=this.getPositionExpressedInLocalSpace().add(r);this.setPositionWithLocalVector(s)}else this.setAbsolutePosition(this.getAbsolutePosition().add(r));return this}addRotation(e,t,i){let r;this.rotationQuaternion?r=this.rotationQuaternion:(r=$.Quaternion[1],Ye.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,r));let s=$.Quaternion[0];return Ye.RotationYawPitchRollToRef(t,e,i,s),r.multiplyInPlace(s),this.rotationQuaternion||r.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==n.BILLBOARDMODE_NONE}computeWorldMatrix(e=!1,t=null){if(this._isWorldMatrixFrozen&&!this._isDirty)return this._worldMatrix;let i=this.getScene().getRenderId();if(!this._isDirty&&!e&&(this._currentRenderId===i||this.isSynchronized()))return this._currentRenderId=i,this._worldMatrix;t=t||this.getScene().activeCamera,this._updateCache();let r=this._cache;r.pivotMatrixUpdated=!1,r.billboardMode=this.billboardMode,r.infiniteDistance=this.infiniteDistance,r.parent=this._parentNode,this._currentRenderId=i,this._childUpdateId+=1,this._isDirty=!1,this._position._isDirty=!1,this._rotation._isDirty=!1,this._scaling._isDirty=!1;let s=this._getEffectiveParent(),a=n._TmpScaling,o=this._position;if(this._infiniteDistance&&!this.parent&&t){let f=t.getWorldMatrix().m;o=n._TmpTranslation,o.copyFromFloats(this._position.x+f[12],this._position.y+f[13],this._position.z+f[14])}a.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant);let l;if(this._rotationQuaternion?(this._rotationQuaternion._isDirty=!1,l=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion&&this.rotation.lengthSquared()&&(this._rotationQuaternion.multiplyInPlace(Ye.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))):(l=n._TmpRotation,Ye.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,l)),this._usePivotMatrix){let c=$.Matrix[1];j.ScalingToRef(a.x,a.y,a.z,c);let f=$.Matrix[0];l.toRotationMatrix(f),this._pivotMatrix.multiplyToRef(c,$.Matrix[4]),$.Matrix[4].multiplyToRef(f,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(o.x,o.y,o.z)}else j.ComposeToRef(a,l,o,this._localMatrix);if(s&&s.getWorldMatrix){if(e&&s.computeWorldMatrix(e),this.billboardMode){if(this._transformToBoneReferal){let d=this.parent;d.getSkeleton().prepare(),d.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),$.Matrix[7])}else $.Matrix[7].copyFrom(s.getWorldMatrix());let c=$.Vector3[5],f=$.Vector3[6],h=$.Quaternion[0];$.Matrix[7].decompose(f,h,c),j.ScalingToRef(f.x,f.y,f.z,$.Matrix[7]),$.Matrix[7].setTranslation(c),n.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(h,c),this._localMatrix.setTranslation(c)),this._localMatrix.multiplyToRef($.Matrix[7],this._worldMatrix)}else if(this._transformToBoneReferal){let c=this.parent;c.getSkeleton().prepare(),this._localMatrix.multiplyToRef(c.getFinalMatrix(),$.Matrix[6]),$.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)}else this._localMatrix.multiplyToRef(s.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(t&&this.billboardMode)if(r.useBillboardPosition){let c=$.Vector3[0];this._worldMatrix.getTranslationToRef(c);let f=t.globalPosition;this._worldMatrix.invertToRef($.Matrix[1]);let h=$.Vector3[1];b.TransformCoordinatesToRef(f,$.Matrix[1],h),h.normalize();let d=-Math.atan2(h.z,h.x)+Math.PI/2,u=Math.sqrt(h.x*h.x+h.z*h.z),m=-Math.atan2(h.y,u);if(Ye.RotationYawPitchRollToRef(d,m,0,$.Quaternion[0]),(this.billboardMode&n.BILLBOARDMODE_ALL)!==n.BILLBOARDMODE_ALL){let p=$.Vector3[1];$.Quaternion[0].toEulerAnglesToRef(p),(this.billboardMode&n.BILLBOARDMODE_X)!==n.BILLBOARDMODE_X&&(p.x=0),(this.billboardMode&n.BILLBOARDMODE_Y)!==n.BILLBOARDMODE_Y&&(p.y=0),(this.billboardMode&n.BILLBOARDMODE_Z)!==n.BILLBOARDMODE_Z&&(p.z=0),j.RotationYawPitchRollToRef(p.y,p.x,p.z,$.Matrix[0])}else j.FromQuaternionToRef($.Quaternion[0],$.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef($.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation($.Vector3[0])}else{let c=$.Vector3[0];this._worldMatrix.getTranslationToRef(c),$.Matrix[1].copyFrom(t.getViewMatrix());let f=this.getScene().useRightHandedSystem;if(f&&$.Matrix[1].multiplyToRef(n._TmpRHRestore,$.Matrix[1]),$.Matrix[1].setTranslationFromFloats(0,0,0),$.Matrix[1].invertToRef($.Matrix[0]),(this.billboardMode&n.BILLBOARDMODE_ALL)!==n.BILLBOARDMODE_ALL){$.Matrix[0].decompose(void 0,$.Quaternion[0],void 0);let h=$.Vector3[1];$.Quaternion[0].toEulerAnglesToRef(h),(this.billboardMode&n.BILLBOARDMODE_X)!==n.BILLBOARDMODE_X&&(h.x=0),(this.billboardMode&n.BILLBOARDMODE_Y)!==n.BILLBOARDMODE_Y&&(h.y=0),(this.billboardMode&n.BILLBOARDMODE_Z)!==n.BILLBOARDMODE_Z&&(h.z=0),f&&(h.y+=Math.PI),j.RotationYawPitchRollToRef(h.y,h.x,h.z,$.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef($.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation($.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):s&&s._nonUniformScaling?this._updateNonUniformScalingState(s._nonUniformScaling):this._updateNonUniformScalingState(!1),this._afterComputeWorldMatrix(),this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._isAbsoluteSynced=!1,this.onAfterWorldMatrixUpdateObservable.notifyObservers(this),this._poseMatrix||(this._poseMatrix=j.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){let t=this.getChildren();for(let i=0;inew n(e,this.getScene()),this);if(r.name=e,r.id=e,t&&(r.parent=t),!i){let s=this.getDescendants(!0);for(let a=0;anew n(e.name,t),e,t,i);if(e.localMatrix?r.setPreTransformMatrix(j.FromArray(e.localMatrix)):e.pivotMatrix&&r.setPivotMatrix(j.FromArray(e.pivotMatrix)),r.setEnabled(e.isEnabled),r._waitingParsedUniqueId=e.uniqueId,e.parentId!==void 0&&(r._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),e.freezeWorldMatrix&&(r._waitingFreezeWorldMatrix=e.freezeWorldMatrix),e.animations){for(let s=0;s(!t||t(r))&&r instanceof n),i}dispose(e,t=!1){if(this.getScene().stopAnimation(this),this.getScene().removeTransformNode(this),this._parentContainer){let i=this._parentContainer.transformNodes.indexOf(this);i>-1&&this._parentContainer.transformNodes.splice(i,1),this._parentContainer=null}if(this.onAfterWorldMatrixUpdateObservable.clear(),e){let i=this.getChildTransformNodes(!0);for(let r of i)r.parent=null,r.computeWorldMatrix(!0)}super.dispose(e,t)}normalizeToUnitCube(e=!0,t=!1,i){let r=null,s=null;t&&(this.rotationQuaternion?(s=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(r=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));let a=this.getHierarchyBoundingVectors(e,i),o=a.max.subtract(a.min),l=Math.max(o.x,o.y,o.z);if(l===0)return this;let c=1/l;return this.scaling.scaleInPlace(c),t&&(this.rotationQuaternion&&s?this.rotationQuaternion.copyFrom(s):this.rotation&&r&&this.rotation.copyFrom(r)),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}};Jt.BILLBOARDMODE_NONE=0;Jt.BILLBOARDMODE_X=1;Jt.BILLBOARDMODE_Y=2;Jt.BILLBOARDMODE_Z=4;Jt.BILLBOARDMODE_ALL=7;Jt.BILLBOARDMODE_USE_POSITION=128;Jt.BillboardUseParentOrientation=!1;Jt._TmpRotation=Ye.Zero();Jt._TmpScaling=b.Zero();Jt._TmpTranslation=b.Zero();Jt._TmpRHRestore=j.Scaling(1,1,-1);Jt._LookAtVectorCache=new b(0,0,0);Jt._RotationAxisCache=new Ye;P([Hr("position")],Jt.prototype,"_position",void 0);P([Hr("rotation")],Jt.prototype,"_rotation",void 0);P([I2("rotationQuaternion")],Jt.prototype,"_rotationQuaternion",void 0);P([Hr("scaling")],Jt.prototype,"_scaling",void 0);P([w("billboardMode")],Jt.prototype,"_billboardMode",void 0);P([w()],Jt.prototype,"scalingDeterminant",void 0);P([w("infiniteDistance")],Jt.prototype,"_infiniteDistance",void 0);P([w()],Jt.prototype,"ignoreNonUniformScaling",void 0);P([w()],Jt.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0)});var yA,lG=C(()=>{Ve();yA=class{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new b(0,0,0),this._diffPositionForCollisions=new b(0,0,0),this._collisionResponse=!0}}});function cG(n){return Math.floor(n/8)}function fG(n){return 1<{PA=class{constructor(e){this.size=e,this._byteArray=new Uint8Array(Math.ceil(this.size/8))}get(e){if(e>=this.size)throw new RangeError("Bit index out of range");let t=cG(e),i=fG(e);return(this._byteArray[t]&i)!==0}set(e,t){if(e>=this.size)throw new RangeError("Bit index out of range");let i=cG(e),r=fG(e);t?this._byteArray[i]|=r:this._byteArray[i]&=~r}}});var dG={};tt(dG,{OptimizeIndices:()=>gse});function gse(n){let e=[],t=n.length/3;for(let l=0;l{let c=[l];for(;c.length>0;){let f=c.pop();if(!r.get(f)){r.set(f,!0),s.push(e[f]);for(let h of e[f]){let d=i.get(h);if(!d)return;for(let u of d)r.get(u)||c.push(u)}}}};for(let l=0;l{hG()});function vse(n,e,t){let i;switch(e){case L.PositionKind:i=r=>r.getPositions();break;case L.NormalKind:i=r=>r.getNormals();break;case L.TangentKind:i=r=>r.getTangents();break;case L.UVKind:i=r=>r.getUVs();break;case L.UV2Kind:i=r=>r.getUV2s();break;case L.ColorKind:i=r=>r.getColors();break;default:return}for(let r=0;r0&&(j.FromFloat32ArrayToRefScaled(t,Math.floor(i[d+u]*16),m,c),l.addToSelf(c));if(s&&a)for(u=0;u<4;u++)m=a[d+u],m>0&&(j.FromFloat32ArrayToRefScaled(t,Math.floor(s[d+u]*16),m,c),l.addToSelf(c));f(n[h],n[h+1],n[h+2],l,o),o.toArray(n,h)}}var Sy,Ty,gr,gm=C(()=>{Gt();hi();Ve();Gi();hr();qh();Z_();pm();pf();lG();hn();IA();zt();Dn();Xu();Hi();Ut();wr();Sy=class{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=b.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}},Ty=class{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new Sy,this._visibility=1,this._skeleton=null,this._layerMask=268435455,this._computeBonesUsingShaders=!0,this._isActive=!1,this._onlyForInstances=!1,this._isActiveIntermediate=!1,this._onlyForInstancesIntermediate=!1,this._actAsRegularMesh=!1,this._currentLOD=new Map,this._collisionRetryCount=3,this._morphTargetManager=null,this._renderingGroupId=0,this._bakedVertexAnimationManager=null,this._material=null,this._positions=null,this._pointerOverDisableMeshTesting=!1,this._meshCollisionData=new yA,this._enableDistantPicking=!1,this._rawBoundingInfo=null,this._sideOrientationHint=!1,this._wasActiveLastFrame=!1}},gr=class n extends Jt{static get BILLBOARDMODE_NONE(){return Jt.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return Jt.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return Jt.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return Jt.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return Jt.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return Jt.BILLBOARDMODE_USE_POSITION}get facetNb(){return this._internalAbstractMeshDataInfo._facetData.facetNb}get partitioningSubdivisions(){return this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions}set partitioningSubdivisions(e){this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions=e}get partitioningBBoxRatio(){return this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio}set partitioningBBoxRatio(e){this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio=e}get mustDepthSortFacets(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSort}set mustDepthSortFacets(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSort=e}get facetDepthSortFrom(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom}set facetDepthSortFrom(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom=e}get collisionRetryCount(){return this._internalAbstractMeshDataInfo._collisionRetryCount}set collisionRetryCount(e){this._internalAbstractMeshDataInfo._collisionRetryCount=e}get isFacetDataEnabled(){return this._internalAbstractMeshDataInfo._facetData.facetDataEnabled}get morphTargetManager(){return this._internalAbstractMeshDataInfo._morphTargetManager}set morphTargetManager(e){this._internalAbstractMeshDataInfo._morphTargetManager!==e&&(this._internalAbstractMeshDataInfo._morphTargetManager=e,this._syncGeometryWithMorphTargetManager())}get bakedVertexAnimationManager(){return this._internalAbstractMeshDataInfo._bakedVertexAnimationManager}set bakedVertexAnimationManager(e){this._internalAbstractMeshDataInfo._bakedVertexAnimationManager!==e&&(this._internalAbstractMeshDataInfo._bakedVertexAnimationManager=e,this._markSubMeshesAsAttributesDirty())}_syncGeometryWithMorphTargetManager(){}_updateNonUniformScalingState(e){return super._updateNonUniformScalingState(e)?(this._markSubMeshesAsMiscDirty(),!0):!1}get rawBoundingInfo(){return this._internalAbstractMeshDataInfo._rawBoundingInfo}set rawBoundingInfo(e){this._internalAbstractMeshDataInfo._rawBoundingInfo=e}set onCollide(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver&&this.onCollideObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver=this.onCollideObservable.add(e)}set onCollisionPositionChange(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver&&this.onCollisionPositionChangeObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver=this.onCollisionPositionChangeObservable.add(e)}get visibility(){return this._internalAbstractMeshDataInfo._visibility}set visibility(e){if(this._internalAbstractMeshDataInfo._visibility===e)return;let t=this._internalAbstractMeshDataInfo._visibility;this._internalAbstractMeshDataInfo._visibility=e,(t===1&&e!==1||t!==1&&e===1)&&this._markSubMeshesAsDirty(i=>{i.markAsMiscDirty(),i.markAsPrePassDirty()})}get pointerOverDisableMeshTesting(){return this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting}set pointerOverDisableMeshTesting(e){this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting=e}get renderingGroupId(){return this._internalAbstractMeshDataInfo._renderingGroupId}set renderingGroupId(e){this._internalAbstractMeshDataInfo._renderingGroupId=e}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){this._setMaterial(e)}_setMaterial(e){this._internalAbstractMeshDataInfo._material!==e&&(this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),this._internalAbstractMeshDataInfo._material=e,e&&e.meshMap&&(e.meshMap[this.uniqueId]=this),this.onMaterialChangedObservable.hasObservers()&&this.onMaterialChangedObservable.notifyObservers(this),this.subMeshes&&(this.resetDrawCache(void 0,e==null),this._unBindEffect()))}getMaterialForRenderPass(e){var t;return(t=this._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:t[e]}setMaterialForRenderPass(e,t){var r;this.resetDrawCache(e),this._internalAbstractMeshDataInfo._materialForRenderPass||(this._internalAbstractMeshDataInfo._materialForRenderPass=[]);let i=this._internalAbstractMeshDataInfo._materialForRenderPass[e];(r=i==null?void 0:i.meshMap)!=null&&r[this.uniqueId]&&(i.meshMap[this.uniqueId]=void 0),this._internalAbstractMeshDataInfo._materialForRenderPass[e]=t,t&&t.meshMap&&(t.meshMap[this.uniqueId]=this)}get receiveShadows(){return this._internalAbstractMeshDataInfo._receiveShadows}set receiveShadows(e){this._internalAbstractMeshDataInfo._receiveShadows!==e&&(this._internalAbstractMeshDataInfo._receiveShadows=e,this._markSubMeshesAsLightDirty())}get hasVertexAlpha(){return this._internalAbstractMeshDataInfo._hasVertexAlpha}set hasVertexAlpha(e){this._internalAbstractMeshDataInfo._hasVertexAlpha!==e&&(this._internalAbstractMeshDataInfo._hasVertexAlpha=e,this._markSubMeshesAsAttributesDirty(),this._markSubMeshesAsMiscDirty())}get useVertexColors(){return this._internalAbstractMeshDataInfo._useVertexColors}set useVertexColors(e){this._internalAbstractMeshDataInfo._useVertexColors!==e&&(this._internalAbstractMeshDataInfo._useVertexColors=e,this._markSubMeshesAsAttributesDirty())}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get numBoneInfluencers(){return this._internalAbstractMeshDataInfo._numBoneInfluencers}set numBoneInfluencers(e){this._internalAbstractMeshDataInfo._numBoneInfluencers!==e&&(this._internalAbstractMeshDataInfo._numBoneInfluencers=e,this._markSubMeshesAsAttributesDirty())}get applyFog(){return this._internalAbstractMeshDataInfo._applyFog}set applyFog(e){this._internalAbstractMeshDataInfo._applyFog!==e&&(this._internalAbstractMeshDataInfo._applyFog=e,this._markSubMeshesAsMiscDirty())}get enableDistantPicking(){return this._internalAbstractMeshDataInfo._enableDistantPicking}set enableDistantPicking(e){this._internalAbstractMeshDataInfo._enableDistantPicking=e}get layerMask(){return this._internalAbstractMeshDataInfo._layerMask}set layerMask(e){e!==this._internalAbstractMeshDataInfo._layerMask&&(this._internalAbstractMeshDataInfo._layerMask=e,this._resyncLightSources())}get collisionMask(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask}set collisionMask(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask=isNaN(e)?-1:e}get collisionResponse(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse}set collisionResponse(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse=e}get collisionGroup(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup}set collisionGroup(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup=isNaN(e)?-1:e}get surroundingMeshes(){return this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes}set surroundingMeshes(e){this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes=e}get lightSources(){return this._lightSources}set skeleton(e){let t=this._internalAbstractMeshDataInfo._skeleton;t&&t.needInitialSkinMatrix&&t._unregisterMeshWithPoseMatrix(this),e&&e.needInitialSkinMatrix&&e._registerMeshWithPoseMatrix(this),this._internalAbstractMeshDataInfo._skeleton=e,this._internalAbstractMeshDataInfo._skeleton||(this._bonesTransformMatrices=null),this._markSubMeshesAsAttributesDirty()}get skeleton(){return this._internalAbstractMeshDataInfo._skeleton}constructor(e,t=null){switch(super(e,t,!1),this._internalAbstractMeshDataInfo=new Ty,this._waitingMaterialId=null,this._waitingMorphTargetManagerId=null,this._waitingSkeletonId=null,this._waitingSkeletonUniqueId=null,this.cullingStrategy=n.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new ie,this.onCollisionPositionChangeObservable=new ie,this.onMaterialChangedObservable=new ie,this.definedFacingForward=!0,this._occlusionQuery=null,this._renderingGroup=null,this.alphaIndex=Number.MAX_VALUE,this.isPickable=n.DefaultIsPickable,this.isNearPickable=!1,this.isNearGrabbable=!1,this.showSubMeshesBoundingBox=!1,this.isBlocker=!1,this.enablePointerMoveEvents=!1,this.outlineColor=ge.Red(),this.outlineWidth=.02,this.overlayColor=ge.Red(),this.overlayAlpha=.5,this.useOctreeForRenderingSelection=!0,this.useOctreeForPicking=!0,this.useOctreeForCollisions=!0,this.alwaysSelectAsActiveMesh=!1,this.doNotSyncBoundingInfo=!1,this.actionManager=null,this.ellipsoid=new b(.5,1,.5),this.ellipsoidOffset=new b(0,0,0),this.edgesWidth=1,this.edgesColor=new lt(1,0,0,1),this._edgesRenderer=null,this._masterMesh=null,this._boundingInfo=null,this._boundingInfoIsDirty=!0,this._renderId=0,this._intersectionsInProgress=new Array,this._unIndexed=!1,this._lightSources=new Array,this._waitingData={lods:null,actions:null,freezeWorldMatrix:null},this._bonesTransformMatrices=null,this._transformMatrixTexture=null,this.onRebuildObservable=new ie,this._onCollisionPositionChange=(i,r,s=null)=>{r.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>Ie.CollisionsEpsilon&&this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),s&&this.onCollideObservable.notifyObservers(s),this.onCollisionPositionChangeObservable.notifyObservers(this.position)},t=this.getScene(),this.layerMask=t.defaultRenderableLayerMask,t.addMesh(this),this._resyncLightSources(),this._uniformBuffer=new fr(this.getScene().getEngine(),void 0,void 0,e,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),t.performancePriority){case 2:this.doNotSyncBoundingInfo=!0;case 1:this.alwaysSelectAsActiveMesh=!0,this.isPickable=!1;break}}_buildUniformLayout(){this._uniformBuffer.addUniform("world",16),this._uniformBuffer.addUniform("visibility",1),this._uniformBuffer.create()}transferToEffect(e){let t=this._uniformBuffer;t.updateMatrix("world",e),t.updateFloat("visibility",this._internalAbstractMeshDataInfo._visibility),t.update()}getMeshUniformBuffer(){return this._uniformBuffer}getClassName(){return"AbstractMesh"}toString(e){let t="Name: "+this.name+", isInstance: "+(this.getClassName()==="InstancedMesh"?"YES":"NO");t+=", # of submeshes: "+(this.subMeshes?this.subMeshes.length:0);let i=this._internalAbstractMeshDataInfo._skeleton;return i&&(t+=", skeleton: "+i.name),e&&(t+=", billboard mode: "+["NONE","X","Y",null,"Z",null,null,"ALL"][this.billboardMode],t+=", freeze wrld mat: "+(this._isWorldMatrixFrozen||this._waitingData.freezeWorldMatrix?"YES":"NO")),t}_getEffectiveParent(){return this._masterMesh&&this.billboardMode!==Jt.BILLBOARDMODE_NONE?this._masterMesh:super._getEffectiveParent()}_getActionManagerForTrigger(e,t=!0){if(this.actionManager&&(t||this.actionManager.isRecursive))if(e){if(this.actionManager.hasSpecificTrigger(e))return this.actionManager}else return this.actionManager;return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_releaseRenderPassId(e){}_rebuild(e=!1){if(this.onRebuildObservable.notifyObservers(this),this._occlusionQuery!==null&&(this._occlusionQuery=null),!!this.subMeshes){for(let t of this.subMeshes)t._rebuild();this.resetDrawCache()}}_resyncLightSources(){this._lightSources.length=0;for(let e of this.getScene().lights)e.isEnabled()&&e.canAffectMesh(this)&&this._lightSources.push(e);this._markSubMeshesAsLightDirty()}_resyncLightSource(e){let t=e.isEnabled()&&e.canAffectMesh(this),i=this._lightSources.indexOf(e),r=!1;if(i===-1){if(!t)return;this._lightSources.push(e)}else{if(t)return;r=!0,this._lightSources.splice(i,1)}this._markSubMeshesAsLightDirty(r)}_unBindEffect(){for(let e of this.subMeshes)e.setEffect(null)}_removeLightSource(e,t){let i=this._lightSources.indexOf(e);i!==-1&&(this._lightSources.splice(i,1),this._markSubMeshesAsLightDirty(t))}_markSubMeshesAsDirty(e){if(this.subMeshes)for(let t of this.subMeshes)for(let i=0;it.markAsLightDirty(e))}_markSubMeshesAsAttributesDirty(){this._markSubMeshesAsDirty(e=>e.markAsAttributesDirty())}_markSubMeshesAsMiscDirty(){this._markSubMeshesAsDirty(e=>e.markAsMiscDirty())}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,super.markAsDirty(e),this._isDirty=!0,this}resetDrawCache(e,t=!1){if(this.subMeshes)for(let i of this.subMeshes)i.resetDrawCache(e,t)}get isBlocked(){return!1}getLOD(e){return this}getTotalVertices(){return 0}getTotalIndices(){return 0}getIndices(){return null}getVerticesData(e){return null}setVerticesData(e,t,i,r){return this}updateVerticesData(e,t,i,r){return this}setIndices(e,t){return this}isVerticesDataPresent(e){return!1}getBoundingInfo(){return this._masterMesh?this._masterMesh.getBoundingInfo():(this._boundingInfoIsDirty&&(this._boundingInfoIsDirty=!1,this._updateBoundingInfo()),this._boundingInfo)}getRawBoundingInfo(){var e;return(e=this.rawBoundingInfo)!=null?e:this.getBoundingInfo()}setBoundingInfo(e){return this._boundingInfo=e,this}get hasBoundingInfo(){return this._boundingInfo!==null}buildBoundingInfo(e,t,i){return this._boundingInfo=new un(e,t,i),this._boundingInfo}normalizeToUnitCube(e=!0,t=!1,i){return super.normalizeToUnitCube(e,t,i)}get useBones(){return this.skeleton&&this.getScene().skeletonsEnabled&&this.isVerticesDataPresent(L.MatricesIndicesKind)&&this.isVerticesDataPresent(L.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===Jt.BILLBOARDMODE_NONE?this._masterMesh.getWorldMatrix():super.getWorldMatrix()}_getWorldMatrixDeterminant(){return this._masterMesh?this._masterMesh._getWorldMatrixDeterminant():super._getWorldMatrixDeterminant()}get isAnInstance(){return!1}get hasInstances(){return!1}get hasThinInstances(){return!1}movePOV(e,t,i){return this.position.addInPlace(this.calcMovePOV(e,t,i)),this}calcMovePOV(e,t,i){let r=new j;(this.rotationQuaternion?this.rotationQuaternion:Ye.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(r);let a=b.Zero(),o=this.definedFacingForward?-1:1;return b.TransformCoordinatesFromFloatsToRef(e*o,t,i*o,r,a),a}rotatePOV(e,t,i){return this.rotation.addInPlace(this.calcRotatePOV(e,t,i)),this}calcRotatePOV(e,t,i){let r=this.definedFacingForward?1:-1;return new b(e*r,t,i*r)}_refreshBoundingInfo(e,t){if(e){let i=bA(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new un(i.minimum,i.maximum)}if(this.subMeshes)for(let i=0;i{if(r){let o=r._vertexData||(r._vertexData={});return o[a]||this.copyVerticesData(a,o),o[a]}return this.getVerticesData(a)};if(t||(t=s(i)),!t)return null;if(r?(r._outputData?r._outputData.set(t):r._outputData=new Float32Array(t),t=r._outputData):(e.applyMorph&&this.morphTargetManager||e.applySkeleton&&this.skeleton)&&(t=t.slice()),e.applyMorph&&this.morphTargetManager&&vse(t,i,this.morphTargetManager),e.applySkeleton&&this.skeleton){let a=s(L.MatricesIndicesKind),o=s(L.MatricesWeightsKind);if(o&&a){let l=this.numBoneInfluencers>4,c=l?s(L.MatricesIndicesExtraKind):null,f=l?s(L.MatricesWeightsExtraKind):null,h=this.skeleton.getTransformMatrices(this);n._ApplySkeleton(t,i,h,a,o,c,f)}}if(e.updatePositionsArray!==!1&&i===L.PositionKind){let a=this._internalAbstractMeshDataInfo._positions||[],o=a.length;if(a.length=t.length/3,o1||!r.IsGlobal)&&r.updateBoundingInfo(e)}return this}_afterComputeWorldMatrix(){this.doNotSyncBoundingInfo||(this._boundingInfoIsDirty=!0)}isInFrustum(e){return this.getBoundingInfo().isInFrustum(e,this.cullingStrategy)}isCompletelyInFrustum(e){return this.getBoundingInfo().isCompletelyInFrustum(e)}intersectsMesh(e,t=!1,i){let r=this.getBoundingInfo(),s=e.getBoundingInfo();if(r.intersects(s,t))return!0;if(i){for(let a of this.getChildMeshes())if(a.intersectsMesh(e,t,!0))return!0}return!1}intersectsPoint(e){return this.getBoundingInfo().intersectsPoint(e)}get checkCollisions(){return this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions}set checkCollisions(e){this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions=e}get collider(){return this._internalAbstractMeshDataInfo._meshCollisionData._collider}moveWithCollisions(e,t=!0){this.getAbsolutePosition().addToRef(this.ellipsoidOffset,this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions);let r=this.getScene().collisionCoordinator;return this._internalAbstractMeshDataInfo._meshCollisionData._collider||(this._internalAbstractMeshDataInfo._meshCollisionData._collider=r.createCollider()),this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius=this.ellipsoid,r.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,e,this._internalAbstractMeshDataInfo._meshCollisionData._collider,this.collisionRetryCount,this,this._onCollisionPositionChange,this.uniqueId,t),this}_collideForSubMesh(e,t,i){var r;if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(t)){e._lastColliderTransformMatrix=t.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];let s=e.verticesStart,a=e.verticesStart+e.verticesCount;for(let o=s;o1&&!a._checkCollision(e)||this._collideForSubMesh(a,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;let t=$.Matrix[0],i=$.Matrix[1];return j.ScalingToRef(1/e._radius.x,1/e._radius.y,1/e._radius.z,t),this.worldMatrixFromCache.multiplyToRef(t,i),this._processCollisionsForSubMeshes(e,i),this}_generatePointsArray(){return!1}intersects(e,t,i,r=!1,s,a=!1){let o=new es,l=this.getClassName(),c=l==="InstancedLinesMesh"||l==="LinesMesh"||l==="GreasedLineMesh"?this.intersectionThreshold:0,f=this.getBoundingInfo();if(!this.subMeshes||!a&&(!e.intersectsSphere(f.boundingSphere,c)||!e.intersectsBox(f.boundingBox,c)))return o;if(r)return o.hit=!a,o.pickedMesh=a?null:this,o.distance=a?0:b.Distance(e.origin,f.boundingSphere.center),o.subMeshId=0,o;if(!this._generatePointsArray())return o;let h=null,d=this._scene.getIntersectingSubMeshCandidates(this,e),u=d.length,m=!1;for(let p=0;p1&&!a&&!_.canIntersects(e))continue;let g=_.intersects(e,this._positions,this.getIndices(),t,i);if(g&&(t||!h||g.distanceo!==this&&o.actionManager===this.actionManager)&&this.actionManager.dispose(),this.actionManager=null),this._internalAbstractMeshDataInfo._skeleton=null,this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null),i=0;i-1&&this._parentContainer.meshes.splice(o,1),this._parentContainer=null}if(t&&this.material&&(this.material.getClassName()==="MultiMaterial"?this.material.dispose(!1,!0,!0):this.material.dispose(!1,!0)),!e)for(i=0;i65535){l=!0;break}l?e.depthSortedIndices=new Uint32Array(i):e.depthSortedIndices=new Uint16Array(i)}if(e.facetDepthSortFunction=function(l,c){return c.sqDistance-l.sqDistance},!e.facetDepthSortFrom){let l=this.getScene().activeCamera;e.facetDepthSortFrom=l?l.position:b.Zero()}e.depthSortedFacets=[];for(let l=0;lOt?s.maximum.x-s.minimum.x:Ot,e.bbSize.y=s.maximum.y-s.minimum.y>Ot?s.maximum.y-s.minimum.y:Ot,e.bbSize.z=s.maximum.z-s.minimum.z>Ot?s.maximum.z-s.minimum.z:Ot;let a=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(a=a>e.bbSize.z?a:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/a),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/a),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/a),e.subDiv.X=e.subDiv.X<1?1:e.subDiv.X,e.subDiv.Y=e.subDiv.Y<1?1:e.subDiv.Y,e.subDiv.Z=e.subDiv.Z<1?1:e.subDiv.Z,e.facetParameters.facetNormals=this.getFacetLocalNormals(),e.facetParameters.facetPositions=this.getFacetLocalPositions(),e.facetParameters.facetPartitioning=this.getFacetLocalPartitioning(),e.facetParameters.bInfo=s,e.facetParameters.bbSize=e.bbSize,e.facetParameters.subDiv=e.subDiv,e.facetParameters.ratio=this.partitioningBBoxRatio,e.facetParameters.depthSort=e.facetDepthSort,e.facetDepthSort&&e.facetDepthSortEnabled&&(this.computeWorldMatrix(!0),this._worldMatrix.invertToRef(e.invertedMatrix),b.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,r&&Me.ComputeNormals(t,i,r,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);let l=e.depthSortedIndices.length/3|0;for(let c=0;cs.subDiv.max||o<0||o>s.subDiv.max||l<0||l>s.subDiv.max?null:s.facetPartitioning[a+s.subDiv.max*o+s.subDiv.max*s.subDiv.max*l]}getClosestFacetAtCoordinates(e,t,i,r,s=!1,a=!0){let o=this.getWorldMatrix(),l=$.Matrix[5];o.invertToRef(l);let c=$.Vector3[8];b.TransformCoordinatesFromFloatsToRef(e,t,i,l,c);let f=this.getClosestFacetAtLocalCoordinates(c.x,c.y,c.z,r,s,a);return r&&b.TransformCoordinatesFromFloatsToRef(r.x,r.y,r.z,o,r),f}getClosestFacetAtLocalCoordinates(e,t,i,r,s=!1,a=!0){let o=null,l,c,f,h,d,u,m,p,_=this.getFacetLocalPositions(),g=this.getFacetLocalNormals(),v=this.getFacetsAtLocalCoordinates(e,t,i);if(!v)return null;let x=Number.MAX_VALUE,A,S,E,R;for(let I=0;I=0||s&&!a&&h<=0)&&(h=E.x*R.x+E.y*R.y+E.z*R.z,d=-(E.x*e+E.y*t+E.z*i-h)/(E.x*E.x+E.y*E.y+E.z*E.z),u=e+E.x*d,m=t+E.y*d,p=i+E.z*d,l=u-e,c=m-t,f=p-i,A=l*l+c*c+f*f,A(uG(),dG));return t(e),this.setIndices(e,this.getTotalVertices()),this}alignWithNormal(e,t){t||(t=Ss.Y);let i=$.Vector3[0],r=$.Vector3[1];return b.CrossToRef(t,e,r),b.CrossToRef(e,r,i),this.rotationQuaternion?Ye.RotationQuaternionFromAxisToRef(i,e,r,this.rotationQuaternion):b.RotationFromAxisToRef(i,e,r,this.rotation),this}_checkOcclusionQuery(e=!1){return!1}disableEdgesRendering(){throw Ze("EdgesRenderer")}enableEdgesRendering(e,t,i){throw Ze("EdgesRenderer")}getConnectedParticleSystems(){return this._scene.particleSystems.filter(e=>e.emitter===this)}};gr.OCCLUSION_TYPE_NONE=0;gr.OCCLUSION_TYPE_OPTIMISTIC=1;gr.OCCLUSION_TYPE_STRICT=2;gr.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0;gr.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1;gr.CULLINGSTRATEGY_STANDARD=0;gr.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1;gr.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2;gr.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3;gr.DefaultIsPickable=!0;P([Ts.filter((...n)=>!Array.isArray(n[0])&&!Array.isArray(n[3])&&!Array.isArray(n[4])&&!Array.isArray(n[5])&&!Array.isArray(n[6]))],gr,"_ApplySkeleton",null);wt("BABYLON.AbstractMesh",gr)});var Nn,mG=C(()=>{Gt();Tr();Ut();Nn=class{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.funcRef=1,this.funcMask=255,this.func=519,this.opStencilFail=7680,this.opDepthFail=7680,this.opStencilDepthPass=7681,this.backFunc=519,this.backOpStencilFail=7680,this.backOpDepthFail=7680,this.backOpStencilDepthPass=7681}get func(){return this._func}set func(e){this._func=e}get backFunc(){return this._backFunc}set backFunc(e){this._backFunc=e}get funcRef(){return this._funcRef}set funcRef(e){this._funcRef=e}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask=e}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail=e}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail=e}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass=e}get backOpStencilFail(){return this._backOpStencilFail}set backOpStencilFail(e){this._backOpStencilFail=e}get backOpDepthFail(){return this._backOpDepthFail}set backOpDepthFail(e){this._backOpDepthFail=e}get backOpStencilDepthPass(){return this._backOpStencilDepthPass}set backOpStencilDepthPass(e){this._backOpStencilDepthPass=e}get mask(){return this._mask}set mask(e){this._mask=e}get enabled(){return this._enabled}set enabled(e){this._enabled=e}getClassName(){return"MaterialStencilState"}copyTo(e){it.Clone(()=>e,this)}serialize(){return it.Serialize(this)}parse(e,t,i){it.Parse(()=>this,e,t,i)}};P([w()],Nn.prototype,"func",null);P([w()],Nn.prototype,"backFunc",null);P([w()],Nn.prototype,"funcRef",null);P([w()],Nn.prototype,"funcMask",null);P([w()],Nn.prototype,"opStencilFail",null);P([w()],Nn.prototype,"opDepthFail",null);P([w()],Nn.prototype,"opStencilDepthPass",null);P([w()],Nn.prototype,"backOpStencilFail",null);P([w()],Nn.prototype,"backOpDepthFail",null);P([w()],Nn.prototype,"backOpStencilDepthPass",null);P([w()],Nn.prototype,"mask",null);P([w()],Nn.prototype,"enabled",null)});function wn(n){n.indexOf("vClipPlane")===-1&&n.push("vClipPlane"),n.indexOf("vClipPlane2")===-1&&n.push("vClipPlane2"),n.indexOf("vClipPlane3")===-1&&n.push("vClipPlane3"),n.indexOf("vClipPlane4")===-1&&n.push("vClipPlane4"),n.indexOf("vClipPlane5")===-1&&n.push("vClipPlane5"),n.indexOf("vClipPlane6")===-1&&n.push("vClipPlane6")}function al(n,e,t){var c,f,h,d,u,m;let i=!!((c=n.clipPlane)!=null?c:e.clipPlane),r=!!((f=n.clipPlane2)!=null?f:e.clipPlane2),s=!!((h=n.clipPlane3)!=null?h:e.clipPlane3),a=!!((d=n.clipPlane4)!=null?d:e.clipPlane4),o=!!((u=n.clipPlane5)!=null?u:e.clipPlane5),l=!!((m=n.clipPlane6)!=null?m:e.clipPlane6);i&&t.push("#define CLIPPLANE"),r&&t.push("#define CLIPPLANE2"),s&&t.push("#define CLIPPLANE3"),a&&t.push("#define CLIPPLANE4"),o&&t.push("#define CLIPPLANE5"),l&&t.push("#define CLIPPLANE6")}function pG(n,e,t){var f,h,d,u,m,p;let i=!1,r=!!((f=n.clipPlane)!=null?f:e.clipPlane),s=!!((h=n.clipPlane2)!=null?h:e.clipPlane2),a=!!((d=n.clipPlane3)!=null?d:e.clipPlane3),o=!!((u=n.clipPlane4)!=null?u:e.clipPlane4),l=!!((m=n.clipPlane5)!=null?m:e.clipPlane5),c=!!((p=n.clipPlane6)!=null?p:e.clipPlane6);return t.CLIPPLANE!==r&&(t.CLIPPLANE=r,i=!0),t.CLIPPLANE2!==s&&(t.CLIPPLANE2=s,i=!0),t.CLIPPLANE3!==a&&(t.CLIPPLANE3=a,i=!0),t.CLIPPLANE4!==o&&(t.CLIPPLANE4=o,i=!0),t.CLIPPLANE5!==l&&(t.CLIPPLANE5=l,i=!0),t.CLIPPLANE6!==c&&(t.CLIPPLANE6=c,i=!0),i}function Fn(n,e,t){var r,s,a,o,l,c;let i=(r=e.clipPlane)!=null?r:t.clipPlane;vm(n,"vClipPlane",i),i=(s=e.clipPlane2)!=null?s:t.clipPlane2,vm(n,"vClipPlane2",i),i=(a=e.clipPlane3)!=null?a:t.clipPlane3,vm(n,"vClipPlane3",i),i=(o=e.clipPlane4)!=null?o:t.clipPlane4,vm(n,"vClipPlane4",i),i=(l=e.clipPlane5)!=null?l:t.clipPlane5,vm(n,"vClipPlane5",i),i=(c=e.clipPlane6)!=null?c:t.clipPlane6,vm(n,"vClipPlane6",i)}function vm(n,e,t){var i;if(t){let r=((i=Ia.getScene())==null?void 0:i.floatingOriginOffset)||b.ZeroReadOnly;n.setFloat4(e,t.normal.x,t.normal.y,t.normal.z,t.d+b.Dot(t.normal,r))}}var ol=C(()=>{J_();Ve()});var le,Da=C(()=>{wr();le=class{static get DiffuseTextureEnabled(){return this._DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){this._DiffuseTextureEnabled!==e&&(this._DiffuseTextureEnabled=e,Ie.MarkAllMaterialsAsDirty(1))}static get BaseWeightTextureEnabled(){return this._BaseWeightTextureEnabled}static set BaseWeightTextureEnabled(e){this._BaseWeightTextureEnabled!==e&&(this._BaseWeightTextureEnabled=e,Ie.MarkAllMaterialsAsDirty(1))}static get BaseDiffuseRoughnessTextureEnabled(){return this._BaseDiffuseRoughnessTextureEnabled}static set BaseDiffuseRoughnessTextureEnabled(e){this._BaseDiffuseRoughnessTextureEnabled!==e&&(this._BaseDiffuseRoughnessTextureEnabled=e,Ie.MarkAllMaterialsAsDirty(1))}static get DetailTextureEnabled(){return this._DetailTextureEnabled}static set DetailTextureEnabled(e){this._DetailTextureEnabled!==e&&(this._DetailTextureEnabled=e,Ie.MarkAllMaterialsAsDirty(1))}static get DecalMapEnabled(){return this._DecalMapEnabled}static set DecalMapEnabled(e){this._DecalMapEnabled!==e&&(this._DecalMapEnabled=e,Ie.MarkAllMaterialsAsDirty(1))}static get AmbientTextureEnabled(){return this._AmbientTextureEnabled}static set AmbientTextureEnabled(e){this._AmbientTextureEnabled!==e&&(this._AmbientTextureEnabled=e,Ie.MarkAllMaterialsAsDirty(1))}static get OpacityTextureEnabled(){return this._OpacityTextureEnabled}static set OpacityTextureEnabled(e){this._OpacityTextureEnabled!==e&&(this._OpacityTextureEnabled=e,Ie.MarkAllMaterialsAsDirty(1))}static get ReflectionTextureEnabled(){return this._ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){this._ReflectionTextureEnabled!==e&&(this._ReflectionTextureEnabled=e,Ie.MarkAllMaterialsAsDirty(1))}static get EmissiveTextureEnabled(){return this._EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){this._EmissiveTextureEnabled!==e&&(this._EmissiveTextureEnabled=e,Ie.MarkAllMaterialsAsDirty(1))}static get SpecularTextureEnabled(){return this._SpecularTextureEnabled}static set SpecularTextureEnabled(e){this._SpecularTextureEnabled!==e&&(this._SpecularTextureEnabled=e,Ie.MarkAllMaterialsAsDirty(1))}static get BumpTextureEnabled(){return this._BumpTextureEnabled}static set BumpTextureEnabled(e){this._BumpTextureEnabled!==e&&(this._BumpTextureEnabled=e,Ie.MarkAllMaterialsAsDirty(1))}static get LightmapTextureEnabled(){return this._LightmapTextureEnabled}static set LightmapTextureEnabled(e){this._LightmapTextureEnabled!==e&&(this._LightmapTextureEnabled=e,Ie.MarkAllMaterialsAsDirty(1))}static get RefractionTextureEnabled(){return this._RefractionTextureEnabled}static set RefractionTextureEnabled(e){this._RefractionTextureEnabled!==e&&(this._RefractionTextureEnabled=e,Ie.MarkAllMaterialsAsDirty(1))}static get ColorGradingTextureEnabled(){return this._ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){this._ColorGradingTextureEnabled!==e&&(this._ColorGradingTextureEnabled=e,Ie.MarkAllMaterialsAsDirty(1))}static get FresnelEnabled(){return this._FresnelEnabled}static set FresnelEnabled(e){this._FresnelEnabled!==e&&(this._FresnelEnabled=e,Ie.MarkAllMaterialsAsDirty(4))}static get ClearCoatTextureEnabled(){return this._ClearCoatTextureEnabled}static set ClearCoatTextureEnabled(e){this._ClearCoatTextureEnabled!==e&&(this._ClearCoatTextureEnabled=e,Ie.MarkAllMaterialsAsDirty(1))}static get ClearCoatBumpTextureEnabled(){return this._ClearCoatBumpTextureEnabled}static set ClearCoatBumpTextureEnabled(e){this._ClearCoatBumpTextureEnabled!==e&&(this._ClearCoatBumpTextureEnabled=e,Ie.MarkAllMaterialsAsDirty(1))}static get ClearCoatTintTextureEnabled(){return this._ClearCoatTintTextureEnabled}static set ClearCoatTintTextureEnabled(e){this._ClearCoatTintTextureEnabled!==e&&(this._ClearCoatTintTextureEnabled=e,Ie.MarkAllMaterialsAsDirty(1))}static get SheenTextureEnabled(){return this._SheenTextureEnabled}static set SheenTextureEnabled(e){this._SheenTextureEnabled!==e&&(this._SheenTextureEnabled=e,Ie.MarkAllMaterialsAsDirty(1))}static get AnisotropicTextureEnabled(){return this._AnisotropicTextureEnabled}static set AnisotropicTextureEnabled(e){this._AnisotropicTextureEnabled!==e&&(this._AnisotropicTextureEnabled=e,Ie.MarkAllMaterialsAsDirty(1))}static get ThicknessTextureEnabled(){return this._ThicknessTextureEnabled}static set ThicknessTextureEnabled(e){this._ThicknessTextureEnabled!==e&&(this._ThicknessTextureEnabled=e,Ie.MarkAllMaterialsAsDirty(1))}static get RefractionIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set RefractionIntensityTextureEnabled(e){this._RefractionIntensityTextureEnabled!==e&&(this._RefractionIntensityTextureEnabled=e,Ie.MarkAllMaterialsAsDirty(1))}static get TranslucencyIntensityTextureEnabled(){return this._TranslucencyIntensityTextureEnabled}static set TranslucencyIntensityTextureEnabled(e){this._TranslucencyIntensityTextureEnabled!==e&&(this._TranslucencyIntensityTextureEnabled=e,Ie.MarkAllMaterialsAsDirty(1))}static get TranslucencyColorTextureEnabled(){return this._TranslucencyColorTextureEnabled}static set TranslucencyColorTextureEnabled(e){this._TranslucencyColorTextureEnabled!==e&&(this._TranslucencyColorTextureEnabled=e,Ie.MarkAllMaterialsAsDirty(1))}static get IridescenceTextureEnabled(){return this._IridescenceTextureEnabled}static set IridescenceTextureEnabled(e){this._IridescenceTextureEnabled!==e&&(this._IridescenceTextureEnabled=e,Ie.MarkAllMaterialsAsDirty(1))}};le._DiffuseTextureEnabled=!0;le._BaseWeightTextureEnabled=!0;le._BaseDiffuseRoughnessTextureEnabled=!0;le._DetailTextureEnabled=!0;le._DecalMapEnabled=!0;le._AmbientTextureEnabled=!0;le._OpacityTextureEnabled=!0;le._ReflectionTextureEnabled=!0;le._EmissiveTextureEnabled=!0;le._SpecularTextureEnabled=!0;le._BumpTextureEnabled=!0;le._LightmapTextureEnabled=!0;le._RefractionTextureEnabled=!0;le._ColorGradingTextureEnabled=!0;le._FresnelEnabled=!0;le._ClearCoatTextureEnabled=!0;le._ClearCoatBumpTextureEnabled=!0;le._ClearCoatTintTextureEnabled=!0;le._SheenTextureEnabled=!0;le._AnisotropicTextureEnabled=!0;le._ThicknessTextureEnabled=!0;le._RefractionIntensityTextureEnabled=!0;le._TranslucencyIntensityTextureEnabled=!0;le._TranslucencyColorTextureEnabled=!0;le._IridescenceTextureEnabled=!0});function Tf(n,e,t){if(!n||n.LOGARITHMICDEPTH||n.indexOf&&n.indexOf("LOGARITHMICDEPTH")>=0){let i=t.activeCamera;i.mode===1&&te.Error("Logarithmic depth is not compatible with orthographic cameras!",20),e.setFloat("logarithmicDepthConstant",2/(Math.log(i.maxZ+1)/Math.LN2))}}var _G=C(()=>{yt()});function Af(n,e,t,i=!1){t&&n.fogEnabled&&(!e||e.applyFog)&&n.fogMode!==0&&(t.setFloat4("vFogInfos",n.fogMode,n.fogStart,n.fogEnd,n.fogDensity),i?(n.fogColor.toLinearSpaceToRef(gG,n.getEngine().useExactSrgbConversions),t.setColor3("vFogColor",gG)):t.setColor3("vFogColor",n.fogColor))}function ll(n,e,t,i,r,s,a,o,l,c){let f=n.numMaxInfluencers||n.numInfluencers;return f<=0?0:(e.push("#define MORPHTARGETS"),n.hasPositions&&e.push("#define MORPHTARGETTEXTURE_HASPOSITIONS"),n.hasNormals&&e.push("#define MORPHTARGETTEXTURE_HASNORMALS"),n.hasTangents&&e.push("#define MORPHTARGETTEXTURE_HASTANGENTS"),n.hasUVs&&e.push("#define MORPHTARGETTEXTURE_HASUVS"),n.hasUV2s&&e.push("#define MORPHTARGETTEXTURE_HASUV2S"),n.hasColors&&e.push("#define MORPHTARGETTEXTURE_HASCOLORS"),n.supportsPositions&&r&&e.push("#define MORPHTARGETS_POSITION"),n.supportsNormals&&s&&e.push("#define MORPHTARGETS_NORMAL"),n.supportsTangents&&a&&e.push("#define MORPHTARGETS_TANGENT"),n.supportsUVs&&o&&e.push("#define MORPHTARGETS_UV"),n.supportsUV2s&&l&&e.push("#define MORPHTARGETS_UV2"),n.supportsColors&&c&&e.push("#define MORPHTARGETS_COLOR"),e.push("#define NUM_MORPH_INFLUENCERS "+f),n.isUsingTextureForTargets&&e.push("#define MORPHTARGETS_TEXTURE"),Zh.NUM_MORPH_INFLUENCERS=f,Zh.NORMAL=s,Zh.TANGENT=a,Zh.UV=o,Zh.UV2=l,Zh.COLOR=c,Qh(t,i,Zh,r),f)}function Qh(n,e,t,i=!0){let r=t.NUM_MORPH_INFLUENCERS;if(r>0&&Le.LastCreatedEngine){let s=Le.LastCreatedEngine.getCaps().maxVertexAttribs,a=e.morphTargetManager;if(a!=null&&a.isUsingTextureForTargets)return;let o=a&&a.supportsPositions&&i,l=a&&a.supportsNormals&&t.NORMAL,c=a&&a.supportsTangents&&t.TANGENT,f=a&&a.supportsUVs&&t.UV1,h=a&&a.supportsUV2s&&t.UV2,d=a&&a.supportsColors&&t.VERTEXCOLOR;for(let u=0;us&&te.Error("Cannot add more vertex attributes for mesh "+e.name)}}function mo(n,e=!1){n.push("world0"),n.push("world1"),n.push("world2"),n.push("world3"),e&&(n.push("previousWorld0"),n.push("previousWorld1"),n.push("previousWorld2"),n.push("previousWorld3"))}function Bn(n,e){let t=n.morphTargetManager;!n||!t||e.setFloatArray("morphTargetInfluences",t.influences)}function xf(n,e){e.bindToEffect(n,"Scene")}function Em(n,e,t,i,r=null,s=!1,a=!1,o=!1,l=!1,c=!1,f=!1,h=0){if(n.texturesEnabled&&r&&le.ReflectionTextureEnabled){if(t.updateMatrix("reflectionMatrix",r.getReflectionTextureMatrix()),t.updateFloat2("vReflectionInfos",r.level*n.iblIntensity,h),o&&r.boundingBoxSize){let d=r;t.updateVector3("vReflectionPosition",d.boundingBoxPosition),t.updateVector3("vReflectionSize",d.boundingBoxSize)}if(s){let d=r.getSize().width;t.updateFloat2("vReflectionFilteringInfo",d,Math.log2(d))}if(c&&!e.USEIRRADIANCEMAP){let d=r.sphericalPolynomial;if(e.USESPHERICALFROMREFLECTIONMAP&&d)if(e.SPHERICAL_HARMONICS){let u=d.preScaledHarmonics;t.updateVector3("vSphericalL00",u.l00),t.updateVector3("vSphericalL1_1",u.l1_1),t.updateVector3("vSphericalL10",u.l10),t.updateVector3("vSphericalL11",u.l11),t.updateVector3("vSphericalL2_2",u.l2_2),t.updateVector3("vSphericalL2_1",u.l2_1),t.updateVector3("vSphericalL20",u.l20),t.updateVector3("vSphericalL21",u.l21),t.updateVector3("vSphericalL22",u.l22)}else t.updateFloat3("vSphericalX",d.x.x,d.x.y,d.x.z),t.updateFloat3("vSphericalY",d.y.x,d.y.y,d.y.z),t.updateFloat3("vSphericalZ",d.z.x,d.z.y,d.z.z),t.updateFloat3("vSphericalXX_ZZ",d.xx.x-d.zz.x,d.xx.y-d.zz.y,d.xx.z-d.zz.z),t.updateFloat3("vSphericalYY_ZZ",d.yy.x-d.zz.x,d.yy.y-d.zz.y,d.yy.z-d.zz.z),t.updateFloat3("vSphericalZZ",d.zz.x,d.zz.y,d.zz.z),t.updateFloat3("vSphericalXY",d.xy.x,d.xy.y,d.xy.z),t.updateFloat3("vSphericalYZ",d.yz.x,d.yz.y,d.yz.z),t.updateFloat3("vSphericalZX",d.zx.x,d.zx.y,d.zx.z)}else l&&e.USEIRRADIANCEMAP&&e.USE_IRRADIANCE_DOMINANT_DIRECTION&&r.irradianceTexture&&t.updateVector3("vReflectionDominantDirection",r.irradianceTexture._dominantDirection);a&&t.updateFloat3("vReflectionMicrosurfaceInfos",r.getSize().width,r.lodGenerationScale,r.lodGenerationOffset)}f&&t.updateColor3("vReflectionColor",i)}function DA(n,e,t,i=null,r=!1){if(i&&le.ReflectionTextureEnabled){e.LODBASEDMICROSFURACE?t.setTexture("reflectionSampler",i):(t.setTexture("reflectionSampler",i._lodTextureMid||i),t.setTexture("reflectionSamplerLow",i._lodTextureLow||i),t.setTexture("reflectionSamplerHigh",i._lodTextureHigh||i)),e.USEIRRADIANCEMAP&&t.setTexture("irradianceSampler",i.irradianceTexture);let s=n.iblCdfGenerator;r&&s&&t.setTexture("icdfSampler",s.getIcdfTexture())}}function ri(n,e,t){e._needUVs=!0,e[t]=!0,n.optimizeUVAllocation&&n.getTextureMatrix().isIdentityAs3x2()?(e[t+"DIRECTUV"]=n.coordinatesIndex+1,e["MAINUV"+(n.coordinatesIndex+1)]=!0):e[t+"DIRECTUV"]=0}function ni(n,e,t){let i=n.getTextureMatrix();e.updateMatrix(t+"Matrix",i)}function Sm(n,e,t){t.BAKED_VERTEX_ANIMATION_TEXTURE&&t.INSTANCES&&n.push("bakedVertexAnimationSettingsInstanced")}function Sse(n,e){return e.set(n),e}function bs(n,e,t){if(!(!e||!n)&&(n.computeBonesUsingShaders&&e._bonesComputationForcedToCPU&&(n.computeBonesUsingShaders=!1),n.useBones&&n.computeBonesUsingShaders&&n.skeleton)){let i=n.skeleton;if(i.isUsingTextureForMatrices&&e.getUniformIndex("boneTextureInfo")>-1){let r=i.getTransformMatrixTexture(n);e.setTexture("boneSampler",r),e.setFloat2("boneTextureInfo",i._textureWidth,i._textureHeight)}else{let r=i.getTransformMatrices(n);r&&(e.setMatrices("mBones",r),t&&n.getScene().prePassRenderer&&n.getScene().prePassRenderer.getIndex(2)&&(t.previousBones[n.uniqueId]||(t.previousBones[n.uniqueId]=r.slice()),e.setMatrices("mPreviousBones",t.previousBones[n.uniqueId]),Sse(r,t.previousBones[n.uniqueId])))}}}function Tse(n,e,t,i,r,s=!0){n._bindLight(e,t,i,r,s)}function Tm(n,e,t,i,r=4){let s=Math.min(e.lightSources.length,r);for(let a=0;a0&&(i.addCPUSkinningFallback(0,e),n.push("matricesIndices"),n.push("matricesWeights"),t.NUM_BONE_INFLUENCERS>4&&(n.push("matricesIndicesExtra"),n.push("matricesWeightsExtra")))}function xm(n,e){(e.INSTANCES||e.THIN_INSTANCES)&&mo(n,!!e.PREPASS_VELOCITY),e.INSTANCESCOLOR&&n.push("instanceColor")}function Rm(n,e,t=4,i=0){let r=0;for(let s=0;s0&&(r=i+s,e.addFallback(r,"LIGHT"+s)),n.SHADOWS||(n["SHADOW"+s]&&e.addFallback(i,"SHADOW"+s),n["SHADOWPCF"+s]&&e.addFallback(i,"SHADOWPCF"+s),n["SHADOWPCSS"+s]&&e.addFallback(i,"SHADOWPCSS"+s),n["SHADOWPOISSON"+s]&&e.addFallback(i,"SHADOWPOISSON"+s),n["SHADOWESM"+s]&&e.addFallback(i,"SHADOWESM"+s),n["SHADOWCLOSEESM"+s]&&e.addFallback(i,"SHADOWCLOSEESM"+s));return r}function Ase(n,e){return e.fogEnabled&&n.applyFog&&e.fogMode!==0}function bm(n,e,t,i,r,s,a,o=!1,l=!1,c,f){var h;if(a._areMiscDirty){a.LOGARITHMICDEPTH=t,a.POINTSIZE=i,a.FOG=r&&Ase(n,e),a.NONUNIFORMSCALING=n.nonUniformScaling,a.ALPHATEST=s,a.DECAL_AFTER_DETAIL=o,a.USE_VERTEX_PULLING=l,a.RIGHT_HANDED=e.useRightHandedSystem;let d=(h=c==null?void 0:c.geometry)==null?void 0:h.getIndexBuffer(),u=c?c.isUnIndexed:!1;a.VERTEX_PULLING_USE_INDEX_BUFFER=!!d&&!u,a.VERTEX_PULLING_INDEX_BUFFER_32BITS=d&&!u?d.is32Bits:!1,a.VERTEXOUTPUT_INVARIANT=!!f}}function Im(n,e,t,i=!1){if(!n.lightsEnabled||i)return!0;let r=e.lightSources,s=Math.min(r.length,t);for(let a=0;a0?(t.NUM_SAMPLES=""+r,a._features.needTypeSuffixInShaderConstants&&(t.NUM_SAMPLES=t.NUM_SAMPLES+"u"),t.REALTIME_FILTERING=!0,n.iblCdfGenerator&&(t.IBL_CDF_FILTERING=!0)):t.REALTIME_FILTERING=!1,t.INVERTCUBICMAP=e.coordinatesMode===_e.INVCUBIC_MODE,t.REFLECTIONMAP_3D=e.isCube,t.REFLECTIONMAP_OPPOSITEZ=t.REFLECTIONMAP_3D&&n.useRightHandedSystem?!e.invertZ:e.invertZ,t.REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,e.coordinatesMode){case _e.EXPLICIT_MODE:t.REFLECTIONMAP_EXPLICIT=!0;break;case _e.PLANAR_MODE:t.REFLECTIONMAP_PLANAR=!0;break;case _e.PROJECTION_MODE:t.REFLECTIONMAP_PROJECTION=!0;break;case _e.SKYBOX_MODE:t.REFLECTIONMAP_SKYBOX=!0;break;case _e.SPHERICAL_MODE:t.REFLECTIONMAP_SPHERICAL=!0;break;case _e.EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case _e.FIXED_EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case _e.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case _e.CUBIC_MODE:case _e.INVCUBIC_MODE:default:t.REFLECTIONMAP_CUBIC=!0,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!!e.boundingBoxSize;break}e.coordinatesMode!==_e.SKYBOX_MODE&&(e.irradianceTexture?(t.USEIRRADIANCEMAP=!0,t.USESPHERICALFROMREFLECTIONMAP=!1,t.USESPHERICALINVERTEX=!1,e.irradianceTexture._dominantDirection?t.USE_IRRADIANCE_DOMINANT_DIRECTION=!0:t.USE_IRRADIANCE_DOMINANT_DIRECTION=!1):e.isCube&&(t.USESPHERICALFROMREFLECTIONMAP=!0,t.USEIRRADIANCEMAP=!1,t.USE_IRRADIANCE_DOMINANT_DIRECTION=!1,t.USESPHERICALINVERTEX=s))}else t.REFLECTION=!1,t.REFLECTIONMAP_3D=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_CUBIC=!1,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,t.INVERTCUBICMAP=!1,t.USESPHERICALFROMREFLECTIONMAP=!1,t.USEIRRADIANCEMAP=!1,t.USE_IRRADIANCE_DOMINANT_DIRECTION=!1,t.USESPHERICALINVERTEX=!1,t.REFLECTIONMAP_OPPOSITEZ=!1,t.LODINREFLECTIONALPHA=!1,t.GAMMAREFLECTION=!1,t.RGBDREFLECTION=!1,t.LINEARSPECULARREFLECTION=!1;return!0}function xse(n,e,t,i,r,s,a){var o;switch(a.needNormals=!0,r["LIGHT"+i]===void 0&&(a.needRebuild=!0),r["LIGHT"+i]=!0,r["SPOTLIGHT"+i]=!1,r["HEMILIGHT"+i]=!1,r["POINTLIGHT"+i]=!1,r["DIRLIGHT"+i]=!1,r["AREALIGHT"+i]=!1,r["CLUSTLIGHT"+i]=!1,t.prepareLightSpecificDefines(r,i),r["LIGHT_FALLOFF_PHYSICAL"+i]=!1,r["LIGHT_FALLOFF_GLTF"+i]=!1,r["LIGHT_FALLOFF_STANDARD"+i]=!1,t.falloffType){case Yt.FALLOFF_GLTF:r["LIGHT_FALLOFF_GLTF"+i]=!0;break;case Yt.FALLOFF_PHYSICAL:r["LIGHT_FALLOFF_PHYSICAL"+i]=!0;break;case Yt.FALLOFF_STANDARD:r["LIGHT_FALLOFF_STANDARD"+i]=!0;break}if(s&&!t.specular.equalsFloats(0,0,0)&&(a.specularEnabled=!0),r["SHADOW"+i]=!1,r["SHADOWCSM"+i]=!1,r["SHADOWCSMDEBUG"+i]=!1,r["SHADOWCSMNUM_CASCADES"+i]=!1,r["SHADOWCSMUSESHADOWMAXZ"+i]=!1,r["SHADOWCSMNOBLEND"+i]=!1,r["SHADOWCSM_RIGHTHANDED"+i]=!1,r["SHADOWPCF"+i]=!1,r["SHADOWPCSS"+i]=!1,r["SHADOWPOISSON"+i]=!1,r["SHADOWESM"+i]=!1,r["SHADOWCLOSEESM"+i]=!1,r["SHADOWCUBE"+i]=!1,r["SHADOWLOWQUALITY"+i]=!1,r["SHADOWMEDIUMQUALITY"+i]=!1,e&&e.receiveShadows&&n.shadowsEnabled&&t.shadowEnabled){let l=(o=t.getShadowGenerator(n.activeCamera))!=null?o:t.getShadowGenerator();if(l){let c=l.getShadowMap();c&&c.renderList&&c.renderList.length>0&&(a.shadowEnabled=!0,l.prepareDefines(r,i))}}t.lightmapMode!=Yt.LIGHTMAP_DEFAULT?(a.lightmapMode=!0,r["LIGHTMAPEXCLUDED"+i]=!0,r["LIGHTMAPNOSPECULAR"+i]=t.lightmapMode==Yt.LIGHTMAP_SHADOWSONLY):(r["LIGHTMAPEXCLUDED"+i]=!1,r["LIGHTMAPNOSPECULAR"+i]=!1)}function Cm(n,e,t,i,r,s=null,a=!1){let o=Mse(n,i);s!==!1&&(o=pG(t,n,i)),i.DEPTHPREPASS!==!e.getColorWrite()&&(i.DEPTHPREPASS=!i.DEPTHPREPASS,o=!0),i.INSTANCES!==r&&(i.INSTANCES=r,o=!0),i.THIN_INSTANCES!==a&&(i.THIN_INSTANCES=a,o=!0),o&&i.markAsUnprocessed()}function Rse(n,e){if(n.useBones&&n.computeBonesUsingShaders&&n.skeleton){e.NUM_BONE_INFLUENCERS=n.numBoneInfluencers;let t=e.BONETEXTURE!==void 0;if(n.skeleton.isUsingTextureForMatrices&&t)e.BONETEXTURE=!0;else{e.BonesPerMesh=n.skeleton.bones.length+1,e.BONETEXTURE=t?!1:void 0;let i=n.getScene().prePassRenderer;if(i&&i.enabled){let r=i.excludedSkinnedMesh.indexOf(n)===-1;e.BONES_VELOCITY_ENABLED=r}}}else e.NUM_BONE_INFLUENCERS=0,e.BonesPerMesh=0,e.BONETEXTURE!==void 0&&(e.BONETEXTURE=!1)}function bse(n,e){let t=n.morphTargetManager;t?(e.MORPHTARGETS_UV=t.supportsUVs&&e.UV1,e.MORPHTARGETS_UV2=t.supportsUV2s&&e.UV2,e.MORPHTARGETS_TANGENT=t.supportsTangents&&e.TANGENT,e.MORPHTARGETS_NORMAL=t.supportsNormals&&e.NORMAL,e.MORPHTARGETS_POSITION=t.supportsPositions,e.MORPHTARGETS_COLOR=t.supportsColors,e.MORPHTARGETTEXTURE_HASUVS=t.hasUVs,e.MORPHTARGETTEXTURE_HASUV2S=t.hasUV2s,e.MORPHTARGETTEXTURE_HASTANGENTS=t.hasTangents,e.MORPHTARGETTEXTURE_HASNORMALS=t.hasNormals,e.MORPHTARGETTEXTURE_HASPOSITIONS=t.hasPositions,e.MORPHTARGETTEXTURE_HASCOLORS=t.hasColors,e.NUM_MORPH_INFLUENCERS=t.numMaxInfluencers||t.numInfluencers,e.MORPHTARGETS=e.NUM_MORPH_INFLUENCERS>0,e.MORPHTARGETS_TEXTURE=t.isUsingTextureForTargets):(e.MORPHTARGETS_UV=!1,e.MORPHTARGETS_UV2=!1,e.MORPHTARGETS_TANGENT=!1,e.MORPHTARGETS_NORMAL=!1,e.MORPHTARGETS_POSITION=!1,e.MORPHTARGETS_COLOR=!1,e.MORPHTARGETTEXTURE_HASUVS=!1,e.MORPHTARGETTEXTURE_HASUV2S=!1,e.MORPHTARGETTEXTURE_HASTANGENTS=!1,e.MORPHTARGETTEXTURE_HASNORMALS=!1,e.MORPHTARGETTEXTURE_HASPOSITIONS=!1,e.MORPHTARGETTEXTURE_HAS_COLORS=!1,e.MORPHTARGETS=!1,e.NUM_MORPH_INFLUENCERS=0)}function Ise(n,e){let t=n.bakedVertexAnimationManager;e.BAKED_VERTEX_ANIMATION_TEXTURE=!!(t&&t.isEnabled)}function ym(n,e,t,i,r=!1,s=!0,a=!0){if(!e._areAttributesDirty&&e._needNormals===e._normals&&e._needUVs===e._uvs)return!1;e._normals=e._needNormals,e._uvs=e._needUVs,e.NORMAL=e._needNormals&&n.isVerticesDataPresent("normal"),e._needNormals&&n.isVerticesDataPresent("tangent")&&(e.TANGENT=!0);for(let o=1;o<=6;++o)e["UV"+o]=e._needUVs?n.isVerticesDataPresent(`uv${o===1?"":o}`):!1;if(t){let o=n.useVertexColors&&n.isVerticesDataPresent("color");e.VERTEXCOLOR=o,e.VERTEXALPHA=n.hasVertexAlpha&&o&&s}return n.isVerticesDataPresent("instanceColor")&&(n.hasInstances||n.hasThinInstances)&&(e.INSTANCESCOLOR=!0),i&&Rse(n,e),r&&bse(n,e),a&&Ise(n,e),!0}function Pm(n,e){if(n.activeCamera){let t=e.MULTIVIEW;e.MULTIVIEW=n.activeCamera.outputRenderTarget!==null&&n.activeCamera.outputRenderTarget.getViewCount()>1,e.MULTIVIEW!=t&&e.markAsUnprocessed()}}function Dm(n,e,t){let i=e.ORDER_INDEPENDENT_TRANSPARENCY,r=e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;e.ORDER_INDEPENDENT_TRANSPARENCY=n.useOrderIndependentTransparency&&t,e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!n.getEngine().getCaps().textureFloatLinearFiltering,(i!==e.ORDER_INDEPENDENT_TRANSPARENCY||r!==e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS)&&e.markAsUnprocessed()}function Lm(n,e,t){let i=e.PREPASS;if(!e._arePrePassDirty)return;let r=[{type:1,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:9,define:"PREPASS_LOCAL_POSITION",index:"PREPASS_LOCAL_POSITION_INDEX"},{type:2,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:11,define:"PREPASS_VELOCITY_LINEAR",index:"PREPASS_VELOCITY_LINEAR_INDEX"},{type:3,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:0,define:"PREPASS_IRRADIANCE_LEGACY",index:"PREPASS_IRRADIANCE_LEGACY_INDEX"},{type:7,define:"PREPASS_ALBEDO_SQRT",index:"PREPASS_ALBEDO_SQRT_INDEX"},{type:5,define:"PREPASS_DEPTH",index:"PREPASS_DEPTH_INDEX"},{type:10,define:"PREPASS_SCREENSPACE_DEPTH",index:"PREPASS_SCREENSPACE_DEPTH_INDEX"},{type:6,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"},{type:8,define:"PREPASS_WORLD_NORMAL",index:"PREPASS_WORLD_NORMAL_INDEX"},{type:14,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"}];if(n.prePassRenderer&&n.prePassRenderer.enabled&&t){e.PREPASS=!0,e.SCENE_MRT_COUNT=n.prePassRenderer.mrtCount,e.PREPASS_NORMAL_WORLDSPACE=n.prePassRenderer.generateNormalsInWorldSpace,e.PREPASS_COLOR=!0,e.PREPASS_COLOR_INDEX=0;for(let s=0;s{yt();Pi();z_();ol();Da();Fr();_G();gG={r:0,g:0,b:0},Zh={NUM_MORPH_INFLUENCERS:0,NORMAL:!1,TANGENT:!1,UV:!1,UV2:!1,COLOR:!1}});var Ee,Vn=C(()=>{Gt();Ut();bi();hi();Pi();hg();pf();yt();Zu();Gh();mG();Un();Tr();RM();Ee=class n{get useVertexPulling(){return this._useVertexPulling}set useVertexPulling(e){this._useVertexPulling!==e&&(this._useVertexPulling=e,this.markAsDirty(n.MiscDirtyFlag))}get _supportGlowLayer(){return!1}set _glowModeEnabled(e){}get shaderLanguage(){return this._shaderLanguage}get canRenderToMRT(){return!1}set alpha(e){if(this._alpha===e)return;let t=this._alpha;this._alpha=e,(t===1||e===1)&&this.markAsDirty(n.MiscDirtyFlag+n.PrePassDirtyFlag)}get alpha(){return this._alpha}set backFaceCulling(e){this._backFaceCulling!==e&&(this._backFaceCulling=e,this.markAsDirty(n.TextureDirtyFlag))}get backFaceCulling(){return this._backFaceCulling}set cullBackFaces(e){this._cullBackFaces!==e&&(this._cullBackFaces=e,this.markAsDirty(n.TextureDirtyFlag))}get cullBackFaces(){return this._cullBackFaces}get blockDirtyMechanism(){return this._blockDirtyMechanism}set blockDirtyMechanism(e){this._blockDirtyMechanism!==e&&(this._blockDirtyMechanism=e,e||this.markDirty())}atomicMaterialsUpdate(e){this.blockDirtyMechanism=!0;try{e(this)}finally{this.blockDirtyMechanism=!1}}get hasRenderTargetTextures(){return this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._eventInfo.hasRenderTargetTextures}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new ie),this._onBindObservable}set onBind(e){this._onBindObserver&&this.onBindObservable.remove(this._onBindObserver),this._onBindObserver=this.onBindObservable.add(e)}get onUnBindObservable(){return this._onUnBindObservable||(this._onUnBindObservable=new ie),this._onUnBindObservable}get onEffectCreatedObservable(){return this._onEffectCreatedObservable||(this._onEffectCreatedObservable=new ie),this._onEffectCreatedObservable}set alphaMode(e){this._alphaMode[0]!==e&&(this._alphaMode[0]=e,this.markAsDirty(n.TextureDirtyFlag))}get alphaMode(){return this._alphaMode[0]}get alphaModes(){return this._alphaMode}setAlphaMode(e,t=0){this._alphaMode[t]!==e&&(this._alphaMode[t]=e,this.markAsDirty(n.TextureDirtyFlag))}set needDepthPrePass(e){this._needDepthPrePass!==e&&(this._needDepthPrePass=e,this._needDepthPrePass&&(this.checkReadyOnEveryCall=!0))}get needDepthPrePass(){return this._needDepthPrePass}get isPrePassCapable(){return!1}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this.markAsDirty(n.MiscDirtyFlag))}get fogEnabled(){return this._fogEnabled}get wireframe(){switch(this._fillMode){case n.WireFrameFillMode:case n.LineListDrawMode:case n.LineLoopDrawMode:case n.LineStripDrawMode:return!0}return this._scene.forceWireframe}set wireframe(e){this.fillMode=e?n.WireFrameFillMode:n.TriangleFillMode}get pointsCloud(){switch(this._fillMode){case n.PointFillMode:case n.PointListDrawMode:return!0}return this._scene.forcePointsCloud}set pointsCloud(e){this.fillMode=e?n.PointFillMode:n.TriangleFillMode}get fillMode(){return this._fillMode}set fillMode(e){this._fillMode!==e&&(this._fillMode=e,this.markAsDirty(n.MiscDirtyFlag))}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){let t=this.getScene().getEngine().getCaps().fragmentDepthSupported;e&&!t&&te.Warn("Logarithmic depth has been requested for a material on a device that doesn't support it."),this._useLogarithmicDepth=e&&t,this._markAllSubMeshesAsMiscDirty()}get isVertexOutputInvariant(){return this._isVertexOutputInvariant}set isVertexOutputInvariant(e){this._isVertexOutputInvariant!==e&&(this._isVertexOutputInvariant=e,this._markAllSubMeshesAsMiscDirty())}_getDrawWrapper(){return this._drawWrapper}_setDrawWrapper(e){this._drawWrapper=e}constructor(e,t,i,r=!1){this.shadowDepthWrapper=null,this.allowShaderHotSwapping=!0,this._shaderLanguage=0,this._forceGLSL=!1,this._useVertexPulling=!1,this.metadata=null,this.reservedDataStore=null,this.checkReadyOnEveryCall=!1,this.checkReadyOnlyOnce=!1,this.state="",this._alpha=1,this._backFaceCulling=!0,this._cullBackFaces=!0,this._blockDirtyMechanism=!1,this.sideOrientation=null,this.onCompiled=null,this.onError=null,this.getRenderTargetTextures=null,this.doNotSerialize=!1,this._storeEffectOnSubMeshes=!1,this.animations=null,this.onDisposeObservable=new ie,this._onDisposeObserver=null,this._onUnBindObservable=null,this._onBindObserver=null,this._alphaMode=[2],this._needDepthPrePass=!1,this.disableDepthWrite=!1,this.disableColorWrite=!1,this.forceDepthWrite=!1,this.depthFunction=0,this.separateCullingPass=!1,this._fogEnabled=!0,this.pointSize=1,this.zOffset=0,this.zOffsetUnits=0,this.stencil=new Nn,this._isVertexOutputInvariant=n.ForceVertexOutputInvariant,this._useUBO=!1,this._fillMode=n.TriangleFillMode,this._cachedDepthWriteState=!1,this._cachedColorWriteState=!1,this._cachedDepthFunctionState=0,this._indexInSceneMaterialArray=-1,this.meshMap=null,this._parentContainer=null,this._uniformBufferLayoutBuilt=!1,this._eventInfo={},this._callbackPluginEventGeneric=()=>{},this._callbackPluginEventIsReadyForSubMesh=()=>{},this._callbackPluginEventPrepareDefines=()=>{},this._callbackPluginEventPrepareDefinesBeforeAttributes=()=>{},this._callbackPluginEventHardBindForSubMesh=()=>{},this._callbackPluginEventBindForSubMesh=()=>{},this._callbackPluginEventHasRenderTargetTextures=()=>{},this._callbackPluginEventFillRenderTargetTextures=()=>{},this._transparencyMode=null,this.name=e;let s=t||Le.LastCreatedScene;s&&(this._scene=s,this._dirtyCallbacks={},this._forceGLSL=r,this._dirtyCallbacks[1]=this._markAllSubMeshesAsTexturesDirty.bind(this),this._dirtyCallbacks[2]=this._markAllSubMeshesAsLightsDirty.bind(this),this._dirtyCallbacks[4]=this._markAllSubMeshesAsFresnelDirty.bind(this),this._dirtyCallbacks[8]=this._markAllSubMeshesAsAttributesDirty.bind(this),this._dirtyCallbacks[16]=this._markAllSubMeshesAsMiscDirty.bind(this),this._dirtyCallbacks[32]=this._markAllSubMeshesAsPrePassDirty.bind(this),this._dirtyCallbacks[127]=this._markAllSubMeshesAsAllDirty.bind(this),this.id=e||pe.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new Jn(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._uniformBuffer=new fr(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,this._createUniformBuffer(),i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),n.OnEventObservable.notifyObservers(this,1))}_createUniformBuffer(){var t;let e=this.getScene().getEngine();(t=this._uniformBuffer)==null||t.dispose(),e.isWebGPU&&!this._forceGLSL?(this._uniformBuffer=new fr(e,void 0,void 0,this.name,!0),this._shaderLanguage=1):this._uniformBuffer=new fr(this._scene.getEngine(),void 0,void 0,this.name),this._uniformBufferLayoutBuilt=!1}toString(e){return"Name: "+this.name}getClassName(){return"Material"}get _isMaterial(){return!0}get isFrozen(){return this.checkReadyOnlyOnce}freeze(){this.markDirty(),this.checkReadyOnlyOnce=!0}unfreeze(){this.markDirty(),this.checkReadyOnlyOnce=!1}isReady(e,t){return!0}isReadyForSubMesh(e,t,i){let r=t.materialDefines;return r?(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=r,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),this._eventInfo.isReadyForSubMesh):!1}getEffect(){return this._drawWrapper.effect}getScene(){return this._scene}_getEffectiveOrientation(e){return this.sideOrientation!==null?this.sideOrientation:e.sideOrientation}get transparencyMode(){return this._transparencyMode}set transparencyMode(e){this._transparencyMode!==e&&(this._transparencyMode=e,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _hasTransparencyMode(){return this._transparencyMode!=null}get _transparencyModeIsBlend(){return this._transparencyMode===n.MATERIAL_ALPHABLEND||this._transparencyMode===n.MATERIAL_ALPHATESTANDBLEND}get _transparencyModeIsTest(){return this._transparencyMode===n.MATERIAL_ALPHATEST||this._transparencyMode===n.MATERIAL_ALPHATESTANDBLEND}get _disableAlphaBlending(){return this._transparencyMode===n.MATERIAL_OPAQUE||this._transparencyMode===n.MATERIAL_ALPHATEST}needAlphaBlending(){return this._hasTransparencyMode?this._transparencyModeIsBlend:this._disableAlphaBlending?!1:this.alpha<1}needAlphaBlendingForMesh(e){return this._hasTransparencyMode?this._transparencyModeIsBlend:e.visibility<1?!0:this._disableAlphaBlending?!1:e.hasVertexAlpha||this.needAlphaBlending()}needAlphaTesting(){return this._hasTransparencyMode?this._transparencyModeIsTest:!1}needAlphaTestingForMesh(e){return this._hasTransparencyMode?this._transparencyModeIsTest:!this.needAlphaBlendingForMesh(e)&&this.needAlphaTesting()}getAlphaTestTexture(){return null}markDirty(e=!1){let t=this.getScene().meshes;for(let i of t)if(i.subMeshes){for(let r of i.subMeshes)if(r.getMaterial()===this)for(let s of r._drawWrappers)s&&this._materialContext===s.materialContext&&(s._wasPreviouslyReady=!1,s._wasPreviouslyUsingInstances=null,s._forceRebindOnNextCall=e)}e&&this.markAsDirty(n.AllDirtyFlag)}_preBind(e,t=null){let i=this._scene.getEngine(),s=(t==null?this.sideOrientation:t)===n.ClockWiseSideOrientation,a=e||this._getDrawWrapper();return bT(a)&&a.materialContext&&(a.materialContext.useVertexPulling=this.useVertexPulling),i.enableEffect(a),i.setState(this.backFaceCulling,this.zOffset,!1,s,this._scene._mirroredCameraPosition?!this.cullBackFaces:this.cullBackFaces,this.stencil,this.zOffsetUnits),s}bind(e,t){}buildUniformLayout(){let e=this._uniformBuffer;this._eventInfo.ubo=e,this._callbackPluginEventGeneric(8,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0}bindForSubMesh(e,t,i){let r=i._drawWrapper;this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),r._forceRebindOnNextCall=!1}bindOnlyWorldMatrix(e){}bindView(e){this._useUBO?this._needToBindSceneUbo=!0:e.setMatrix("view",this.getScene().getViewMatrix())}bindViewProjection(e){this._useUBO?this._needToBindSceneUbo=!0:(e.setMatrix("viewProjection",this.getScene().getTransformMatrix()),e.setMatrix("projection",this.getScene().getProjectionMatrix()),e.setMatrix("inverseProjection",this.getScene().getInverseProjectionMatrix()))}bindEyePosition(e,t){this._useUBO?this._needToBindSceneUbo=!0:this._scene.bindEyePosition(e,t)}_afterBind(e,t=null,i){if(this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,xf(t,this.getScene().getSceneUniformBuffer()),this._scene.finalizeSceneUbo()),e?this._scene._cachedVisibility=e.visibility:this._scene._cachedVisibility=1,this._onBindObservable&&e&&this._onBindObservable.notifyObservers(e),this.disableDepthWrite){let r=this._scene.getEngine();this._cachedDepthWriteState=r.getDepthWrite(),r.setDepthWrite(!1)}if(this.disableColorWrite){let r=this._scene.getEngine();this._cachedColorWriteState=r.getColorWrite(),r.setColorWrite(!1)}if(this.depthFunction!==0){let r=this._scene.getEngine();this._cachedDepthFunctionState=r.getDepthFunction()||0,r.setDepthFunction(this.depthFunction)}}unbind(){this._scene.getSceneUniformBuffer().unbindEffect(),this._onUnBindObservable&&this._onUnBindObservable.notifyObservers(this),this.depthFunction!==0&&this._scene.getEngine().setDepthFunction(this._cachedDepthFunctionState),this.disableDepthWrite&&this._scene.getEngine().setDepthWrite(this._cachedDepthWriteState),this.disableColorWrite&&this._scene.getEngine().setColorWrite(this._cachedColorWriteState)}getAnimatables(){return this._eventInfo.animatables=[],this._callbackPluginEventGeneric(256,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(512,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(1024,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}_clonePlugins(e,t){let i={};if(this._serializePlugins(i),n._ParsePlugins(i,e,this._scene,t),this.pluginManager)for(let r of this.pluginManager._plugins){let s=e.pluginManager.getPlugin(r.name);s&&r.copyTo(s)}}getBindedMeshes(){if(this.meshMap){let e=[];for(let t in this.meshMap){let i=this.meshMap[t];i&&e.push(i)}return e}else return this._scene.meshes.filter(t=>t.material===this)}forceCompilation(e,t,i,r){let s={clipPlane:!1,useInstances:!1,...i},a=this.getScene(),o=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;let l=()=>{if(!this._scene||!this._scene.getEngine())return;let c=a.clipPlane;if(s.clipPlane&&(a.clipPlane=new to(0,0,0,1)),this._storeEffectOnSubMeshes){let f=!0,h=null;if(e.subMeshes){let d=new Rs(0,0,0,0,0,e,void 0,!1,!1);d.materialDefines&&(d.materialDefines._renderId=-1),this.isReadyForSubMesh(e,d,s.useInstances)||(d.effect&&d.effect.getCompilationError()&&d.effect.allFallbacksProcessed()?h=d.effect.getCompilationError():(f=!1,setTimeout(l,16)))}f&&(this.allowShaderHotSwapping=o,h&&r&&r(h),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=o,t&&t(this)):setTimeout(l,16);s.clipPlane&&(a.clipPlane=c)};l()}async forceCompilationAsync(e,t){return await new Promise((i,r)=>{this.forceCompilation(e,()=>{i()},t,s=>{r(s)})})}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(n._DirtyCallbackArray.length=0,e&n.ImageProcessingDirtyFlag&&n._DirtyCallbackArray.push(n._ImageProcessingDirtyCallBack),e&n.TextureDirtyFlag&&n._DirtyCallbackArray.push(n._TextureDirtyCallBack),e&n.LightDirtyFlag&&n._DirtyCallbackArray.push(n._LightsDirtyCallBack),e&n.FresnelDirtyFlag&&n._DirtyCallbackArray.push(n._FresnelDirtyCallBack),e&n.AttributesDirtyFlag&&n._DirtyCallbackArray.push(n._AttributeDirtyCallBack),e&n.MiscDirtyFlag&&n._DirtyCallbackArray.push(n._MiscDirtyCallBack),e&n.PrePassDirtyFlag&&n._DirtyCallbackArray.push(n._PrePassDirtyCallBack),n._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(n._RunDirtyCallBacks),this.getScene().resetCachedMaterial())}resetDrawCache(){let e=this.getScene().meshes;for(let t of e)if(t.subMeshes)for(let i of t.subMeshes)i.getMaterial()===this&&i.resetDrawCache()}_markAllSubMeshesAsDirty(e){let t=this.getScene();if(t.blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;let i=t.meshes;for(let r of i)if(r.subMeshes){for(let s of r.subMeshes)if((s.getMaterial()||(t._hasDefaultMaterial?t.defaultMaterial:null))===this)for(let o of s._drawWrappers)!o||!o.defines||!o.defines.markAllAsDirty||this._materialContext===o.materialContext&&e(o.defines)}}_markScenePrePassDirty(){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;let e=this.getScene().enablePrePassRenderer();e&&e.markAsDirty()}_markAllSubMeshesAsAllDirty(){this._markAllSubMeshesAsDirty(n._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(n._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(n._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(n._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(n._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(n._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(n._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(n._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(n._PrePassDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(n._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(this._scene.performancePriority!==0){this.checkReadyOnlyOnce=!0;let e=this._scene.onScenePerformancePriorityChangedObservable.addOnce(()=>{this.checkReadyOnlyOnce=!1});this.onDisposeObservable.add(()=>{this._scene.onScenePerformancePriorityChangedObservable.remove(e)})}}setPrePassRenderer(e){return!1}dispose(e,t,i){let r=this.getScene();if(r.stopAnimation(this),r.freeProcessedMaterials(),r.removeMaterial(this),this._eventInfo.forceDisposeTextures=t,this._callbackPluginEventGeneric(2,this._eventInfo),this._parentContainer){let s=this._parentContainer.materials.indexOf(this);s>-1&&this._parentContainer.materials.splice(s,1),this._parentContainer=null}if(i!==!0)if(this.meshMap)for(let s in this.meshMap){let a=this.meshMap[s];this._disposeMeshResources(a)}else{let s=r.meshes;for(let a of s)this._disposeMeshResources(a)}this._uniformBuffer.dispose(),this._drawWrapper.effect&&(this._storeEffectOnSubMeshes||this._drawWrapper.effect.dispose(),this._drawWrapper.effect=null),this.metadata=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._onBindObservable&&this._onBindObservable.clear(),this._onUnBindObservable&&this._onUnBindObservable.clear(),this._onEffectCreatedObservable&&this._onEffectCreatedObservable.clear(),this._eventInfo&&(this._eventInfo={})}_disposeMeshResources(e){var r;if(!e)return;let t=e.geometry,i=e._internalAbstractMeshDataInfo._materialForRenderPass;if(this._storeEffectOnSubMeshes){if(e.subMeshes&&i)for(let s of e.subMeshes){let a=s._drawWrappers;for(let o=0;on.markAllAsDirty();Ee._ImageProcessingDirtyCallBack=n=>n.markAsImageProcessingDirty();Ee._TextureDirtyCallBack=n=>n.markAsTexturesDirty();Ee._FresnelDirtyCallBack=n=>n.markAsFresnelDirty();Ee._MiscDirtyCallBack=n=>n.markAsMiscDirty();Ee._PrePassDirtyCallBack=n=>n.markAsPrePassDirty();Ee._LightsDirtyCallBack=n=>n.markAsLightDirty();Ee._AttributeDirtyCallBack=n=>n.markAsAttributesDirty();Ee._FresnelAndMiscDirtyCallBack=n=>{Ee._FresnelDirtyCallBack(n),Ee._MiscDirtyCallBack(n)};Ee._TextureAndMiscDirtyCallBack=n=>{Ee._TextureDirtyCallBack(n),Ee._MiscDirtyCallBack(n)};Ee._DirtyCallbackArray=[];Ee._RunDirtyCallBacks=n=>{for(let e of Ee._DirtyCallbackArray)e(n)};P([w()],Ee.prototype,"id",void 0);P([w()],Ee.prototype,"uniqueId",void 0);P([w()],Ee.prototype,"name",void 0);P([w()],Ee.prototype,"metadata",void 0);P([w()],Ee.prototype,"checkReadyOnEveryCall",void 0);P([w()],Ee.prototype,"checkReadyOnlyOnce",void 0);P([w()],Ee.prototype,"state",void 0);P([w("alpha")],Ee.prototype,"_alpha",void 0);P([w("backFaceCulling")],Ee.prototype,"_backFaceCulling",void 0);P([w("cullBackFaces")],Ee.prototype,"_cullBackFaces",void 0);P([w()],Ee.prototype,"sideOrientation",void 0);P([w()],Ee.prototype,"_alphaMode",void 0);P([w()],Ee.prototype,"_needDepthPrePass",void 0);P([w()],Ee.prototype,"disableDepthWrite",void 0);P([w()],Ee.prototype,"disableColorWrite",void 0);P([w()],Ee.prototype,"forceDepthWrite",void 0);P([w()],Ee.prototype,"depthFunction",void 0);P([w()],Ee.prototype,"separateCullingPass",void 0);P([w("fogEnabled")],Ee.prototype,"_fogEnabled",void 0);P([w()],Ee.prototype,"pointSize",void 0);P([w()],Ee.prototype,"zOffset",void 0);P([w()],Ee.prototype,"zOffsetUnits",void 0);P([w()],Ee.prototype,"pointsCloud",null);P([w()],Ee.prototype,"fillMode",null);P([w()],Ee.prototype,"useLogarithmicDepth",null);P([w()],Ee.prototype,"_isVertexOutputInvariant",void 0);P([w()],Ee.prototype,"transparencyMode",null)});var wm,vG=C(()=>{Vn();uf();Hi();wm=class n extends Ee{get subMaterials(){return this._subMaterials}set subMaterials(e){this._subMaterials=e,this._hookArray(e)}getChildren(){return this.subMaterials}constructor(e,t){super(e,t,!0),this._waitingSubMaterialsUniqueIds=[],this.getScene().addMultiMaterial(this),this.subMaterials=[],this._storeEffectOnSubMeshes=!0}_hookArray(e){let t=e.push;e.push=(...r)=>{let s=t.apply(e,r);return this._markAllSubMeshesAsTexturesDirty(),s};let i=e.splice;e.splice=(r,s)=>{let a=i.call(e,r,s!=null?s:e.length);return this._markAllSubMeshesAsTexturesDirty(),a}}getSubMaterial(e){return e<0||e>=this.subMaterials.length?this.getScene().defaultMaterial:this.subMaterials[e]}getActiveTextures(){return super.getActiveTextures().concat(...this.subMaterials.map(e=>e?e.getActiveTextures():[]))}hasTexture(e){var t;if(super.hasTexture(e))return!0;for(let i=0;i=0&&r.multiMaterials.splice(s,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){let i=new n(e.name,t);if(i.id=e.id,i._loadedUniqueId=e.uniqueId,qt&&qt.AddTagsTo(i,e.tags),e.materialsUniqueIds)i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds;else for(let r of e.materials)i.subMaterials.push(t.getLastMaterialById(r));return i}};wt("BABYLON.MultiMaterial",wm)});var LA,EG=C(()=>{LA=class{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}});var Fm,OA,Ay,NA,xy,Ry,cl,Z,Ii=C(()=>{hi();bi();W_();uf();py();sl();Ve();zt();qs();Gi();hr();CA();gm();hg();Vn();vG();MA();Tr();yt();Hi();hn();om();EG();Fm=class{},OA=class{constructor(){this.batchCache=new NA(this),this.batchCacheReplacementModeInFrozenMode=new NA(this),this.instancesBufferSize=512*4}},Ay=class{constructor(){this.renderPasses={}}},NA=class{constructor(e){this.parent=e,this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=[],this.hardwareInstancedRendering=[]}},xy=class{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=512,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}},Ry=class{constructor(){this._areNormalsFrozen=!1,this._source=null,this.meshMap=null,this._preActivateId=-1,this._LODLevels=new Array,this._useLODScreenCoverage=!1,this._effectiveMaterial=null,this._forcedInstanceCount=0,this._overrideRenderingFillMode=null}},cl={source:null,parent:null,doNotCloneChildren:!1,clonePhysicsImpostor:!0,cloneThinInstances:!1},Z=class n extends gr{static _GetDefaultSideOrientation(e){return e||n.FRONTSIDE}get useLODScreenCoverage(){return this._internalMeshDataInfo._useLODScreenCoverage}set useLODScreenCoverage(e){this._internalMeshDataInfo._useLODScreenCoverage=e,this._sortLODLevels()}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(e&&this._internalMeshDataInfo._sourcePositions&&(this.setVerticesData(L.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(L.NormalKind,this._internalMeshDataInfo._sourceNormals,!0),this._internalMeshDataInfo._sourcePositions=null,this._internalMeshDataInfo._sourceNormals=null),this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get onBeforeRenderObservable(){return this._internalMeshDataInfo._onBeforeRenderObservable||(this._internalMeshDataInfo._onBeforeRenderObservable=new ie),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new ie),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new ie),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new ie),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new ie),this._internalMeshDataInfo._onBeforeDrawObservable}set onBeforeDraw(e){this._onBeforeDrawObserver&&this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver),this._onBeforeDrawObserver=this.onBeforeDrawObservable.add(e)}get hasInstances(){return this.instances.length>0}get hasThinInstances(){return(this.forcedInstanceCount||this._thinInstanceDataStorage.instancesCount||0)>0}get forcedInstanceCount(){return this._internalMeshDataInfo._forcedInstanceCount}set forcedInstanceCount(e){this._internalMeshDataInfo._forcedInstanceCount=e}get sideOrientation(){return this._internalMeshDataInfo._sideOrientation}set sideOrientation(e){this._internalMeshDataInfo._sideOrientation=e,this._internalAbstractMeshDataInfo._sideOrientationHint=this._scene.useRightHandedSystem&&e===1||!this._scene.useRightHandedSystem&&e===0}get _effectiveSideOrientation(){return this._internalMeshDataInfo._effectiveSideOrientation}get overrideMaterialSideOrientation(){return this.sideOrientation}set overrideMaterialSideOrientation(e){this.sideOrientation=e,this.material&&(this.material.sideOrientation=null)}get overrideRenderingFillMode(){return this._internalMeshDataInfo._overrideRenderingFillMode}set overrideRenderingFillMode(e){this._internalMeshDataInfo._overrideRenderingFillMode=e}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){e&&(this.material&&this.material.sideOrientation===null||this._internalAbstractMeshDataInfo._sideOrientationHint)&&(e.sideOrientation=null),this._setMaterial(e)}get source(){return this._internalMeshDataInfo._source}get cloneMeshMap(){return this._internalMeshDataInfo.meshMap}get isUnIndexed(){return this._unIndexed}set isUnIndexed(e){this._unIndexed!==e&&(this._unIndexed=e,this._markSubMeshesAsAttributesDirty())}get worldMatrixInstancedBuffer(){let e=this._instanceDataStorage.useMonoDataStorageRenderPass?this._instanceDataStorage.dataStorageRenderPass:this._instanceDataStorage.renderPasses[this._instanceDataStorage.engine.currentRenderPassId];return e?e.instancesData:void 0}get previousWorldMatrixInstancedBuffer(){let e=this._instanceDataStorage.useMonoDataStorageRenderPass?this._instanceDataStorage.dataStorageRenderPass:this._instanceDataStorage.renderPasses[this._instanceDataStorage.engine.currentRenderPassId];return e?e.instancesPreviousData:void 0}get manualUpdateOfWorldMatrixInstancedBuffer(){return this._instanceDataStorage.manualUpdate}set manualUpdateOfWorldMatrixInstancedBuffer(e){this._instanceDataStorage.manualUpdate=e}get manualUpdateOfPreviousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.previousManualUpdate}set manualUpdateOfPreviousWorldMatrixInstancedBuffer(e){this._instanceDataStorage.previousManualUpdate=e}get forceWorldMatrixInstancedBufferUpdate(){return this._instanceDataStorage.forceMatrixUpdates}set forceWorldMatrixInstancedBufferUpdate(e){this._instanceDataStorage.forceMatrixUpdates=e}_copySource(e,t,i=!0,r=!1){var a,o;let s=this.getScene();if(e._geometry&&e._geometry.applyToMesh(this),tl.DeepCopy(e,this,["name","material","skeleton","instances","parent","uniqueId","source","metadata","morphTargetManager","hasInstances","worldMatrixInstancedBuffer","previousWorldMatrixInstancedBuffer","hasLODLevels","geometry","isBlocked","areNormalsFrozen","facetNb","isFacetDataEnabled","lightSources","useBones","isAnInstance","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","cloneMeshMap","hasBoundingInfo","physicsBody","physicsImpostor"],["_poseMatrix"]),this._internalMeshDataInfo._source=e,s.useClonedMeshMap&&(e._internalMeshDataInfo.meshMap||(e._internalMeshDataInfo.meshMap={}),e._internalMeshDataInfo.meshMap[this.uniqueId]=this),this._originalBuilderSideOrientation=e._originalBuilderSideOrientation,this._creationDataStorage=e._creationDataStorage,e._ranges){let l=e._ranges;for(let c in l)Object.prototype.hasOwnProperty.call(l,c)&&l[c]&&this.createAnimationRange(c,l[c].from,l[c].to)}if(e.metadata&&e.metadata.clone?this.metadata=e.metadata.clone():this.metadata=e.metadata,this._internalMetadata=e._internalMetadata,qt&&qt.HasTags(e)&&qt.AddTagsTo(this,qt.GetTags(e,!0)),this.setEnabled(e.isEnabled(!1)),this.parent=e.parent,this.setPivotMatrix(e.getPivotMatrix(),this._postMultiplyPivotMatrix),this.id=this.name+"."+e.id,this.material=e.material,!t){let l=e.getDescendants(!0);for(let c=0;c{m&&_&&(this._uniformBuffer?this.transferToEffect(p):_.bindOnlyWorldMatrix(p))};let o,l=!1;if(i&&i._addToSceneRootNodes===void 0){let m=i;o=(c=m.parent)!=null?c:null,r=(f=m.source)!=null?f:null,s=(h=m.doNotCloneChildren)!=null?h:!1,a=(d=m.clonePhysicsImpostor)!=null?d:!0,l=(u=m.cloneThinInstances)!=null?u:!1}else o=i;r&&this._copySource(r,s,a,l),o!==null&&(this.parent=o),this._instanceDataStorage.hardwareInstancedRendering=this.getEngine().getCaps().instancedArrays,this._internalMeshDataInfo._onMeshReadyObserverAdded=m=>{m.unregisterOnNextCall=!0,this.isReady(!0)?this.onMeshReadyObservable.notifyObservers(this):this._internalMeshDataInfo._checkReadinessObserver||(this._internalMeshDataInfo._checkReadinessObserver=this._scene.onBeforeRenderObservable.add(()=>{this.isReady(!0)&&(this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),this._internalMeshDataInfo._checkReadinessObserver=null,this.onMeshReadyObservable.notifyObservers(this))}))},this.onMeshReadyObservable=new ie(this._internalMeshDataInfo._onMeshReadyObserverAdded),r&&r.onClonedObservable.notifyObservers(this)}instantiateHierarchy(e=null,t,i){let r=this.getTotalVertices()===0||t&&t.doNotInstantiate&&(t.doNotInstantiate===!0||t.doNotInstantiate(this))?this.clone("Clone of "+(this.name||this.id),e||this.parent,!0):this.createInstance("instance of "+(this.name||this.id));r.parent=e||this.parent,r.position=this.position.clone(),r.scaling=this.scaling.clone(),this.rotationQuaternion?r.rotationQuaternion=this.rotationQuaternion.clone():r.rotation=this.rotation.clone(),i&&i(this,r);for(let s of this.getChildTransformNodes(!0))s.getClassName()==="InstancedMesh"&&r.getClassName()==="Mesh"&&s.sourceMesh===this?s.instantiateHierarchy(r,{doNotInstantiate:t&&t.doNotInstantiate||!1,newSourcedMesh:r},i):s.instantiateHierarchy(r,t,i);return r}getClassName(){return"Mesh"}get _isMesh(){return!0}toString(e){let t=super.toString(e);if(t+=", n vertices: "+this.getTotalVertices(),t+=", parent: "+(this._waitingParentId?this._waitingParentId:this.parent?this.parent.name:"NONE"),this.animations)for(let i=0;i0}getLODLevels(){return this._internalMeshDataInfo._LODLevels}_sortLODLevels(){let e=this._internalMeshDataInfo._useLODScreenCoverage?-1:1;this._internalMeshDataInfo._LODLevels.sort((t,i)=>t.distanceOrScreenCoveragei.distanceOrScreenCoverage?-e:0)}addLODLevel(e,t){if(t&&t._masterMesh)return te.Warn("You cannot use a mesh as LOD level twice"),this;let i=new LA(e,t);return this._internalMeshDataInfo._LODLevels.push(i),t&&(t._masterMesh=this),this._sortLODLevels(),this}getLODLevelAtDistance(e){let t=this._internalMeshDataInfo;for(let i=0;io*a)return this.onLODLevelSelection&&this.onLODLevelSelection(a,this,this),this;for(let l=0;l0||this.hasThinInstances);this.computeWorldMatrix();let a=this.material||r.defaultMaterial;if(a){if(a._storeEffectOnSubMeshes)for(let p of this.subMeshes){let _=p.getMaterial();if(_){if(_._storeEffectOnSubMeshes){if(!_.isReadyForSubMesh(this,p,s))return!1}else if(!_.isReady(this,s))return!1}}else if(!a.isReady(this,s))return!1}let o=i.currentRenderPassId;for(let p of this.lightSources){let _=p.getShadowGenerators();if(!_)continue;let g=_.values();for(let v=g.next();v.done!==!0;v=g.next()){let x=v.value;if(x&&(!((l=x.getShadowMap())!=null&&l.renderList)||(c=x.getShadowMap())!=null&&c.renderList&&((h=(f=x.getShadowMap())==null?void 0:f.renderList)==null?void 0:h.indexOf(this))!==-1)){let S=(d=x.getShadowMap().renderPassIds)!=null?d:[i.currentRenderPassId];for(let E=0;E0){let i=this.getIndices();if(!i)return null;let r=i.length,s=!1;if(e)s=!0;else for(let a of this.subMeshes){if(a.indexStart+a.indexCount>r){s=!0;break}if(a.verticesStart+a.verticesCount>t){s=!0;break}}if(!s)return this.subMeshes[0]}return this.releaseSubMeshes(),new Rs(0,0,t,0,this.getTotalIndices()||(this.isUnIndexed?t:0),this)}subdivide(e){if(e<1)return;let t=this.getTotalIndices(),i=t/e|0,r=0;for(;i%3!==0;)i++;this.releaseSubMeshes();for(let s=0;s=t);s++)Rs.CreateFromIndices(0,r,r+i>=t?t-r:i,this,void 0,!1),r+=i;this.refreshBoundingInfo(),this.synchronizeInstances()}setVerticesData(e,t,i=!1,r){if(this._geometry)this._geometry.setVerticesData(e,t,i,r);else{let s=new Me;s.set(t,e);let a=this.getScene();new mn(mn.RandomId(),a,s,i,this)}return this}removeVerticesData(e){this._geometry&&this._geometry.removeVerticesData(e)}markVerticesDataAsUpdatable(e,t=!0){let i=this.getVertexBuffer(e);!i||i.isUpdatable()===t||this.setVerticesData(e,this.getVerticesData(e),t)}setVerticesBuffer(e,t=!0,i=null){return this._geometry||(this._geometry=mn.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(e,i,t),this}updateVerticesData(e,t,i,r){return this._geometry?(r?(this.makeGeometryUnique(),this.updateVerticesData(e,t,i,!1)):this._geometry.updateVerticesData(e,t,i),this):this}updateMeshPositions(e,t=!0){let i=this.getVerticesData(L.PositionKind);if(!i)return this;if(e(i),this.updateVerticesData(L.PositionKind,i,!1,!1),t){let r=this.getIndices(),s=this.getVerticesData(L.NormalKind);if(!s)return this;Me.ComputeNormals(i,r,s),this.updateVerticesData(L.NormalKind,s,!1,!1)}return this}makeGeometryUnique(){if(!this._geometry)return this;if(this._geometry.meshes.length===1)return this;let e=this._geometry,t=this._geometry.copy(mn.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndexBuffer(e,t,i,r=null){let s=this._geometry;s||(s=new mn(mn.RandomId(),this.getScene(),void 0,void 0,this)),s.setIndexBuffer(e,t,i,r)}setIndices(e,t=null,i=!1,r=!1){if(this._geometry)this._geometry.setIndices(e,t,i,r);else{let s=new Me;s.indices=e;let a=this.getScene();new mn(mn.RandomId(),a,s,i,this,t)}return this}updateIndices(e,t,i=!1){return this._geometry?(this._geometry.updateIndices(e,t,i),this):this}toLeftHanded(){return this._geometry?(this._geometry.toLeftHanded(),this):this}_bind(e,t,i,r=!0){if(!this._geometry)return this;let s=this.getScene().getEngine(),a;if(this._unIndexed)this._getRenderingFillMode(i)===Ee.WireFrameFillMode?a=e._getLinesIndexBuffer(this.getIndices(),s):a=null;else switch(this._getRenderingFillMode(i)){case Ee.PointFillMode:a=null;break;case Ee.WireFrameFillMode:a=e._getLinesIndexBuffer(this.getIndices(),s);break;default:case Ee.TriangleFillMode:a=this._geometry.getIndexBuffer();break}return this._bindDirect(t,a,r)}_bindDirect(e,t,i=!0){if(!this._geometry)return this;if(this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(e),!i||!this._userInstancedBuffersStorage||this.hasThinInstances)this._geometry._bind(e,t);else{if(!this._instanceDataStorage.useMonoDataStorageRenderPass&&this._userInstancedBuffersStorage.renderPasses&&this._userInstancedBuffersStorage.renderPasses[this._instanceDataStorage.engine.currentRenderPassId]){let r=this._userInstancedBuffersStorage.renderPasses[this._instanceDataStorage.engine.currentRenderPassId];for(let s in r)this._userInstancedBuffersStorage.vertexBuffers[s]=r[s]}this._geometry._bind(e,t,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects)}return this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this._internalMeshDataInfo._onBeforeDrawObservable&&this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);let s=this.getScene().getEngine(),a=s._currentMaterialContext,o=a&&a.useVertexPulling;return this._unIndexed&&t!==Ee.WireFrameFillMode||t==Ee.PointFillMode?s.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||i):t==Ee.WireFrameFillMode?s.drawElementsType(t,0,e._linesIndexCount,this.forcedInstanceCount||i):o?s.drawArraysType(t,e.indexStart,e.indexCount,this.forcedInstanceCount||i):s.drawElementsType(t,e.indexStart,e.indexCount,this.forcedInstanceCount||i),this}registerBeforeRender(e){return this.onBeforeRenderObservable.add(e),this}unregisterBeforeRender(e){return this.onBeforeRenderObservable.removeCallback(e),this}registerAfterRender(e){return this.onAfterRenderObservable.add(e),this}unregisterAfterRender(e){return this.onAfterRenderObservable.removeCallback(e),this}_getInstancesRenderList(e,t=!1){let i=this._instanceDataStorage.useMonoDataStorageRenderPass?this._instanceDataStorage.dataStorageRenderPass:this._getInstanceDataStorage();if(this._instanceDataStorage.isFrozen){if(t)return i.batchCacheReplacementModeInFrozenMode.hardwareInstancedRendering[e]=!1,i.batchCacheReplacementModeInFrozenMode.renderSelf[e]=!0,i.batchCacheReplacementModeInFrozenMode;if(i.previousBatch)return i.previousBatch}let r=this.getScene(),s=r._isInIntermediateRendering(),a=s?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,o=i.batchCache;if(o.mustReturn=!1,o.renderSelf[e]=t||!a&&this.isEnabled()&&this.isVisible,o.visibleInstances[e]=null,i.visibleInstances&&!t){let l=i.visibleInstances,c=r.getRenderId(),f=s?l.intermediateDefaultRenderId:l.defaultRenderId;o.visibleInstances[e]=l[c],!o.visibleInstances[e]&&f&&(o.visibleInstances[e]=l[f])}return o.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&o.visibleInstances[e]!==null&&o.visibleInstances[e]!==void 0,i.previousBatch=o,o}_updateInstancedBuffers(e,t,i,r,s,a){var v;let o=t.visibleInstances[e._id],l=o?o.length:0,c=t.parent,f=this._instanceDataStorage,h=c.instancesBuffer,d=c.instancesPreviousBuffer,u=0,m=0,p=t.renderSelf[e._id],_=this._scene.floatingOriginOffset,g=!h||i!==c.instancesBufferSize||this._scene.needsPreviousWorldMatrices&&!c.instancesPreviousBuffer;if(!this._instanceDataStorage.manualUpdate&&(!f.isFrozen||g)){let x=this.getWorldMatrix();if(p){this._scene.needsPreviousWorldMatrices&&(f.masterMeshPreviousWorldMatrix?(f.masterMeshPreviousWorldMatrix.copyToArray(c.instancesPreviousData,u),f.masterMeshPreviousWorldMatrix.copyFrom(x)):(f.masterMeshPreviousWorldMatrix=x.clone(),f.masterMeshPreviousWorldMatrix.copyToArray(c.instancesPreviousData,u))),x.copyToArray(c.instancesData,u);let A=x.asArray();c.instancesData[u+12]=A[12]-_.x,c.instancesData[u+13]=A[13]-_.y,c.instancesData[u+14]=A[14]-_.z,u+=16,m++}if(o){if(n.INSTANCEDMESH_SORT_TRANSPARENT&&this._scene.activeCamera&&((v=e.getMaterial())!=null&&v.needAlphaBlendingForMesh(e.getRenderingMesh()))){let A=this._scene.activeCamera.globalPosition;for(let S=0;SS._distanceToCamera>E._distanceToCamera?-1:S._distanceToCamera1&&r.activeCamera===r.activeCameras[0]||a<=1,l=this._occlusionDataStorage&&this._occlusionDataStorage.occlusionForRenderPassId!==-1&&this._occlusionDataStorage.occlusionForRenderPassId!==s.currentRenderPassId;if(o&&this._checkOcclusionQuery(l)&&!this._occlusionDataStorage.forceRenderingWhenOccluded)return this;let c=this._getInstancesRenderList(e._id,!!i);if(c.mustReturn)return this;if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;let f=0,h=null;this.ignoreCameraMaxZ&&r.activeCamera&&!r._isInIntermediateRendering()&&(f=r.activeCamera.maxZ,h=r.activeCamera,r.activeCamera.maxZ=0,r.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);let d=e.getRenderingMesh(),u=c.hardwareInstancedRendering[e._id]||d.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,m=this._instanceDataStorage,p=e.getMaterial();if(!p)return h&&(h.maxZ=f,r.updateTransformMatrix(!0)),this;if(!m.isFrozen||!this._internalMeshDataInfo._effectiveMaterial||this._internalMeshDataInfo._effectiveMaterial!==p){if(p._storeEffectOnSubMeshes){if(!p.isReadyForSubMesh(this,e,u))return h&&(h.maxZ=f,r.updateTransformMatrix(!0)),this}else if(!p.isReady(this,u))return h&&(h.maxZ=f,r.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=p}else if(p._storeEffectOnSubMeshes&&!((M=e._drawWrapper)!=null&&M._wasPreviouslyReady)||!p._storeEffectOnSubMeshes&&!p._getDrawWrapper()._wasPreviouslyReady)return h&&(h.maxZ=f,r.updateTransformMatrix(!0)),this;if(t){let O=this._internalMeshDataInfo._effectiveMaterial;if(O.alphaModes.length===1)s.setAlphaMode(O.alphaMode);else for(let V=0;Vg&&r++,S!==0&&x++,v+=S,g=S}if(c[x]++,x>a&&(a=x),v===0)s++;else{let A=1/v,S=0;for(let E=0;Ef&&o++}}let h=this.skeleton.bones.length,d=this.getVerticesData(L.MatricesIndicesKind),u=this.getVerticesData(L.MatricesIndicesExtraKind),m=0;for(let _=0;_=h||v<0)&&m++}let p="Number of Weights = "+i/4+` +fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=toRGBD(textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb);}`;T.ShadersStoreWGSL[LC]||(T.ShadersStoreWGSL[LC]=lU);sne={name:LC,shader:lU}});var lm,OC=C(()=>{Yl();lC();lm=class{static ExpandRGBDTexture(e){let t=e._texture;if(!t||!e.isRGBD)return;let i=t.getEngine(),r=i.getCaps(),s=t.isReady,a=!1;r.textureHalfFloatRender&&r.textureHalfFloatLinearFiltering?(a=!0,t.type=2):r.textureFloatRender&&r.textureFloatLinearFiltering&&(a=!0,t.type=1),a&&(t.isReady=!1,t._isRGBD=!1,t.invertY=!1);let o=async()=>{let l=i.isWebGPU,c=l?1:0;t.isReady=!1,l?await Promise.resolve().then(()=>(MC(),IC)):await Promise.resolve().then(()=>(PC(),yC));let f=new Ri("rgbdDecode","rgbdDecode",null,null,1,null,3,i,!1,void 0,t.type,void 0,null,!1,void 0,c);f.externalTextureSamplerBinding=!0;let h=i.createRenderTargetTexture(t.width,{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:t.samplingMode,type:t.type,format:5});f.onEffectCreatedObservable.addOnce(d=>{d.executeWhenCompiled(()=>{f.onApply=u=>{u._bindTexture("textureSampler",t),u.setFloat2("scale",1,1)},e.getScene().postProcessManager.directRender([f],h,!0),i.restoreDefaultFramebuffer(),i._releaseTexture(t),f&&f.dispose(),h._swapAndDie(t),t.isReady=!0})})};a&&(s?o():e.onLoadObservable.addOnce(o))}static async EncodeTextureToRGBD(e,t,i=0){return t.getEngine().isWebGPU?await Promise.resolve().then(()=>(fU(),cU)):await Promise.resolve().then(()=>(oU(),aU)),await hB("rgbdEncode",e,t,i,1,5)}}});var NC=C(()=>{kM();k_();pi.prototype._sphericalPolynomialTargetSize=0;pi.prototype.forceSphericalPolynomialsRecompute=function(){this._texture&&(this._texture._sphericalPolynomial=null,this._texture._sphericalPolynomialPromise=null,this._texture._sphericalPolynomialComputed=!1)};Object.defineProperty(pi.prototype,"sphericalPolynomial",{get:function(){if(this._texture){if(this._texture._sphericalPolynomial||this._texture._sphericalPolynomialComputed)return this._texture._sphericalPolynomial;if(this._texture.isReady)return this._texture._sphericalPolynomialPromise||(this._texture._sphericalPolynomialPromise=Hl.ConvertCubeMapTextureToSphericalPolynomial(this),this._texture._sphericalPolynomialPromise===null?this._texture._sphericalPolynomialComputed=!0:this._texture._sphericalPolynomialPromise.then(n=>{this._texture._sphericalPolynomial=n,this._texture._sphericalPolynomialComputed=!0})),null}return null},set:function(n){this._texture&&(this._texture._sphericalPolynomial=n)},enumerable:!0,configurable:!0})});function mU(n){let e=new DataView(n.buffer,n.byteOffset,n.byteLength),t=0;for(let a=0;ahU)throw new Error(`Unsupported babylon environment map version "${n.version}". Latest supported version is "${hU}".`);return n.version===2||(n={...n,version:2,imageType:gA}),n}function ane(n,e){e=ig(e);let t=e.specular,i=Math.log2(e.width);if(i=Math.round(i)+1,t.mipmaps.length!==6*i)throw new Error(`Unsupported specular mipmaps number "${t.mipmaps.length}"`);let r=new Array(i);for(let s=0;s{if(t){let u=e.createTexture(null,!0,!0,null,1,null,m=>{d(m)},n);i==null||i.onEffectCreatedObservable.addOnce(m=>{m.executeWhenCompiled(()=>{i.externalTextureSamplerBinding=!0,i.onApply=p=>{p._bindTexture("textureSampler",u),p.setFloat2("scale",1,e._features.needsInvertingBitmap&&n instanceof ImageBitmap?-1:1)},e.scenes.length&&(e.scenes[0].postProcessManager.directRender([i],c,!0,s,a),e.restoreDefaultFramebuffer(),u.dispose(),URL.revokeObjectURL(r),h())})})}else{if(e._uploadImageToTexture(f,n,s,a),o){let u=l[a];u&&e._uploadImageToTexture(u._texture,n,s,0)}h()}})}async function lne(n,e,t=gA){let i=n.getEngine();n.format=5,n.type=0,n.generateMipMaps=!0,n._cachedAnisotropicFilteringLevel=null,i.updateTextureSamplingMode(3,n),await _U(n,e,!0,t),n.isReady=!0}async function cne(n,e,t,i=gA,r=null){let s=n.getEngine(),a=new Pi(s,5),o=new pi(s,a);n._irradianceTexture=o,o._dominantDirection=r,a.isCube=!0,a.format=5,a.type=0,a.generateMipMaps=!0,a._cachedAnisotropicFilteringLevel=null,a.generateMipMaps=!0,a.width=t,a.height=t,s.updateTextureSamplingMode(3,a),await _U(a,[e],!1,i),s.generateMipMapsForCubemap(a),a.isReady=!0}async function _U(n,e,t,i=gA){if(!_e.IsExponentOfTwo(n.width))throw new Error("Texture size must be a power of two");let r=p2(n.width)+1,s=n.getEngine(),a=!1,o=!1,l=null,c=null,f=null,h=s.getCaps();h.textureLOD?s._features.supportRenderAndCopyToLodForFloatTextures?h.textureHalfFloatRender&&h.textureHalfFloatLinearFiltering?(a=!0,n.type=2):h.textureFloatRender&&h.textureFloatLinearFiltering&&(a=!0,n.type=1):a=!1:(a=!1,o=t);let d=0;if(a)s.isWebGPU?(d=1,await Promise.resolve().then(()=>(MC(),IC))):await Promise.resolve().then(()=>(PC(),yC)),l=new Ri("rgbdDecode","rgbdDecode",null,null,1,null,3,s,!1,void 0,n.type,void 0,null,!1,void 0,d),n._isRGBD=!1,n.invertY=!1,c=s.createRenderTargetCubeTexture(n.width,{generateDepthBuffer:!1,generateMipMaps:!0,generateStencilBuffer:!1,samplingMode:3,type:n.type,format:5});else if(n._isRGBD=!0,n.invertY=!0,o){f={};let p=n._lodGenerationScale,_=n._lodGenerationOffset;for(let g=0;g<3;g++){let x=1-g/2,A=_,S=(r-1)*p+_,E=A+(S-A)*x,R=Math.round(Math.min(Math.max(E,0),S)),I=new Pi(s,2);I.isCube=!0,I.invertY=!0,I.generateMipMaps=!1,s.updateTextureSamplingMode(2,I);let y=new pi(null);switch(y._isCube=!0,y._texture=I,f[R]=y,g){case 0:n._lodTextureLow=y;break;case 1:n._lodTextureMid=y;break;case 2:n._lodTextureHigh=y;break}}}let u=[];for(let m=0;mawait uU(S,s,a,l,x,p,m,o,f,c,n));else{let S=new Image;S.src=x,A=new Promise((E,R)=>{S.onload=()=>{uU(S,s,a,l,x,p,m,o,f,c,n).then(()=>E()).catch(I=>{R(I)})},S.onerror=I=>{R(I)}})}u.push(A)}if(await Promise.all(u),e.length{Ii();Ge();Ln();F_();vs();k_();As();Yl();Pt();OC();tC();NC();rm();gA="image/png",hU=2,dU=[134,22,135,150,246,214,150,54]});var EU={};tt(EU,{_ENVTextureLoader:()=>wC});var wC,SU=C(()=>{vU();wC=class{constructor(){this.supportCascades=!1}loadCubeData(e,t,i,r,s){if(Array.isArray(e))return;let a=mU(e);if(a){t.width=a.width,t.height=a.width;try{gU(t,a),pU(t,e,a).then(()=>{t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()},o=>{s==null||s("Can not upload environment levels",o)})}catch(o){s==null||s("Can not upload environment file",o)}}else s&&s("Can not parse the environment file",null)}loadData(){throw".env not supported in 2d."}}});var $l,TU=C(()=>{Ge();$l=class{static ConvertPanoramaToCubemap(e,t,i,r,s=!1,a=!0){if(!e)throw"ConvertPanoramaToCubemap: input cannot be null";let o;if(e.length!=t*i*3){if(e.length!=t*i*4)throw"ConvertPanoramaToCubemap: input size is wrong";o=4}else o=3;let l=this.CreateCubemapTexture(r,this.FACE_FRONT,e,t,i,s,a,o),c=this.CreateCubemapTexture(r,this.FACE_BACK,e,t,i,s,a,o),f=this.CreateCubemapTexture(r,this.FACE_LEFT,e,t,i,s,a,o),h=this.CreateCubemapTexture(r,this.FACE_RIGHT,e,t,i,s,a,o),d=this.CreateCubemapTexture(r,this.FACE_UP,e,t,i,s,a,o),u=this.CreateCubemapTexture(r,this.FACE_DOWN,e,t,i,s,a,o);return{front:l,back:c,left:f,right:h,up:d,down:u,size:r,type:1,format:4,gammaSpace:!1}}static CreateCubemapTexture(e,t,i,r,s,a,o,l){let c=new ArrayBuffer(e*e*4*3),f=new Float32Array(c),h=a?Math.max(1,Math.round(r/4/e)):1,d=1/h,u=d*d,m=t[1].subtract(t[0]).scale(d/e),p=t[3].subtract(t[2]).scale(d/e),_=1/e,g=0;for(let v=0;vMath.PI;)o-=2*Math.PI;let c=o/Math.PI,f=l/Math.PI;c=c*.5+.5;let h=Math.round(c*i);h<0?h=0:h>=i&&(h=i-1);let d=Math.round(f*r);d<0?d=0:d>=r&&(d=r-1);let u=a?r-d-1:d,m=t[u*i*s+h*s+0],p=t[u*i*s+h*s+1],_=t[u*i*s+h*s+2];return{r:m,g:p,b:_}}};$l.FACE_LEFT=[new b(-1,-1,-1),new b(1,-1,-1),new b(-1,1,-1),new b(1,1,-1)];$l.FACE_RIGHT=[new b(1,-1,1),new b(-1,-1,1),new b(1,1,1),new b(-1,1,1)];$l.FACE_FRONT=[new b(1,-1,-1),new b(1,-1,1),new b(1,1,-1),new b(1,1,1)];$l.FACE_BACK=[new b(-1,-1,1),new b(-1,-1,-1),new b(-1,1,1),new b(-1,1,-1)];$l.FACE_DOWN=[new b(1,1,-1),new b(1,1,1),new b(-1,1,-1),new b(-1,1,1)];$l.FACE_UP=[new b(-1,-1,-1),new b(-1,-1,1),new b(1,-1,-1),new b(1,-1,1)]});function fne(n,e){return e>1023?n*Math.pow(2,1023)*Math.pow(2,e-1023):e<-1074?n*Math.pow(2,-1074)*Math.pow(2,e+1074):n*Math.pow(2,e)}function AU(n,e,t,i,r,s){r>0?(r=fne(1,r-136),n[s+0]=e*r,n[s+1]=t*r,n[s+2]=i*r):(n[s+0]=0,n[s+1]=0,n[s+2]=0)}function FC(n,e){let t="",i;for(let r=e;r32767)throw"HDR Bad header format, unsupported size";return r+=e.length+1,{height:l,width:o,dataPosition:r}}function RU(n,e){return hne(n,e)}function hne(n,e){let t=e.height,i=e.width,r,s,a,o,l,c=e.dataPosition,f,h,d,u=new ArrayBuffer(i*4),m=new Uint8Array(u),p=new ArrayBuffer(e.width*e.height*4*3),_=new Float32Array(p);for(;t>0;){if(r=n[c++],s=n[c++],a=n[c++],o=n[c++],r!=2||s!=2||a&128||e.width<8||e.width>32767)return dne(n,e);if((a<<8|o)!=i)throw"HDR Bad header format, wrong scan line width";for(f=0,d=0;d<4;d++)for(h=(d+1)*i;f128){if(l=r-128,l==0||l>h-f)throw"HDR Bad Format, bad scanline data (run)";for(;l-- >0;)m[f++]=s}else{if(l=r,l==0||l>h-f)throw"HDR Bad Format, bad scanline data (non-run)";if(m[f++]=s,--l>0)for(let g=0;g0;){for(l=0;l{TU()});var IU={};tt(IU,{_HDRTextureLoader:()=>BC});var BC,MU=C(()=>{bU();BC=class{constructor(){this.supportCascades=!1}loadCubeData(){throw".hdr not supported in Cube."}loadData(e,t,i){let r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=xU(r),a=RU(r,s),o=s.width*s.height,l=new Float32Array(o*4);for(let c=0;c{let c=t.getEngine();t.type=1,t.format=5,t._gammaSpace=!1,c._uploadDataToTextureDirectly(t,l)})}}});var ho,CU=C(()=>{Pt();ho=class n{constructor(e,t){if(this.data=e,this.isInvalid=!1,!n.IsValid(e)){this.isInvalid=!0,te.Error("texture missing KTX identifier");return}let i=Uint32Array.BYTES_PER_ELEMENT,r=new DataView(this.data.buffer,this.data.byteOffset+12,13*i),a=r.getUint32(0,!0)===67305985;if(this.glType=r.getUint32(1*i,a),this.glTypeSize=r.getUint32(2*i,a),this.glFormat=r.getUint32(3*i,a),this.glInternalFormat=r.getUint32(4*i,a),this.glBaseInternalFormat=r.getUint32(5*i,a),this.pixelWidth=r.getUint32(6*i,a),this.pixelHeight=r.getUint32(7*i,a),this.pixelDepth=r.getUint32(8*i,a),this.numberOfArrayElements=r.getUint32(9*i,a),this.numberOfFaces=r.getUint32(10*i,a),this.numberOfMipmapLevels=r.getUint32(11*i,a),this.bytesOfKeyValueData=r.getUint32(12*i,a),this.glType!==0){te.Error("only compressed formats currently supported"),this.isInvalid=!0;return}else this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels);if(this.pixelHeight===0||this.pixelDepth!==0){te.Error("only 2D textures currently supported"),this.isInvalid=!0;return}if(this.numberOfArrayElements!==0){te.Error("texture arrays not currently supported"),this.isInvalid=!0;return}if(this.numberOfFaces!==t){te.Error("number of faces expected"+t+", but found "+this.numberOfFaces),this.isInvalid=!0;return}this.loadType=n.COMPRESSED_2D}uploadLevels(e,t){switch(this.loadType){case n.COMPRESSED_2D:this._upload2DCompressedLevels(e,t);break;case n.TEX_2D:case n.COMPRESSED_3D:case n.TEX_3D:}}_upload2DCompressedLevels(e,t){let i=n.HEADER_LEN+this.bytesOfKeyValueData,r=this.pixelWidth,s=this.pixelHeight,a=t?this.numberOfMipmapLevels:1;for(let o=0;o=12){let t=new Uint8Array(e.buffer,e.byteOffset,12);if(t[0]===171&&t[1]===75&&t[2]===84&&t[3]===88&&t[4]===32&&t[5]===49&&t[6]===49&&t[7]===187&&t[8]===13&&t[9]===10&&t[10]===26&&t[11]===10)return!0}return!1}};ho.HEADER_LEN=64;ho.COMPRESSED_2D=0;ho.COMPRESSED_3D=1;ho.TEX_2D=2;ho.TEX_3D=3});var UC,rg,yU=C(()=>{UC=class{constructor(e){this._pendingActions=new Array,this._workerInfos=e.map(t=>({workerPromise:Promise.resolve(t),idle:!0}))}dispose(){for(let e of this._workerInfos)e.workerPromise.then(t=>{t.terminate()});this._workerInfos.length=0,this._pendingActions.length=0}push(e){this._executeOnIdleWorker(e)||this._pendingActions.push(e)}_executeOnIdleWorker(e){for(let t of this._workerInfos)if(t.idle)return this._execute(t,e),!0;return!1}_execute(e,t){e.idle=!1,e.workerPromise.then(i=>{t(i,()=>{let r=this._pendingActions.shift();r?this._execute(e,r):e.idle=!0})})}},rg=class n extends UC{constructor(e,t,i=n.DefaultOptions){super([]),this._maxWorkers=e,this._createWorkerAsync=t,this._options=i}push(e){if(!this._executeOnIdleWorker(e))if(this._workerInfos.length{t(i,()=>{r(),e.idle&&(e.timeoutId=setTimeout(()=>{e.workerPromise.then(a=>{a.terminate()});let s=this._workerInfos.indexOf(e);s!==-1&&this._workerInfos.splice(s,1)},this._options.idleTimeElapsedBeforeRelease))})})}};rg.DefaultOptions={idleTimeElapsedBeforeRelease:1e3}});var PU,cm,DU,LU=C(()=>{(function(n){n[n.ETC1S=0]="ETC1S",n[n.UASTC4x4=1]="UASTC4x4"})(PU||(PU={}));(function(n){n[n.ASTC_4X4_RGBA=0]="ASTC_4X4_RGBA",n[n.ASTC_4x4_RGBA=0]="ASTC_4x4_RGBA",n[n.BC7_RGBA=1]="BC7_RGBA",n[n.BC3_RGBA=2]="BC3_RGBA",n[n.BC1_RGB=3]="BC1_RGB",n[n.PVRTC1_4_RGBA=4]="PVRTC1_4_RGBA",n[n.PVRTC1_4_RGB=5]="PVRTC1_4_RGB",n[n.ETC2_RGBA=6]="ETC2_RGBA",n[n.ETC1_RGB=7]="ETC1_RGB",n[n.RGBA32=8]="RGBA32",n[n.R8=9]="R8",n[n.RG8=10]="RG8"})(cm||(cm={}));(function(n){n[n.COMPRESSED_RGBA_BPTC_UNORM_EXT=36492]="COMPRESSED_RGBA_BPTC_UNORM_EXT",n[n.COMPRESSED_RGBA_ASTC_4X4_KHR=37808]="COMPRESSED_RGBA_ASTC_4X4_KHR",n[n.COMPRESSED_RGB_S3TC_DXT1_EXT=33776]="COMPRESSED_RGB_S3TC_DXT1_EXT",n[n.COMPRESSED_RGBA_S3TC_DXT5_EXT=33779]="COMPRESSED_RGBA_S3TC_DXT5_EXT",n[n.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=35842]="COMPRESSED_RGBA_PVRTC_4BPPV1_IMG",n[n.COMPRESSED_RGB_PVRTC_4BPPV1_IMG=35840]="COMPRESSED_RGB_PVRTC_4BPPV1_IMG",n[n.COMPRESSED_RGBA8_ETC2_EAC=37496]="COMPRESSED_RGBA8_ETC2_EAC",n[n.COMPRESSED_RGB8_ETC2=37492]="COMPRESSED_RGB8_ETC2",n[n.COMPRESSED_RGB_ETC1_WEBGL=36196]="COMPRESSED_RGB_ETC1_WEBGL",n[n.RGBA8Format=32856]="RGBA8Format",n[n.R8Format=33321]="R8Format",n[n.RG8Format=33323]="RG8Format"})(DU||(DU={}))});function ng(n,e){let t=(e==null?void 0:e.jsDecoderModule)||KTX2DECODER;n&&(n.wasmBaseUrl&&(t.Transcoder.WasmBaseUrl=n.wasmBaseUrl),n.wasmUASTCToASTC&&(t.LiteTranscoder_UASTC_ASTC.WasmModuleURL=n.wasmUASTCToASTC),n.wasmUASTCToBC7&&(t.LiteTranscoder_UASTC_BC7.WasmModuleURL=n.wasmUASTCToBC7),n.wasmUASTCToRGBA_UNORM&&(t.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL=n.wasmUASTCToRGBA_UNORM),n.wasmUASTCToRGBA_SRGB&&(t.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL=n.wasmUASTCToRGBA_SRGB),n.wasmUASTCToR8_UNORM&&(t.LiteTranscoder_UASTC_R8_UNORM.WasmModuleURL=n.wasmUASTCToR8_UNORM),n.wasmUASTCToRG8_UNORM&&(t.LiteTranscoder_UASTC_RG8_UNORM.WasmModuleURL=n.wasmUASTCToRG8_UNORM),n.jsMSCTranscoder&&(t.MSCTranscoder.JSModuleURL=n.jsMSCTranscoder),n.wasmMSCTranscoder&&(t.MSCTranscoder.WasmModuleURL=n.wasmMSCTranscoder),n.wasmZSTDDecoder&&(t.ZSTDDecoder.WasmModuleURL=n.wasmZSTDDecoder)),e&&(e.wasmUASTCToASTC&&(t.LiteTranscoder_UASTC_ASTC.WasmBinary=e.wasmUASTCToASTC),e.wasmUASTCToBC7&&(t.LiteTranscoder_UASTC_BC7.WasmBinary=e.wasmUASTCToBC7),e.wasmUASTCToRGBA_UNORM&&(t.LiteTranscoder_UASTC_RGBA_UNORM.WasmBinary=e.wasmUASTCToRGBA_UNORM),e.wasmUASTCToRGBA_SRGB&&(t.LiteTranscoder_UASTC_RGBA_SRGB.WasmBinary=e.wasmUASTCToRGBA_SRGB),e.wasmUASTCToR8_UNORM&&(t.LiteTranscoder_UASTC_R8_UNORM.WasmBinary=e.wasmUASTCToR8_UNORM),e.wasmUASTCToRG8_UNORM&&(t.LiteTranscoder_UASTC_RG8_UNORM.WasmBinary=e.wasmUASTCToRG8_UNORM),e.jsMSCTranscoder&&(t.MSCTranscoder.JSModule=e.jsMSCTranscoder),e.wasmMSCTranscoder&&(t.MSCTranscoder.WasmBinary=e.wasmMSCTranscoder),e.wasmZSTDDecoder&&(t.ZSTDDecoder.WasmBinary=e.wasmZSTDDecoder))}function OU(n){typeof n=="undefined"&&typeof KTX2DECODER!="undefined"&&(n=KTX2DECODER);let e;onmessage=t=>{if(t.data)switch(t.data.action){case"init":{let i=t.data.urls;i&&(i.jsDecoderModule&&typeof n=="undefined"&&(importScripts(i.jsDecoderModule),n=KTX2DECODER),ng(i)),t.data.wasmBinaries&&ng(void 0,{...t.data.wasmBinaries,jsDecoderModule:n}),e=new n.KTX2Decoder,postMessage({action:"init"});break}case"setDefaultDecoderOptions":{n.KTX2Decoder.DefaultDecoderOptions=t.data.options;break}case"decode":e.decode(t.data.data,t.data.caps,t.data.options).then(i=>{let r=[];for(let s=0;s{postMessage({action:"decoded",success:!1,msg:i})});break}}}async function NU(n,e,t){return await new Promise((i,r)=>{let s=o=>{n.removeEventListener("error",s),n.removeEventListener("message",a),r(o)},a=o=>{o.data.action==="init"&&(n.removeEventListener("error",s),n.removeEventListener("message",a),i(n))};n.addEventListener("error",s),n.addEventListener("message",a),n.postMessage({action:"init",urls:t,wasmBinaries:e})})}var wU=C(()=>{});var VC,Jl,FU=C(()=>{yU();Ii();LU();wU();VC=class{constructor(){this._isDirty=!0,this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC=!0,this._ktx2DecoderOptions={}}get isDirty(){return this._isDirty}get useRGBAIfASTCBC7NotAvailableWhenUASTC(){return this._useRGBAIfASTCBC7NotAvailableWhenUASTC}set useRGBAIfASTCBC7NotAvailableWhenUASTC(e){this._useRGBAIfASTCBC7NotAvailableWhenUASTC!==e&&(this._useRGBAIfASTCBC7NotAvailableWhenUASTC=e,this._isDirty=!0)}get useRGBAIfOnlyBC1BC3AvailableWhenUASTC(){return this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC}set useRGBAIfOnlyBC1BC3AvailableWhenUASTC(e){this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC!==e&&(this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC=e,this._isDirty=!0)}get forceRGBA(){return this._forceRGBA}set forceRGBA(e){this._forceRGBA!==e&&(this._forceRGBA=e,this._isDirty=!0)}get forceR8(){return this._forceR8}set forceR8(e){this._forceR8!==e&&(this._forceR8=e,this._isDirty=!0)}get forceRG8(){return this._forceRG8}set forceRG8(e){this._forceRG8!==e&&(this._forceRG8=e,this._isDirty=!0)}get bypassTranscoders(){return this._bypassTranscoders}set bypassTranscoders(e){this._bypassTranscoders!==e&&(this._bypassTranscoders=e,this._isDirty=!0)}_getKTX2DecoderOptions(){if(!this._isDirty)return this._ktx2DecoderOptions;this._isDirty=!1;let e={};return this._useRGBAIfASTCBC7NotAvailableWhenUASTC!==void 0&&(e.useRGBAIfASTCBC7NotAvailableWhenUASTC=this._useRGBAIfASTCBC7NotAvailableWhenUASTC),this._forceRGBA!==void 0&&(e.forceRGBA=this._forceRGBA),this._forceR8!==void 0&&(e.forceR8=this._forceR8),this._forceRG8!==void 0&&(e.forceRG8=this._forceRG8),this._bypassTranscoders!==void 0&&(e.bypassTranscoders=this._bypassTranscoders),this.useRGBAIfOnlyBC1BC3AvailableWhenUASTC&&(e.transcodeFormatDecisionTree={UASTC:{transcodeFormat:[cm.BC1_RGB,cm.BC3_RGBA],yes:{transcodeFormat:cm.RGBA32,engineFormat:32856,roundToMultiple4:!1}}}),this._ktx2DecoderOptions=e,e}},Jl=class n{static GetDefaultNumWorkers(){return typeof navigator!="object"||!navigator.hardwareConcurrency?1:Math.min(Math.floor(navigator.hardwareConcurrency*.5),4)}static _Initialize(e){if(n._WorkerPoolPromise||n._DecoderModulePromise)return;let t={wasmBaseUrl:_e.ScriptBaseUrl,jsDecoderModule:_e.GetBabylonScriptURL(this.URLConfig.jsDecoderModule,!0),wasmUASTCToASTC:_e.GetBabylonScriptURL(this.URLConfig.wasmUASTCToASTC,!0),wasmUASTCToBC7:_e.GetBabylonScriptURL(this.URLConfig.wasmUASTCToBC7,!0),wasmUASTCToRGBA_UNORM:_e.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_UNORM,!0),wasmUASTCToRGBA_SRGB:_e.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_SRGB,!0),wasmUASTCToR8_UNORM:_e.GetBabylonScriptURL(this.URLConfig.wasmUASTCToR8_UNORM,!0),wasmUASTCToRG8_UNORM:_e.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRG8_UNORM,!0),jsMSCTranscoder:_e.GetBabylonScriptURL(this.URLConfig.jsMSCTranscoder,!0),wasmMSCTranscoder:_e.GetBabylonScriptURL(this.URLConfig.wasmMSCTranscoder,!0),wasmZSTDDecoder:_e.GetBabylonScriptURL(this.URLConfig.wasmZSTDDecoder,!0)};e&&typeof Worker=="function"&&typeof URL!="undefined"?n._WorkerPoolPromise=new Promise(i=>{let r=`${ng}(${OU})()`,s=URL.createObjectURL(new Blob([r],{type:"application/javascript"}));i(new rg(e,async()=>await NU(new Worker(s),void 0,t)))}):typeof n._KTX2DecoderModule=="undefined"?n._DecoderModulePromise=_e.LoadBabylonScriptAsync(t.jsDecoderModule).then(()=>(n._KTX2DecoderModule=KTX2DECODER,n._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread=!1,n._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,ng(t,n._KTX2DecoderModule),new n._KTX2DecoderModule.KTX2Decoder)):(n._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread=!1,n._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,n._DecoderModulePromise=Promise.resolve(new n._KTX2DecoderModule.KTX2Decoder))}constructor(e,t=n.DefaultNumWorkers){var r,s;this._engine=e;let i=typeof t=="object"&&t.workerPool||n.WorkerPool;if(i)n._WorkerPoolPromise=Promise.resolve(i);else{typeof t=="object"?n._KTX2DecoderModule=(r=t==null?void 0:t.binariesAndModulesContainer)==null?void 0:r.jsDecoderModule:typeof KTX2DECODER!="undefined"&&(n._KTX2DecoderModule=KTX2DECODER);let a=typeof t=="number"?t:(s=t.numWorkers)!=null?s:n.DefaultNumWorkers;n._Initialize(a)}}async _uploadAsync(e,t,i){let r=this._engine.getCaps(),s={astc:!!r.astc,bptc:!!r.bptc,s3tc:!!r.s3tc,pvrtc:!!r.pvrtc,etc2:!!r.etc2,etc1:!!r.etc1};if(n._WorkerPoolPromise){let a=await n._WorkerPoolPromise;return await new Promise((o,l)=>{a.push((c,f)=>{let h=m=>{c.removeEventListener("error",h),c.removeEventListener("message",d),l(m),f()},d=m=>{if(m.data.action==="decoded"){if(c.removeEventListener("error",h),c.removeEventListener("message",d),!m.data.success)l({message:m.data.msg});else try{this._createTexture(m.data.decodedData,t,i),o()}catch(p){l({message:p})}f()}};c.addEventListener("error",h),c.addEventListener("message",d),c.postMessage({action:"setDefaultDecoderOptions",options:n.DefaultDecoderOptions._getKTX2DecoderOptions()});let u=new Uint8Array(e.byteLength);u.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),c.postMessage({action:"decode",data:u,caps:s,options:i},[u.buffer])})})}else if(n._DecoderModulePromise){let a=await n._DecoderModulePromise;return n.DefaultDecoderOptions.isDirty&&(n._KTX2DecoderModule.KTX2Decoder.DefaultDecoderOptions=n.DefaultDecoderOptions._getKTX2DecoderOptions()),await new Promise((o,l)=>{a.decode(e,r).then(c=>{this._createTexture(c,t),o()}).catch(c=>{l({message:c})})})}throw new Error("KTX2 decoder module is not available")}_createTexture(e,t,i){this._engine._bindTextureDirectly(3553,t),i&&(i.transcodedFormat=e.transcodedFormat,i.isInGammaSpace=e.isInGammaSpace,i.hasAlpha=e.hasAlpha,i.transcoderName=e.transcoderName);let s=!0;switch(e.transcodedFormat){case 32856:t.type=0,t.format=5;break;case 33321:t.type=0,t.format=6;break;case 33323:t.type=0,t.format=7;break;default:t.format=e.transcodedFormat,s=!1;break}if(t._gammaSpace=e.isInGammaSpace,t.generateMipMaps=e.mipmaps.length>1,t.width=e.mipmaps[0].width,t.height=e.mipmaps[0].height,e.errors)throw new Error("KTX2 container - could not transcode the data. "+e.errors);for(let a=0;a=12){let t=new Uint8Array(e.buffer,e.byteOffset,12);if(t[0]===171&&t[1]===75&&t[2]===84&&t[3]===88&&t[4]===32&&t[5]===50&&t[6]===48&&t[7]===187&&t[8]===13&&t[9]===10&&t[10]===26&&t[11]===10)return!0}return!1}};Jl.URLConfig={jsDecoderModule:"https://cdn.babylonjs.com/babylon.ktx2Decoder.js",wasmUASTCToASTC:null,wasmUASTCToBC7:null,wasmUASTCToRGBA_UNORM:null,wasmUASTCToRGBA_SRGB:null,wasmUASTCToR8_UNORM:null,wasmUASTCToRG8_UNORM:null,jsMSCTranscoder:null,wasmMSCTranscoder:null,wasmZSTDDecoder:null};Jl.DefaultNumWorkers=Jl.GetDefaultNumWorkers();Jl.DefaultDecoderOptions=new VC});var kC={};tt(kC,{_KTXTextureLoader:()=>GC});function une(n){switch(n){case 35916:return 33776;case 35918:return 33778;case 35919:return 33779;case 37493:return 37492;case 37497:return 37496;case 37495:return 37494;case 37840:return 37808;case 37841:return 37809;case 37842:return 37810;case 37843:return 37811;case 37844:return 37812;case 37845:return 37813;case 37846:return 37814;case 37847:return 37815;case 37848:return 37816;case 37849:return 37817;case 37850:return 37818;case 37851:return 37819;case 37852:return 37820;case 37853:return 37821;case 36493:return 36492}return null}var GC,WC=C(()=>{CU();FU();Pt();GC=class{constructor(){this.supportCascades=!1}loadCubeData(e,t,i,r){if(Array.isArray(e))return;t._invertVScale=!t.invertY;let s=t.getEngine(),a=new ho(e,6),o=a.numberOfMipmapLevels>1&&t.generateMipMaps;s._unpackFlipY(!0),a.uploadLevels(t,t.generateMipMaps),t.width=a.pixelWidth,t.height=a.pixelHeight,s._setCubeMapTextureParams(t,o,a.numberOfMipmapLevels-1),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()}loadData(e,t,i,r){if(ho.IsValid(e)){t._invertVScale=!t.invertY;let s=new ho(e,1),a=une(s.glInternalFormat);a?(t.format=a,t._useSRGBBuffer=t.getEngine()._getUseSRGBBuffer(!0,t.generateMipMaps),t._gammaSpace=!0):t.format=s.glInternalFormat,i(s.pixelWidth,s.pixelHeight,t.generateMipMaps,!0,()=>{s.uploadLevels(t,t.generateMipMaps)},s.isInvalid)}else Jl.IsValid(e)?new Jl(t.getEngine())._uploadAsync(e,t,r).then(()=>{i(t.width,t.height,t.generateMipMaps,!0,()=>{},!1)},a=>{te.Warn(`Failed to load KTX2 texture data: ${a.message}`),i(0,0,!1,!1,()=>{},!0)}):(te.Error("texture missing KTX identifier"),i(0,0,!1,!1,()=>{},!0))}}});function vA(n){let e=0;return{id_length:n[e++],colormap_type:n[e++],image_type:n[e++],colormap_index:n[e++]|n[e++]<<8,colormap_length:n[e++]|n[e++]<<8,colormap_size:n[e++],origin:[n[e++]|n[e++]<<8,n[e++]|n[e++]<<8],width:n[e++]|n[e++]<<8,height:n[e++]|n[e++]<<8,pixel_size:n[e++],flags:n[e]}}function HC(n,e){if(e.length<19){te.Error("Unable to load TGA file - Not enough data to contain header");return}let t=18,i=vA(e);if(i.id_length+t>e.length){te.Error("Unable to load TGA file - Not enough data");return}t+=i.id_length;let r=!1,s=!1,a=!1;switch(i.image_type){case gne:r=!0;case mne:s=!0;break;case vne:r=!0;case pne:break;case Ene:r=!0;case _ne:a=!0;break}let o,l=i.pixel_size>>3,c=i.width*i.height*l,f;if(s&&(f=e.subarray(t,t+=i.colormap_length*(i.colormap_size>>3))),r){o=new Uint8Array(c);let A,S,E,R=0,I=new Uint8Array(l);for(;t>Tne){default:case Rne:h=0,u=1,_=i.width,d=0,m=1,p=i.height;break;case Ane:h=0,u=1,_=i.width,d=i.height-1,m=-1,p=-1;break;case bne:h=i.width-1,u=-1,_=-1,d=0,m=1,p=i.height;break;case xne:h=i.width-1,u=-1,_=-1,d=i.height-1,m=-1,p=-1;break}let g="_getImageData"+(a?"Grey":"")+i.pixel_size+"bits",v=Lne[g](i,f,o,d,m,p,h,u,_);n.getEngine()._uploadDataToTextureDirectly(n,v)}function Ine(n,e,t,i,r,s,a,o,l){let c=t,f=e,h=n.width,d=n.height,u,m=0,p,_,g=new Uint8Array(h*d*4);for(_=i;_!==s;_+=r)for(p=a;p!==l;p+=o,m++)u=c[m],g[(p+h*_)*4+3]=255,g[(p+h*_)*4+2]=f[u*3+0],g[(p+h*_)*4+1]=f[u*3+1],g[(p+h*_)*4+0]=f[u*3+2];return g}function Mne(n,e,t,i,r,s,a,o,l){let c=t,f=n.width,h=n.height,d,u=0,m,p,_=new Uint8Array(f*h*4);for(p=i;p!==s;p+=r)for(m=a;m!==l;m+=o,u+=2){d=c[u+0]+(c[u+1]<<8);let g=((d&31744)>>10)*255/31|0,v=((d&992)>>5)*255/31|0,x=(d&31)*255/31|0;_[(m+f*p)*4+0]=g,_[(m+f*p)*4+1]=v,_[(m+f*p)*4+2]=x,_[(m+f*p)*4+3]=d&32768?0:255}return _}function Cne(n,e,t,i,r,s,a,o,l){let c=t,f=n.width,h=n.height,d=0,u,m,p=new Uint8Array(f*h*4);for(m=i;m!==s;m+=r)for(u=a;u!==l;u+=o,d+=3)p[(u+f*m)*4+3]=255,p[(u+f*m)*4+2]=c[d+0],p[(u+f*m)*4+1]=c[d+1],p[(u+f*m)*4+0]=c[d+2];return p}function yne(n,e,t,i,r,s,a,o,l){let c=t,f=n.width,h=n.height,d=0,u,m,p=new Uint8Array(f*h*4);for(m=i;m!==s;m+=r)for(u=a;u!==l;u+=o,d+=4)p[(u+f*m)*4+2]=c[d+0],p[(u+f*m)*4+1]=c[d+1],p[(u+f*m)*4+0]=c[d+2],p[(u+f*m)*4+3]=c[d+3];return p}function Pne(n,e,t,i,r,s,a,o,l){let c=t,f=n.width,h=n.height,d,u=0,m,p,_=new Uint8Array(f*h*4);for(p=i;p!==s;p+=r)for(m=a;m!==l;m+=o,u++)d=c[u],_[(m+f*p)*4+0]=d,_[(m+f*p)*4+1]=d,_[(m+f*p)*4+2]=d,_[(m+f*p)*4+3]=255;return _}function Dne(n,e,t,i,r,s,a,o,l){let c=t,f=n.width,h=n.height,d=0,u,m,p=new Uint8Array(f*h*4);for(m=i;m!==s;m+=r)for(u=a;u!==l;u+=o,d+=2)p[(u+f*m)*4+0]=c[d+0],p[(u+f*m)*4+1]=c[d+0],p[(u+f*m)*4+2]=c[d+0],p[(u+f*m)*4+3]=c[d+1];return p}var mne,pne,_ne,gne,vne,Ene,Sne,Tne,Ane,xne,Rne,bne,Lne,BU=C(()=>{Pt();mne=1,pne=2,_ne=3,gne=9,vne=10,Ene=11,Sne=48,Tne=4,Ane=0,xne=1,Rne=2,bne=3;Lne={GetTGAHeader:vA,UploadContent:HC,_getImageData8bits:Ine,_getImageData16bits:Mne,_getImageData24bits:Cne,_getImageData32bits:yne,_getImageDataGrey8bits:Pne,_getImageDataGrey16bits:Dne}});var UU={};tt(UU,{_TGATextureLoader:()=>zC});var zC,VU=C(()=>{BU();zC=class{constructor(){this.supportCascades=!1}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){let r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=vA(r);i(s.width,s.height,t.generateMipMaps,!1,()=>{HC(t,r)})}}});var sg=C(()=>{});function Nne(){let n=new ArrayBuffer(4),e=new Float32Array(n),t=new Uint32Array(n),i=new Uint32Array(512),r=new Uint32Array(512);for(let l=0;l<256;++l){let c=l-127;c<-27?(i[l]=0,i[l|256]=32768,r[l]=24,r[l|256]=24):c<-14?(i[l]=1024>>-c-14,i[l|256]=1024>>-c-14|32768,r[l]=-c-1,r[l|256]=-c-1):c<=15?(i[l]=c+15<<10,i[l|256]=c+15<<10|32768,r[l]=13,r[l|256]=13):c<128?(i[l]=31744,i[l|256]=64512,r[l]=24,r[l|256]=24):(i[l]=31744,i[l|256]=64512,r[l]=13,r[l|256]=13)}let s=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let l=1;l<1024;++l){let c=l<<13,f=0;for(;(c&8388608)===0;)c<<=1,f-=8388608;c&=-8388609,f+=947912704,s[l]=c|f}for(let l=1024;l<2048;++l)s[l]=939524096+(l-1024<<13);for(let l=1;l<31;++l)a[l]=l<<23;a[31]=1199570944,a[32]=2147483648;for(let l=33;l<63;++l)a[l]=2147483648+(l-32<<23);a[63]=3347054592;for(let l=1;l<64;++l)l!==32&&(o[l]=1024);return{floatView:e,uint32View:t,baseTable:i,shiftTable:r,mantissaTable:s,exponentTable:a,offsetTable:o}}function TA(n,e){let t=new Uint8Array(n),i=0;for(;t[e.value+i]!=0;)i+=1;let r=new TextDecoder().decode(t.slice(e.value,e.value+i));return e.value=e.value+i+1,r}function uo(n,e){let t=n.getInt32(e.value,!0);return e.value+=4,t}function Ks(n,e){let t=n.getUint32(e.value,!0);return e.value+=4,t}function ag(n,e){let t=n.getUint8(e.value);return e.value+=1,t}function fm(n,e){let t=n.getUint16(e.value,!0);return e.value+=2,t}function YC(n,e){let t=n[e.value];return e.value+=1,t}function WU(n,e){let t;return"getBigInt64"in DataView.prototype?t=Number(n.getBigInt64(e.value,!0)):t=n.getUint32(e.value+4,!0)+Number(n.getUint32(e.value,!0)<<32),e.value+=8,t}function Sn(n,e){let t=n.getFloat32(e.value,!0);return e.value+=4,t}function HU(n,e){return wne(fm(n,e))}function wne(n){let e=(n&31744)>>10,t=n&1023;return(n>>15?-1:1)*(e?e===31?t?NaN:1/0:Math.pow(2,e-15)*(1+t/1024):6103515625e-14*(t/1024))}function Fne(n){if(Math.abs(n)>65504)throw new Error("Value out of range.Consider using float instead of half-float.");n=wt(n,-65504,65504),EA.floatView[0]=n;let e=EA.uint32View[0],t=e>>23&511;return EA.baseTable[t]+((e&8388607)>>EA.shiftTable[t])}function zU(n,e){return Fne(Sn(n,e))}function Bne(n,e,t){let i=new TextDecoder().decode(new Uint8Array(n).slice(e.value,e.value+t));return e.value=e.value+t,i}function Une(n,e){let t=uo(n,e),i=Ks(n,e);return[t,i]}function Vne(n,e){let t=Ks(n,e),i=Ks(n,e);return[t,i]}function Gne(n,e){let t=Sn(n,e),i=Sn(n,e);return[t,i]}function kne(n,e){let t=Sn(n,e),i=Sn(n,e),r=Sn(n,e);return[t,i,r]}function Wne(n,e,t){let i=e.value,r=[];for(;e.values||(e[r++]=n[t++],r>s));)e[r++]=n[i++]}var rl,XC,EA,og=C(()=>{Ln();sg();(function(n){n[n.NO_COMPRESSION=0]="NO_COMPRESSION",n[n.RLE_COMPRESSION=1]="RLE_COMPRESSION",n[n.ZIPS_COMPRESSION=2]="ZIPS_COMPRESSION",n[n.ZIP_COMPRESSION=3]="ZIP_COMPRESSION",n[n.PIZ_COMPRESSION=4]="PIZ_COMPRESSION",n[n.PXR24_COMPRESSION=5]="PXR24_COMPRESSION"})(rl||(rl={}));(function(n){n[n.INCREASING_Y=0]="INCREASING_Y",n[n.DECREASING_Y=1]="DECREASING_Y"})(XC||(XC={}));EA=Nne()});function qC(n,e){if(n.getUint32(0,!0)!=Kne)throw new Error("Incorrect OpenEXR format");let t=n.getUint8(4),i=n.getUint8(5),r={singleTile:!!(i&2),longName:!!(i&4),deepFormat:!!(i&8),multiPart:!!(i&16)};e.value=8;let s={},a=!0;for(;a;){let o=TA(n.buffer,e);if(!o)a=!1;else{let l=TA(n.buffer,e),c=Ks(n,e),f=XU(n,e,l,c);f===void 0?te.Warn(`Unknown header attribute type ${l}'.`):s[o]=f}}if((i&-5)!=0)throw new Error("Unsupported file format");return{version:t,spec:r,...s}}var Kne,YU=C(()=>{Pt();og();Kne=20000630});function eV(n,e){let t=0;for(let r=0;r<65536;++r)(r==0||n[r>>3]&1<<(r&7))&&(e[t++]=r);let i=t-1;for(;t<65536;)e[t++]=0;return i}function Qne(n){for(let e=0;e<16384;e++)n[e]={},n[e].len=0,n[e].lit=0,n[e].p=null}function ZU(n,e,t,i,r){for(;t>t&(1<>i;if(c=new Uint8Array([c])[0],o.value+c>l)return null;let f=a[o.value-1];for(;c-- >0;)a[o.value++]=f}else if(o.value0;--t){let i=e+lg[t]>>1;lg[t]=e,e=i}for(let t=0;t<65537;++t){let i=n[t];i>0&&(n[t]=i|lg[i]++<<6)}}function Jne(n,e,t,i,r,s){let a=e,o=0,l=0;for(;i<=r;i++){if(a.value-e.value>t)return;let c=ZU(6,o,l,n,a),f=c.l;if(o=c.c,l=c.lc,s[i]=f,f==63){if(a.value-e.value>t)throw new Error("Error in HufUnpackEncTable");c=ZU(8,o,l,n,a);let h=c.l+6;if(o=c.c,l=c.lc,i+h>r+1)throw new Error("Error in HufUnpackEncTable");for(;h--;)s[i++]=0;i--}else if(f>=59){let h=f-59+2;if(i+h>r+1)throw new Error("Error in HufUnpackEncTable");for(;h--;)s[i++]=0;i--}}$ne(s)}function tV(n){return n&63}function iV(n){return n>>6}function ese(n,e,t,i){for(;e<=t;e++){let r=iV(n[e]),s=tV(n[e]);if(r>>s)throw new Error("Invalid table entry");if(s>14){let a=i[r>>s-14];if(a.len)throw new Error("Invalid table entry");if(a.lit++,a.p){let o=a.p;a.p=new Array(a.lit);for(let l=0;l0;o--){let l=i[(r<<14-s)+a];if(l.len||l.p)throw new Error("Invalid table entry");l.len=s,l.lit=e,a++}}}return!0}function tse(n,e,t,i,r,s,a,o,l){let c=0,f=0,h=a,d=Math.trunc(i.value+(r+7)/8);for(;i.value=14;){let p=c>>f-14&16383,_=e[p];if(_.len){f-=_.len;let g=ZC(_.lit,s,c,f,t,i,o,l,h);g&&(c=g.c,f=g.lc)}else{if(!_.p)throw new Error("hufDecode issues");let g;for(g=0;g<_.lit;g++){let v=tV(n[_.p[g]]);for(;f=v&&iV(n[_.p[g]])==(c>>f-v&(1<>=u,f-=u;f>0;){let m=e[c<<14-f&16383];if(m.len){f-=m.len;let p=ZC(m.lit,s,c,f,t,i,o,l,h);p&&(c=p.c,f=p.lc)}else throw new Error("HufDecode issues")}return!0}function rV(n,e,t,i,r,s){let a={value:0},o=t.value,l=Ks(e,t),c=Ks(e,t);t.value+=4;let f=Ks(e,t);if(t.value+=4,l<0||l>=65537||c<0||c>=65537)throw new Error("Wrong HUF_ENCSIZE");let h=new Array(65537),d=new Array(16384);Qne(d);let u=i-(t.value-o);if(Jne(n,t,u,l,c,h),f>8*(i-(t.value-o)))throw new Error("Wrong hufUncompress");ese(h,l,c,d),tse(h,d,n,t,f,c,s,r,a)}function $C(n){return n&65535}function QU(n){let e=$C(n);return e>32767?e-65536:e}function hm(n,e){let t=QU(n),r=QU(e),s=t+(r&1)+(r>>1),a=s,o=s-r;return{a,b:o}}function dm(n,e){let t=$C(n),i=$C(e),r=t-(i>>1)&qU;return{a:i+r-Zne&qU,b:r}}function nV(n,e,t,i,r,s,a){let o=a<16384,l=t>r?r:t,c=1,f,h;for(;c<=l;)c<<=1;for(c>>=1,f=c,c>>=1;c>=1;){h=0;let d=h+s*(r-f),u=s*c,m=s*f,p=i*c,_=i*f,g,v,x,A;for(;h<=d;h+=m){let S=h,E=h+i*(t-f);for(;S<=E;S+=_){let R=S+p,I=S+u,y=I+p;if(o){let M=hm(n[S+e],n[I+e]);g=M.a,x=M.b,M=hm(n[R+e],n[y+e]),v=M.a,A=M.b,M=hm(g,v),n[S+e]=M.a,n[R+e]=M.b,M=hm(x,A),n[I+e]=M.a,n[y+e]=M.b}else{let M=dm(n[S+e],n[I+e]);g=M.a,x=M.b,M=dm(n[R+e],n[y+e]),v=M.a,A=M.b,M=dm(g,v),n[S+e]=M.a,n[R+e]=M.b,M=dm(x,A),n[I+e]=M.a,n[y+e]=M.b}}if(t&c){let R=S+u,I;o?I=hm(n[S+e],n[R+e]):I=dm(n[S+e],n[R+e]),g=I.a,n[R+e]=I.b,n[S+e]=g}}if(r&c){let S=h,E=h+i*(t-f);for(;S<=E;S+=_){let R=S+p,I;o?I=hm(n[S+e],n[R+e]):I=dm(n[S+e],n[R+e]),g=I.a,n[R+e]=I.b,n[S+e]=g}}f=c,c>>=1}return h}function sV(n,e,t){for(let i=0;i{og();sg();JU=16,Zne=1<0;){let s=r.getInt8(i++);if(s<0){let a=-s;e-=a+1;for(let o=0;o{});function JC(n){return new DataView(n.array.buffer,n.offset.value,n.size)}function fV(n){let e=n.viewer.buffer.slice(n.offset.value,n.offset.value+n.size),t=new Uint8Array(oV(e)),i=new Uint8Array(t.length);return KC(t),jC(t,i),new DataView(i.buffer)}function ey(n){let e=n.array.slice(n.offset.value,n.offset.value+n.size),t=fflate.unzlibSync(e),i=new Uint8Array(t.length);return KC(t),jC(t,i),new DataView(i.buffer)}function hV(n){let e=n.array.slice(n.offset.value,n.offset.value+n.size),t=fflate.unzlibSync(e),i=n.lines*n.channels*n.width,r=n.type==1?new Uint16Array(i):new Uint32Array(i),s=0,a=0,o=new Array(4);for(let l=0;l=8192)throw new Error("Wrong PIZ_COMPRESSION BITMAP_SIZE");if(o<=l)for(let m=0;m{aV();lV();og();sg()});var ya,nl,ty=C(()=>{(function(n){n[n.Float=0]="Float",n[n.HalfFloat=1]="HalfFloat"})(ya||(ya={}));nl=class{};nl.DefaultOutputType=ya.HalfFloat;nl.FFLATEUrl="https://unpkg.com/fflate@0.8.2"});async function iy(n,e,t,i){let r={size:0,viewer:e,array:new Uint8Array(e.buffer),offset:t,width:n.dataWindow.xMax-n.dataWindow.xMin+1,height:n.dataWindow.yMax-n.dataWindow.yMin+1,channels:n.channels.length,channelLineOffsets:{},scanOrder:()=>0,bytesPerLine:0,outLineWidth:0,lines:0,scanlineBlockSize:0,inputSize:null,type:0,uncompress:null,getter:()=>0,format:5,outputChannels:0,decodeChannels:{},blockCount:null,byteArray:null,linearSpace:!1,textureType:0};switch(n.compression){case rl.NO_COMPRESSION:r.lines=1,r.uncompress=JC;break;case rl.RLE_COMPRESSION:r.lines=1,r.uncompress=fV;break;case rl.ZIPS_COMPRESSION:r.lines=1,r.uncompress=ey,await _e.LoadScriptAsync(nl.FFLATEUrl);break;case rl.ZIP_COMPRESSION:r.lines=16,r.uncompress=ey,await _e.LoadScriptAsync(nl.FFLATEUrl);break;case rl.PIZ_COMPRESSION:r.lines=32,r.uncompress=dV;break;case rl.PXR24_COMPRESSION:r.lines=16,r.uncompress=hV,await _e.LoadScriptAsync(nl.FFLATEUrl);break;default:throw new Error(rl[n.compression]+" is unsupported")}r.scanlineBlockSize=r.lines;let s={};for(let c of n.channels)switch(c.name){case"R":case"G":case"B":case"A":s[c.name]=!0,r.type=c.pixelType;break;case"Y":s[c.name]=!0,r.type=c.pixelType;break;default:break}let a=!1;if(s.R&&s.G&&s.B&&s.A)r.outputChannels=4,r.decodeChannels={R:0,G:1,B:2,A:3};else if(s.R&&s.G&&s.B)a=!0,r.outputChannels=4,r.decodeChannels={R:0,G:1,B:2,A:3};else if(s.R&&s.G)r.outputChannels=2,r.decodeChannels={R:0,G:1};else if(s.R)r.outputChannels=1,r.decodeChannels={R:0};else if(s.Y)r.outputChannels=1,r.decodeChannels={Y:0};else throw new Error("EXRLoader.parse: file contains unsupported data channels.");if(r.type===1)switch(i){case ya.Float:r.getter=HU,r.inputSize=2;break;case ya.HalfFloat:r.getter=fm,r.inputSize=2;break}else if(r.type===2)switch(i){case ya.Float:r.getter=Sn,r.inputSize=4;break;case ya.HalfFloat:r.getter=zU,r.inputSize=4}else throw new Error("Unsupported pixelType "+r.type+" for "+n.compression);r.blockCount=r.height/r.scanlineBlockSize;for(let c=0;cc:r.scanOrder=c=>r.height-1-c,r.outputChannels==4?(r.format=5,r.linearSpace=!0):(r.format=6,r.linearSpace=!1),r}function ry(n,e,t,i){let r={value:0};for(let s=0;sn.height?n.height-a:n.scanlineBlockSize;let l=n.size=n.height)continue;let d=c*n.bytesPerLine,u=(n.height-1-h)*n.outLineWidth;for(let m=0;m{og();uV();sg();Ii();ty()});var pV={};tt(pV,{ReadExrDataAsync:()=>ise,_ExrTextureLoader:()=>ny});async function ise(n){let e=new DataView(n),t={value:0},i=qC(e,t);try{let r=await iy(i,e,t,ya.Float);return ry(r,i,e,t),r.byteArray?{width:i.dataWindow.xMax-i.dataWindow.xMin+1,height:i.dataWindow.yMax-i.dataWindow.yMin+1,data:new Float32Array(r.byteArray)}:(te.Error("Failed to decode EXR data: No byte array available."),{width:0,height:0,data:null})}catch(r){te.Error("Failed to load EXR data: ",r)}return{width:0,height:0,data:null}}var ny,_V=C(()=>{YU();mV();ty();Pt();ny=class{constructor(){this.supportCascades=!1}loadCubeData(e,t,i,r,s){throw".exr not supported in Cube."}loadData(e,t,i){let r=new DataView(e.buffer),s={value:0},a=qC(r,s);iy(a,r,s,nl.DefaultOutputType).then(o=>{ry(o,a,r,s);let l=a.dataWindow.xMax-a.dataWindow.xMin+1,c=a.dataWindow.yMax-a.dataWindow.yMin+1;i(l,c,t.generateMipMaps,!1,()=>{let f=t.getEngine();t.format=a.format,t.type=o.textureType,t.invertY=!1,t._gammaSpace=!a.linearSpace,o.byteArray&&f._uploadDataToTextureDirectly(t,o.byteArray,0,0,void 0,!0)})}).catch(o=>{te.Error("Failed to load EXR texture: ",o)})}}});function ec(n,e){rse(n)&&te.Warn(`Extension with the name '${n}' already exists`),xA.set(n,e)}function rse(n){return xA.delete(n)}function RA(n,e){(e==="image/ktx"||e==="image/ktx2")&&(n=".ktx"),xA.has(n)||(n.endsWith(".ies")&&ec(".ies",async()=>await Promise.resolve().then(()=>(pB(),mB)).then(i=>new i._IESTextureLoader)),n.endsWith(".dds")&&ec(".dds",async()=>await Promise.resolve().then(()=>(gB(),_B)).then(i=>new i._DDSTextureLoader)),n.endsWith(".basis")&&ec(".basis",async()=>await Promise.resolve().then(()=>(xB(),AB)).then(i=>new i._BasisTextureLoader)),n.endsWith(".env")&&ec(".env",async()=>await Promise.resolve().then(()=>(SU(),EU)).then(i=>new i._ENVTextureLoader)),n.endsWith(".hdr")&&ec(".hdr",async()=>await Promise.resolve().then(()=>(MU(),IU)).then(i=>new i._HDRTextureLoader)),(n.endsWith(".ktx")||n.endsWith(".ktx2"))&&(ec(".ktx",async()=>await Promise.resolve().then(()=>(WC(),kC)).then(i=>new i._KTXTextureLoader)),ec(".ktx2",async()=>await Promise.resolve().then(()=>(WC(),kC)).then(i=>new i._KTXTextureLoader))),n.endsWith(".tga")&&ec(".tga",async()=>await Promise.resolve().then(()=>(VU(),UU)).then(i=>new i._TGATextureLoader)),n.endsWith(".exr")&&ec(".exr",async()=>await Promise.resolve().then(()=>(_V(),pV)).then(i=>new i._ExrTextureLoader)));let t=xA.get(n);return t?Promise.resolve(t(e)):null}var xA,sy=C(()=>{Pt();xA=new Map});function gV(n){let e=n.split("?")[0],t=e.lastIndexOf(".");return t>-1?e.substring(t).toLowerCase():""}var vV=C(()=>{});var EV=C(()=>{vs();Pt();Wl();B_();wr();sy();vV();Me.prototype._partialLoadFile=function(n,e,t,i,r=null){let s=o=>{t[e]=o,t._internalCount++,t._internalCount===6&&i(t)},a=(o,l)=>{r&&o&&r(o.status+" "+o.statusText,l)};this._loadFile(n,s,void 0,void 0,!0,a)};Me.prototype._cascadeLoadFiles=function(n,e,t,i=null){let r=[];r._internalCount=0;for(let s=0;s<6;s++)this._partialLoadFile(t[s],s,r,e,i)};Me.prototype._cascadeLoadImgs=function(n,e,t,i,r=null,s){let a=[];a._internalCount=0;for(let o=0;o<6;o++)this._partialLoadImg(i[o],o,a,n,e,t,r,s)};Me.prototype._partialLoadImg=function(n,e,t,i,r,s,a=null,o){let l=lf();sm(n,h=>{t[e]=h,t._internalCount++,i&&i.removePendingData(l),t._internalCount===6&&s&&s(r,t)},(h,d)=>{i&&i.removePendingData(l),a&&a(h,d)},i?i.offlineProvider:null,o),i&&i.addPendingData(l)};Me.prototype.createCubeTextureBase=function(n,e,t,i,r=null,s=null,a,o=null,l=!1,c=0,f=0,h=null,d=null,u=null,m=!1,p=null){let _=h||new Pi(this,7);_.isCube=!0,_.url=n,_.generateMipMaps=!i,_._lodGenerationScale=c,_._lodGenerationOffset=f,_._useSRGBBuffer=!!m&&this._caps.supportSRGBBuffers&&(this.version>1||this.isWebGPU||!!i),_!==h&&(_.label=n.substring(0,60)),this._doNotHandleContextLost||(_._extension=o,_._files=t,_._buffer=p);let g=n;this._transformTextureUrl&&!h&&(n=this._transformTextureUrl(n));let v=o!=null?o:gV(n),x=RA(v),A=(E,R)=>{_.dispose(),s?s(E,R):E&&te.Warn(E)},S=(E,R)=>{n===g?E&&A(E.status+" "+E.statusText,R):(te.Warn(`Failed to load ${n}, falling back to the ${g}`),this.createCubeTextureBase(g,e,t,!!i,r,A,a,o,l,c,f,_,d,u,m,p))};if(x)x.then(E=>{let R=I=>{d&&d(_,I),E.loadCubeData(I,_,l,r,(y,M)=>{A(y,M)})};p?R(p):t&&t.length===6?E.supportCascades?this._cascadeLoadFiles(e,I=>R(I.map(y=>new Uint8Array(y))),t,A):A("Textures type does not support cascades."):this._loadFile(n,I=>R(new Uint8Array(I)),void 0,e?e.offlineProvider||null:void 0,!0,S)});else{if(!t||t.length===0)throw new Error("Cannot load cubemap because files were not defined, or the correct loader was not found.");this._cascadeLoadImgs(e,_,(E,R)=>{u&&u(E,R)},t,A)}return this._internalTexturesCache.push(_),_}});var FV={};tt(FV,{DDSTools:()=>ao});function bA(n){return n.charCodeAt(0)+(n.charCodeAt(1)<<8)+(n.charCodeAt(2)<<16)+(n.charCodeAt(3)<<24)}function sse(n){return String.fromCharCode(n&255,n>>8&255,n>>16&255,n>>24&255)}var nse,SV,TV,AV,xV,RV,bV,IV,MV,ay,CV,yV,PV,DV,ase,oy,ose,lse,LV,OV,ly,NV,cy,wV,cse,fse,hse,dse,use,mse,pse,ao,uC=C(()=>{Ln();Pt();kM();lC();EV();nse=542327876,SV=131072,TV=512,AV=4,xV=64,RV=131072;bV=bA("DXT1"),IV=bA("DXT3"),MV=bA("DXT5"),ay=bA("DX10"),CV=113,yV=116,PV=2,DV=10,ase=88,oy=31,ose=0,lse=1,LV=2,OV=3,ly=4,NV=7,cy=20,wV=21,cse=22,fse=23,hse=24,dse=25,use=26,mse=28,pse=32,ao=class n{static GetDDSInfo(e){let t=new Int32Array(e.buffer,e.byteOffset,oy),i=new Int32Array(e.buffer,e.byteOffset,oy+4),r=1;t[LV]&SV&&(r=Math.max(1,t[NV]));let s=t[wV],a=s===ay?i[pse]:0,o=0;switch(s){case CV:o=2;break;case yV:o=1;break;case ay:if(a===DV){o=2;break}if(a===PV){o=1;break}}return{width:t[ly],height:t[OV],mipmapCount:r,isFourCC:(t[cy]&AV)===AV,isRGB:(t[cy]&xV)===xV,isLuminance:(t[cy]&RV)===RV,isCube:(t[mse]&TV)===TV,isCompressed:s===bV||s===IV||s===MV,dxgiFormat:a,textureType:o}}static _GetHalfFloatAsFloatRGBAArrayBuffer(e,t,i,r,s,a){let o=new Float32Array(r),l=new Uint16Array(s,i),c=0;for(let f=0;f>8)}static _GetRGBArrayBuffer(e,t,i,r,s,a,o,l){let c=new Uint8Array(r),f=new Uint8Array(s,i),h=0;for(let d=0;d0?r.sphericalPolynomial=Hl.ConvertCubeMapToSphericalPolynomial({size:d[ly],right:f[0],left:f[1],up:f[2],down:f[3],front:f[4],back:f[5],format:5,type:1,gammaSpace:!1}):r.sphericalPolynomial=void 0}};ao.StoreLODInAlphaChannel=!1});var BV=C(()=>{Zn();vs();Pt();F_();k_();bt.prototype.createPrefilteredCubeTexture=function(n,e,t,i,r=null,s=null,a,o=null,l=!0){let c=async f=>{var g;if(!f){r&&r(null);return}let h=f.texture;if(l?f.info.sphericalPolynomial&&(h._sphericalPolynomial=f.info.sphericalPolynomial):h._sphericalPolynomial=(g=h._sphericalPolynomial)!=null?g:new $o,h._source=9,this.getCaps().textureLOD){r&&r(h);return}let d=3,u=this._gl,m=f.width;if(!m)return;let{DDSTools:p}=await Promise.resolve().then(()=>(uC(),FV)),_=[];for(let v=0;v{Zn();yT();bt.prototype.createUniformBuffer=function(n,e){let t=this._gl.createBuffer();if(!t)throw new Error("Unable to create uniform buffer");let i=new qo(t);return this.bindUniformBuffer(i),n instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,n,this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(n),this._gl.STATIC_DRAW),this.bindUniformBuffer(null),i.references=1,i};bt.prototype.createDynamicUniformBuffer=function(n,e){let t=this._gl.createBuffer();if(!t)throw new Error("Unable to create dynamic uniform buffer");let i=new qo(t);return this.bindUniformBuffer(i),n instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,n,this._gl.DYNAMIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(n),this._gl.DYNAMIC_DRAW),this.bindUniformBuffer(null),i.references=1,i};bt.prototype.updateUniformBuffer=function(n,e,t,i){this.bindUniformBuffer(n),t===void 0&&(t=0),i===void 0?e instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,t,e):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,t,new Float32Array(e)):e instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,e.subarray(t,t+i)):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,new Float32Array(e).subarray(t,t+i)),this.bindUniformBuffer(null)};bt.prototype.bindUniformBuffer=function(n){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,n?n.underlyingResource:null)};bt.prototype.bindUniformBufferBase=function(n,e,t){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,e,n?n.underlyingResource:null)};bt.prototype.bindUniformBlock=function(n,e,t){let i=n.program,r=this._gl.getUniformBlockIndex(i,e);r!==4294967295&&this._gl.uniformBlockBinding(i,r,t)}});var VV=C(()=>{ga();wr();Me.prototype.displayLoadingUI=function(){if(!fr())return;let n=this.loadingScreen;n&&n.displayLoadingUI()};Me.prototype.hideLoadingUI=function(){if(!fr())return;let n=this._loadingScreen;n&&n.hideLoadingUI()};Object.defineProperty(Me.prototype,"loadingScreen",{get:function(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=Me.DefaultLoadingScreenFactory(this._renderingCanvas)),this._loadingScreen},set:function(n){this._loadingScreen=n},enumerable:!0,configurable:!0});Object.defineProperty(Me.prototype,"loadingUIText",{set:function(n){this.loadingScreen.loadingUIText=n},enumerable:!0,configurable:!0});Object.defineProperty(Me.prototype,"loadingUIBackgroundColor",{set:function(n){this.loadingScreen.loadingUIBackgroundColor=n},enumerable:!0,configurable:!0})});var GV=C(()=>{wr();Me.prototype.getInputElement=function(){return this._renderingCanvas};Me.prototype.getRenderingCanvasClientRect=function(){return this._renderingCanvas?this._renderingCanvas.getBoundingClientRect():null};Me.prototype.getInputElementClientRect=function(){return this._renderingCanvas?this.getInputElement().getBoundingClientRect():null};Me.prototype.getAspectRatio=function(n,e=!1){let t=n.viewport;return this.getRenderWidth(e)*t.width/(this.getRenderHeight(e)*t.height)};Me.prototype.getScreenAspectRatio=function(){return this.getRenderWidth(!0)/this.getRenderHeight(!0)};Me.prototype._verifyPointerLock=function(){var n;(n=this._onPointerLockChange)==null||n.call(this)}});var fy=C(()=>{wr();Me.prototype.setAlphaEquation=function(n,e=0){if(this._alphaEquation[e]!==n){switch(n){case 0:this._alphaState.setAlphaEquationParameters(32774,32774,e);break;case 1:this._alphaState.setAlphaEquationParameters(32778,32778,e);break;case 2:this._alphaState.setAlphaEquationParameters(32779,32779,e);break;case 3:this._alphaState.setAlphaEquationParameters(32776,32776,e);break;case 4:this._alphaState.setAlphaEquationParameters(32775,32775,e);break;case 5:this._alphaState.setAlphaEquationParameters(32775,32774,e);break}this._alphaEquation[e]=n}}});var kV=C(()=>{wr();fy();Me.prototype.getInputElement=function(){return this._renderingCanvas};Me.prototype.getDepthFunction=function(){return this._depthCullingState.depthFunc};Me.prototype.setDepthFunction=function(n){this._depthCullingState.depthFunc=n};Me.prototype.setDepthFunctionToGreater=function(){this.setDepthFunction(516)};Me.prototype.setDepthFunctionToGreaterOrEqual=function(){this.setDepthFunction(518)};Me.prototype.setDepthFunctionToLess=function(){this.setDepthFunction(513)};Me.prototype.setDepthFunctionToLessOrEqual=function(){this.setDepthFunction(515)};Me.prototype.getDepthWrite=function(){return this._depthCullingState.depthMask};Me.prototype.setDepthWrite=function(n){this._depthCullingState.depthMask=n};Me.prototype.setAlphaConstants=function(n,e,t,i){this._alphaState.setAlphaBlendConstants(n,e,t,i)};Me.prototype.getAlphaMode=function(n=0){return this._alphaMode[n]};Me.prototype.getAlphaEquation=function(n=0){return this._alphaEquation[n]}});var WV=C(()=>{wr();fy();Me.prototype.getStencilBuffer=function(){return this._stencilState.stencilTest};Me.prototype.setStencilBuffer=function(n){this._stencilState.stencilTest=n};Me.prototype.getStencilMask=function(){return this._stencilState.stencilMask};Me.prototype.setStencilMask=function(n){this._stencilState.stencilMask=n};Me.prototype.getStencilFunction=function(){return this._stencilState.stencilFunc};Me.prototype.getStencilBackFunction=function(){return this._stencilState.stencilBackFunc};Me.prototype.getStencilFunctionReference=function(){return this._stencilState.stencilFuncRef};Me.prototype.getStencilFunctionMask=function(){return this._stencilState.stencilFuncMask};Me.prototype.setStencilFunction=function(n){this._stencilState.stencilFunc=n};Me.prototype.setStencilBackFunction=function(n){this._stencilState.stencilBackFunc=n};Me.prototype.setStencilFunctionReference=function(n){this._stencilState.stencilFuncRef=n};Me.prototype.setStencilFunctionMask=function(n){this._stencilState.stencilFuncMask=n};Me.prototype.getStencilOperationFail=function(){return this._stencilState.stencilOpStencilFail};Me.prototype.getStencilBackOperationFail=function(){return this._stencilState.stencilBackOpStencilFail};Me.prototype.getStencilOperationDepthFail=function(){return this._stencilState.stencilOpDepthFail};Me.prototype.getStencilBackOperationDepthFail=function(){return this._stencilState.stencilBackOpDepthFail};Me.prototype.getStencilOperationPass=function(){return this._stencilState.stencilOpStencilDepthPass};Me.prototype.getStencilBackOperationPass=function(){return this._stencilState.stencilBackOpStencilDepthPass};Me.prototype.setStencilOperationFail=function(n){this._stencilState.stencilOpStencilFail=n};Me.prototype.setStencilBackOperationFail=function(n){this._stencilState.stencilBackOpStencilFail=n};Me.prototype.setStencilOperationDepthFail=function(n){this._stencilState.stencilOpDepthFail=n};Me.prototype.setStencilBackOperationDepthFail=function(n){this._stencilState.stencilBackOpDepthFail=n};Me.prototype.setStencilOperationPass=function(n){this._stencilState.stencilOpStencilDepthPass=n};Me.prototype.setStencilBackOperationPass=function(n){this._stencilState.stencilBackOpStencilDepthPass=n};Me.prototype.cacheStencilState=function(){this._cachedStencilBuffer=this.getStencilBuffer(),this._cachedStencilFunction=this.getStencilFunction(),this._cachedStencilMask=this.getStencilMask(),this._cachedStencilOperationPass=this.getStencilOperationPass(),this._cachedStencilOperationFail=this.getStencilOperationFail(),this._cachedStencilOperationDepthFail=this.getStencilOperationDepthFail(),this._cachedStencilReference=this.getStencilFunctionReference()};Me.prototype.restoreStencilState=function(){this.setStencilFunction(this._cachedStencilFunction),this.setStencilMask(this._cachedStencilMask),this.setStencilBuffer(this._cachedStencilBuffer),this.setStencilOperationPass(this._cachedStencilOperationPass),this.setStencilOperationFail(this._cachedStencilOperationFail),this.setStencilOperationDepthFail(this._cachedStencilOperationDepthFail),this.setStencilFunctionReference(this._cachedStencilReference)}});var HV=C(()=>{wr();Me.prototype.getRenderPassNames=function(){return this._renderPassNames};Me.prototype.getCurrentRenderPassName=function(){return this._renderPassNames[this.currentRenderPassId]};Me.prototype.createRenderPassId=function(n){let e=++Me._RenderPassIdCounter;return this._renderPassNames[e]=n!=null?n:"NONAME",e};Me.prototype.releaseRenderPassId=function(n){this._renderPassNames[n]=void 0;for(let e=0;e{wr();Me.prototype._loadFileAsync=async function(n,e,t){return await new Promise((i,r)=>{this._loadFile(n,s=>{i(s)},void 0,e,t,(s,a)=>{r(a)})})}});var XV=C(()=>{sy();wr();Me.GetCompatibleTextureLoader=RA});function _se(n){!n||!n.setAttribute||(n.setAttribute("touch-action","none"),n.style.touchAction="none",n.style.webkitTapHighlightColor="transparent")}function YV(n,e,t){n._onCanvasFocus=()=>{n.onCanvasFocusObservable.notifyObservers(n)},n._onCanvasBlur=()=>{n.onCanvasBlurObservable.notifyObservers(n)},n._onCanvasContextMenu=r=>{n.disableContextMenu&&r.preventDefault()},e.addEventListener("focus",n._onCanvasFocus),e.addEventListener("blur",n._onCanvasBlur),e.addEventListener("contextmenu",n._onCanvasContextMenu),n._onBlur=()=>{n.disablePerformanceMonitorInBackground&&n.performanceMonitor.disable(),n._windowIsBackground=!0},n._onFocus=()=>{n.disablePerformanceMonitorInBackground&&n.performanceMonitor.enable(),n._windowIsBackground=!1},n._onCanvasPointerOut=r=>{document.elementFromPoint(r.clientX,r.clientY)!==e&&n.onCanvasPointerOutObservable.notifyObservers(r)};let i=n.getHostWindow();i&&typeof i.addEventListener=="function"&&(i.addEventListener("blur",n._onBlur),i.addEventListener("focus",n._onFocus)),e.addEventListener("pointerout",n._onCanvasPointerOut),t.doNotHandleTouchAction||_se(e),!Me.audioEngine&&t.audioEngine&&Me.AudioEngineFactory&&(Me.audioEngine=Me.AudioEngineFactory(n.getRenderingCanvas(),n.getAudioContext(),n.getAudioDestination())),sf()&&(n._onFullscreenChange=()=>{n.isFullscreen=!!document.fullscreenElement,n.isFullscreen&&n._pointerLockRequested&&e&&hy(e)},document.addEventListener("fullscreenchange",n._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",n._onFullscreenChange,!1),n._onPointerLockChange=()=>{n.isPointerLock=document.pointerLockElement===e},document.addEventListener("pointerlockchange",n._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",n._onPointerLockChange,!1)),n.enableOfflineSupport=Me.OfflineProviderFactory!==void 0,n._deterministicLockstep=!!t.deterministicLockstep,n._lockstepMaxSteps=t.lockstepMaxSteps||0,n._timeStep=t.timeStep||1/60}function KV(n,e){Oe.Instances.length===1&&Me.audioEngine&&(Me.audioEngine.dispose(),Me.audioEngine=null);let t=n.getHostWindow();t&&typeof t.removeEventListener=="function"&&(t.removeEventListener("blur",n._onBlur),t.removeEventListener("focus",n._onFocus)),e&&(e.removeEventListener("focus",n._onCanvasFocus),e.removeEventListener("blur",n._onCanvasBlur),e.removeEventListener("pointerout",n._onCanvasPointerOut),e.removeEventListener("contextmenu",n._onCanvasContextMenu)),sf()&&(document.removeEventListener("fullscreenchange",n._onFullscreenChange),document.removeEventListener("mozfullscreenchange",n._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",n._onFullscreenChange),document.removeEventListener("msfullscreenchange",n._onFullscreenChange),document.removeEventListener("pointerlockchange",n._onPointerLockChange),document.removeEventListener("mspointerlockchange",n._onPointerLockChange),document.removeEventListener("mozpointerlockchange",n._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",n._onPointerLockChange))}function jV(n){let e=document.createElement("span");e.textContent="Hg",e.style.font=n;let t=document.createElement("div");t.style.display="inline-block",t.style.width="1px",t.style.height="0px",t.style.verticalAlign="bottom";let i=document.createElement("div");i.style.whiteSpace="nowrap",i.appendChild(e),i.appendChild(t),document.body.appendChild(i);let r,s;try{s=t.getBoundingClientRect().top-e.getBoundingClientRect().top,t.style.verticalAlign="baseline",r=t.getBoundingClientRect().top-e.getBoundingClientRect().top}finally{document.body.removeChild(i)}return{ascent:r,height:s,descent:s-r}}async function qV(n,e,t){return await new Promise((i,r)=>{let s=new Image;s.onload=()=>{s.decode().then(()=>{n.createImageBitmap(s,t).then(a=>{i(a)})})},s.onerror=()=>{r(`Error loading image ${s.src}`)},s.src=e})}function ZV(n,e,t,i){let s=n.createCanvas(t,i).getContext("2d");if(!s)throw new Error("Unable to get 2d context for resizeImageBitmap");return s.drawImage(e,0,0),s.getImageData(0,0,t,i).data}function QV(n){let e=n.requestFullscreen||n.webkitRequestFullscreen;e&&e.call(n)}function $V(){let n=document;document.exitFullscreen?document.exitFullscreen():n.webkitCancelFullScreen&&n.webkitCancelFullScreen()}function hy(n){if(n.requestPointerLock){let e=n.requestPointerLock();e instanceof Promise?e.then(()=>{n.focus()}).catch(()=>{}):n.focus()}}function JV(){document.exitPointerLock&&document.exitPointerLock()}var eG=C(()=>{ga();wr();Di()});var Ue,dy=C(()=>{vs();Di();Zn();Q3();yT();Pt();MM();$3();i2();r2();n2();s2();l2();c2();f2();BV();UV();VV();GV();kV();WV();HV();DM();zV();XV();wr();eG();RC();jo();Ue=class n extends bt{static get NpmPackage(){return Me.NpmPackage}static get Version(){return Me.Version}static get Instances(){return Oe.Instances}static get LastCreatedEngine(){return Oe.LastCreatedEngine}static get LastCreatedScene(){return Oe.LastCreatedScene}static DefaultLoadingScreenFactory(e){return Me.DefaultLoadingScreenFactory(e)}get _supportsHardwareTextureRescaling(){return!!n._RescalePostProcessFactory}_measureFps(){this._performanceMonitor.sampleFrame(),this._fps=this._performanceMonitor.averageFPS,this._deltaTime=this._performanceMonitor.instantaneousFrameTime||0}get performanceMonitor(){return this._performanceMonitor}constructor(e,t,i,r=!1){super(e,t,i,r),this.customAnimationFrameRequester=null,this._performanceMonitor=new DT,this._drawCalls=new il,e&&(this._features.supportRenderPasses=!0)}_initGLContext(){super._initGLContext(),this._rescalePostProcess=null}_sharedInit(e){super._sharedInit(e),YV(this,e,this._creationOptions)}resizeImageBitmap(e,t,i){return ZV(this,e,t,i)}async _createImageBitmapFromSource(e,t){return await qV(this,e,t)}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&QV(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&$V()}setDitheringState(e){e?this._gl.enable(this._gl.DITHER):this._gl.disable(this._gl.DITHER)}setRasterizerState(e){e?this._gl.disable(this._gl.RASTERIZER_DISCARD):this._gl.enable(this._gl.RASTERIZER_DISCARD)}setDirectViewport(e,t,i,r){let s=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,r),s}scissorClear(e,t,i,r,s){this.enableScissor(e,t,i,r),this.clear(s,!0,!0,!0),this.disableScissor()}enableScissor(e,t,i,r){let s=this._gl;s.enable(s.SCISSOR_TEST),s.scissor(e,t,i,r)}disableScissor(){let e=this._gl;e.disable(e.SCISSOR_TEST)}getVertexShaderSource(e){let t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[0]):null}getFragmentShaderSource(e){let t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[1]):null}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e,this._framebufferDimensionsObject&&this.onResizeObservable.notifyObservers(this)}_rebuildBuffers(){for(let e of this.scenes)e.resetCachedMaterial(),e._rebuildGeometries();for(let e of this._virtualScenes)e.resetCachedMaterial(),e._rebuildGeometries();super._rebuildBuffers()}getFontOffset(e){return jV(e)}_cancelFrame(){if(this.customAnimationFrameRequester){if(this._frameHandler!==0){this._frameHandler=0;let{cancelAnimationFrame:e}=this.customAnimationFrameRequester;e&&e(this.customAnimationFrameRequester.requestID)}}else super._cancelFrame()}_renderLoop(e){this._processFrame(e),this._activeRenderLoops.length>0&&this._frameHandler===0&&(this.customAnimationFrameRequester?(this.customAnimationFrameRequester.requestID=this._queueNewFrame(this.customAnimationFrameRequester.renderFunction||this._boundRenderFunction,this.customAnimationFrameRequester),this._frameHandler=this.customAnimationFrameRequester.requestID):this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()))}enterPointerlock(){this._renderingCanvas&&hy(this._renderingCanvas)}exitPointerlock(){JV()}beginFrame(){this._measureFps(),super.beginFrame()}_deletePipelineContext(e){let t=e;t&&t.program&&t.transformFeedback&&(this.deleteTransformFeedback(t.transformFeedback),t.transformFeedback=null),super._deletePipelineContext(e)}createShaderProgram(e,t,i,r,s,a=null){s=s||this._gl,this.onBeforeShaderCompilationObservable.notifyObservers(this);let o=super.createShaderProgram(e,t,i,r,s,a);return this.onAfterShaderCompilationObservable.notifyObservers(this),o}_createShaderProgram(e,t,i,r,s=null){let a=r.createProgram();if(e.program=a,!a)throw new Error("Unable to create program");if(r.attachShader(a,t),r.attachShader(a,i),this.webGLVersion>1&&s){let o=this.createTransformFeedback();this.bindTransformFeedback(o),this.setTranformFeedbackVaryings(a,s),e.transformFeedback=o}return r.linkProgram(a),this.webGLVersion>1&&s&&this.bindTransformFeedback(null),e.context=r,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),a}_releaseTexture(e){super._releaseTexture(e)}_releaseRenderTargetWrapper(e){super._releaseRenderTargetWrapper(e);for(let t of this.scenes){for(let i of t.postProcesses)i._outputTexture===e&&(i._outputTexture=null);for(let i of t.cameras)for(let r of i._postProcesses)r&&r._outputTexture===e&&(r._outputTexture=null)}}_rescaleTexture(e,t,i,r,s){this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._gl.CLAMP_TO_EDGE),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._gl.CLAMP_TO_EDGE);let a=this.createRenderTargetTexture({width:t.width,height:t.height},{generateMipMaps:!1,type:0,samplingMode:2,generateDepthBuffer:!1,generateStencilBuffer:!1});if(!this._rescalePostProcess&&n._RescalePostProcessFactory&&(this._rescalePostProcess=n._RescalePostProcessFactory(this)),this._rescalePostProcess){this._rescalePostProcess.externalTextureSamplerBinding=!0;let o=()=>{this._rescalePostProcess.onApply=function(f){f._bindTexture("textureSampler",e)};let c=i;c||(c=this.scenes[this.scenes.length-1]),c.postProcessManager.directRender([this._rescalePostProcess],a,!0),this._bindTextureDirectly(this._gl.TEXTURE_2D,t,!0),this._gl.copyTexImage2D(this._gl.TEXTURE_2D,0,r,0,0,t.width,t.height,0),this.unBindFramebuffer(a),a.dispose(),s&&s()},l=this._rescalePostProcess.getEffect();l?l.executeWhenCompiled(o):this._rescalePostProcess.onEffectCreatedObservable.addOnce(c=>{c.executeWhenCompiled(o)})}}wrapWebGLTexture(e,t=!1,i=3,r=0,s=0){let a=new ku(e,this._gl),o=new Pi(this,0,!0);return o._hardwareTexture=a,o.baseWidth=r,o.baseHeight=s,o.width=r,o.height=s,o.isReady=!0,o.useMipMaps=t,this.updateTextureSamplingMode(i,o),o}_uploadImageToTexture(e,t,i=0,r=0){let s=this._gl,a=this._getWebGLTextureType(e.type),o=this._getInternalFormat(e.format),l=this._getRGBABufferInternalSizedFormat(e.type,o),c=e.isCube?s.TEXTURE_CUBE_MAP:s.TEXTURE_2D;this._bindTextureDirectly(c,e,!0),this._unpackFlipY(e.invertY);let f=s.TEXTURE_2D;e.isCube&&(f=s.TEXTURE_CUBE_MAP_POSITIVE_X+i),s.texImage2D(f,r,l,o,a,t),this._bindTextureDirectly(c,null,!0)}updateTextureComparisonFunction(e,t){if(this.webGLVersion===1){te.Error("WebGL 1 does not support texture comparison.");return}let i=this._gl;e.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,e,!0),t===0?(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):(this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),t===0?(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)),e._comparisonFunction=t}createInstancesBuffer(e){let t=this._gl.createBuffer();if(!t)throw new Error("Unable to create instance buffer");let i=new qo(t);return i.capacity=e,this.bindArrayBuffer(i),this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW),i.references=1,i}deleteInstancesBuffer(e){this._gl.deleteBuffer(e)}async _clientWaitAsync(e,t=0,i=10){let r=this._gl;return await new Promise((s,a)=>{Ko(()=>{let o=r.clientWaitSync(e,t,0);if(o==r.WAIT_FAILED)throw new Error("clientWaitSync failed");return o!=r.TIMEOUT_EXPIRED},s,a,i)})}_readPixelsAsync(e,t,i,r,s,a,o){if(this._webGLVersion<2)throw new Error("_readPixelsAsync only work on WebGL2+");let l=this._gl,c=l.createBuffer();l.bindBuffer(l.PIXEL_PACK_BUFFER,c),l.bufferData(l.PIXEL_PACK_BUFFER,o.byteLength,l.STREAM_READ),l.readPixels(e,t,i,r,s,a,0),l.bindBuffer(l.PIXEL_PACK_BUFFER,null);let f=l.fenceSync(l.SYNC_GPU_COMMANDS_COMPLETE,0);return f?(l.flush(),this._clientWaitAsync(f,0,10).then(()=>(l.deleteSync(f),l.bindBuffer(l.PIXEL_PACK_BUFFER,c),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,o),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),l.deleteBuffer(c),o))):null}dispose(){this.hideLoadingUI(),this._rescalePostProcess&&this._rescalePostProcess.dispose(),KV(this,this._renderingCanvas),super.dispose()}};Ue.ALPHA_DISABLE=0;Ue.ALPHA_ADD=1;Ue.ALPHA_COMBINE=2;Ue.ALPHA_SUBTRACT=3;Ue.ALPHA_MULTIPLY=4;Ue.ALPHA_MAXIMIZED=5;Ue.ALPHA_ONEONE=6;Ue.ALPHA_PREMULTIPLIED=7;Ue.ALPHA_PREMULTIPLIED_PORTERDUFF=8;Ue.ALPHA_INTERPOLATE=9;Ue.ALPHA_SCREENMODE=10;Ue.DELAYLOADSTATE_NONE=0;Ue.DELAYLOADSTATE_LOADED=1;Ue.DELAYLOADSTATE_LOADING=2;Ue.DELAYLOADSTATE_NOTLOADED=4;Ue.NEVER=512;Ue.ALWAYS=519;Ue.LESS=513;Ue.EQUAL=514;Ue.LEQUAL=515;Ue.GREATER=516;Ue.GEQUAL=518;Ue.NOTEQUAL=517;Ue.KEEP=7680;Ue.REPLACE=7681;Ue.INCR=7682;Ue.DECR=7683;Ue.INVERT=5386;Ue.INCR_WRAP=34055;Ue.DECR_WRAP=34056;Ue.TEXTURE_CLAMP_ADDRESSMODE=0;Ue.TEXTURE_WRAP_ADDRESSMODE=1;Ue.TEXTURE_MIRROR_ADDRESSMODE=2;Ue.TEXTUREFORMAT_ALPHA=0;Ue.TEXTUREFORMAT_LUMINANCE=1;Ue.TEXTUREFORMAT_LUMINANCE_ALPHA=2;Ue.TEXTUREFORMAT_RGB=4;Ue.TEXTUREFORMAT_RGBA=5;Ue.TEXTUREFORMAT_RED=6;Ue.TEXTUREFORMAT_R=6;Ue.TEXTUREFORMAT_R16_UNORM=33322;Ue.TEXTUREFORMAT_RG16_UNORM=33324;Ue.TEXTUREFORMAT_RGB16_UNORM=32852;Ue.TEXTUREFORMAT_RGBA16_UNORM=32859;Ue.TEXTUREFORMAT_R16_SNORM=36760;Ue.TEXTUREFORMAT_RG16_SNORM=36761;Ue.TEXTUREFORMAT_RGB16_SNORM=36762;Ue.TEXTUREFORMAT_RGBA16_SNORM=36763;Ue.TEXTUREFORMAT_RG=7;Ue.TEXTUREFORMAT_RED_INTEGER=8;Ue.TEXTUREFORMAT_R_INTEGER=8;Ue.TEXTUREFORMAT_RG_INTEGER=9;Ue.TEXTUREFORMAT_RGB_INTEGER=10;Ue.TEXTUREFORMAT_RGBA_INTEGER=11;Ue.TEXTURETYPE_UNSIGNED_BYTE=0;Ue.TEXTURETYPE_UNSIGNED_INT=0;Ue.TEXTURETYPE_FLOAT=1;Ue.TEXTURETYPE_HALF_FLOAT=2;Ue.TEXTURETYPE_BYTE=3;Ue.TEXTURETYPE_SHORT=4;Ue.TEXTURETYPE_UNSIGNED_SHORT=5;Ue.TEXTURETYPE_INT=6;Ue.TEXTURETYPE_UNSIGNED_INTEGER=7;Ue.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8;Ue.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9;Ue.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10;Ue.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11;Ue.TEXTURETYPE_UNSIGNED_INT_24_8=12;Ue.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13;Ue.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14;Ue.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15;Ue.TEXTURE_NEAREST_SAMPLINGMODE=1;Ue.TEXTURE_BILINEAR_SAMPLINGMODE=2;Ue.TEXTURE_TRILINEAR_SAMPLINGMODE=3;Ue.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8;Ue.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11;Ue.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3;Ue.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4;Ue.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5;Ue.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6;Ue.TEXTURE_NEAREST_LINEAR=7;Ue.TEXTURE_NEAREST_NEAREST=1;Ue.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9;Ue.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10;Ue.TEXTURE_LINEAR_LINEAR=2;Ue.TEXTURE_LINEAR_NEAREST=12;Ue.TEXTURE_EXPLICIT_MODE=0;Ue.TEXTURE_SPHERICAL_MODE=1;Ue.TEXTURE_PLANAR_MODE=2;Ue.TEXTURE_CUBIC_MODE=3;Ue.TEXTURE_PROJECTION_MODE=4;Ue.TEXTURE_SKYBOX_MODE=5;Ue.TEXTURE_INVCUBIC_MODE=6;Ue.TEXTURE_EQUIRECTANGULAR_MODE=7;Ue.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8;Ue.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;Ue.SCALEMODE_FLOOR=1;Ue.SCALEMODE_NEAREST=2;Ue.SCALEMODE_CEILING=3});var uy,_i,js=C(()=>{Gt();Ge();Vt();di();Di();hn();Tr();uy=class{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new ie,this._onClonedObservable=new ie,this._inheritVisibility=!1,this._isVisible=!0}},_i=class n{static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,i,r){let s=this._NodeConstructors[e];return s?s(t,i,r):null}set accessibilityTag(e){this._accessibilityTag=e,this.onAccessibilityTagChangedObservable.notifyObservers(e)}get accessibilityTag(){return this._accessibilityTag}get doNotSerialize(){return this._nodeDataStorage._doNotSerialize?!0:this._parentNode?this._parentNode.doNotSerialize:!1}set doNotSerialize(e){this._nodeDataStorage._doNotSerialize=e}isDisposed(){return this._nodeDataStorage._isDisposed}set parent(e){if(this._parentNode===e)return;let t=this._parentNode;if(this._parentNode&&this._parentNode._children!==void 0&&this._parentNode._children!==null){let i=this._parentNode._children.indexOf(this);i!==-1&&this._parentNode._children.splice(i,1),!e&&!this._nodeDataStorage._isDisposed&&this._addToSceneRootNodes()}this._parentNode=e,this._isDirty=!0,this._parentNode&&((this._parentNode._children===void 0||this._parentNode._children===null)&&(this._parentNode._children=new Array),this._parentNode._children.push(this),t||this._removeFromSceneRootNodes()),this._syncParentEnabledState()}get parent(){return this._parentNode}get inheritVisibility(){return this._nodeDataStorage._inheritVisibility}set inheritVisibility(e){this._nodeDataStorage._inheritVisibility=e}get isVisible(){return this.inheritVisibility&&this._parentNode&&!this._parentNode.isVisible?!1:this._nodeDataStorage._isVisible}set isVisible(e){this._nodeDataStorage._isVisible=e}_serializeAsParent(e){e.parentId=this.uniqueId}_addToSceneRootNodes(){this._nodeDataStorage._sceneRootNodesIndex===-1&&(this._nodeDataStorage._sceneRootNodesIndex=this._scene.rootNodes.length,this._scene.rootNodes.push(this))}_removeFromSceneRootNodes(){if(this._nodeDataStorage._sceneRootNodesIndex!==-1){let e=this._scene.rootNodes,t=e.length-1;e[this._nodeDataStorage._sceneRootNodesIndex]=e[t],e[this._nodeDataStorage._sceneRootNodesIndex]._nodeDataStorage._sceneRootNodesIndex=this._nodeDataStorage._sceneRootNodesIndex,this._scene.rootNodes.pop(),this._nodeDataStorage._sceneRootNodesIndex=-1}}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}getClassName(){return"Node"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get onEnabledStateChangedObservable(){return this._nodeDataStorage._onEnabledStateChangedObservable}get onClonedObservable(){return this._nodeDataStorage._onClonedObservable}constructor(e,t=null,i=!0){this._isDirty=!1,this._nodeDataStorage=new uy,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new ie,this._parentContainer=null,this.animations=[],this._ranges={},this.onReady=null,this._currentRenderId=-1,this._parentUpdateId=-1,this._childUpdateId=-1,this._waitingParentId=null,this._waitingParentInstanceIndex=null,this._waitingParsedUniqueId=null,this._cache={},this._parentNode=null,this._children=null,this._worldMatrix=K.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new ie,this._onDisposeObserver=null,this._behaviors=new Array,this.name=e,this.id=e,this._scene=t||Oe.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache(),i&&this._addToSceneRootNodes()}getScene(){return this._scene}getEngine(){return this._scene.getEngine()}addBehavior(e,t=!1){return this._behaviors.indexOf(e)!==-1?this:(e.init(),this._scene.isLoading&&!t?this._scene.onDataLoadedObservable.addOnce(()=>{this._behaviors.includes(e)&&e.attach(this)}):e.attach(this),this._behaviors.push(e),this)}removeBehavior(e){let t=this._behaviors.indexOf(e);return t===-1?this:(this._behaviors[t].detach(),this._behaviors.splice(t,1),this)}get behaviors(){return this._behaviors}getBehaviorByName(e){for(let t of this._behaviors)if(t.name===e)return t;return null}getWorldMatrix(){return this._currentRenderId!==this._scene.getRenderId()&&this.computeWorldMatrix(),this._worldMatrix}_getWorldMatrixDeterminant(){return this._worldMatrixDeterminantIsDirty&&(this._worldMatrixDeterminantIsDirty=!1,this._worldMatrixDeterminant=this._worldMatrix.determinant()),this._worldMatrixDeterminant}get worldMatrixFromCache(){return this._worldMatrix}_initCache(){this._cache={}}updateCache(e){!e&&this.isSynchronized()||this._updateCache()}_getActionManagerForTrigger(e,t=!0){return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_updateCache(e){}_isSynchronized(){return!0}_markSyncedWithParent(){this._parentNode&&(this._parentUpdateId=this._parentNode._childUpdateId)}isSynchronizedWithParent(){return this._parentNode?this._parentNode._isDirty||this._parentUpdateId!==this._parentNode._childUpdateId?!1:this._parentNode.isSynchronized():!0}isSynchronized(){return this._parentNode&&!this.isSynchronizedWithParent()?!1:this._isSynchronized()}isReady(e=!1){return this._nodeDataStorage._isReady}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}isEnabled(e=!0){return e===!1?this._nodeDataStorage._isEnabled:this._nodeDataStorage._isEnabled?this._nodeDataStorage._isParentEnabled:!1}_syncParentEnabledState(){if(this._nodeDataStorage._isParentEnabled=this._parentNode?this._parentNode.isEnabled():!0,this._children)for(let e of this._children)e._syncParentEnabledState()}setEnabled(e){this._nodeDataStorage._isEnabled!==e&&(this._nodeDataStorage._isEnabled=e,this._syncParentEnabledState(),this._nodeDataStorage._onEnabledStateChangedObservable.notifyObservers(e))}isDescendantOf(e){return this.parent?this.parent===e?!0:this.parent.isDescendantOf(e):!1}_getDescendants(e,t=!1,i){if(this._children)for(let r=0;r(!t||t(r))&&r.cullingStrategy!==void 0),i}getChildren(e,t=!0){return this.getDescendants(t,e)}_setReady(e){if(e!==this._nodeDataStorage._isReady){if(!e){this._nodeDataStorage._isReady=!1;return}this.onReady&&this.onReady(this),this._nodeDataStorage._isReady=!0}}getAnimationByName(e){for(let t=0;tnew n(e,this.getScene()),this);if(t&&(r.parent=t),!i){let s=this.getDescendants(!0);for(let a=0;a{throw qe("AnimationRange")};_i._NodeConstructors={};P([w()],_i.prototype,"name",void 0);P([w()],_i.prototype,"id",void 0);P([w()],_i.prototype,"uniqueId",void 0);P([w()],_i.prototype,"state",void 0);P([w()],_i.prototype,"metadata",void 0)});function my(n,e,t){try{let i=n.next();i.done?e(i):i.value?i.value.then(()=>{i.value=void 0,e(i)},t):e(i)}catch(i){t(i)}}function tG(n=25){let e;return(t,i,r)=>{let s=performance.now();e===void 0||s-e>n?(e=s,setTimeout(()=>{my(t,i,r)},0)):my(t,i,r)}}function iG(n,e,t,i,r){let s=()=>{let a,o=l=>{l.done?t(l.value):a===void 0?a=!0:s()};do a=void 0,!r||!r.aborted?e(n,o,i):i(new Error("Aborted")),a===void 0&&(a=!1);while(a)};s()}function fg(n,e){let t;return iG(n,my,i=>t=i,i=>{throw i},e),t}async function rG(n,e,t){return await new Promise((i,r)=>{iG(n,e,i,r,t)})}function nG(n,e){return(...t)=>fg(n(...t),e)}var py=C(()=>{});var mt,sl=C(()=>{Gt();Vt();so();Ii();di();Ge();js();Pt();Hi();hn();$u();FT();Tr();mt=class n extends _i{get position(){return this._position}set position(e){this._position=e}set upVector(e){this._upVector=e}get upVector(){return this._upVector}get screenArea(){var i,r,s,a;let e,t;if(this.mode===n.PERSPECTIVE_CAMERA)this.fovMode===n.FOVMODE_VERTICAL_FIXED?(t=this.minZ*2*Math.tan(this.fov/2),e=this.getEngine().getAspectRatio(this)*t):(e=this.minZ*2*Math.tan(this.fov/2),t=e/this.getEngine().getAspectRatio(this));else{let o=this.getEngine().getRenderWidth()/2,l=this.getEngine().getRenderHeight()/2;e=((i=this.orthoRight)!=null?i:o)-((r=this.orthoLeft)!=null?r:-o),t=((s=this.orthoTop)!=null?s:l)-((a=this.orthoBottom)!=null?a:-l)}return e*t}set orthoLeft(e){this._orthoLeft=e;for(let t of this._rigCameras)t.orthoLeft=e}get orthoLeft(){return this._orthoLeft}set orthoRight(e){this._orthoRight=e;for(let t of this._rigCameras)t.orthoRight=e}get orthoRight(){return this._orthoRight}set orthoBottom(e){this._orthoBottom=e;for(let t of this._rigCameras)t.orthoBottom=e}get orthoBottom(){return this._orthoBottom}set orthoTop(e){this._orthoTop=e;for(let t of this._rigCameras)t.orthoTop=e}get orthoTop(){return this._orthoTop}setFocalLength(e,t=36){this.fov=2*Math.atan(t/(2*e))}set mode(e){this._mode=e;for(let t of this._rigCameras)t.mode=e}get mode(){return this._mode}get hasMoved(){return this._hasMoved}constructor(e,t,i,r=!0){super(e,i,!1),this._position=b.Zero(),this._upVector=b.Up(),this.oblique=null,this._orthoLeft=null,this._orthoRight=null,this._orthoBottom=null,this._orthoTop=null,this.fov=.8,this.projectionPlaneTilt=0,this.minZ=1,this.maxZ=1e4,this.inertia=.9,this._mode=n.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new io(0,0,1,1),this.layerMask=268435455,this.fovMode=n.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=n.RIG_MODE_NONE,this.ignoreCameraMaxZ=!1,this.customRenderTargets=[],this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new ie,this.onProjectionMatrixChangedObservable=new ie,this.onAfterCheckInputsObservable=new ie,this.onRestoreStateObservable=new ie,this.isRigCamera=!1,this._hasMoved=!1,this._rigCameras=new Array,this._skipRendering=!1,this._projectionMatrix=new K,this._postProcesses=new Array,this._activeMeshes=new Bi(256),this._globalPosition=b.Zero(),this._computedViewMatrix=K.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=K.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=Xe.Identity(),this._isCamera=!0,this._isLeftCamera=!1,this._isRightCamera=!1,this.layerMask=this.getScene().defaultCameraLayerMask,this.getScene().addCamera(this),r&&!this.getScene().activeCamera&&(this.getScene().activeCamera=this),this.position=t,this.renderPassId=this.getScene().getEngine().createRenderPassId(`Camera ${e}`)}storeState(){return this._stateStored=!0,this._storedFov=this.fov,this}hasStateStored(){return!!this._stateStored}_restoreStateValues(){return this._stateStored?(this.fov=this._storedFov,!0):!1}restoreState(){return this._restoreStateValues()?(this.onRestoreStateObservable.notifyObservers(this),!0):!1}getClassName(){return"Camera"}toString(e){let t="Name: "+this.name;if(t+=", type: "+this.getClassName(),this.animations)for(let i=0;i-1?(te.Error("You're trying to reuse a post process not defined as reusable."),0):(t==null||t<0?this._postProcesses.push(e):this._postProcesses[t]===null?this._postProcesses[t]=e:this._postProcesses.splice(t,0,e),this._cascadePostProcessesToRigCams(),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._postProcesses.indexOf(e))}detachPostProcess(e){let t=this._postProcesses.indexOf(e);t!==-1&&(this._postProcesses[t]=null),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._cascadePostProcessesToRigCams()}getWorldMatrix(){return this._isSynchronizedViewMatrix()?this._worldMatrix:(this.getViewMatrix(),this._worldMatrix)}_getViewMatrix(){return K.Identity()}getViewMatrix(e){return!e&&this._isSynchronizedViewMatrix()?this._computedViewMatrix:(this._hasMoved=!0,this.updateCache(),this._computedViewMatrix=this._getViewMatrix(),this._currentRenderId=this.getScene().getRenderId(),this._childUpdateId++,this._refreshFrustumPlanes=!0,this._cameraRigParams&&this._cameraRigParams.vrPreViewMatrix&&this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix,this._computedViewMatrix),this.parent&&this.parent.onViewMatrixChangedObservable&&this.parent.onViewMatrixChangedObservable.notifyObservers(this.parent),this.onViewMatrixChangedObservable.notifyObservers(this),this._computedViewMatrix.invertToRef(this._worldMatrix),this._worldMatrix.getTranslationToRef(this._globalPosition),this._computedViewMatrix)}freezeProjectionMatrix(e){this._doNotComputeProjectionMatrix=!0,e!==void 0&&(this._projectionMatrix=e)}unfreezeProjectionMatrix(){this._doNotComputeProjectionMatrix=!1}getProjectionMatrix(e){var a,o,l,c,f,h,d,u,m,p,_,g,v,x,A,S,E,R,I;if(this._doNotComputeProjectionMatrix||!e&&this._isSynchronizedProjectionMatrix())return this._projectionMatrix;let t=this.ignoreCameraMaxZ?0:this.maxZ;this._cache.mode=this.mode,this._cache.minZ=this.minZ,this._cache.maxZ=t,this._refreshFrustumPlanes=!0;let i=this.getEngine(),r=this.getScene(),s=i.useReverseDepthBuffer;if(this.mode===n.PERSPECTIVE_CAMERA){this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=i.getAspectRatio(this),this._cache.projectionPlaneTilt=this.projectionPlaneTilt,this.minZ<=0&&(this.minZ=.1);let y;r.useRightHandedSystem?y=K.PerspectiveFovRHToRef:y=K.PerspectiveFovLHToRef,y(this.fov,i.getAspectRatio(this),s?t:this.minZ,s?this.minZ:t,this._projectionMatrix,this.fovMode===n.FOVMODE_VERTICAL_FIXED,i.isNDCHalfZRange,this.projectionPlaneTilt,s)}else{let y=i.getRenderWidth()/2,M=i.getRenderHeight()/2;r.useRightHandedSystem?this.oblique?K.ObliqueOffCenterRHToRef((a=this.orthoLeft)!=null?a:-y,(o=this.orthoRight)!=null?o:y,(l=this.orthoBottom)!=null?l:-M,(c=this.orthoTop)!=null?c:M,s?t:this.minZ,s?this.minZ:t,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,i.isNDCHalfZRange):K.OrthoOffCenterRHToRef((f=this.orthoLeft)!=null?f:-y,(h=this.orthoRight)!=null?h:y,(d=this.orthoBottom)!=null?d:-M,(u=this.orthoTop)!=null?u:M,s?t:this.minZ,s?this.minZ:t,this._projectionMatrix,i.isNDCHalfZRange):this.oblique?K.ObliqueOffCenterLHToRef((m=this.orthoLeft)!=null?m:-y,(p=this.orthoRight)!=null?p:y,(_=this.orthoBottom)!=null?_:-M,(g=this.orthoTop)!=null?g:M,s?t:this.minZ,s?this.minZ:t,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,i.isNDCHalfZRange):K.OrthoOffCenterLHToRef((v=this.orthoLeft)!=null?v:-y,(x=this.orthoRight)!=null?x:y,(A=this.orthoBottom)!=null?A:-M,(S=this.orthoTop)!=null?S:M,s?t:this.minZ,s?this.minZ:t,this._projectionMatrix,i.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.obliqueAngle=(E=this.oblique)==null?void 0:E.angle,this._cache.obliqueLength=(R=this.oblique)==null?void 0:R.length,this._cache.obliqueOffset=(I=this.oblique)==null?void 0:I.offset,this._cache.renderWidth=i.getRenderWidth(),this._cache.renderHeight=i.getRenderHeight()}return this.onProjectionMatrixChangedObservable.notifyObservers(this),this._projectionMatrix}getTransformationMatrix(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix}_computeObliqueDistance(e){let t=this,i=this;return(t.radius||(i.target?b.Distance(this.position,i.target):this.position.length()))+e}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?of.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=of.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)}isInFrustum(e,t=!1){if(this._updateFrustumPlanes(),t&&this.rigCameras.length>0){let i=!1;for(let r of this.rigCameras)r._updateFrustumPlanes(),i=i||e.isInFrustum(r._frustumPlanes);return i}else return e.isInFrustum(this._frustumPlanes)}isCompletelyInFrustum(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)}getForwardRay(e=100,t,i){throw qe("Ray")}getForwardRayToRef(e,t=100,i,r){throw qe("Ray")}dispose(e,t=!1){for(this.onViewMatrixChangedObservable.clear(),this.onProjectionMatrixChangedObservable.clear(),this.onAfterCheckInputsObservable.clear(),this.onRestoreStateObservable.clear(),this.inputs&&this.inputs.clear(),this.getScene().stopAnimation(this),this.getScene().removeCamera(this);this._rigCameras.length>0;){let r=this._rigCameras.pop();r&&r.dispose()}if(this._parentContainer){let r=this._parentContainer.cameras.indexOf(this);r>-1&&this._parentContainer.cameras.splice(r,1),this._parentContainer=null}if(this._rigPostProcess)this._rigPostProcess.dispose(this),this._rigPostProcess=null,this._postProcesses.length=0;else if(this.cameraRigMode!==n.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses.length=0;else{let r=this._postProcesses.length;for(;--r>=0;){let s=this._postProcesses[r];s&&s.dispose(this)}}let i=this.customRenderTargets.length;for(;--i>=0;)this.customRenderTargets[i].dispose();this.customRenderTargets.length=0,this._activeMeshes.dispose(),this.getScene().getEngine().releaseRenderPassId(this.renderPassId),super.dispose(e,t)}get isLeftCamera(){return this._isLeftCamera}get isRightCamera(){return this._isRightCamera}get leftCamera(){return this._rigCameras.length<1?null:this._rigCameras[0]}get rightCamera(){return this._rigCameras.length<2?null:this._rigCameras[1]}getLeftTarget(){return this._rigCameras.length<1?null:this._rigCameras[0].getTarget()}getRightTarget(){return this._rigCameras.length<2?null:this._rigCameras[1].getTarget()}setCameraRigMode(e,t){if(this.cameraRigMode!==e){for(;this._rigCameras.length>0;){let i=this._rigCameras.pop();i&&i.dispose()}if(this.cameraRigMode=e,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=t.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=_e.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==n.RIG_MODE_NONE){let i=this.createRigCamera(this.name+"_L",0);i&&(i._isLeftCamera=!0);let r=this.createRigCamera(this.name+"_R",1);r&&(r._isRightCamera=!0),i&&r&&(this._rigCameras.push(i),this._rigCameras.push(r))}this._setRigMode(t),this._cascadePostProcessesToRigCams(),this.update()}}_setRigMode(e){}_getVRProjectionMatrix(){return K.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov,this._cameraRigParams.vrMetrics.aspectRatio,this.minZ,this.ignoreCameraMaxZ?0:this.maxZ,this._cameraRigParams.vrWorkMatrix,!0,this.getEngine().isNDCHalfZRange),this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix,this._projectionMatrix),this._projectionMatrix}setCameraRigParameter(e,t){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[e]=t,e==="interaxialDistance"&&(this._cameraRigParams.stereoHalfAngle=_e.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;en._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){let i=e.type,r=n.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),s=it.Parse(r,e,t);if(e.parentId!==void 0&&(s._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),s.inputs&&(s.inputs.parse(e),s._setupInputs()),e.upVector&&(s.upVector=b.FromArray(e.upVector)),s.setPosition&&(s.position.copyFromFloats(0,0,0),s.setPosition(b.FromArray(e.position))),e.target&&s.setTarget&&s.setTarget(b.FromArray(e.target)),e.cameraRigMode){let a=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};s.setCameraRigMode(e.cameraRigMode,a)}if(e.animations){for(let a=0;a{throw qe("UniversalCamera")};mt.PERSPECTIVE_CAMERA=0;mt.ORTHOGRAPHIC_CAMERA=1;mt.FOVMODE_VERTICAL_FIXED=0;mt.FOVMODE_HORIZONTAL_FIXED=1;mt.RIG_MODE_NONE=0;mt.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10;mt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11;mt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12;mt.RIG_MODE_STEREOSCOPIC_OVERUNDER=13;mt.RIG_MODE_STEREOSCOPIC_INTERLACED=14;mt.RIG_MODE_VR=20;mt.RIG_MODE_CUSTOM=22;mt.ForceAttachControlToAlwaysPreventDefault=!1;P([Hr("position")],mt.prototype,"_position",void 0);P([Hr("upVector")],mt.prototype,"_upVector",void 0);P([w()],mt.prototype,"orthoLeft",null);P([w()],mt.prototype,"orthoRight",null);P([w()],mt.prototype,"orthoBottom",null);P([w()],mt.prototype,"orthoTop",null);P([w()],mt.prototype,"fov",void 0);P([w()],mt.prototype,"projectionPlaneTilt",void 0);P([w()],mt.prototype,"minZ",void 0);P([w()],mt.prototype,"maxZ",void 0);P([w()],mt.prototype,"inertia",void 0);P([w()],mt.prototype,"mode",null);P([w()],mt.prototype,"layerMask",void 0);P([w()],mt.prototype,"fovMode",void 0);P([w()],mt.prototype,"cameraRigMode",void 0);P([w()],mt.prototype,"interaxialDistance",void 0);P([w()],mt.prototype,"isStereoscopicSideBySide",void 0);P([w()],mt.prototype,"ignoreCameraMaxZ",void 0)});var jh,_y=C(()=>{jh=class{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0,this._internalSubMeshId=0}}});var Ef,gy=C(()=>{Zo();Ge();Dn();Ef=class n{constructor(e,t,i){this.vectors=dn(8,b.Zero),this.center=b.Zero(),this.centerWorld=b.Zero(),this.extendSize=b.Zero(),this.extendSizeWorld=b.Zero(),this.directions=dn(3,b.Zero),this.vectorsWorld=dn(8,b.Zero),this.minimumWorld=b.Zero(),this.maximumWorld=b.Zero(),this.minimum=b.Zero(),this.maximum=b.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}reConstruct(e,t,i){let r=e.x,s=e.y,a=e.z,o=t.x,l=t.y,c=t.z,f=this.vectors;this.minimum.copyFromFloats(r,s,a),this.maximum.copyFromFloats(o,l,c),f[0].copyFromFloats(r,s,a),f[1].copyFromFloats(o,l,c),f[2].copyFromFloats(o,s,a),f[3].copyFromFloats(r,l,a),f[4].copyFromFloats(r,s,c),f[5].copyFromFloats(o,l,a),f[6].copyFromFloats(r,l,c),f[7].copyFromFloats(o,s,c),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||K.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){let t=n._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),r=i.length();i.normalizeFromLength(r);let s=r*e,a=i.scaleInPlace(s*.5),o=this.center.subtractToRef(a,t[1]),l=this.center.addToRef(a,t[2]);return this.reConstruct(o,l,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){let t=this.minimumWorld,i=this.maximumWorld,r=this.directions,s=this.vectorsWorld,a=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let o=0;o<8;++o)s[o].copyFrom(a[o]);this.extendSizeWorld.copyFrom(this.extendSize),this.centerWorld.copyFrom(this.center)}else{t.setAll(Number.MAX_VALUE),i.setAll(-Number.MAX_VALUE);for(let o=0;o<8;++o){let l=s[o];b.TransformCoordinatesToRef(a[o],e,l),t.minimizeInPlace(l),i.maximizeInPlace(l)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}b.FromArrayToRef(e.m,0,r[0]),b.FromArrayToRef(e.m,4,r[1]),b.FromArrayToRef(e.m,8,r[2]),this._worldMatrix=e}isInFrustum(e){return n.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return n.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){let t=this.minimumWorld,i=this.maximumWorld,r=t.x,s=t.y,a=t.z,o=i.x,l=i.y,c=i.z,f=e.x,h=e.y,d=e.z,u=-Nt;return!(o-ff-r||l-hh-s||c-dd-a)}intersectsSphere(e){return n.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){let i=this.minimumWorld,r=this.maximumWorld,s=i.x,a=i.y,o=i.z,l=r.x,c=r.y,f=r.z,h=e.x,d=e.y,u=e.z,m=t.x,p=t.y,_=t.z;return!(lm||cp||f_)}dispose(){var e,t;(e=this._drawWrapperFront)==null||e.dispose(),(t=this._drawWrapperBack)==null||t.dispose()}static Intersects(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)}static IntersectsSphere(e,t,i,r){let s=n._TmpVector3[0];return b.ClampToRef(i,e,t,s),b.DistanceSquared(i,s)<=r*r}static IsCompletelyInFrustum(e,t){for(let i=0;i<6;++i){let r=t[i];for(let s=0;s<8;++s)if(r.dotCoordinate(e[s])<0)return!1}return!0}static IsInFrustum(e,t){for(let i=0;i<6;++i){let r=!0,s=t[i];for(let a=0;a<8;++a)if(s.dotCoordinate(e[a])>=0){r=!1;break}if(r)return!1}return!0}};Ef._TmpVector3=dn(3,b.Zero)});var um,sG=C(()=>{Zo();Ge();um=class n{constructor(e,t,i){this.center=b.Zero(),this.centerWorld=b.Zero(),this.minimum=b.Zero(),this.maximum=b.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);let r=b.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=r*.5,this._update(i||K.IdentityReadOnly)}scale(e){let t=this.radius*e,i=n._TmpVector3,r=i[0].setAll(t),s=this.center.subtractToRef(r,i[1]),a=this.center.addToRef(r,i[2]);return this.reConstruct(s,a,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{b.TransformCoordinatesToRef(this.center,e,this.centerWorld);let t=n._TmpVector3[0];b.TransformNormalFromFloatsToRef(1,1,1,e,t),this.radiusWorld=Math.max(Math.abs(t.x),Math.abs(t.y),Math.abs(t.z))*this.radius}}isInFrustum(e){let t=this.centerWorld,i=this.radiusWorld;for(let r=0;r<6;r++)if(e[r].dotCoordinate(t)<=-i)return!1;return!0}isCenterInFrustum(e){let t=this.centerWorld;for(let i=0;i<6;i++)if(e[i].dotCoordinate(t)<0)return!1;return!0}intersectsPoint(e){let t=b.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld{Zo();Ge();gy();sG();vy={min:0,max:0},Ey={min:0,max:0},aG=(n,e,t)=>{let i=b.Dot(e.centerWorld,n),r=Math.abs(b.Dot(e.directions[0],n))*e.extendSize.x,s=Math.abs(b.Dot(e.directions[1],n))*e.extendSize.y,a=Math.abs(b.Dot(e.directions[2],n))*e.extendSize.z,o=r+s+a;t.min=i-o,t.max=i+o},es=(n,e,t)=>(aG(n,e,vy),aG(n,t,Ey),!(vy.min>Ey.max||Ey.min>vy.max)),un=class n{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new Ef(e,t,i),this.boundingSphere=new um(e,t,i)}reConstruct(e,t,i){this.boundingBox.reConstruct(e,t,i),this.boundingSphere.reConstruct(e,t,i)}get minimum(){return this.boundingBox.minimum}get maximum(){return this.boundingBox.maximum}get isLocked(){return this._isLocked}set isLocked(e){this._isLocked=e}update(e){this._isLocked||(this.boundingBox._update(e),this.boundingSphere._update(e))}centerOn(e,t){let i=n._TmpVector3[0].copyFrom(e).subtractInPlace(t),r=n._TmpVector3[1].copyFrom(e).addInPlace(t);return this.boundingBox.reConstruct(i,r,this.boundingBox.getWorldMatrix()),this.boundingSphere.reConstruct(i,r,this.boundingBox.getWorldMatrix()),this}encapsulate(e){let t=b.Minimize(this.minimum,e),i=b.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){let t=$.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);let i=$.Vector3[0];return b.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,i),this.encapsulate(i),b.TransformCoordinatesToRef(e.boundingBox.maximumWorld,t,i),this.encapsulate(i),this}scale(e){return this.boundingBox.scale(e),this.boundingSphere.scale(e),this}isInFrustum(e,t=0){return(t===2||t===3)&&this.boundingSphere.isCenterInFrustum(e)?!0:this.boundingSphere.isInFrustum(e)?t===1||t===3?!0:this.boundingBox.isInFrustum(e):!1}get diagonalLength(){let e=this.boundingBox;return e.maximumWorld.subtractToRef(e.minimumWorld,n._TmpVector3[0]).length()}isCompletelyInFrustum(e){return this.boundingBox.isCompletelyInFrustum(e)}_checkCollision(e){return e._canDoCollision(this.boundingSphere.centerWorld,this.boundingSphere.radiusWorld,this.boundingBox.minimumWorld,this.boundingBox.maximumWorld)}intersectsPoint(e){return!(!this.boundingSphere.centerWorld||!this.boundingSphere.intersectsPoint(e)||!this.boundingBox.intersectsPoint(e))}intersects(e,t){if(!um.Intersects(this.boundingSphere,e.boundingSphere)||!Ef.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;let i=this.boundingBox,r=e.boundingBox;return!(!es(i.directions[0],i,r)||!es(i.directions[1],i,r)||!es(i.directions[2],i,r)||!es(r.directions[0],i,r)||!es(r.directions[1],i,r)||!es(r.directions[2],i,r)||!es(b.Cross(i.directions[0],r.directions[0]),i,r)||!es(b.Cross(i.directions[0],r.directions[1]),i,r)||!es(b.Cross(i.directions[0],r.directions[2]),i,r)||!es(b.Cross(i.directions[1],r.directions[0]),i,r)||!es(b.Cross(i.directions[1],r.directions[1]),i,r)||!es(b.Cross(i.directions[1],r.directions[2]),i,r)||!es(b.Cross(i.directions[2],r.directions[0]),i,r)||!es(b.Cross(i.directions[2],r.directions[1]),i,r)||!es(b.Cross(i.directions[2],r.directions[2]),i,r))}};un._TmpVector3=dn(2,b.Zero)});function oG(n,e,t,i,r=null){let s=new b(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new b(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return pm.extractMinAndMaxIndexed(n,e,t,i,s,a),r&&(s.x-=s.x*r.x+r.y,s.y-=s.y*r.x+r.y,s.z-=s.z*r.x+r.y,a.x+=a.x*r.x+r.y,a.y+=a.y*r.x+r.y,a.z+=a.z*r.x+r.y),{minimum:s,maximum:a}}function IA(n,e,t,i=null,r){let s=new b(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new b(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return r||(r=3),pm.extractMinAndMax(n,e,t,r,s,a),i&&(s.x-=s.x*i.x+i.y,s.y-=s.y*i.x+i.y,s.z-=s.z*i.x+i.y,a.x+=a.x*i.x+i.y,a.y+=a.y*i.x+i.y,a.z+=a.z*i.x+i.y),{minimum:s,maximum:a}}var pm,MA=C(()=>{Gt();Ge();Vt();pm=class{static extractMinAndMaxIndexed(e,t,i,r,s,a){for(let o=i;o!Array.isArray(n[0])&&!Array.isArray(n[1]))],pm,"extractMinAndMaxIndexed",null);P([Ss.filter((...n)=>!Array.isArray(n[0]))],pm,"extractMinAndMax",null)});var xs,hg=C(()=>{ki();_y();mm();MA();Gh();xs=class n{get materialDefines(){var t;let e=this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.defines:(t=this._getDrawWrapper())==null?void 0:t.defines;return typeof e=="string"?null:e}set materialDefines(e){var i;let t=(i=this._mainDrawWrapperOverride)!=null?i:this._getDrawWrapper(void 0,!0);t.defines=e}_getDrawWrapper(e,t=!1){e=e!=null?e:this._engine.currentRenderPassId;let i=this._drawWrappers[e];return!i&&t&&(this._drawWrappers[e]=i=new $n(this._mesh.getScene().getEngine())),i}_removeDrawWrapper(e,t=!0,i=!1){var r;t&&((r=this._drawWrappers[e])==null||r.dispose(i)),this._drawWrappers[e]=void 0}get effect(){var e,t;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.effect:(t=(e=this._getDrawWrapper())==null?void 0:e.effect)!=null?t:null}get _drawWrapper(){var e;return(e=this._mainDrawWrapperOverride)!=null?e:this._getDrawWrapper(void 0,!0)}get _drawWrapperOverride(){return this._mainDrawWrapperOverride}_setMainDrawWrapperOverride(e){this._mainDrawWrapperOverride=e}setEffect(e,t=null,i,r=!0){let s=this._drawWrapper;s.setEffect(e,t,r),i!==void 0&&(s.materialContext=i),e||(s.defines=null,s.materialContext=void 0)}resetDrawCache(e,t=!1){if(this._drawWrappers)if(e!==void 0){this._removeDrawWrapper(e,!0,t);return}else for(let i of this._drawWrappers)i==null||i.dispose(t);this._drawWrappers=[]}static AddToMesh(e,t,i,r,s,a,o,l=!0){return new n(e,t,i,r,s,a,o,l)}constructor(e,t,i,r,s,a,o,l=!0,c=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=r,this.indexCount=s,this._mainDrawWrapperOverride=null,this._linesIndexCount=0,this._linesIndexBuffer=null,this._lastColliderWorldVertices=null,this._lastColliderTransformMatrix=null,this._wasDispatched=!1,this._renderId=0,this._alphaIndex=0,this._distanceToCamera=0,this._currentMaterial=null,this._mesh=a,this._renderingMesh=o||a,c&&a.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=a.subMeshes.length-1,l&&(this.refreshBoundingInfo(),a.computeWorldMatrix(!0))}get IsGlobal(){return this.verticesStart===0&&this.verticesCount===this._mesh.getTotalVertices()&&this.indexStart===0&&this.indexCount===this._mesh.getTotalIndices()}getBoundingInfo(){return this.IsGlobal||this._mesh.hasThinInstances?this._mesh.getBoundingInfo():this._boundingInfo}setBoundingInfo(e){return this._boundingInfo=e,this}getMesh(){return this._mesh}getRenderingMesh(){return this._renderingMesh}getReplacementMesh(){return this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null}getEffectiveMesh(){let e=this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null;return e||this._renderingMesh}getMaterial(e=!0){var i;let t=(i=this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId))!=null?i:this._renderingMesh.material;if(t){if(this._isMultiMaterial(t)){let r=t.getSubMaterial(this.materialIndex);return this._currentMaterial!==r&&(this._currentMaterial=r,this.resetDrawCache()),r}}else return e&&this._mesh.getScene()._hasDefaultMaterial?this._mesh.getScene().defaultMaterial:null;return t}_isMultiMaterial(e){return e.getSubMaterial!==void 0}refreshBoundingInfo(e=null){if(this._lastColliderWorldVertices=null,this.IsGlobal||!this._renderingMesh||!this._renderingMesh.geometry)return this;if(e||(e=this._renderingMesh.getVerticesData(L.PositionKind)),!e)return this._boundingInfo=this._mesh.getBoundingInfo(),this;let t=this._renderingMesh.getIndices(),i;if(this.indexStart===0&&this.indexCount===t.length){let r=this._renderingMesh.getBoundingInfo();i={minimum:r.minimum.clone(),maximum:r.maximum.clone()}}else i=oG(e,t,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new un(i.minimum,i.maximum),this}_checkCollision(e){return this.getBoundingInfo()._checkCollision(e)}updateBoundingInfo(e){let t=this.getBoundingInfo();return t||(this.refreshBoundingInfo(),t=this.getBoundingInfo()),t&&t.update(e),this}isInFrustum(e){let t=this.getBoundingInfo();return t?t.isInFrustum(e,this._mesh.cullingStrategy):!1}isCompletelyInFrustum(e){let t=this.getBoundingInfo();return t?t.isCompletelyInFrustum(e):!1}render(e){return this._renderingMesh.render(this,e,this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:void 0),this}_getLinesIndexBuffer(e,t){if(!this._linesIndexBuffer){let i=Math.floor(this.indexCount/3)*6,s=this.verticesStart+this.verticesCount>65535?new Uint32Array(i):new Uint16Array(i),a=0;if(e.length===0)for(let o=this.indexStart;ol&&(l=d)}return new n(e,o,l-o+1,t,i,r,s,a)}}});var dg,Ce,dr=C(()=>{Gt();Ge();ki();hn();zt();Pt();Vt();py();U_();hg();dg=class{},Ce=class n{constructor(){this.uniqueId=0,this.metadata={},this._applyTo=nG(this._applyToCoroutine.bind(this)),this.uniqueId=n._UniqueIdGenerator,n._UniqueIdGenerator++}set(e,t){switch(e.length||te.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case L.PositionKind:this.positions=e;break;case L.NormalKind:this.normals=e;break;case L.TangentKind:this.tangents=e;break;case L.UVKind:this.uvs=e;break;case L.UV2Kind:this.uvs2=e;break;case L.UV3Kind:this.uvs3=e;break;case L.UV4Kind:this.uvs4=e;break;case L.UV5Kind:this.uvs5=e;break;case L.UV6Kind:this.uvs6=e;break;case L.ColorKind:this.colors=e;break;case L.MatricesIndicesKind:this.matricesIndices=e;break;case L.MatricesWeightsKind:this.matricesWeights=e;break;case L.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case L.MatricesWeightsExtraKind:this.matricesWeightsExtra=e;break}}applyToMesh(e,t){return this._applyTo(e,t,!1),this}applyToGeometry(e,t){return this._applyTo(e,t,!1),this}updateMesh(e){return this._update(e),this}updateGeometry(e){return this._update(e),this}*_applyToCoroutine(e,t=!1,i){if(this.positions&&(e.setVerticesData(L.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(L.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(L.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(L.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(L.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(L.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(L.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(L.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(L.UV6Kind,this.uvs6,t),i&&(yield)),this.colors){let r=this.positions&&this.colors.length===this.positions.length?3:4;e.setVerticesData(L.ColorKind,this.colors,t,r),this.hasVertexAlpha&&e.hasVertexAlpha!==void 0&&(e.hasVertexAlpha=!0),i&&(yield)}if(this.matricesIndices&&(e.setVerticesData(L.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(L.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(L.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(L.MatricesWeightsExtraKind,this.matricesWeightsExtra,t),i&&(yield)),this.indices?(e.setIndices(this.indices,null,t),i&&(yield)):e.setIndices([],null),e.subMeshes&&this.materialInfos&&this.materialInfos.length>1){let r=e;r.subMeshes=[];for(let s of this.materialInfos)new xs(s.materialIndex,s.verticesStart,s.verticesCount,s.indexStart,s.indexCount,r)}return this}_update(e,t,i){return this.positions&&e.updateVerticesData(L.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(L.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(L.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(L.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(L.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(L.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(L.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(L.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(L.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(L.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(L.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(L.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(L.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(L.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,r=e.length){let s=$.Vector3[0],a=$.Vector3[1];for(let o=i;o({vertexData:o})):[{vertexData:e}];return fg(this._mergeCoroutine(void 0,a,t,!1,i,r,s))}*_mergeCoroutine(e,t,i=!1,r,s,a=!1,o=!1){var u,m,p,_;this._validate();let l=t.map(g=>g.vertexData),c=this;if(o)for(let g of l)g&&(g._validate(),!this.normals&&g.normals&&(this.normals=new Float32Array(this.positions.length)),!this.tangents&&g.tangents&&(this.tangents=new Float32Array(this.positions.length/3*4)),!this.uvs&&g.uvs&&(this.uvs=new Float32Array(this.positions.length/3*2)),!this.uvs2&&g.uvs2&&(this.uvs2=new Float32Array(this.positions.length/3*2)),!this.uvs3&&g.uvs3&&(this.uvs3=new Float32Array(this.positions.length/3*2)),!this.uvs4&&g.uvs4&&(this.uvs4=new Float32Array(this.positions.length/3*2)),!this.uvs5&&g.uvs5&&(this.uvs5=new Float32Array(this.positions.length/3*2)),!this.uvs6&&g.uvs6&&(this.uvs6=new Float32Array(this.positions.length/3*2)),!this.colors&&g.colors&&(this.colors=new Float32Array(this.positions.length/3*4),this.colors.fill(1)),!this.matricesIndices&&g.matricesIndices&&(this.matricesIndices=new Float32Array(this.positions.length/3*4)),!this.matricesWeights&&g.matricesWeights&&(this.matricesWeights=new Float32Array(this.positions.length/3*4)),!this.matricesIndicesExtra&&g.matricesIndicesExtra&&(this.matricesIndicesExtra=new Float32Array(this.positions.length/3*4)),!this.matricesWeightsExtra&&g.matricesWeightsExtra&&(this.matricesWeightsExtra=new Float32Array(this.positions.length/3*4)));for(let g of l)if(g){if(o)this.normals&&!g.normals&&(g.normals=new Float32Array(g.positions.length)),this.tangents&&!g.tangents&&(g.tangents=new Float32Array(g.positions.length/3*4)),this.uvs&&!g.uvs&&(g.uvs=new Float32Array(g.positions.length/3*2)),this.uvs2&&!g.uvs2&&(g.uvs2=new Float32Array(g.positions.length/3*2)),this.uvs3&&!g.uvs3&&(g.uvs3=new Float32Array(g.positions.length/3*2)),this.uvs4&&!g.uvs4&&(g.uvs4=new Float32Array(g.positions.length/3*2)),this.uvs5&&!g.uvs5&&(g.uvs5=new Float32Array(g.positions.length/3*2)),this.uvs6&&!g.uvs6&&(g.uvs6=new Float32Array(g.positions.length/3*2)),this.colors&&!g.colors&&(g.colors=new Float32Array(g.positions.length/3*4),g.colors.fill(1)),this.matricesIndices&&!g.matricesIndices&&(g.matricesIndices=new Float32Array(g.positions.length/3*4)),this.matricesWeights&&!g.matricesWeights&&(g.matricesWeights=new Float32Array(g.positions.length/3*4)),this.matricesIndicesExtra&&!g.matricesIndicesExtra&&(g.matricesIndicesExtra=new Float32Array(g.positions.length/3*4)),this.matricesWeightsExtra&&!g.matricesWeightsExtra&&(g.matricesWeightsExtra=new Float32Array(g.positions.length/3*4));else if(g._validate(),!this.normals!=!g.normals||!this.tangents!=!g.tangents||!this.uvs!=!g.uvs||!this.uvs2!=!g.uvs2||!this.uvs3!=!g.uvs3||!this.uvs4!=!g.uvs4||!this.uvs5!=!g.uvs5||!this.uvs6!=!g.uvs6||!this.colors!=!g.colors||!this.matricesIndices!=!g.matricesIndices||!this.matricesWeights!=!g.matricesWeights||!this.matricesIndicesExtra!=!g.matricesIndicesExtra||!this.matricesWeightsExtra!=!g.matricesWeightsExtra)throw new Error("Cannot merge vertex data that do not have the same set of attributes")}if(a){let g,v=0,x=0,A=[],S=null,E=[];for(let I of this.splitBasedOnMaterialID())E.push({vertexData:I,transform:e});for(let I of t)if(I.vertexData)for(let y of I.vertexData.splitBasedOnMaterialID())E.push({vertexData:y,transform:I.transform});E.sort((I,y)=>{let M=I.vertexData.materialInfos?I.vertexData.materialInfos[0].materialIndex:0,D=y.vertexData.materialInfos?y.vertexData.materialInfos[0].materialIndex:0;return M>D?1:M===D?0:-1});for(let I of E){let y=I.vertexData;if(y.materialInfos?g=y.materialInfos[0].materialIndex:g=0,S&&S.materialIndex===g)S.indexCount+=y.indices.length,S.verticesCount+=y.positions.length/3;else{let M=new dg;M.materialIndex=g,M.indexStart=v,M.indexCount=y.indices.length,M.verticesStart=x,M.verticesCount=y.positions.length/3,A.push(M),S=M}v+=y.indices.length,x+=y.positions.length/3}let R=E.splice(0,1)[0];c=R.vertexData,e=R.transform,l=E.map(I=>I.vertexData),t=E,this.materialInfos=A}let f=l.reduce((g,v)=>{var x,A;return g+((A=(x=v.indices)==null?void 0:x.length)!=null?A:0)},(m=(u=c.indices)==null?void 0:u.length)!=null?m:0),d=s||l.some(g=>g.indices===c.indices)?(p=c.indices)==null?void 0:p.slice():c.indices;if(f>0){let g=(_=d==null?void 0:d.length)!=null?_:0;if(d||(d=new Array(f)),d.length!==f){if(Array.isArray(d))d.length=f;else{let x=i||d instanceof Uint32Array?new Uint32Array(f):new Uint16Array(f);x.set(d),d=x}e&&e.determinant()<0&&n._FlipFaces(d,0,g)}let v=c.positions?c.positions.length/3:0;for(let{vertexData:x,transform:A}of t)if(x.indices){for(let S=0;S[g.vertexData.positions,g.transform])),r&&(yield),c.normals&&(this.normals=n._MergeElement(L.NormalKind,c.normals,e,t.map(g=>[g.vertexData.normals,g.transform])),r&&(yield)),c.tangents&&(this.tangents=n._MergeElement(L.TangentKind,c.tangents,e,t.map(g=>[g.vertexData.tangents,g.transform])),r&&(yield)),c.uvs&&(this.uvs=n._MergeElement(L.UVKind,c.uvs,e,t.map(g=>[g.vertexData.uvs,g.transform])),r&&(yield)),c.uvs2&&(this.uvs2=n._MergeElement(L.UV2Kind,c.uvs2,e,t.map(g=>[g.vertexData.uvs2,g.transform])),r&&(yield)),c.uvs3&&(this.uvs3=n._MergeElement(L.UV3Kind,c.uvs3,e,t.map(g=>[g.vertexData.uvs3,g.transform])),r&&(yield)),c.uvs4&&(this.uvs4=n._MergeElement(L.UV4Kind,c.uvs4,e,t.map(g=>[g.vertexData.uvs4,g.transform])),r&&(yield)),c.uvs5&&(this.uvs5=n._MergeElement(L.UV5Kind,c.uvs5,e,t.map(g=>[g.vertexData.uvs5,g.transform])),r&&(yield)),c.uvs6&&(this.uvs6=n._MergeElement(L.UV6Kind,c.uvs6,e,t.map(g=>[g.vertexData.uvs6,g.transform])),r&&(yield)),c.colors&&(this.colors=n._MergeElement(L.ColorKind,c.colors,e,t.map(g=>[g.vertexData.colors,g.transform])),(c.hasVertexAlpha!==void 0||t.some(g=>g.vertexData.hasVertexAlpha!==void 0))&&(this.hasVertexAlpha=c.hasVertexAlpha||t.some(g=>g.vertexData.hasVertexAlpha)),r&&(yield)),c.matricesIndices&&(this.matricesIndices=n._MergeElement(L.MatricesIndicesKind,c.matricesIndices,e,t.map(g=>[g.vertexData.matricesIndices,g.transform])),r&&(yield)),c.matricesWeights&&(this.matricesWeights=n._MergeElement(L.MatricesWeightsKind,c.matricesWeights,e,t.map(g=>[g.vertexData.matricesWeights,g.transform])),r&&(yield)),c.matricesIndicesExtra&&(this.matricesIndicesExtra=n._MergeElement(L.MatricesIndicesExtraKind,c.matricesIndicesExtra,e,t.map(g=>[g.vertexData.matricesIndicesExtra,g.transform])),r&&(yield)),c.matricesWeightsExtra&&(this.matricesWeightsExtra=n._MergeElement(L.MatricesWeightsExtraKind,c.matricesWeightsExtra,e,t.map(g=>[g.vertexData.matricesWeightsExtra,g.transform]))),this}static _MergeElement(e,t,i,r){let s=r.filter(l=>l[0]!==null&&l[0]!==void 0);if(!t&&s.length==0)return t;if(!t)return this._MergeElement(e,s[0][0],s[0][1],s.slice(1));let a=s.reduce((l,c)=>l+c[0].length,t.length),o=e===L.PositionKind?n._TransformVector3Coordinates:e===L.NormalKind?n._TransformVector3Normals:e===L.TangentKind?n._TransformVector4Normals:()=>{};if(t instanceof Float32Array){let l=new Float32Array(a);l.set(t),i&&o(l,i,0,t.length);let c=t.length;for(let[f,h]of s)l.set(f,c),h&&o(l,h,c,f.length),c+=f.length;return l}else{let l=new Array(a);for(let f=0;f{let a=L.DeduceStride(r);if(s.length%a!==0)throw new Error("The "+r+"s array count must be a multiple of "+a);return s.length/a},t=e(L.PositionKind,this.positions),i=(r,s)=>{let a=e(r,s);if(a!==t)throw new Error("The "+r+"s element count ("+a+") does not match the positions count ("+t+")")};this.normals&&i(L.NormalKind,this.normals),this.tangents&&i(L.TangentKind,this.tangents),this.uvs&&i(L.UVKind,this.uvs),this.uvs2&&i(L.UV2Kind,this.uvs2),this.uvs3&&i(L.UV3Kind,this.uvs3),this.uvs4&&i(L.UV4Kind,this.uvs4),this.uvs5&&i(L.UV5Kind,this.uvs5),this.uvs6&&i(L.UV6Kind,this.uvs6),this.colors&&i(L.ColorKind,this.colors),this.matricesIndices&&i(L.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&i(L.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&i(L.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&i(L.MatricesWeightsExtraKind,this.matricesWeightsExtra)}clone(){let e=this.serialize();return n.Parse(e)}serialize(){let e={};if(this.positions&&(e.positions=Array.from(this.positions)),this.normals&&(e.normals=Array.from(this.normals)),this.tangents&&(e.tangents=Array.from(this.tangents)),this.uvs&&(e.uvs=Array.from(this.uvs)),this.uvs2&&(e.uvs2=Array.from(this.uvs2)),this.uvs3&&(e.uvs3=Array.from(this.uvs3)),this.uvs4&&(e.uvs4=Array.from(this.uvs4)),this.uvs5&&(e.uvs5=Array.from(this.uvs5)),this.uvs6&&(e.uvs6=Array.from(this.uvs6)),this.colors&&(e.colors=Array.from(this.colors),e.hasVertexAlpha=this.hasVertexAlpha),this.matricesIndices&&(e.matricesIndices=Array.from(this.matricesIndices),e.matricesIndicesExpanded=!0),this.matricesWeights&&(e.matricesWeights=Array.from(this.matricesWeights)),this.matricesIndicesExtra&&(e.matricesIndicesExtra=Array.from(this.matricesIndicesExtra),e.matricesIndicesExtraExpanded=!0),this.matricesWeightsExtra&&(e.matricesWeightsExtra=Array.from(this.matricesWeightsExtra)),e.indices=this.indices?Array.from(this.indices):[],this.materialInfos){e.materialInfos=[];for(let t of this.materialInfos){let i={indexStart:t.indexStart,indexCount:t.indexCount,materialIndex:t.materialIndex,verticesStart:t.verticesStart,verticesCount:t.verticesCount};e.materialInfos.push(i)}}return e}static ExtractFromMesh(e,t,i){return n._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return n._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){let r=new n;if(e.isVerticesDataPresent(L.PositionKind)&&(r.positions=e.getVerticesData(L.PositionKind,t,i)),e.isVerticesDataPresent(L.NormalKind)&&(r.normals=e.getVerticesData(L.NormalKind,t,i)),e.isVerticesDataPresent(L.TangentKind)&&(r.tangents=e.getVerticesData(L.TangentKind,t,i)),e.isVerticesDataPresent(L.UVKind)&&(r.uvs=e.getVerticesData(L.UVKind,t,i)),e.isVerticesDataPresent(L.UV2Kind)&&(r.uvs2=e.getVerticesData(L.UV2Kind,t,i)),e.isVerticesDataPresent(L.UV3Kind)&&(r.uvs3=e.getVerticesData(L.UV3Kind,t,i)),e.isVerticesDataPresent(L.UV4Kind)&&(r.uvs4=e.getVerticesData(L.UV4Kind,t,i)),e.isVerticesDataPresent(L.UV5Kind)&&(r.uvs5=e.getVerticesData(L.UV5Kind,t,i)),e.isVerticesDataPresent(L.UV6Kind)&&(r.uvs6=e.getVerticesData(L.UV6Kind,t,i)),e.isVerticesDataPresent(L.ColorKind)){let s=e.geometry||e,a=s.getVertexBuffer(L.ColorKind),o=s.getVerticesData(L.ColorKind,t,i);if(a.getSize()===3){let l=new Float32Array(o.length*4/3);for(let c=0,f=0;c!Array.isArray(n[0]))],Ce,"_TransformVector3Coordinates",null);P([Ss.filter((...n)=>!Array.isArray(n[0]))],Ce,"_TransformVector3Normals",null);P([Ss.filter((...n)=>!Array.isArray(n[0]))],Ce,"_TransformVector4Normals",null);P([Ss.filter((...n)=>!Array.isArray(n[0]))],Ce,"_FlipFaces",null)});var Xr,CA=C(()=>{Xr=class n{static get ForceFullSceneLoadingForIncremental(){return n._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){n._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return n._ShowLoadingScreen}static set ShowLoadingScreen(e){n._ShowLoadingScreen=e}static get loggingLevel(){return n._LoggingLevel}static set loggingLevel(e){n._LoggingLevel=e}static get CleanBoneMatrixWeights(){return n._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){n._CleanBoneMatrixWeights=e}};Xr._ForceFullSceneLoadingForIncremental=!1;Xr._ShowLoadingScreen=!0;Xr._CleanBoneMatrixWeights=!1;Xr._LoggingLevel=0});var mn,yA=C(()=>{Ge();zt();dr();ki();hg();CA();mm();Ii();df();MA();Di();en();rm();mn=class n{get boundingBias(){return this._boundingBias}set boundingBias(e){this._boundingBias?this._boundingBias.copyFrom(e):this._boundingBias=e.clone(),this._updateBoundingInfo(!0,null)}static CreateGeometryForMesh(e){let t=new n(n.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,i,r=!1,s=null,a=null){this.delayLoadState=0,this._totalVertices=0,this._isDisposed=!1,this._extend={minimum:new b(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),maximum:new b(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)},this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this._scene=t||Oe.LastCreatedScene,this._scene&&(this.id=e,this.uniqueId=this._scene.getUniqueId(),this._engine=this._scene.getEngine(),this._meshes=[],this._vertexBuffers={},this._indices=[],this._updatable=r,a!==null&&(this._totalVertices=a),i?this.setAllVerticesData(i,r):a===null&&(this._totalVertices=0),this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),s&&(this.applyToMesh(s),s.computeWorldMatrix(!0)))}get extend(){return this._extend}getScene(){return this._scene}getEngine(){return this._engine}isReady(){return this.delayLoadState===1||this.delayLoadState===0}get doNotSerialize(){for(let e=0;e{t._rebuild()})}setAllVerticesData(e,t){e.applyToGeometry(this,t),this._notifyUpdate()}setVerticesData(e,t,i=!1,r){i&&Array.isArray(t)&&(t=new Float32Array(t));let s=new L(this._engine,t,e,{updatable:i,postponeInternalCreation:this._meshes.length===0,stride:r,label:"Geometry_"+this.id+"_"+e});this.setVerticesBuffer(s)}removeVerticesData(e){this._vertexBuffers[e]&&(this._vertexBuffers[e].dispose(),delete this._vertexBuffers[e]),this._vertexArrayObjects&&this._disposeVertexArrayObjects()}setVerticesBuffer(e,t=null,i=!0){let r=e.getKind();this._vertexBuffers[r]&&i&&this._vertexBuffers[r].dispose(),e._buffer&&e._ownsBuffer&&e._buffer._increaseReferences(),this._vertexBuffers[r]=e;let s=this._meshes,a=s.length;if(r===L.PositionKind){this._totalVertices=t!=null?t:e._maxVerticesCount,this._updateExtend(this.useBoundingInfoFromGeometry&&this._boundingInfo?null:e.getFloatData(this._totalVertices)),this._resetPointsArrayCache();let o=this._extend&&this._extend.minimum||new b(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),l=this._extend&&this._extend.maximum||new b(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE);for(let c=0;c65535:e.is32Bits=r;for(let s of this._meshes)s._createGlobalSubMesh(!0),s.synchronizeInstances();this._notifyUpdate()}setIndices(e,t=null,i=!1,r=!1){this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indices=e,this._indexBufferIsUpdatable=i,this._meshes.length!==0&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,i,"Geometry_"+this.id+"_IndexBuffer")),t!=null&&(this._totalVertices=t);for(let s of this._meshes)s._createGlobalSubMesh(!r),s.synchronizeInstances();this._notifyUpdate()}getTotalIndices(){return this.isReady()?this._totalIndices!==void 0?this._totalIndices:this._indices.length:0}getIndices(e,t){if(!this.isReady())return null;let i=this._indices;return!t&&(!e||this._meshes.length===1)?i:i.slice()}getIndexBuffer(){return this.isReady()?this._indexBuffer:null}_releaseVertexArrayObject(e=null){!e||!this._vertexArrayObjects||this._vertexArrayObjects[e.key]&&(this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e.key]),delete this._vertexArrayObjects[e.key])}releaseForMesh(e,t){let i=this._meshes,r=i.indexOf(e);r!==-1&&(i.splice(r,1),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject(),e._geometry=null,i.length===0&&t&&this.dispose())}applyToMesh(e){if(e._geometry===this)return;let t=e._geometry;t&&t.releaseForMesh(e),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject();let i=this._meshes;e._geometry=this,e._internalAbstractMeshDataInfo._positions=null,this._scene.pushGeometry(this),i.push(e),this.isReady()?this._applyToMesh(e):this._boundingInfo&&e.setBoundingInfo(this._boundingInfo)}_updateExtend(e=null){if(this.useBoundingInfoFromGeometry&&this._boundingInfo)this._extend={minimum:this._boundingInfo.minimum.clone(),maximum:this._boundingInfo.maximum.clone()};else{if(!e&&(e=this.getVerticesData(L.PositionKind),!e))return;this._extend=IA(e,0,this._totalVertices,this.boundingBias,3)}}_applyToMesh(e){for(let t in this._vertexBuffers){let i=this._vertexBuffers[t];i._buffer.getBuffer()||i.create(),t===L.PositionKind&&(this._extend||this._updateExtend(),e.buildBoundingInfo(this._extend.minimum,this._extend.maximum),e._createGlobalSubMesh(e.isUnIndexed),e._updateBoundingInfo())}!this._indexBuffer&&this._indices&&this._indices.length>0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable,"Geometry_"+this.id+"_IndexBuffer")),e._syncGeometryWithMorphTargetManager(),e.synchronizeInstances()}_notifyUpdate(e){this.onGeometryUpdated&&this.onGeometryUpdated(this,e),this._vertexArrayObjects&&this._disposeVertexArrayObjects();for(let t of this._meshes)t._markSubMeshesAsAttributesDirty()}load(e,t){if(this.delayLoadState!==2){if(this.isReady()){t&&t();return}this.delayLoadState=2,this._queueLoad(e,t)}}_queueLoad(e,t){this.delayLoadingFile&&(e.addPendingData(this),e._loadFile(this.delayLoadingFile,i=>{if(!this._delayLoadingFunction)return;this._delayLoadingFunction(JSON.parse(i),this),this.delayLoadState=1,this._delayInfo=[],e.removePendingData(this);let r=this._meshes,s=r.length;for(let a=0;a0){for(let r=0;r0){for(let r=0;r0){for(let r=0;r-1&&this._parentContainer.geometries.splice(r,1),this._parentContainer=null}this._isDisposed=!0}copy(e){let t=new n(e,this._scene),i=this.getIndices(void 0,!0);i&&t.setIndices(i);let r=!1,s;for(s in this._vertexBuffers){let a=this.getVertexBuffer(s),o=a.getData();if(!o)continue;let l=a.isUpdatable(),c=a.getSize(),{type:f,byteOffset:h,byteStride:d,normalized:u}=a;r=r||l;let m=this._totalVertices;if(a.getIsInstanced()){let g;o instanceof Array?g=o.length*4:g=o.byteLength,m=g/d}let p=L2(o,c,f,h,d,m,!0),_=new L(this._engine,p,s,{updatable:l,useBytes:!1,stride:c,size:c,offset:0,type:f,normalized:u,takeBufferOwnership:!0,instanced:a.getIsInstanced()});t.setVerticesBuffer(_,m)}t._updatable=r,t.delayLoadState=this.delayLoadState,t.delayLoadingFile=this.delayLoadingFile,t._delayLoadingFunction=this._delayLoadingFunction;for(s in this._delayInfo)t._delayInfo=t._delayInfo||[],t._delayInfo.push(s);return t._boundingInfo=new un(this._extend.minimum,this._extend.maximum),t}serialize(){let e={};return e.id=this.id,e.uniqueId=this.uniqueId,e.updatable=this._updatable,Zt&&Zt.HasTags(this)&&(e.tags=Zt.GetTags(this)),e}_toNumberArray(e){return Array.isArray(e)?e:Array.prototype.slice.call(e)}clearCachedData(){this._totalIndices=this._indices.length,this._indices=[],this._resetPointsArrayCache();for(let e in this._vertexBuffers)Object.prototype.hasOwnProperty.call(this._vertexBuffers,e)&&(this._vertexBuffers[e]._buffer._data=null)}serializeVerticeData(){let e=this.serialize();return this.isVerticesDataPresent(L.PositionKind)&&(e.positions=this._toNumberArray(this.getVerticesData(L.PositionKind)),this.isVertexBufferUpdatable(L.PositionKind)&&(e.positionsUpdatable=!0)),this.isVerticesDataPresent(L.NormalKind)&&(e.normals=this._toNumberArray(this.getVerticesData(L.NormalKind)),this.isVertexBufferUpdatable(L.NormalKind)&&(e.normalsUpdatable=!0)),this.isVerticesDataPresent(L.TangentKind)&&(e.tangents=this._toNumberArray(this.getVerticesData(L.TangentKind)),this.isVertexBufferUpdatable(L.TangentKind)&&(e.tangentsUpdatable=!0)),this.isVerticesDataPresent(L.UVKind)&&(e.uvs=this._toNumberArray(this.getVerticesData(L.UVKind)),this.isVertexBufferUpdatable(L.UVKind)&&(e.uvsUpdatable=!0)),this.isVerticesDataPresent(L.UV2Kind)&&(e.uvs2=this._toNumberArray(this.getVerticesData(L.UV2Kind)),this.isVertexBufferUpdatable(L.UV2Kind)&&(e.uvs2Updatable=!0)),this.isVerticesDataPresent(L.UV3Kind)&&(e.uvs3=this._toNumberArray(this.getVerticesData(L.UV3Kind)),this.isVertexBufferUpdatable(L.UV3Kind)&&(e.uvs3Updatable=!0)),this.isVerticesDataPresent(L.UV4Kind)&&(e.uvs4=this._toNumberArray(this.getVerticesData(L.UV4Kind)),this.isVertexBufferUpdatable(L.UV4Kind)&&(e.uvs4Updatable=!0)),this.isVerticesDataPresent(L.UV5Kind)&&(e.uvs5=this._toNumberArray(this.getVerticesData(L.UV5Kind)),this.isVertexBufferUpdatable(L.UV5Kind)&&(e.uvs5Updatable=!0)),this.isVerticesDataPresent(L.UV6Kind)&&(e.uvs6=this._toNumberArray(this.getVerticesData(L.UV6Kind)),this.isVertexBufferUpdatable(L.UV6Kind)&&(e.uvs6Updatable=!0)),this.isVerticesDataPresent(L.ColorKind)&&(e.colors=this._toNumberArray(this.getVerticesData(L.ColorKind)),this.isVertexBufferUpdatable(L.ColorKind)&&(e.colorsUpdatable=!0)),this.isVerticesDataPresent(L.MatricesIndicesKind)&&(e.matricesIndices=this._toNumberArray(this.getVerticesData(L.MatricesIndicesKind)),e.matricesIndicesExpanded=!0,this.isVertexBufferUpdatable(L.MatricesIndicesKind)&&(e.matricesIndicesUpdatable=!0)),this.isVerticesDataPresent(L.MatricesWeightsKind)&&(e.matricesWeights=this._toNumberArray(this.getVerticesData(L.MatricesWeightsKind)),this.isVertexBufferUpdatable(L.MatricesWeightsKind)&&(e.matricesWeightsUpdatable=!0)),e.indices=this._toNumberArray(this.getIndices()),e}static ExtractFromMesh(e,t){let i=e._geometry;return i?i.copy(t):null}static RandomId(){return _e.RandomId()}static _GetGeometryByLoadedUniqueId(e,t){for(let i=0;i0){let o=new Float32Array(e,a.positionsAttrDesc.offset,a.positionsAttrDesc.count);t.setVerticesData(L.PositionKind,o,!1)}if(a.normalsAttrDesc&&a.normalsAttrDesc.count>0){let o=new Float32Array(e,a.normalsAttrDesc.offset,a.normalsAttrDesc.count);t.setVerticesData(L.NormalKind,o,!1)}if(a.tangetsAttrDesc&&a.tangetsAttrDesc.count>0){let o=new Float32Array(e,a.tangetsAttrDesc.offset,a.tangetsAttrDesc.count);t.setVerticesData(L.TangentKind,o,!1)}if(a.uvsAttrDesc&&a.uvsAttrDesc.count>0){let o=new Float32Array(e,a.uvsAttrDesc.offset,a.uvsAttrDesc.count);if(Mt)for(let l=1;l0){let o=new Float32Array(e,a.uvs2AttrDesc.offset,a.uvs2AttrDesc.count);if(Mt)for(let l=1;l0){let o=new Float32Array(e,a.uvs3AttrDesc.offset,a.uvs3AttrDesc.count);if(Mt)for(let l=1;l0){let o=new Float32Array(e,a.uvs4AttrDesc.offset,a.uvs4AttrDesc.count);if(Mt)for(let l=1;l0){let o=new Float32Array(e,a.uvs5AttrDesc.offset,a.uvs5AttrDesc.count);if(Mt)for(let l=1;l0){let o=new Float32Array(e,a.uvs6AttrDesc.offset,a.uvs6AttrDesc.count);if(Mt)for(let l=1;l0){let o=new Float32Array(e,a.colorsAttrDesc.offset,a.colorsAttrDesc.count);t.setVerticesData(L.ColorKind,o,!1,a.colorsAttrDesc.stride)}if(a.matricesIndicesAttrDesc&&a.matricesIndicesAttrDesc.count>0){let o=new Int32Array(e,a.matricesIndicesAttrDesc.offset,a.matricesIndicesAttrDesc.count),l=[];for(let c=0;c>8),l.push((f&16711680)>>16),l.push(f>>24&255)}t.setVerticesData(L.MatricesIndicesKind,l,!1)}if(a.matricesIndicesExtraAttrDesc&&a.matricesIndicesExtraAttrDesc.count>0){let o=new Int32Array(e,a.matricesIndicesExtraAttrDesc.offset,a.matricesIndicesExtraAttrDesc.count),l=[];for(let c=0;c>8),l.push((f&16711680)>>16),l.push(f>>24&255)}t.setVerticesData(L.MatricesIndicesExtraKind,l,!1)}if(a.matricesWeightsAttrDesc&&a.matricesWeightsAttrDesc.count>0){let o=new Float32Array(e,a.matricesWeightsAttrDesc.offset,a.matricesWeightsAttrDesc.count);t.setVerticesData(L.MatricesWeightsKind,o,!1)}if(a.indicesAttrDesc&&a.indicesAttrDesc.count>0){let o=new Int32Array(e,a.indicesAttrDesc.offset,a.indicesAttrDesc.count);t.setIndices(o,null)}if(a.subMeshesAttrDesc&&a.subMeshesAttrDesc.count>0){let o=new Int32Array(e,a.subMeshesAttrDesc.offset,a.subMeshesAttrDesc.count*5);t.subMeshes=[];for(let l=0;l>8),a.push((l&16711680)>>16),a.push(l>>24&255)}t.setVerticesData(L.MatricesIndicesKind,a,e.matricesIndices._updatable||e.matricesIndicesUpdatable)}else delete e.matricesIndices._isExpanded,delete e.matricesIndicesExpanded,t.setVerticesData(L.MatricesIndicesKind,e.matricesIndices,e.matricesIndices._updatable||e.matricesIndicesUpdatable);if(e.matricesIndicesExtra)if(e.matricesIndicesExtraExpanded||e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,delete e.matricesIndicesExtraExpanded,t.setVerticesData(L.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable||e.matricesIndicesExtraUpdatable);else{let a=[];for(let o=0;o>8),a.push((l&16711680)>>16),a.push(l>>24&255)}t.setVerticesData(L.MatricesIndicesExtraKind,a,e.matricesIndicesExtra._updatable||e.matricesIndicesExtraUpdatable)}e.matricesWeights&&(n._CleanMatricesWeights(e,t),t.setVerticesData(L.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(L.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let a=0;a-1){let h=t.getScene().getLastSkeletonById(e.skeletonId);if(!h)return;r=h.bones.length}else return;let s=t.getVerticesData(L.MatricesIndicesKind),a=t.getVerticesData(L.MatricesIndicesExtraKind),o=e.matricesWeights,l=e.matricesWeightsExtra,c=e.numBoneInfluencer,f=o.length;for(let h=0;hc-1)&&(u=c-1),d>.001){let m=1/d;for(let p=0;p<4;p++)o[h+p]*=m;if(l)for(let p=0;p<4;p++)l[h+p]*=m}else u>=4?(l[h+u-4]=1-d,a[h+u-4]=r):(o[h+u]=1-d,s[h+u]=r)}t.setVerticesData(L.MatricesIndicesKind,s),e.matricesWeightsExtra&&t.setVerticesData(L.MatricesIndicesExtraKind,a)}static Parse(e,t,i){let r=new n(e.id,t,void 0,e.updatable);return r._loadedUniqueId=e.uniqueId,Zt&&Zt.AddTagsTo(r,e.tags),e.delayLoadingFile?(r.delayLoadState=4,r.delayLoadingFile=i+e.delayLoadingFile,r._boundingInfo=new un(b.FromArray(e.boundingBoxMinimum),b.FromArray(e.boundingBoxMaximum)),r._delayInfo=[],e.hasUVs&&r._delayInfo.push(L.UVKind),e.hasUVs2&&r._delayInfo.push(L.UV2Kind),e.hasUVs3&&r._delayInfo.push(L.UV3Kind),e.hasUVs4&&r._delayInfo.push(L.UV4Kind),e.hasUVs5&&r._delayInfo.push(L.UV5Kind),e.hasUVs6&&r._delayInfo.push(L.UV6Kind),e.hasColors&&r._delayInfo.push(L.ColorKind),e.hasMatricesIndices&&r._delayInfo.push(L.MatricesIndicesKind),e.hasMatricesWeights&&r._delayInfo.push(L.MatricesWeightsKind),r._delayLoadingFunction=Ce.ImportVertexData):Ce.ImportVertexData(e,r),t.pushGeometry(r,!0),r}}});var ei,qh=C(()=>{Gt();Vt();Tr();di();Ge();js();Hi();ei=class n extends _i{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=(this._billboardMode&n.BILLBOARDMODE_USE_POSITION)!==0)}get infiniteDistance(){return this._infiniteDistance}set infiniteDistance(e){this._infiniteDistance!==e&&(this._infiniteDistance=e)}constructor(e,t=null,i=!0){super(e,t,!1),this._forward=new b(0,0,1),this._up=new b(0,1,0),this._right=new b(1,0,0),this._position=b.Zero(),this._rotation=b.Zero(),this._rotationQuaternion=null,this._scaling=b.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=n.BILLBOARDMODE_NONE,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=K.Zero(),this._usePivotMatrix=!1,this._absolutePosition=b.Zero(),this._absoluteScaling=b.Zero(),this._absoluteRotationQuaternion=Xe.Identity(),this._pivotMatrix=K.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new ie,this._nonUniformScaling=!1,i&&this.getScene().addTransformNode(this)}getClassName(){return"TransformNode"}get position(){return this._position}set position(e){this._position=e,this._markAsDirtyInternal()}isUsingPivotMatrix(){return this._usePivotMatrix}isUsingPostMultiplyPivotMatrix(){return this._postMultiplyPivotMatrix}get rotation(){return this._rotation}set rotation(e){this._rotation=e,this._rotationQuaternion=null,this._markAsDirtyInternal()}get scaling(){return this._scaling}set scaling(e){this._scaling=e,this._markAsDirtyInternal()}get rotationQuaternion(){return this._rotationQuaternion}set rotationQuaternion(e){this._rotationQuaternion=e,e&&this._rotation.setAll(0),this._markAsDirtyInternal()}_markAsDirtyInternal(){this._isDirty||(this._isDirty=!0,this.customMarkAsDirty&&this.customMarkAsDirty())}get forward(){return b.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return b.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return b.TransformNormalFromFloatsToRef(this.getScene().useRightHandedSystem?-1:1,0,0,this.getWorldMatrix(),this._right),this._right.normalize()}updatePoseMatrix(e){return this._poseMatrix?(this._poseMatrix.copyFrom(e),this):(this._poseMatrix=e.clone(),this)}getPoseMatrix(){return this._poseMatrix||(this._poseMatrix=K.Identity()),this._poseMatrix}_isSynchronized(){let e=this._cache;return!(this._billboardMode!==e.billboardMode||this._billboardMode!==n.BILLBOARDMODE_NONE||e.pivotMatrixUpdated||this._infiniteDistance||this._position._isDirty||this._scaling._isDirty||this._rotationQuaternion&&this._rotationQuaternion._isDirty||this._rotation._isDirty)}_initCache(){super._initCache();let e=this._cache;e.localMatrixUpdated=!1,e.billboardMode=-1,e.infiniteDistance=!1,e.useBillboardPosition=!1}get absolutePosition(){return this.getAbsolutePosition()}get absoluteScaling(){return this._syncAbsoluteScalingAndRotation(),this._absoluteScaling}get absoluteRotationQuaternion(){return this._syncAbsoluteScalingAndRotation(),this._absoluteRotationQuaternion}setPreTransformMatrix(e){return this.setPivotMatrix(e,!1)}setPivotMatrix(e,t=!0){return this._pivotMatrix.copyFrom(e),this._usePivotMatrix=!this._pivotMatrix.isIdentity(),this._cache.pivotMatrixUpdated=!0,this._postMultiplyPivotMatrix=t,this._postMultiplyPivotMatrix&&(this._pivotMatrixInverse?this._pivotMatrix.invertToRef(this._pivotMatrixInverse):this._pivotMatrixInverse=K.Invert(this._pivotMatrix)),this}getPivotMatrix(){return this._pivotMatrix}instantiateHierarchy(e=null,t,i){let r=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);r&&i&&i(this,r);for(let s of this.getChildTransformNodes(!0))s.instantiateHierarchy(r,t,i);return r}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||Xe.Identity(),e.decompose(this._scaling,this._rotationQuaternion,this._position),this.computeWorldMatrix(!0)):(this._worldMatrix=e,this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._afterComputeWorldMatrix()):(this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0)),this._isDirty=!1,this._isWorldMatrixFrozen=!0,this}unfreezeWorldMatrix(){return this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0),this}get isWorldMatrixFrozen(){return this._isWorldMatrixFrozen}getAbsolutePosition(){return this.computeWorldMatrix(),this._absolutePosition}setAbsolutePosition(e){if(!e)return this;let t,i,r;if(e.x===void 0){if(arguments.length<3)return this;t=arguments[0],i=arguments[1],r=arguments[2]}else t=e.x,i=e.y,r=e.z;if(this.parent){let s=$.Matrix[0];this.parent.getWorldMatrix().invertToRef(s),b.TransformCoordinatesFromFloatsToRef(t,i,r,s,this.position)}else this.position.x=t,this.position.y=i,this.position.z=r;return this._absolutePosition.copyFrom(e),this}setPositionWithLocalVector(e){return this.computeWorldMatrix(),this.position=b.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();let e=$.Matrix[0];return this._localMatrix.invertToRef(e),b.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=b.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,r=0,s=0){let a=n._LookAtVectorCache,o=s===0?this.position:this.getAbsolutePosition();if(e.subtractToRef(o,a),this.setDirection(a,t,i,r),s===1&&this.parent)if(this.rotationQuaternion){let l=$.Matrix[0];this.rotationQuaternion.toRotationMatrix(l);let c=$.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(c),c.invert(),l.multiplyToRef(c,l),this.rotationQuaternion.fromRotationMatrix(l)}else{let l=$.Quaternion[0];Xe.FromEulerVectorToRef(this.rotation,l);let c=$.Matrix[0];l.toRotationMatrix(c);let f=$.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(f),f.invert(),c.multiplyToRef(f,c),l.fromRotationMatrix(c),l.toEulerAnglesToRef(this.rotation)}return this}getDirection(e){let t=b.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return b.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,r=0){let s=-Math.atan2(e.z,e.x)+Math.PI/2,a=Math.sqrt(e.x*e.x+e.z*e.z),o=-Math.atan2(e.y,a);return this.rotationQuaternion?Xe.RotationYawPitchRollToRef(s+t,o+i,r,this.rotationQuaternion):(this.rotation.x=o+i,this.rotation.y=s+t,this.rotation.z=r),this}setPivotPoint(e,t=0){this.getScene().getRenderId()==0&&this.computeWorldMatrix(!0);let i=this.getWorldMatrix();if(t==1){let r=$.Matrix[0];i.invertToRef(r),e=b.TransformCoordinates(e,r)}return this.setPivotMatrix(K.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){let e=b.Zero();return this.getPivotPointToRef(e),e}getPivotPointToRef(e){return e.x=-this._pivotMatrix.m[12],e.y=-this._pivotMatrix.m[13],e.z=-this._pivotMatrix.m[14],this}getAbsolutePivotPoint(){let e=b.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),b.TransformCoordinatesToRef(e,this.getWorldMatrix(),e),this}markAsDirty(e){if(this._isDirty)return this;if(this._children)for(let t of this._children)t.markAsDirty(e);return super.markAsDirty(e)}setParent(e,t=!1,i=!1){if(!e&&!this.parent)return this;let r=$.Quaternion[0],s=$.Vector3[0],a=$.Vector3[1],o=$.Matrix[1];K.IdentityToRef(o);let l=$.Matrix[0];this.computeWorldMatrix(!0);let c=this.rotationQuaternion;return c||(c=n._TmpRotation,Xe.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,c)),K.ComposeToRef(this.scaling,c,this.position,l),this.parent&&l.multiplyToRef(this.parent.computeWorldMatrix(!0),l),e&&(e.computeWorldMatrix(!0).invertToRef(o),l.multiplyToRef(o,l)),l.decompose(a,r,s,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(r):r.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(a),this.position.copyFrom(s),this.parent=e,i&&this.setPivotMatrix(K.Identity()),this}addChild(e,t=!1){return e.setParent(this,t),this}removeChild(e,t=!1){return e.parent!==this?this:(e.setParent(null,t),this)}get nonUniformScaling(){return this._nonUniformScaling}_updateNonUniformScalingState(e){return this._nonUniformScaling===e?!1:(this._nonUniformScaling=e,!0)}attachToBone(e,t){return this._currentParentWhenAttachingToBone=this.parent,this._transformToBoneReferal=t,this.parent=e,e.getSkeleton().prepare(!0),e.getFinalMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this}detachFromBone(e=!1){return this.parent?(this.parent.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this._transformToBoneReferal=null,e?this.parent=this._currentParentWhenAttachingToBone:this.parent=null,this):(e&&(this.parent=this._currentParentWhenAttachingToBone),this)}rotate(e,t,i){e.normalize(),this.rotationQuaternion||(this.rotationQuaternion=this.rotation.toQuaternion(),this.rotation.setAll(0));let r;if(!i||i===0)r=Xe.RotationAxisToRef(e,t,n._RotationAxisCache),this.rotationQuaternion.multiplyToRef(r,this.rotationQuaternion);else{if(this.parent){let s=this.parent.getWorldMatrix(),a=$.Matrix[0];s.invertToRef(a),e=b.TransformNormal(e,a),s.determinant()<0&&(t*=-1)}r=Xe.RotationAxisToRef(e,t,n._RotationAxisCache),r.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=Xe.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));let r=$.Vector3[0],s=$.Vector3[1],a=$.Vector3[2],o=$.Quaternion[0],l=$.Matrix[0],c=$.Matrix[1],f=$.Matrix[2],h=$.Matrix[3];return e.subtractToRef(this.position,r),K.TranslationToRef(r.x,r.y,r.z,l),K.TranslationToRef(-r.x,-r.y,-r.z,c),K.RotationAxisToRef(t,i,f),c.multiplyToRef(f,h),h.multiplyToRef(l,h),h.decompose(s,o,a),this.position.addInPlace(a),o.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){let r=e.scale(t);if(!i||i===0){let s=this.getPositionExpressedInLocalSpace().add(r);this.setPositionWithLocalVector(s)}else this.setAbsolutePosition(this.getAbsolutePosition().add(r));return this}addRotation(e,t,i){let r;this.rotationQuaternion?r=this.rotationQuaternion:(r=$.Quaternion[1],Xe.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,r));let s=$.Quaternion[0];return Xe.RotationYawPitchRollToRef(t,e,i,s),r.multiplyInPlace(s),this.rotationQuaternion||r.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==n.BILLBOARDMODE_NONE}computeWorldMatrix(e=!1,t=null){if(this._isWorldMatrixFrozen&&!this._isDirty)return this._worldMatrix;let i=this.getScene().getRenderId();if(!this._isDirty&&!e&&(this._currentRenderId===i||this.isSynchronized()))return this._currentRenderId=i,this._worldMatrix;t=t||this.getScene().activeCamera,this._updateCache();let r=this._cache;r.pivotMatrixUpdated=!1,r.billboardMode=this.billboardMode,r.infiniteDistance=this.infiniteDistance,r.parent=this._parentNode,this._currentRenderId=i,this._childUpdateId+=1,this._isDirty=!1,this._position._isDirty=!1,this._rotation._isDirty=!1,this._scaling._isDirty=!1;let s=this._getEffectiveParent(),a=n._TmpScaling,o=this._position;if(this._infiniteDistance&&!this.parent&&t){let f=t.getWorldMatrix().m;o=n._TmpTranslation,o.copyFromFloats(this._position.x+f[12],this._position.y+f[13],this._position.z+f[14])}a.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant);let l;if(this._rotationQuaternion?(this._rotationQuaternion._isDirty=!1,l=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion&&this.rotation.lengthSquared()&&(this._rotationQuaternion.multiplyInPlace(Xe.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))):(l=n._TmpRotation,Xe.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,l)),this._usePivotMatrix){let c=$.Matrix[1];K.ScalingToRef(a.x,a.y,a.z,c);let f=$.Matrix[0];l.toRotationMatrix(f),this._pivotMatrix.multiplyToRef(c,$.Matrix[4]),$.Matrix[4].multiplyToRef(f,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(o.x,o.y,o.z)}else K.ComposeToRef(a,l,o,this._localMatrix);if(s&&s.getWorldMatrix){if(e&&s.computeWorldMatrix(e),this.billboardMode){if(this._transformToBoneReferal){let d=this.parent;d.getSkeleton().prepare(),d.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),$.Matrix[7])}else $.Matrix[7].copyFrom(s.getWorldMatrix());let c=$.Vector3[5],f=$.Vector3[6],h=$.Quaternion[0];$.Matrix[7].decompose(f,h,c),K.ScalingToRef(f.x,f.y,f.z,$.Matrix[7]),$.Matrix[7].setTranslation(c),n.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(h,c),this._localMatrix.setTranslation(c)),this._localMatrix.multiplyToRef($.Matrix[7],this._worldMatrix)}else if(this._transformToBoneReferal){let c=this.parent;c.getSkeleton().prepare(),this._localMatrix.multiplyToRef(c.getFinalMatrix(),$.Matrix[6]),$.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)}else this._localMatrix.multiplyToRef(s.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(t&&this.billboardMode)if(r.useBillboardPosition){let c=$.Vector3[0];this._worldMatrix.getTranslationToRef(c);let f=t.globalPosition;this._worldMatrix.invertToRef($.Matrix[1]);let h=$.Vector3[1];b.TransformCoordinatesToRef(f,$.Matrix[1],h),h.normalize();let d=-Math.atan2(h.z,h.x)+Math.PI/2,u=Math.sqrt(h.x*h.x+h.z*h.z),m=-Math.atan2(h.y,u);if(Xe.RotationYawPitchRollToRef(d,m,0,$.Quaternion[0]),(this.billboardMode&n.BILLBOARDMODE_ALL)!==n.BILLBOARDMODE_ALL){let p=$.Vector3[1];$.Quaternion[0].toEulerAnglesToRef(p),(this.billboardMode&n.BILLBOARDMODE_X)!==n.BILLBOARDMODE_X&&(p.x=0),(this.billboardMode&n.BILLBOARDMODE_Y)!==n.BILLBOARDMODE_Y&&(p.y=0),(this.billboardMode&n.BILLBOARDMODE_Z)!==n.BILLBOARDMODE_Z&&(p.z=0),K.RotationYawPitchRollToRef(p.y,p.x,p.z,$.Matrix[0])}else K.FromQuaternionToRef($.Quaternion[0],$.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef($.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation($.Vector3[0])}else{let c=$.Vector3[0];this._worldMatrix.getTranslationToRef(c),$.Matrix[1].copyFrom(t.getViewMatrix());let f=this.getScene().useRightHandedSystem;if(f&&$.Matrix[1].multiplyToRef(n._TmpRHRestore,$.Matrix[1]),$.Matrix[1].setTranslationFromFloats(0,0,0),$.Matrix[1].invertToRef($.Matrix[0]),(this.billboardMode&n.BILLBOARDMODE_ALL)!==n.BILLBOARDMODE_ALL){$.Matrix[0].decompose(void 0,$.Quaternion[0],void 0);let h=$.Vector3[1];$.Quaternion[0].toEulerAnglesToRef(h),(this.billboardMode&n.BILLBOARDMODE_X)!==n.BILLBOARDMODE_X&&(h.x=0),(this.billboardMode&n.BILLBOARDMODE_Y)!==n.BILLBOARDMODE_Y&&(h.y=0),(this.billboardMode&n.BILLBOARDMODE_Z)!==n.BILLBOARDMODE_Z&&(h.z=0),f&&(h.y+=Math.PI),K.RotationYawPitchRollToRef(h.y,h.x,h.z,$.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef($.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation($.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):s&&s._nonUniformScaling?this._updateNonUniformScalingState(s._nonUniformScaling):this._updateNonUniformScalingState(!1),this._afterComputeWorldMatrix(),this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._isAbsoluteSynced=!1,this.onAfterWorldMatrixUpdateObservable.notifyObservers(this),this._poseMatrix||(this._poseMatrix=K.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){let t=this.getChildren();for(let i=0;inew n(e,this.getScene()),this);if(r.name=e,r.id=e,t&&(r.parent=t),!i){let s=this.getDescendants(!0);for(let a=0;anew n(e.name,t),e,t,i);if(e.localMatrix?r.setPreTransformMatrix(K.FromArray(e.localMatrix)):e.pivotMatrix&&r.setPivotMatrix(K.FromArray(e.pivotMatrix)),r.setEnabled(e.isEnabled),r._waitingParsedUniqueId=e.uniqueId,e.parentId!==void 0&&(r._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),e.freezeWorldMatrix&&(r._waitingFreezeWorldMatrix=e.freezeWorldMatrix),e.animations){for(let s=0;s(!t||t(r))&&r instanceof n),i}dispose(e,t=!1){if(this.getScene().stopAnimation(this),this.getScene().removeTransformNode(this),this._parentContainer){let i=this._parentContainer.transformNodes.indexOf(this);i>-1&&this._parentContainer.transformNodes.splice(i,1),this._parentContainer=null}if(this.onAfterWorldMatrixUpdateObservable.clear(),e){let i=this.getChildTransformNodes(!0);for(let r of i)r.parent=null,r.computeWorldMatrix(!0)}super.dispose(e,t)}normalizeToUnitCube(e=!0,t=!1,i){let r=null,s=null;t&&(this.rotationQuaternion?(s=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(r=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));let a=this.getHierarchyBoundingVectors(e,i),o=a.max.subtract(a.min),l=Math.max(o.x,o.y,o.z);if(l===0)return this;let c=1/l;return this.scaling.scaleInPlace(c),t&&(this.rotationQuaternion&&s?this.rotationQuaternion.copyFrom(s):this.rotation&&r&&this.rotation.copyFrom(r)),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}};ei.BILLBOARDMODE_NONE=0;ei.BILLBOARDMODE_X=1;ei.BILLBOARDMODE_Y=2;ei.BILLBOARDMODE_Z=4;ei.BILLBOARDMODE_ALL=7;ei.BILLBOARDMODE_USE_POSITION=128;ei.BillboardUseParentOrientation=!1;ei._TmpRotation=Xe.Zero();ei._TmpScaling=b.Zero();ei._TmpTranslation=b.Zero();ei._TmpRHRestore=K.Scaling(1,1,-1);ei._LookAtVectorCache=new b(0,0,0);ei._RotationAxisCache=new Xe;P([Hr("position")],ei.prototype,"_position",void 0);P([Hr("rotation")],ei.prototype,"_rotation",void 0);P([I2("rotationQuaternion")],ei.prototype,"_rotationQuaternion",void 0);P([Hr("scaling")],ei.prototype,"_scaling",void 0);P([w("billboardMode")],ei.prototype,"_billboardMode",void 0);P([w()],ei.prototype,"scalingDeterminant",void 0);P([w("infiniteDistance")],ei.prototype,"_infiniteDistance",void 0);P([w()],ei.prototype,"ignoreNonUniformScaling",void 0);P([w()],ei.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0)});var PA,lG=C(()=>{Ge();PA=class{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new b(0,0,0),this._diffPositionForCollisions=new b(0,0,0),this._collisionResponse=!0}}});function cG(n){return Math.floor(n/8)}function fG(n){return 1<{DA=class{constructor(e){this.size=e,this._byteArray=new Uint8Array(Math.ceil(this.size/8))}get(e){if(e>=this.size)throw new RangeError("Bit index out of range");let t=cG(e),i=fG(e);return(this._byteArray[t]&i)!==0}set(e,t){if(e>=this.size)throw new RangeError("Bit index out of range");let i=cG(e),r=fG(e);t?this._byteArray[i]|=r:this._byteArray[i]&=~r}}});var dG={};tt(dG,{OptimizeIndices:()=>gse});function gse(n){let e=[],t=n.length/3;for(let l=0;l{let c=[l];for(;c.length>0;){let f=c.pop();if(!r.get(f)){r.set(f,!0),s.push(e[f]);for(let h of e[f]){let d=i.get(h);if(!d)return;for(let u of d)r.get(u)||c.push(u)}}}};for(let l=0;l{hG()});function vse(n,e,t){let i;switch(e){case L.PositionKind:i=r=>r.getPositions();break;case L.NormalKind:i=r=>r.getNormals();break;case L.TangentKind:i=r=>r.getTangents();break;case L.UVKind:i=r=>r.getUVs();break;case L.UV2Kind:i=r=>r.getUV2s();break;case L.ColorKind:i=r=>r.getColors();break;default:return}for(let r=0;r0&&(K.FromFloat32ArrayToRefScaled(t,Math.floor(i[d+u]*16),m,c),l.addToSelf(c));if(s&&a)for(u=0;u<4;u++)m=a[d+u],m>0&&(K.FromFloat32ArrayToRefScaled(t,Math.floor(s[d+u]*16),m,c),l.addToSelf(c));f(n[h],n[h+1],n[h+2],l,o),o.toArray(n,h)}}var Sy,Ty,vr,_m=C(()=>{Gt();di();Ge();ki();dr();qh();Z_();mm();mf();lG();hn();MA();zt();Dn();zu();Hi();Vt();wr();Sy=class{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=b.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}},Ty=class{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new Sy,this._visibility=1,this._skeleton=null,this._layerMask=268435455,this._computeBonesUsingShaders=!0,this._isActive=!1,this._onlyForInstances=!1,this._isActiveIntermediate=!1,this._onlyForInstancesIntermediate=!1,this._actAsRegularMesh=!1,this._currentLOD=new Map,this._collisionRetryCount=3,this._morphTargetManager=null,this._renderingGroupId=0,this._bakedVertexAnimationManager=null,this._material=null,this._positions=null,this._pointerOverDisableMeshTesting=!1,this._meshCollisionData=new PA,this._enableDistantPicking=!1,this._rawBoundingInfo=null,this._sideOrientationHint=!1,this._wasActiveLastFrame=!1}},vr=class n extends ei{static get BILLBOARDMODE_NONE(){return ei.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return ei.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return ei.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return ei.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return ei.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return ei.BILLBOARDMODE_USE_POSITION}get facetNb(){return this._internalAbstractMeshDataInfo._facetData.facetNb}get partitioningSubdivisions(){return this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions}set partitioningSubdivisions(e){this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions=e}get partitioningBBoxRatio(){return this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio}set partitioningBBoxRatio(e){this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio=e}get mustDepthSortFacets(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSort}set mustDepthSortFacets(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSort=e}get facetDepthSortFrom(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom}set facetDepthSortFrom(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom=e}get collisionRetryCount(){return this._internalAbstractMeshDataInfo._collisionRetryCount}set collisionRetryCount(e){this._internalAbstractMeshDataInfo._collisionRetryCount=e}get isFacetDataEnabled(){return this._internalAbstractMeshDataInfo._facetData.facetDataEnabled}get morphTargetManager(){return this._internalAbstractMeshDataInfo._morphTargetManager}set morphTargetManager(e){this._internalAbstractMeshDataInfo._morphTargetManager!==e&&(this._internalAbstractMeshDataInfo._morphTargetManager=e,this._syncGeometryWithMorphTargetManager())}get bakedVertexAnimationManager(){return this._internalAbstractMeshDataInfo._bakedVertexAnimationManager}set bakedVertexAnimationManager(e){this._internalAbstractMeshDataInfo._bakedVertexAnimationManager!==e&&(this._internalAbstractMeshDataInfo._bakedVertexAnimationManager=e,this._markSubMeshesAsAttributesDirty())}_syncGeometryWithMorphTargetManager(){}_updateNonUniformScalingState(e){return super._updateNonUniformScalingState(e)?(this._markSubMeshesAsMiscDirty(),!0):!1}get rawBoundingInfo(){return this._internalAbstractMeshDataInfo._rawBoundingInfo}set rawBoundingInfo(e){this._internalAbstractMeshDataInfo._rawBoundingInfo=e}set onCollide(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver&&this.onCollideObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver=this.onCollideObservable.add(e)}set onCollisionPositionChange(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver&&this.onCollisionPositionChangeObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver=this.onCollisionPositionChangeObservable.add(e)}get visibility(){return this._internalAbstractMeshDataInfo._visibility}set visibility(e){if(this._internalAbstractMeshDataInfo._visibility===e)return;let t=this._internalAbstractMeshDataInfo._visibility;this._internalAbstractMeshDataInfo._visibility=e,(t===1&&e!==1||t!==1&&e===1)&&this._markSubMeshesAsDirty(i=>{i.markAsMiscDirty(),i.markAsPrePassDirty()})}get pointerOverDisableMeshTesting(){return this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting}set pointerOverDisableMeshTesting(e){this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting=e}get renderingGroupId(){return this._internalAbstractMeshDataInfo._renderingGroupId}set renderingGroupId(e){this._internalAbstractMeshDataInfo._renderingGroupId=e}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){this._setMaterial(e)}_setMaterial(e){this._internalAbstractMeshDataInfo._material!==e&&(this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),this._internalAbstractMeshDataInfo._material=e,e&&e.meshMap&&(e.meshMap[this.uniqueId]=this),this.onMaterialChangedObservable.hasObservers()&&this.onMaterialChangedObservable.notifyObservers(this),this.subMeshes&&(this.resetDrawCache(void 0,e==null),this._unBindEffect()))}getMaterialForRenderPass(e){var t;return(t=this._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:t[e]}setMaterialForRenderPass(e,t){var r;this.resetDrawCache(e),this._internalAbstractMeshDataInfo._materialForRenderPass||(this._internalAbstractMeshDataInfo._materialForRenderPass=[]);let i=this._internalAbstractMeshDataInfo._materialForRenderPass[e];(r=i==null?void 0:i.meshMap)!=null&&r[this.uniqueId]&&(i.meshMap[this.uniqueId]=void 0),this._internalAbstractMeshDataInfo._materialForRenderPass[e]=t,t&&t.meshMap&&(t.meshMap[this.uniqueId]=this)}get receiveShadows(){return this._internalAbstractMeshDataInfo._receiveShadows}set receiveShadows(e){this._internalAbstractMeshDataInfo._receiveShadows!==e&&(this._internalAbstractMeshDataInfo._receiveShadows=e,this._markSubMeshesAsLightDirty())}get hasVertexAlpha(){return this._internalAbstractMeshDataInfo._hasVertexAlpha}set hasVertexAlpha(e){this._internalAbstractMeshDataInfo._hasVertexAlpha!==e&&(this._internalAbstractMeshDataInfo._hasVertexAlpha=e,this._markSubMeshesAsAttributesDirty(),this._markSubMeshesAsMiscDirty())}get useVertexColors(){return this._internalAbstractMeshDataInfo._useVertexColors}set useVertexColors(e){this._internalAbstractMeshDataInfo._useVertexColors!==e&&(this._internalAbstractMeshDataInfo._useVertexColors=e,this._markSubMeshesAsAttributesDirty())}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get numBoneInfluencers(){return this._internalAbstractMeshDataInfo._numBoneInfluencers}set numBoneInfluencers(e){this._internalAbstractMeshDataInfo._numBoneInfluencers!==e&&(this._internalAbstractMeshDataInfo._numBoneInfluencers=e,this._markSubMeshesAsAttributesDirty())}get applyFog(){return this._internalAbstractMeshDataInfo._applyFog}set applyFog(e){this._internalAbstractMeshDataInfo._applyFog!==e&&(this._internalAbstractMeshDataInfo._applyFog=e,this._markSubMeshesAsMiscDirty())}get enableDistantPicking(){return this._internalAbstractMeshDataInfo._enableDistantPicking}set enableDistantPicking(e){this._internalAbstractMeshDataInfo._enableDistantPicking=e}get layerMask(){return this._internalAbstractMeshDataInfo._layerMask}set layerMask(e){e!==this._internalAbstractMeshDataInfo._layerMask&&(this._internalAbstractMeshDataInfo._layerMask=e,this._resyncLightSources())}get collisionMask(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask}set collisionMask(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask=isNaN(e)?-1:e}get collisionResponse(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse}set collisionResponse(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse=e}get collisionGroup(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup}set collisionGroup(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup=isNaN(e)?-1:e}get surroundingMeshes(){return this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes}set surroundingMeshes(e){this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes=e}get lightSources(){return this._lightSources}set skeleton(e){let t=this._internalAbstractMeshDataInfo._skeleton;t&&t.needInitialSkinMatrix&&t._unregisterMeshWithPoseMatrix(this),e&&e.needInitialSkinMatrix&&e._registerMeshWithPoseMatrix(this),this._internalAbstractMeshDataInfo._skeleton=e,this._internalAbstractMeshDataInfo._skeleton||(this._bonesTransformMatrices=null),this._markSubMeshesAsAttributesDirty()}get skeleton(){return this._internalAbstractMeshDataInfo._skeleton}constructor(e,t=null){switch(super(e,t,!1),this._internalAbstractMeshDataInfo=new Ty,this._waitingMaterialId=null,this._waitingMorphTargetManagerId=null,this._waitingSkeletonId=null,this._waitingSkeletonUniqueId=null,this.cullingStrategy=n.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new ie,this.onCollisionPositionChangeObservable=new ie,this.onMaterialChangedObservable=new ie,this.definedFacingForward=!0,this._occlusionQuery=null,this._renderingGroup=null,this.alphaIndex=Number.MAX_VALUE,this.isPickable=n.DefaultIsPickable,this.isNearPickable=!1,this.isNearGrabbable=!1,this.showSubMeshesBoundingBox=!1,this.isBlocker=!1,this.enablePointerMoveEvents=!1,this.outlineColor=ve.Red(),this.outlineWidth=.02,this.overlayColor=ve.Red(),this.overlayAlpha=.5,this.useOctreeForRenderingSelection=!0,this.useOctreeForPicking=!0,this.useOctreeForCollisions=!0,this.alwaysSelectAsActiveMesh=!1,this.doNotSyncBoundingInfo=!1,this.actionManager=null,this.ellipsoid=new b(.5,1,.5),this.ellipsoidOffset=new b(0,0,0),this.edgesWidth=1,this.edgesColor=new lt(1,0,0,1),this._edgesRenderer=null,this._masterMesh=null,this._boundingInfo=null,this._boundingInfoIsDirty=!0,this._renderId=0,this._intersectionsInProgress=new Array,this._unIndexed=!1,this._lightSources=new Array,this._waitingData={lods:null,actions:null,freezeWorldMatrix:null},this._bonesTransformMatrices=null,this._transformMatrixTexture=null,this.onRebuildObservable=new ie,this._onCollisionPositionChange=(i,r,s=null)=>{r.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>Me.CollisionsEpsilon&&this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),s&&this.onCollideObservable.notifyObservers(s),this.onCollisionPositionChangeObservable.notifyObservers(this.position)},t=this.getScene(),this.layerMask=t.defaultRenderableLayerMask,t.addMesh(this),this._resyncLightSources(),this._uniformBuffer=new hr(this.getScene().getEngine(),void 0,void 0,e,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),t.performancePriority){case 2:this.doNotSyncBoundingInfo=!0;case 1:this.alwaysSelectAsActiveMesh=!0,this.isPickable=!1;break}}_buildUniformLayout(){this._uniformBuffer.addUniform("world",16),this._uniformBuffer.addUniform("visibility",1),this._uniformBuffer.create()}transferToEffect(e){let t=this._uniformBuffer;t.updateMatrix("world",e),t.updateFloat("visibility",this._internalAbstractMeshDataInfo._visibility),t.update()}getMeshUniformBuffer(){return this._uniformBuffer}getClassName(){return"AbstractMesh"}toString(e){let t="Name: "+this.name+", isInstance: "+(this.getClassName()==="InstancedMesh"?"YES":"NO");t+=", # of submeshes: "+(this.subMeshes?this.subMeshes.length:0);let i=this._internalAbstractMeshDataInfo._skeleton;return i&&(t+=", skeleton: "+i.name),e&&(t+=", billboard mode: "+["NONE","X","Y",null,"Z",null,null,"ALL"][this.billboardMode],t+=", freeze wrld mat: "+(this._isWorldMatrixFrozen||this._waitingData.freezeWorldMatrix?"YES":"NO")),t}_getEffectiveParent(){return this._masterMesh&&this.billboardMode!==ei.BILLBOARDMODE_NONE?this._masterMesh:super._getEffectiveParent()}_getActionManagerForTrigger(e,t=!0){if(this.actionManager&&(t||this.actionManager.isRecursive))if(e){if(this.actionManager.hasSpecificTrigger(e))return this.actionManager}else return this.actionManager;return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_releaseRenderPassId(e){}_rebuild(e=!1){if(this.onRebuildObservable.notifyObservers(this),this._occlusionQuery!==null&&(this._occlusionQuery=null),!!this.subMeshes){for(let t of this.subMeshes)t._rebuild();this.resetDrawCache()}}_resyncLightSources(){this._lightSources.length=0;for(let e of this.getScene().lights)e.isEnabled()&&e.canAffectMesh(this)&&this._lightSources.push(e);this._markSubMeshesAsLightDirty()}_resyncLightSource(e){let t=e.isEnabled()&&e.canAffectMesh(this),i=this._lightSources.indexOf(e),r=!1;if(i===-1){if(!t)return;this._lightSources.push(e)}else{if(t)return;r=!0,this._lightSources.splice(i,1)}this._markSubMeshesAsLightDirty(r)}_unBindEffect(){for(let e of this.subMeshes)e.setEffect(null)}_removeLightSource(e,t){let i=this._lightSources.indexOf(e);i!==-1&&(this._lightSources.splice(i,1),this._markSubMeshesAsLightDirty(t))}_markSubMeshesAsDirty(e){if(this.subMeshes)for(let t of this.subMeshes)for(let i=0;it.markAsLightDirty(e))}_markSubMeshesAsAttributesDirty(){this._markSubMeshesAsDirty(e=>e.markAsAttributesDirty())}_markSubMeshesAsMiscDirty(){this._markSubMeshesAsDirty(e=>e.markAsMiscDirty())}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,super.markAsDirty(e),this._isDirty=!0,this}resetDrawCache(e,t=!1){if(this.subMeshes)for(let i of this.subMeshes)i.resetDrawCache(e,t)}get isBlocked(){return!1}getLOD(e){return this}getTotalVertices(){return 0}getTotalIndices(){return 0}getIndices(){return null}getVerticesData(e){return null}setVerticesData(e,t,i,r){return this}updateVerticesData(e,t,i,r){return this}setIndices(e,t){return this}isVerticesDataPresent(e){return!1}getBoundingInfo(){return this._masterMesh?this._masterMesh.getBoundingInfo():(this._boundingInfoIsDirty&&(this._boundingInfoIsDirty=!1,this._updateBoundingInfo()),this._boundingInfo)}getRawBoundingInfo(){var e;return(e=this.rawBoundingInfo)!=null?e:this.getBoundingInfo()}setBoundingInfo(e){return this._boundingInfo=e,this}get hasBoundingInfo(){return this._boundingInfo!==null}buildBoundingInfo(e,t,i){return this._boundingInfo=new un(e,t,i),this._boundingInfo}normalizeToUnitCube(e=!0,t=!1,i){return super.normalizeToUnitCube(e,t,i)}get useBones(){return this.skeleton&&this.getScene().skeletonsEnabled&&this.isVerticesDataPresent(L.MatricesIndicesKind)&&this.isVerticesDataPresent(L.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===ei.BILLBOARDMODE_NONE?this._masterMesh.getWorldMatrix():super.getWorldMatrix()}_getWorldMatrixDeterminant(){return this._masterMesh?this._masterMesh._getWorldMatrixDeterminant():super._getWorldMatrixDeterminant()}get isAnInstance(){return!1}get hasInstances(){return!1}get hasThinInstances(){return!1}movePOV(e,t,i){return this.position.addInPlace(this.calcMovePOV(e,t,i)),this}calcMovePOV(e,t,i){let r=new K;(this.rotationQuaternion?this.rotationQuaternion:Xe.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(r);let a=b.Zero(),o=this.definedFacingForward?-1:1;return b.TransformCoordinatesFromFloatsToRef(e*o,t,i*o,r,a),a}rotatePOV(e,t,i){return this.rotation.addInPlace(this.calcRotatePOV(e,t,i)),this}calcRotatePOV(e,t,i){let r=this.definedFacingForward?1:-1;return new b(e*r,t,i*r)}_refreshBoundingInfo(e,t){if(e){let i=IA(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new un(i.minimum,i.maximum)}if(this.subMeshes)for(let i=0;i{if(r){let o=r._vertexData||(r._vertexData={});return o[a]||this.copyVerticesData(a,o),o[a]}return this.getVerticesData(a)};if(t||(t=s(i)),!t)return null;if(r?(r._outputData?r._outputData.set(t):r._outputData=new Float32Array(t),t=r._outputData):(e.applyMorph&&this.morphTargetManager||e.applySkeleton&&this.skeleton)&&(t=t.slice()),e.applyMorph&&this.morphTargetManager&&vse(t,i,this.morphTargetManager),e.applySkeleton&&this.skeleton){let a=s(L.MatricesIndicesKind),o=s(L.MatricesWeightsKind);if(o&&a){let l=this.numBoneInfluencers>4,c=l?s(L.MatricesIndicesExtraKind):null,f=l?s(L.MatricesWeightsExtraKind):null,h=this.skeleton.getTransformMatrices(this);n._ApplySkeleton(t,i,h,a,o,c,f)}}if(e.updatePositionsArray!==!1&&i===L.PositionKind){let a=this._internalAbstractMeshDataInfo._positions||[],o=a.length;if(a.length=t.length/3,o1||!r.IsGlobal)&&r.updateBoundingInfo(e)}return this}_afterComputeWorldMatrix(){this.doNotSyncBoundingInfo||(this._boundingInfoIsDirty=!0)}isInFrustum(e){return this.getBoundingInfo().isInFrustum(e,this.cullingStrategy)}isCompletelyInFrustum(e){return this.getBoundingInfo().isCompletelyInFrustum(e)}intersectsMesh(e,t=!1,i){let r=this.getBoundingInfo(),s=e.getBoundingInfo();if(r.intersects(s,t))return!0;if(i){for(let a of this.getChildMeshes())if(a.intersectsMesh(e,t,!0))return!0}return!1}intersectsPoint(e){return this.getBoundingInfo().intersectsPoint(e)}get checkCollisions(){return this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions}set checkCollisions(e){this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions=e}get collider(){return this._internalAbstractMeshDataInfo._meshCollisionData._collider}moveWithCollisions(e,t=!0){this.getAbsolutePosition().addToRef(this.ellipsoidOffset,this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions);let r=this.getScene().collisionCoordinator;return this._internalAbstractMeshDataInfo._meshCollisionData._collider||(this._internalAbstractMeshDataInfo._meshCollisionData._collider=r.createCollider()),this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius=this.ellipsoid,r.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,e,this._internalAbstractMeshDataInfo._meshCollisionData._collider,this.collisionRetryCount,this,this._onCollisionPositionChange,this.uniqueId,t),this}_collideForSubMesh(e,t,i){var r;if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(t)){e._lastColliderTransformMatrix=t.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];let s=e.verticesStart,a=e.verticesStart+e.verticesCount;for(let o=s;o1&&!a._checkCollision(e)||this._collideForSubMesh(a,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;let t=$.Matrix[0],i=$.Matrix[1];return K.ScalingToRef(1/e._radius.x,1/e._radius.y,1/e._radius.z,t),this.worldMatrixFromCache.multiplyToRef(t,i),this._processCollisionsForSubMeshes(e,i),this}_generatePointsArray(){return!1}intersects(e,t,i,r=!1,s,a=!1){let o=new Jn,l=this.getClassName(),c=l==="InstancedLinesMesh"||l==="LinesMesh"||l==="GreasedLineMesh"?this.intersectionThreshold:0,f=this.getBoundingInfo();if(!this.subMeshes||!a&&(!e.intersectsSphere(f.boundingSphere,c)||!e.intersectsBox(f.boundingBox,c)))return o;if(r)return o.hit=!a,o.pickedMesh=a?null:this,o.distance=a?0:b.Distance(e.origin,f.boundingSphere.center),o.subMeshId=0,o;if(!this._generatePointsArray())return o;let h=null,d=this._scene.getIntersectingSubMeshCandidates(this,e),u=d.length,m=!1;for(let p=0;p1&&!a&&!_.canIntersects(e))continue;let g=_.intersects(e,this._positions,this.getIndices(),t,i);if(g&&(t||!h||g.distanceo!==this&&o.actionManager===this.actionManager)&&this.actionManager.dispose(),this.actionManager=null),this._internalAbstractMeshDataInfo._skeleton=null,this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null),i=0;i-1&&this._parentContainer.meshes.splice(o,1),this._parentContainer=null}if(t&&this.material&&(this.material.getClassName()==="MultiMaterial"?this.material.dispose(!1,!0,!0):this.material.dispose(!1,!0)),!e)for(i=0;i65535){l=!0;break}l?e.depthSortedIndices=new Uint32Array(i):e.depthSortedIndices=new Uint16Array(i)}if(e.facetDepthSortFunction=function(l,c){return c.sqDistance-l.sqDistance},!e.facetDepthSortFrom){let l=this.getScene().activeCamera;e.facetDepthSortFrom=l?l.position:b.Zero()}e.depthSortedFacets=[];for(let l=0;lNt?s.maximum.x-s.minimum.x:Nt,e.bbSize.y=s.maximum.y-s.minimum.y>Nt?s.maximum.y-s.minimum.y:Nt,e.bbSize.z=s.maximum.z-s.minimum.z>Nt?s.maximum.z-s.minimum.z:Nt;let a=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(a=a>e.bbSize.z?a:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/a),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/a),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/a),e.subDiv.X=e.subDiv.X<1?1:e.subDiv.X,e.subDiv.Y=e.subDiv.Y<1?1:e.subDiv.Y,e.subDiv.Z=e.subDiv.Z<1?1:e.subDiv.Z,e.facetParameters.facetNormals=this.getFacetLocalNormals(),e.facetParameters.facetPositions=this.getFacetLocalPositions(),e.facetParameters.facetPartitioning=this.getFacetLocalPartitioning(),e.facetParameters.bInfo=s,e.facetParameters.bbSize=e.bbSize,e.facetParameters.subDiv=e.subDiv,e.facetParameters.ratio=this.partitioningBBoxRatio,e.facetParameters.depthSort=e.facetDepthSort,e.facetDepthSort&&e.facetDepthSortEnabled&&(this.computeWorldMatrix(!0),this._worldMatrix.invertToRef(e.invertedMatrix),b.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,r&&Ce.ComputeNormals(t,i,r,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);let l=e.depthSortedIndices.length/3|0;for(let c=0;cs.subDiv.max||o<0||o>s.subDiv.max||l<0||l>s.subDiv.max?null:s.facetPartitioning[a+s.subDiv.max*o+s.subDiv.max*s.subDiv.max*l]}getClosestFacetAtCoordinates(e,t,i,r,s=!1,a=!0){let o=this.getWorldMatrix(),l=$.Matrix[5];o.invertToRef(l);let c=$.Vector3[8];b.TransformCoordinatesFromFloatsToRef(e,t,i,l,c);let f=this.getClosestFacetAtLocalCoordinates(c.x,c.y,c.z,r,s,a);return r&&b.TransformCoordinatesFromFloatsToRef(r.x,r.y,r.z,o,r),f}getClosestFacetAtLocalCoordinates(e,t,i,r,s=!1,a=!0){let o=null,l,c,f,h,d,u,m,p,_=this.getFacetLocalPositions(),g=this.getFacetLocalNormals(),v=this.getFacetsAtLocalCoordinates(e,t,i);if(!v)return null;let x=Number.MAX_VALUE,A,S,E,R;for(let I=0;I=0||s&&!a&&h<=0)&&(h=E.x*R.x+E.y*R.y+E.z*R.z,d=-(E.x*e+E.y*t+E.z*i-h)/(E.x*E.x+E.y*E.y+E.z*E.z),u=e+E.x*d,m=t+E.y*d,p=i+E.z*d,l=u-e,c=m-t,f=p-i,A=l*l+c*c+f*f,A(uG(),dG));return t(e),this.setIndices(e,this.getTotalVertices()),this}alignWithNormal(e,t){t||(t=Es.Y);let i=$.Vector3[0],r=$.Vector3[1];return b.CrossToRef(t,e,r),b.CrossToRef(e,r,i),this.rotationQuaternion?Xe.RotationQuaternionFromAxisToRef(i,e,r,this.rotationQuaternion):b.RotationFromAxisToRef(i,e,r,this.rotation),this}_checkOcclusionQuery(e=!1){return!1}disableEdgesRendering(){throw qe("EdgesRenderer")}enableEdgesRendering(e,t,i){throw qe("EdgesRenderer")}getConnectedParticleSystems(){return this._scene.particleSystems.filter(e=>e.emitter===this)}};vr.OCCLUSION_TYPE_NONE=0;vr.OCCLUSION_TYPE_OPTIMISTIC=1;vr.OCCLUSION_TYPE_STRICT=2;vr.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0;vr.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1;vr.CULLINGSTRATEGY_STANDARD=0;vr.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1;vr.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2;vr.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3;vr.DefaultIsPickable=!0;P([Ss.filter((...n)=>!Array.isArray(n[0])&&!Array.isArray(n[3])&&!Array.isArray(n[4])&&!Array.isArray(n[5])&&!Array.isArray(n[6]))],vr,"_ApplySkeleton",null);Ft("BABYLON.AbstractMesh",vr)});var Nn,mG=C(()=>{Gt();Tr();Vt();Nn=class{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.funcRef=1,this.funcMask=255,this.func=519,this.opStencilFail=7680,this.opDepthFail=7680,this.opStencilDepthPass=7681,this.backFunc=519,this.backOpStencilFail=7680,this.backOpDepthFail=7680,this.backOpStencilDepthPass=7681}get func(){return this._func}set func(e){this._func=e}get backFunc(){return this._backFunc}set backFunc(e){this._backFunc=e}get funcRef(){return this._funcRef}set funcRef(e){this._funcRef=e}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask=e}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail=e}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail=e}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass=e}get backOpStencilFail(){return this._backOpStencilFail}set backOpStencilFail(e){this._backOpStencilFail=e}get backOpDepthFail(){return this._backOpDepthFail}set backOpDepthFail(e){this._backOpDepthFail=e}get backOpStencilDepthPass(){return this._backOpStencilDepthPass}set backOpStencilDepthPass(e){this._backOpStencilDepthPass=e}get mask(){return this._mask}set mask(e){this._mask=e}get enabled(){return this._enabled}set enabled(e){this._enabled=e}getClassName(){return"MaterialStencilState"}copyTo(e){it.Clone(()=>e,this)}serialize(){return it.Serialize(this)}parse(e,t,i){it.Parse(()=>this,e,t,i)}};P([w()],Nn.prototype,"func",null);P([w()],Nn.prototype,"backFunc",null);P([w()],Nn.prototype,"funcRef",null);P([w()],Nn.prototype,"funcMask",null);P([w()],Nn.prototype,"opStencilFail",null);P([w()],Nn.prototype,"opDepthFail",null);P([w()],Nn.prototype,"opStencilDepthPass",null);P([w()],Nn.prototype,"backOpStencilFail",null);P([w()],Nn.prototype,"backOpDepthFail",null);P([w()],Nn.prototype,"backOpStencilDepthPass",null);P([w()],Nn.prototype,"mask",null);P([w()],Nn.prototype,"enabled",null)});function wn(n){n.indexOf("vClipPlane")===-1&&n.push("vClipPlane"),n.indexOf("vClipPlane2")===-1&&n.push("vClipPlane2"),n.indexOf("vClipPlane3")===-1&&n.push("vClipPlane3"),n.indexOf("vClipPlane4")===-1&&n.push("vClipPlane4"),n.indexOf("vClipPlane5")===-1&&n.push("vClipPlane5"),n.indexOf("vClipPlane6")===-1&&n.push("vClipPlane6")}function al(n,e,t){var c,f,h,d,u,m;let i=!!((c=n.clipPlane)!=null?c:e.clipPlane),r=!!((f=n.clipPlane2)!=null?f:e.clipPlane2),s=!!((h=n.clipPlane3)!=null?h:e.clipPlane3),a=!!((d=n.clipPlane4)!=null?d:e.clipPlane4),o=!!((u=n.clipPlane5)!=null?u:e.clipPlane5),l=!!((m=n.clipPlane6)!=null?m:e.clipPlane6);i&&t.push("#define CLIPPLANE"),r&&t.push("#define CLIPPLANE2"),s&&t.push("#define CLIPPLANE3"),a&&t.push("#define CLIPPLANE4"),o&&t.push("#define CLIPPLANE5"),l&&t.push("#define CLIPPLANE6")}function pG(n,e,t){var f,h,d,u,m,p;let i=!1,r=!!((f=n.clipPlane)!=null?f:e.clipPlane),s=!!((h=n.clipPlane2)!=null?h:e.clipPlane2),a=!!((d=n.clipPlane3)!=null?d:e.clipPlane3),o=!!((u=n.clipPlane4)!=null?u:e.clipPlane4),l=!!((m=n.clipPlane5)!=null?m:e.clipPlane5),c=!!((p=n.clipPlane6)!=null?p:e.clipPlane6);return t.CLIPPLANE!==r&&(t.CLIPPLANE=r,i=!0),t.CLIPPLANE2!==s&&(t.CLIPPLANE2=s,i=!0),t.CLIPPLANE3!==a&&(t.CLIPPLANE3=a,i=!0),t.CLIPPLANE4!==o&&(t.CLIPPLANE4=o,i=!0),t.CLIPPLANE5!==l&&(t.CLIPPLANE5=l,i=!0),t.CLIPPLANE6!==c&&(t.CLIPPLANE6=c,i=!0),i}function Fn(n,e,t){var r,s,a,o,l,c;let i=(r=e.clipPlane)!=null?r:t.clipPlane;gm(n,"vClipPlane",i),i=(s=e.clipPlane2)!=null?s:t.clipPlane2,gm(n,"vClipPlane2",i),i=(a=e.clipPlane3)!=null?a:t.clipPlane3,gm(n,"vClipPlane3",i),i=(o=e.clipPlane4)!=null?o:t.clipPlane4,gm(n,"vClipPlane4",i),i=(l=e.clipPlane5)!=null?l:t.clipPlane5,gm(n,"vClipPlane5",i),i=(c=e.clipPlane6)!=null?c:t.clipPlane6,gm(n,"vClipPlane6",i)}function gm(n,e,t){var i;if(t){let r=((i=ba.getScene())==null?void 0:i.floatingOriginOffset)||b.ZeroReadOnly;n.setFloat4(e,t.normal.x,t.normal.y,t.normal.z,t.d+b.Dot(t.normal,r))}}var ol=C(()=>{J_();Ge()});var ce,Pa=C(()=>{wr();ce=class{static get DiffuseTextureEnabled(){return this._DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){this._DiffuseTextureEnabled!==e&&(this._DiffuseTextureEnabled=e,Me.MarkAllMaterialsAsDirty(1))}static get BaseWeightTextureEnabled(){return this._BaseWeightTextureEnabled}static set BaseWeightTextureEnabled(e){this._BaseWeightTextureEnabled!==e&&(this._BaseWeightTextureEnabled=e,Me.MarkAllMaterialsAsDirty(1))}static get BaseDiffuseRoughnessTextureEnabled(){return this._BaseDiffuseRoughnessTextureEnabled}static set BaseDiffuseRoughnessTextureEnabled(e){this._BaseDiffuseRoughnessTextureEnabled!==e&&(this._BaseDiffuseRoughnessTextureEnabled=e,Me.MarkAllMaterialsAsDirty(1))}static get DetailTextureEnabled(){return this._DetailTextureEnabled}static set DetailTextureEnabled(e){this._DetailTextureEnabled!==e&&(this._DetailTextureEnabled=e,Me.MarkAllMaterialsAsDirty(1))}static get DecalMapEnabled(){return this._DecalMapEnabled}static set DecalMapEnabled(e){this._DecalMapEnabled!==e&&(this._DecalMapEnabled=e,Me.MarkAllMaterialsAsDirty(1))}static get AmbientTextureEnabled(){return this._AmbientTextureEnabled}static set AmbientTextureEnabled(e){this._AmbientTextureEnabled!==e&&(this._AmbientTextureEnabled=e,Me.MarkAllMaterialsAsDirty(1))}static get OpacityTextureEnabled(){return this._OpacityTextureEnabled}static set OpacityTextureEnabled(e){this._OpacityTextureEnabled!==e&&(this._OpacityTextureEnabled=e,Me.MarkAllMaterialsAsDirty(1))}static get ReflectionTextureEnabled(){return this._ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){this._ReflectionTextureEnabled!==e&&(this._ReflectionTextureEnabled=e,Me.MarkAllMaterialsAsDirty(1))}static get EmissiveTextureEnabled(){return this._EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){this._EmissiveTextureEnabled!==e&&(this._EmissiveTextureEnabled=e,Me.MarkAllMaterialsAsDirty(1))}static get SpecularTextureEnabled(){return this._SpecularTextureEnabled}static set SpecularTextureEnabled(e){this._SpecularTextureEnabled!==e&&(this._SpecularTextureEnabled=e,Me.MarkAllMaterialsAsDirty(1))}static get BumpTextureEnabled(){return this._BumpTextureEnabled}static set BumpTextureEnabled(e){this._BumpTextureEnabled!==e&&(this._BumpTextureEnabled=e,Me.MarkAllMaterialsAsDirty(1))}static get LightmapTextureEnabled(){return this._LightmapTextureEnabled}static set LightmapTextureEnabled(e){this._LightmapTextureEnabled!==e&&(this._LightmapTextureEnabled=e,Me.MarkAllMaterialsAsDirty(1))}static get RefractionTextureEnabled(){return this._RefractionTextureEnabled}static set RefractionTextureEnabled(e){this._RefractionTextureEnabled!==e&&(this._RefractionTextureEnabled=e,Me.MarkAllMaterialsAsDirty(1))}static get ColorGradingTextureEnabled(){return this._ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){this._ColorGradingTextureEnabled!==e&&(this._ColorGradingTextureEnabled=e,Me.MarkAllMaterialsAsDirty(1))}static get FresnelEnabled(){return this._FresnelEnabled}static set FresnelEnabled(e){this._FresnelEnabled!==e&&(this._FresnelEnabled=e,Me.MarkAllMaterialsAsDirty(4))}static get ClearCoatTextureEnabled(){return this._ClearCoatTextureEnabled}static set ClearCoatTextureEnabled(e){this._ClearCoatTextureEnabled!==e&&(this._ClearCoatTextureEnabled=e,Me.MarkAllMaterialsAsDirty(1))}static get ClearCoatBumpTextureEnabled(){return this._ClearCoatBumpTextureEnabled}static set ClearCoatBumpTextureEnabled(e){this._ClearCoatBumpTextureEnabled!==e&&(this._ClearCoatBumpTextureEnabled=e,Me.MarkAllMaterialsAsDirty(1))}static get ClearCoatTintTextureEnabled(){return this._ClearCoatTintTextureEnabled}static set ClearCoatTintTextureEnabled(e){this._ClearCoatTintTextureEnabled!==e&&(this._ClearCoatTintTextureEnabled=e,Me.MarkAllMaterialsAsDirty(1))}static get SheenTextureEnabled(){return this._SheenTextureEnabled}static set SheenTextureEnabled(e){this._SheenTextureEnabled!==e&&(this._SheenTextureEnabled=e,Me.MarkAllMaterialsAsDirty(1))}static get AnisotropicTextureEnabled(){return this._AnisotropicTextureEnabled}static set AnisotropicTextureEnabled(e){this._AnisotropicTextureEnabled!==e&&(this._AnisotropicTextureEnabled=e,Me.MarkAllMaterialsAsDirty(1))}static get ThicknessTextureEnabled(){return this._ThicknessTextureEnabled}static set ThicknessTextureEnabled(e){this._ThicknessTextureEnabled!==e&&(this._ThicknessTextureEnabled=e,Me.MarkAllMaterialsAsDirty(1))}static get RefractionIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set RefractionIntensityTextureEnabled(e){this._RefractionIntensityTextureEnabled!==e&&(this._RefractionIntensityTextureEnabled=e,Me.MarkAllMaterialsAsDirty(1))}static get TranslucencyIntensityTextureEnabled(){return this._TranslucencyIntensityTextureEnabled}static set TranslucencyIntensityTextureEnabled(e){this._TranslucencyIntensityTextureEnabled!==e&&(this._TranslucencyIntensityTextureEnabled=e,Me.MarkAllMaterialsAsDirty(1))}static get TranslucencyColorTextureEnabled(){return this._TranslucencyColorTextureEnabled}static set TranslucencyColorTextureEnabled(e){this._TranslucencyColorTextureEnabled!==e&&(this._TranslucencyColorTextureEnabled=e,Me.MarkAllMaterialsAsDirty(1))}static get IridescenceTextureEnabled(){return this._IridescenceTextureEnabled}static set IridescenceTextureEnabled(e){this._IridescenceTextureEnabled!==e&&(this._IridescenceTextureEnabled=e,Me.MarkAllMaterialsAsDirty(1))}};ce._DiffuseTextureEnabled=!0;ce._BaseWeightTextureEnabled=!0;ce._BaseDiffuseRoughnessTextureEnabled=!0;ce._DetailTextureEnabled=!0;ce._DecalMapEnabled=!0;ce._AmbientTextureEnabled=!0;ce._OpacityTextureEnabled=!0;ce._ReflectionTextureEnabled=!0;ce._EmissiveTextureEnabled=!0;ce._SpecularTextureEnabled=!0;ce._BumpTextureEnabled=!0;ce._LightmapTextureEnabled=!0;ce._RefractionTextureEnabled=!0;ce._ColorGradingTextureEnabled=!0;ce._FresnelEnabled=!0;ce._ClearCoatTextureEnabled=!0;ce._ClearCoatBumpTextureEnabled=!0;ce._ClearCoatTintTextureEnabled=!0;ce._SheenTextureEnabled=!0;ce._AnisotropicTextureEnabled=!0;ce._ThicknessTextureEnabled=!0;ce._RefractionIntensityTextureEnabled=!0;ce._TranslucencyIntensityTextureEnabled=!0;ce._TranslucencyColorTextureEnabled=!0;ce._IridescenceTextureEnabled=!0});function Sf(n,e,t){if(!n||n.LOGARITHMICDEPTH||n.indexOf&&n.indexOf("LOGARITHMICDEPTH")>=0){let i=t.activeCamera;i.mode===1&&te.Error("Logarithmic depth is not compatible with orthographic cameras!",20),e.setFloat("logarithmicDepthConstant",2/(Math.log(i.maxZ+1)/Math.LN2))}}var _G=C(()=>{Pt()});function Tf(n,e,t,i=!1){t&&n.fogEnabled&&(!e||e.applyFog)&&n.fogMode!==0&&(t.setFloat4("vFogInfos",n.fogMode,n.fogStart,n.fogEnd,n.fogDensity),i?(n.fogColor.toLinearSpaceToRef(gG,n.getEngine().useExactSrgbConversions),t.setColor3("vFogColor",gG)):t.setColor3("vFogColor",n.fogColor))}function ll(n,e,t,i,r,s,a,o,l,c){let f=n.numMaxInfluencers||n.numInfluencers;return f<=0?0:(e.push("#define MORPHTARGETS"),n.hasPositions&&e.push("#define MORPHTARGETTEXTURE_HASPOSITIONS"),n.hasNormals&&e.push("#define MORPHTARGETTEXTURE_HASNORMALS"),n.hasTangents&&e.push("#define MORPHTARGETTEXTURE_HASTANGENTS"),n.hasUVs&&e.push("#define MORPHTARGETTEXTURE_HASUVS"),n.hasUV2s&&e.push("#define MORPHTARGETTEXTURE_HASUV2S"),n.hasColors&&e.push("#define MORPHTARGETTEXTURE_HASCOLORS"),n.supportsPositions&&r&&e.push("#define MORPHTARGETS_POSITION"),n.supportsNormals&&s&&e.push("#define MORPHTARGETS_NORMAL"),n.supportsTangents&&a&&e.push("#define MORPHTARGETS_TANGENT"),n.supportsUVs&&o&&e.push("#define MORPHTARGETS_UV"),n.supportsUV2s&&l&&e.push("#define MORPHTARGETS_UV2"),n.supportsColors&&c&&e.push("#define MORPHTARGETS_COLOR"),e.push("#define NUM_MORPH_INFLUENCERS "+f),n.isUsingTextureForTargets&&e.push("#define MORPHTARGETS_TEXTURE"),Zh.NUM_MORPH_INFLUENCERS=f,Zh.NORMAL=s,Zh.TANGENT=a,Zh.UV=o,Zh.UV2=l,Zh.COLOR=c,Qh(t,i,Zh,r),f)}function Qh(n,e,t,i=!0){let r=t.NUM_MORPH_INFLUENCERS;if(r>0&&Oe.LastCreatedEngine){let s=Oe.LastCreatedEngine.getCaps().maxVertexAttribs,a=e.morphTargetManager;if(a!=null&&a.isUsingTextureForTargets)return;let o=a&&a.supportsPositions&&i,l=a&&a.supportsNormals&&t.NORMAL,c=a&&a.supportsTangents&&t.TANGENT,f=a&&a.supportsUVs&&t.UV1,h=a&&a.supportsUV2s&&t.UV2,d=a&&a.supportsColors&&t.VERTEXCOLOR;for(let u=0;us&&te.Error("Cannot add more vertex attributes for mesh "+e.name)}}function mo(n,e=!1){n.push("world0"),n.push("world1"),n.push("world2"),n.push("world3"),e&&(n.push("previousWorld0"),n.push("previousWorld1"),n.push("previousWorld2"),n.push("previousWorld3"))}function Bn(n,e){let t=n.morphTargetManager;!n||!t||e.setFloatArray("morphTargetInfluences",t.influences)}function Af(n,e){e.bindToEffect(n,"Scene")}function vm(n,e,t,i,r=null,s=!1,a=!1,o=!1,l=!1,c=!1,f=!1,h=0){if(n.texturesEnabled&&r&&ce.ReflectionTextureEnabled){if(t.updateMatrix("reflectionMatrix",r.getReflectionTextureMatrix()),t.updateFloat2("vReflectionInfos",r.level*n.iblIntensity,h),o&&r.boundingBoxSize){let d=r;t.updateVector3("vReflectionPosition",d.boundingBoxPosition),t.updateVector3("vReflectionSize",d.boundingBoxSize)}if(s){let d=r.getSize().width;t.updateFloat2("vReflectionFilteringInfo",d,Math.log2(d))}if(c&&!e.USEIRRADIANCEMAP){let d=r.sphericalPolynomial;if(e.USESPHERICALFROMREFLECTIONMAP&&d)if(e.SPHERICAL_HARMONICS){let u=d.preScaledHarmonics;t.updateVector3("vSphericalL00",u.l00),t.updateVector3("vSphericalL1_1",u.l1_1),t.updateVector3("vSphericalL10",u.l10),t.updateVector3("vSphericalL11",u.l11),t.updateVector3("vSphericalL2_2",u.l2_2),t.updateVector3("vSphericalL2_1",u.l2_1),t.updateVector3("vSphericalL20",u.l20),t.updateVector3("vSphericalL21",u.l21),t.updateVector3("vSphericalL22",u.l22)}else t.updateFloat3("vSphericalX",d.x.x,d.x.y,d.x.z),t.updateFloat3("vSphericalY",d.y.x,d.y.y,d.y.z),t.updateFloat3("vSphericalZ",d.z.x,d.z.y,d.z.z),t.updateFloat3("vSphericalXX_ZZ",d.xx.x-d.zz.x,d.xx.y-d.zz.y,d.xx.z-d.zz.z),t.updateFloat3("vSphericalYY_ZZ",d.yy.x-d.zz.x,d.yy.y-d.zz.y,d.yy.z-d.zz.z),t.updateFloat3("vSphericalZZ",d.zz.x,d.zz.y,d.zz.z),t.updateFloat3("vSphericalXY",d.xy.x,d.xy.y,d.xy.z),t.updateFloat3("vSphericalYZ",d.yz.x,d.yz.y,d.yz.z),t.updateFloat3("vSphericalZX",d.zx.x,d.zx.y,d.zx.z)}else l&&e.USEIRRADIANCEMAP&&e.USE_IRRADIANCE_DOMINANT_DIRECTION&&r.irradianceTexture&&t.updateVector3("vReflectionDominantDirection",r.irradianceTexture._dominantDirection);a&&t.updateFloat3("vReflectionMicrosurfaceInfos",r.getSize().width,r.lodGenerationScale,r.lodGenerationOffset)}f&&t.updateColor3("vReflectionColor",i)}function LA(n,e,t,i=null,r=!1){if(i&&ce.ReflectionTextureEnabled){e.LODBASEDMICROSFURACE?t.setTexture("reflectionSampler",i):(t.setTexture("reflectionSampler",i._lodTextureMid||i),t.setTexture("reflectionSamplerLow",i._lodTextureLow||i),t.setTexture("reflectionSamplerHigh",i._lodTextureHigh||i)),e.USEIRRADIANCEMAP&&t.setTexture("irradianceSampler",i.irradianceTexture);let s=n.iblCdfGenerator;r&&s&&t.setTexture("icdfSampler",s.getIcdfTexture())}}function ni(n,e,t){e._needUVs=!0,e[t]=!0,n.optimizeUVAllocation&&n.getTextureMatrix().isIdentityAs3x2()?(e[t+"DIRECTUV"]=n.coordinatesIndex+1,e["MAINUV"+(n.coordinatesIndex+1)]=!0):e[t+"DIRECTUV"]=0}function si(n,e,t){let i=n.getTextureMatrix();e.updateMatrix(t+"Matrix",i)}function Em(n,e,t){t.BAKED_VERTEX_ANIMATION_TEXTURE&&t.INSTANCES&&n.push("bakedVertexAnimationSettingsInstanced")}function Sse(n,e){return e.set(n),e}function Rs(n,e,t){if(!(!e||!n)&&(n.computeBonesUsingShaders&&e._bonesComputationForcedToCPU&&(n.computeBonesUsingShaders=!1),n.useBones&&n.computeBonesUsingShaders&&n.skeleton)){let i=n.skeleton;if(i.isUsingTextureForMatrices&&e.getUniformIndex("boneTextureInfo")>-1){let r=i.getTransformMatrixTexture(n);e.setTexture("boneSampler",r),e.setFloat2("boneTextureInfo",i._textureWidth,i._textureHeight)}else{let r=i.getTransformMatrices(n);r&&(e.setMatrices("mBones",r),t&&n.getScene().prePassRenderer&&n.getScene().prePassRenderer.getIndex(2)&&(t.previousBones[n.uniqueId]||(t.previousBones[n.uniqueId]=r.slice()),e.setMatrices("mPreviousBones",t.previousBones[n.uniqueId]),Sse(r,t.previousBones[n.uniqueId])))}}}function Tse(n,e,t,i,r,s=!0){n._bindLight(e,t,i,r,s)}function Sm(n,e,t,i,r=4){let s=Math.min(e.lightSources.length,r);for(let a=0;a0&&(i.addCPUSkinningFallback(0,e),n.push("matricesIndices"),n.push("matricesWeights"),t.NUM_BONE_INFLUENCERS>4&&(n.push("matricesIndicesExtra"),n.push("matricesWeightsExtra")))}function Am(n,e){(e.INSTANCES||e.THIN_INSTANCES)&&mo(n,!!e.PREPASS_VELOCITY),e.INSTANCESCOLOR&&n.push("instanceColor")}function xm(n,e,t=4,i=0){let r=0;for(let s=0;s0&&(r=i+s,e.addFallback(r,"LIGHT"+s)),n.SHADOWS||(n["SHADOW"+s]&&e.addFallback(i,"SHADOW"+s),n["SHADOWPCF"+s]&&e.addFallback(i,"SHADOWPCF"+s),n["SHADOWPCSS"+s]&&e.addFallback(i,"SHADOWPCSS"+s),n["SHADOWPOISSON"+s]&&e.addFallback(i,"SHADOWPOISSON"+s),n["SHADOWESM"+s]&&e.addFallback(i,"SHADOWESM"+s),n["SHADOWCLOSEESM"+s]&&e.addFallback(i,"SHADOWCLOSEESM"+s));return r}function Ase(n,e){return e.fogEnabled&&n.applyFog&&e.fogMode!==0}function Rm(n,e,t,i,r,s,a,o=!1,l=!1,c,f){var h;if(a._areMiscDirty){a.LOGARITHMICDEPTH=t,a.POINTSIZE=i,a.FOG=r&&Ase(n,e),a.NONUNIFORMSCALING=n.nonUniformScaling,a.ALPHATEST=s,a.DECAL_AFTER_DETAIL=o,a.USE_VERTEX_PULLING=l,a.RIGHT_HANDED=e.useRightHandedSystem;let d=(h=c==null?void 0:c.geometry)==null?void 0:h.getIndexBuffer(),u=c?c.isUnIndexed:!1;a.VERTEX_PULLING_USE_INDEX_BUFFER=!!d&&!u,a.VERTEX_PULLING_INDEX_BUFFER_32BITS=d&&!u?d.is32Bits:!1,a.VERTEXOUTPUT_INVARIANT=!!f}}function bm(n,e,t,i=!1){if(!n.lightsEnabled||i)return!0;let r=e.lightSources,s=Math.min(r.length,t);for(let a=0;a0?(t.NUM_SAMPLES=""+r,a._features.needTypeSuffixInShaderConstants&&(t.NUM_SAMPLES=t.NUM_SAMPLES+"u"),t.REALTIME_FILTERING=!0,n.iblCdfGenerator&&(t.IBL_CDF_FILTERING=!0)):t.REALTIME_FILTERING=!1,t.INVERTCUBICMAP=e.coordinatesMode===ge.INVCUBIC_MODE,t.REFLECTIONMAP_3D=e.isCube,t.REFLECTIONMAP_OPPOSITEZ=t.REFLECTIONMAP_3D&&n.useRightHandedSystem?!e.invertZ:e.invertZ,t.REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,e.coordinatesMode){case ge.EXPLICIT_MODE:t.REFLECTIONMAP_EXPLICIT=!0;break;case ge.PLANAR_MODE:t.REFLECTIONMAP_PLANAR=!0;break;case ge.PROJECTION_MODE:t.REFLECTIONMAP_PROJECTION=!0;break;case ge.SKYBOX_MODE:t.REFLECTIONMAP_SKYBOX=!0;break;case ge.SPHERICAL_MODE:t.REFLECTIONMAP_SPHERICAL=!0;break;case ge.EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case ge.FIXED_EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case ge.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case ge.CUBIC_MODE:case ge.INVCUBIC_MODE:default:t.REFLECTIONMAP_CUBIC=!0,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!!e.boundingBoxSize;break}e.coordinatesMode!==ge.SKYBOX_MODE&&(e.irradianceTexture?(t.USEIRRADIANCEMAP=!0,t.USESPHERICALFROMREFLECTIONMAP=!1,t.USESPHERICALINVERTEX=!1,e.irradianceTexture._dominantDirection?t.USE_IRRADIANCE_DOMINANT_DIRECTION=!0:t.USE_IRRADIANCE_DOMINANT_DIRECTION=!1):e.isCube&&(t.USESPHERICALFROMREFLECTIONMAP=!0,t.USEIRRADIANCEMAP=!1,t.USE_IRRADIANCE_DOMINANT_DIRECTION=!1,t.USESPHERICALINVERTEX=s))}else t.REFLECTION=!1,t.REFLECTIONMAP_3D=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_CUBIC=!1,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,t.INVERTCUBICMAP=!1,t.USESPHERICALFROMREFLECTIONMAP=!1,t.USEIRRADIANCEMAP=!1,t.USE_IRRADIANCE_DOMINANT_DIRECTION=!1,t.USESPHERICALINVERTEX=!1,t.REFLECTIONMAP_OPPOSITEZ=!1,t.LODINREFLECTIONALPHA=!1,t.GAMMAREFLECTION=!1,t.RGBDREFLECTION=!1,t.LINEARSPECULARREFLECTION=!1;return!0}function xse(n,e,t,i,r,s,a){var o;switch(a.needNormals=!0,r["LIGHT"+i]===void 0&&(a.needRebuild=!0),r["LIGHT"+i]=!0,r["SPOTLIGHT"+i]=!1,r["HEMILIGHT"+i]=!1,r["POINTLIGHT"+i]=!1,r["DIRLIGHT"+i]=!1,r["AREALIGHT"+i]=!1,r["CLUSTLIGHT"+i]=!1,t.prepareLightSpecificDefines(r,i),r["LIGHT_FALLOFF_PHYSICAL"+i]=!1,r["LIGHT_FALLOFF_GLTF"+i]=!1,r["LIGHT_FALLOFF_STANDARD"+i]=!1,t.falloffType){case Yt.FALLOFF_GLTF:r["LIGHT_FALLOFF_GLTF"+i]=!0;break;case Yt.FALLOFF_PHYSICAL:r["LIGHT_FALLOFF_PHYSICAL"+i]=!0;break;case Yt.FALLOFF_STANDARD:r["LIGHT_FALLOFF_STANDARD"+i]=!0;break}if(s&&!t.specular.equalsFloats(0,0,0)&&(a.specularEnabled=!0),r["SHADOW"+i]=!1,r["SHADOWCSM"+i]=!1,r["SHADOWCSMDEBUG"+i]=!1,r["SHADOWCSMNUM_CASCADES"+i]=!1,r["SHADOWCSMUSESHADOWMAXZ"+i]=!1,r["SHADOWCSMNOBLEND"+i]=!1,r["SHADOWCSM_RIGHTHANDED"+i]=!1,r["SHADOWPCF"+i]=!1,r["SHADOWPCSS"+i]=!1,r["SHADOWPOISSON"+i]=!1,r["SHADOWESM"+i]=!1,r["SHADOWCLOSEESM"+i]=!1,r["SHADOWCUBE"+i]=!1,r["SHADOWLOWQUALITY"+i]=!1,r["SHADOWMEDIUMQUALITY"+i]=!1,e&&e.receiveShadows&&n.shadowsEnabled&&t.shadowEnabled){let l=(o=t.getShadowGenerator(n.activeCamera))!=null?o:t.getShadowGenerator();if(l){let c=l.getShadowMap();c&&c.renderList&&c.renderList.length>0&&(a.shadowEnabled=!0,l.prepareDefines(r,i))}}t.lightmapMode!=Yt.LIGHTMAP_DEFAULT?(a.lightmapMode=!0,r["LIGHTMAPEXCLUDED"+i]=!0,r["LIGHTMAPNOSPECULAR"+i]=t.lightmapMode==Yt.LIGHTMAP_SHADOWSONLY):(r["LIGHTMAPEXCLUDED"+i]=!1,r["LIGHTMAPNOSPECULAR"+i]=!1)}function Mm(n,e,t,i,r,s=null,a=!1){let o=Mse(n,i);s!==!1&&(o=pG(t,n,i)),i.DEPTHPREPASS!==!e.getColorWrite()&&(i.DEPTHPREPASS=!i.DEPTHPREPASS,o=!0),i.INSTANCES!==r&&(i.INSTANCES=r,o=!0),i.THIN_INSTANCES!==a&&(i.THIN_INSTANCES=a,o=!0),o&&i.markAsUnprocessed()}function Rse(n,e){if(n.useBones&&n.computeBonesUsingShaders&&n.skeleton){e.NUM_BONE_INFLUENCERS=n.numBoneInfluencers;let t=e.BONETEXTURE!==void 0;if(n.skeleton.isUsingTextureForMatrices&&t)e.BONETEXTURE=!0;else{e.BonesPerMesh=n.skeleton.bones.length+1,e.BONETEXTURE=t?!1:void 0;let i=n.getScene().prePassRenderer;if(i&&i.enabled){let r=i.excludedSkinnedMesh.indexOf(n)===-1;e.BONES_VELOCITY_ENABLED=r}}}else e.NUM_BONE_INFLUENCERS=0,e.BonesPerMesh=0,e.BONETEXTURE!==void 0&&(e.BONETEXTURE=!1)}function bse(n,e){let t=n.morphTargetManager;t?(e.MORPHTARGETS_UV=t.supportsUVs&&e.UV1,e.MORPHTARGETS_UV2=t.supportsUV2s&&e.UV2,e.MORPHTARGETS_TANGENT=t.supportsTangents&&e.TANGENT,e.MORPHTARGETS_NORMAL=t.supportsNormals&&e.NORMAL,e.MORPHTARGETS_POSITION=t.supportsPositions,e.MORPHTARGETS_COLOR=t.supportsColors,e.MORPHTARGETTEXTURE_HASUVS=t.hasUVs,e.MORPHTARGETTEXTURE_HASUV2S=t.hasUV2s,e.MORPHTARGETTEXTURE_HASTANGENTS=t.hasTangents,e.MORPHTARGETTEXTURE_HASNORMALS=t.hasNormals,e.MORPHTARGETTEXTURE_HASPOSITIONS=t.hasPositions,e.MORPHTARGETTEXTURE_HASCOLORS=t.hasColors,e.NUM_MORPH_INFLUENCERS=t.numMaxInfluencers||t.numInfluencers,e.MORPHTARGETS=e.NUM_MORPH_INFLUENCERS>0,e.MORPHTARGETS_TEXTURE=t.isUsingTextureForTargets):(e.MORPHTARGETS_UV=!1,e.MORPHTARGETS_UV2=!1,e.MORPHTARGETS_TANGENT=!1,e.MORPHTARGETS_NORMAL=!1,e.MORPHTARGETS_POSITION=!1,e.MORPHTARGETS_COLOR=!1,e.MORPHTARGETTEXTURE_HASUVS=!1,e.MORPHTARGETTEXTURE_HASUV2S=!1,e.MORPHTARGETTEXTURE_HASTANGENTS=!1,e.MORPHTARGETTEXTURE_HASNORMALS=!1,e.MORPHTARGETTEXTURE_HASPOSITIONS=!1,e.MORPHTARGETTEXTURE_HAS_COLORS=!1,e.MORPHTARGETS=!1,e.NUM_MORPH_INFLUENCERS=0)}function Ise(n,e){let t=n.bakedVertexAnimationManager;e.BAKED_VERTEX_ANIMATION_TEXTURE=!!(t&&t.isEnabled)}function Cm(n,e,t,i,r=!1,s=!0,a=!0){if(!e._areAttributesDirty&&e._needNormals===e._normals&&e._needUVs===e._uvs)return!1;e._normals=e._needNormals,e._uvs=e._needUVs,e.NORMAL=e._needNormals&&n.isVerticesDataPresent("normal"),e._needNormals&&n.isVerticesDataPresent("tangent")&&(e.TANGENT=!0);for(let o=1;o<=6;++o)e["UV"+o]=e._needUVs?n.isVerticesDataPresent(`uv${o===1?"":o}`):!1;if(t){let o=n.useVertexColors&&n.isVerticesDataPresent("color");e.VERTEXCOLOR=o,e.VERTEXALPHA=n.hasVertexAlpha&&o&&s}return n.isVerticesDataPresent("instanceColor")&&(n.hasInstances||n.hasThinInstances)&&(e.INSTANCESCOLOR=!0),i&&Rse(n,e),r&&bse(n,e),a&&Ise(n,e),!0}function ym(n,e){if(n.activeCamera){let t=e.MULTIVIEW;e.MULTIVIEW=n.activeCamera.outputRenderTarget!==null&&n.activeCamera.outputRenderTarget.getViewCount()>1,e.MULTIVIEW!=t&&e.markAsUnprocessed()}}function Pm(n,e,t){let i=e.ORDER_INDEPENDENT_TRANSPARENCY,r=e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;e.ORDER_INDEPENDENT_TRANSPARENCY=n.useOrderIndependentTransparency&&t,e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!n.getEngine().getCaps().textureFloatLinearFiltering,(i!==e.ORDER_INDEPENDENT_TRANSPARENCY||r!==e.ORDER_INDEPENDENT_TRANSPARENCY_16BITS)&&e.markAsUnprocessed()}function Dm(n,e,t){let i=e.PREPASS;if(!e._arePrePassDirty)return;let r=[{type:1,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:9,define:"PREPASS_LOCAL_POSITION",index:"PREPASS_LOCAL_POSITION_INDEX"},{type:2,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:11,define:"PREPASS_VELOCITY_LINEAR",index:"PREPASS_VELOCITY_LINEAR_INDEX"},{type:3,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:0,define:"PREPASS_IRRADIANCE_LEGACY",index:"PREPASS_IRRADIANCE_LEGACY_INDEX"},{type:7,define:"PREPASS_ALBEDO_SQRT",index:"PREPASS_ALBEDO_SQRT_INDEX"},{type:5,define:"PREPASS_DEPTH",index:"PREPASS_DEPTH_INDEX"},{type:10,define:"PREPASS_SCREENSPACE_DEPTH",index:"PREPASS_SCREENSPACE_DEPTH_INDEX"},{type:6,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"},{type:8,define:"PREPASS_WORLD_NORMAL",index:"PREPASS_WORLD_NORMAL_INDEX"},{type:14,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"}];if(n.prePassRenderer&&n.prePassRenderer.enabled&&t){e.PREPASS=!0,e.SCENE_MRT_COUNT=n.prePassRenderer.mrtCount,e.PREPASS_NORMAL_WORLDSPACE=n.prePassRenderer.generateNormalsInWorldSpace,e.PREPASS_COLOR=!0,e.PREPASS_COLOR_INDEX=0;for(let s=0;s{Pt();Di();z_();ol();Pa();Fr();_G();gG={r:0,g:0,b:0},Zh={NUM_MORPH_INFLUENCERS:0,NORMAL:!1,TANGENT:!1,UV:!1,UV2:!1,COLOR:!1}});var Ee,Vn=C(()=>{Gt();Vt();Ii();di();Di();hg();mf();Pt();qu();Gh();mG();Un();Tr();RM();Ee=class n{get useVertexPulling(){return this._useVertexPulling}set useVertexPulling(e){this._useVertexPulling!==e&&(this._useVertexPulling=e,this.markAsDirty(n.MiscDirtyFlag))}get _supportGlowLayer(){return!1}set _glowModeEnabled(e){}get shaderLanguage(){return this._shaderLanguage}get canRenderToMRT(){return!1}set alpha(e){if(this._alpha===e)return;let t=this._alpha;this._alpha=e,(t===1||e===1)&&this.markAsDirty(n.MiscDirtyFlag+n.PrePassDirtyFlag)}get alpha(){return this._alpha}set backFaceCulling(e){this._backFaceCulling!==e&&(this._backFaceCulling=e,this.markAsDirty(n.TextureDirtyFlag))}get backFaceCulling(){return this._backFaceCulling}set cullBackFaces(e){this._cullBackFaces!==e&&(this._cullBackFaces=e,this.markAsDirty(n.TextureDirtyFlag))}get cullBackFaces(){return this._cullBackFaces}get blockDirtyMechanism(){return this._blockDirtyMechanism}set blockDirtyMechanism(e){this._blockDirtyMechanism!==e&&(this._blockDirtyMechanism=e,e||this.markDirty())}atomicMaterialsUpdate(e){this.blockDirtyMechanism=!0;try{e(this)}finally{this.blockDirtyMechanism=!1}}get hasRenderTargetTextures(){return this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._eventInfo.hasRenderTargetTextures}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new ie),this._onBindObservable}set onBind(e){this._onBindObserver&&this.onBindObservable.remove(this._onBindObserver),this._onBindObserver=this.onBindObservable.add(e)}get onUnBindObservable(){return this._onUnBindObservable||(this._onUnBindObservable=new ie),this._onUnBindObservable}get onEffectCreatedObservable(){return this._onEffectCreatedObservable||(this._onEffectCreatedObservable=new ie),this._onEffectCreatedObservable}set alphaMode(e){this._alphaMode[0]!==e&&(this._alphaMode[0]=e,this.markAsDirty(n.TextureDirtyFlag))}get alphaMode(){return this._alphaMode[0]}get alphaModes(){return this._alphaMode}setAlphaMode(e,t=0){this._alphaMode[t]!==e&&(this._alphaMode[t]=e,this.markAsDirty(n.TextureDirtyFlag))}set needDepthPrePass(e){this._needDepthPrePass!==e&&(this._needDepthPrePass=e,this._needDepthPrePass&&(this.checkReadyOnEveryCall=!0))}get needDepthPrePass(){return this._needDepthPrePass}get isPrePassCapable(){return!1}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this.markAsDirty(n.MiscDirtyFlag))}get fogEnabled(){return this._fogEnabled}get wireframe(){switch(this._fillMode){case n.WireFrameFillMode:case n.LineListDrawMode:case n.LineLoopDrawMode:case n.LineStripDrawMode:return!0}return this._scene.forceWireframe}set wireframe(e){this.fillMode=e?n.WireFrameFillMode:n.TriangleFillMode}get pointsCloud(){switch(this._fillMode){case n.PointFillMode:case n.PointListDrawMode:return!0}return this._scene.forcePointsCloud}set pointsCloud(e){this.fillMode=e?n.PointFillMode:n.TriangleFillMode}get fillMode(){return this._fillMode}set fillMode(e){this._fillMode!==e&&(this._fillMode=e,this.markAsDirty(n.MiscDirtyFlag))}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){let t=this.getScene().getEngine().getCaps().fragmentDepthSupported;e&&!t&&te.Warn("Logarithmic depth has been requested for a material on a device that doesn't support it."),this._useLogarithmicDepth=e&&t,this._markAllSubMeshesAsMiscDirty()}get isVertexOutputInvariant(){return this._isVertexOutputInvariant}set isVertexOutputInvariant(e){this._isVertexOutputInvariant!==e&&(this._isVertexOutputInvariant=e,this._markAllSubMeshesAsMiscDirty())}_getDrawWrapper(){return this._drawWrapper}_setDrawWrapper(e){this._drawWrapper=e}constructor(e,t,i,r=!1){this.shadowDepthWrapper=null,this.allowShaderHotSwapping=!0,this._shaderLanguage=0,this._forceGLSL=!1,this._useVertexPulling=!1,this.metadata=null,this.reservedDataStore=null,this.checkReadyOnEveryCall=!1,this.checkReadyOnlyOnce=!1,this.state="",this._alpha=1,this._backFaceCulling=!0,this._cullBackFaces=!0,this._blockDirtyMechanism=!1,this.sideOrientation=null,this.onCompiled=null,this.onError=null,this.getRenderTargetTextures=null,this.doNotSerialize=!1,this._storeEffectOnSubMeshes=!1,this.animations=null,this.onDisposeObservable=new ie,this._onDisposeObserver=null,this._onUnBindObservable=null,this._onBindObserver=null,this._alphaMode=[2],this._needDepthPrePass=!1,this.disableDepthWrite=!1,this.disableColorWrite=!1,this.forceDepthWrite=!1,this.depthFunction=0,this.separateCullingPass=!1,this._fogEnabled=!0,this.pointSize=1,this.zOffset=0,this.zOffsetUnits=0,this.stencil=new Nn,this._isVertexOutputInvariant=n.ForceVertexOutputInvariant,this._useUBO=!1,this._fillMode=n.TriangleFillMode,this._cachedDepthWriteState=!1,this._cachedColorWriteState=!1,this._cachedDepthFunctionState=0,this._indexInSceneMaterialArray=-1,this.meshMap=null,this._parentContainer=null,this._uniformBufferLayoutBuilt=!1,this._eventInfo={},this._callbackPluginEventGeneric=()=>{},this._callbackPluginEventIsReadyForSubMesh=()=>{},this._callbackPluginEventPrepareDefines=()=>{},this._callbackPluginEventPrepareDefinesBeforeAttributes=()=>{},this._callbackPluginEventHardBindForSubMesh=()=>{},this._callbackPluginEventBindForSubMesh=()=>{},this._callbackPluginEventHasRenderTargetTextures=()=>{},this._callbackPluginEventFillRenderTargetTextures=()=>{},this._transparencyMode=null,this.name=e;let s=t||Oe.LastCreatedScene;s&&(this._scene=s,this._dirtyCallbacks={},this._forceGLSL=r,this._dirtyCallbacks[1]=this._markAllSubMeshesAsTexturesDirty.bind(this),this._dirtyCallbacks[2]=this._markAllSubMeshesAsLightsDirty.bind(this),this._dirtyCallbacks[4]=this._markAllSubMeshesAsFresnelDirty.bind(this),this._dirtyCallbacks[8]=this._markAllSubMeshesAsAttributesDirty.bind(this),this._dirtyCallbacks[16]=this._markAllSubMeshesAsMiscDirty.bind(this),this._dirtyCallbacks[32]=this._markAllSubMeshesAsPrePassDirty.bind(this),this._dirtyCallbacks[127]=this._markAllSubMeshesAsAllDirty.bind(this),this.id=e||_e.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new $n(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._uniformBuffer=new hr(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,this._createUniformBuffer(),i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),n.OnEventObservable.notifyObservers(this,1))}_createUniformBuffer(){var t;let e=this.getScene().getEngine();(t=this._uniformBuffer)==null||t.dispose(),e.isWebGPU&&!this._forceGLSL?(this._uniformBuffer=new hr(e,void 0,void 0,this.name,!0),this._shaderLanguage=1):this._uniformBuffer=new hr(this._scene.getEngine(),void 0,void 0,this.name),this._uniformBufferLayoutBuilt=!1}toString(e){return"Name: "+this.name}getClassName(){return"Material"}get _isMaterial(){return!0}get isFrozen(){return this.checkReadyOnlyOnce}freeze(){this.markDirty(),this.checkReadyOnlyOnce=!0}unfreeze(){this.markDirty(),this.checkReadyOnlyOnce=!1}isReady(e,t){return!0}isReadyForSubMesh(e,t,i){let r=t.materialDefines;return r?(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=r,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),this._eventInfo.isReadyForSubMesh):!1}getEffect(){return this._drawWrapper.effect}getScene(){return this._scene}_getEffectiveOrientation(e){return this.sideOrientation!==null?this.sideOrientation:e.sideOrientation}get transparencyMode(){return this._transparencyMode}set transparencyMode(e){this._transparencyMode!==e&&(this._transparencyMode=e,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _hasTransparencyMode(){return this._transparencyMode!=null}get _transparencyModeIsBlend(){return this._transparencyMode===n.MATERIAL_ALPHABLEND||this._transparencyMode===n.MATERIAL_ALPHATESTANDBLEND}get _transparencyModeIsTest(){return this._transparencyMode===n.MATERIAL_ALPHATEST||this._transparencyMode===n.MATERIAL_ALPHATESTANDBLEND}get _disableAlphaBlending(){return this._transparencyMode===n.MATERIAL_OPAQUE||this._transparencyMode===n.MATERIAL_ALPHATEST}needAlphaBlending(){return this._hasTransparencyMode?this._transparencyModeIsBlend:this._disableAlphaBlending?!1:this.alpha<1}needAlphaBlendingForMesh(e){return this._hasTransparencyMode?this._transparencyModeIsBlend:e.visibility<1?!0:this._disableAlphaBlending?!1:e.hasVertexAlpha||this.needAlphaBlending()}needAlphaTesting(){return this._hasTransparencyMode?this._transparencyModeIsTest:!1}needAlphaTestingForMesh(e){return this._hasTransparencyMode?this._transparencyModeIsTest:!this.needAlphaBlendingForMesh(e)&&this.needAlphaTesting()}getAlphaTestTexture(){return null}markDirty(e=!1){let t=this.getScene().meshes;for(let i of t)if(i.subMeshes){for(let r of i.subMeshes)if(r.getMaterial()===this)for(let s of r._drawWrappers)s&&this._materialContext===s.materialContext&&(s._wasPreviouslyReady=!1,s._wasPreviouslyUsingInstances=null,s._forceRebindOnNextCall=e)}e&&this.markAsDirty(n.AllDirtyFlag)}_preBind(e,t=null){let i=this._scene.getEngine(),s=(t==null?this.sideOrientation:t)===n.ClockWiseSideOrientation,a=e||this._getDrawWrapper();return IT(a)&&a.materialContext&&(a.materialContext.useVertexPulling=this.useVertexPulling),i.enableEffect(a),i.setState(this.backFaceCulling,this.zOffset,!1,s,this._scene._mirroredCameraPosition?!this.cullBackFaces:this.cullBackFaces,this.stencil,this.zOffsetUnits),s}bind(e,t){}buildUniformLayout(){let e=this._uniformBuffer;this._eventInfo.ubo=e,this._callbackPluginEventGeneric(8,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0}bindForSubMesh(e,t,i){let r=i._drawWrapper;this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),r._forceRebindOnNextCall=!1}bindOnlyWorldMatrix(e){}bindView(e){this._useUBO?this._needToBindSceneUbo=!0:e.setMatrix("view",this.getScene().getViewMatrix())}bindViewProjection(e){this._useUBO?this._needToBindSceneUbo=!0:(e.setMatrix("viewProjection",this.getScene().getTransformMatrix()),e.setMatrix("projection",this.getScene().getProjectionMatrix()),e.setMatrix("inverseProjection",this.getScene().getInverseProjectionMatrix()))}bindEyePosition(e,t){this._useUBO?this._needToBindSceneUbo=!0:this._scene.bindEyePosition(e,t)}_afterBind(e,t=null,i){if(this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,Af(t,this.getScene().getSceneUniformBuffer()),this._scene.finalizeSceneUbo()),e?this._scene._cachedVisibility=e.visibility:this._scene._cachedVisibility=1,this._onBindObservable&&e&&this._onBindObservable.notifyObservers(e),this.disableDepthWrite){let r=this._scene.getEngine();this._cachedDepthWriteState=r.getDepthWrite(),r.setDepthWrite(!1)}if(this.disableColorWrite){let r=this._scene.getEngine();this._cachedColorWriteState=r.getColorWrite(),r.setColorWrite(!1)}if(this.depthFunction!==0){let r=this._scene.getEngine();this._cachedDepthFunctionState=r.getDepthFunction()||0,r.setDepthFunction(this.depthFunction)}}unbind(){this._scene.getSceneUniformBuffer().unbindEffect(),this._onUnBindObservable&&this._onUnBindObservable.notifyObservers(this),this.depthFunction!==0&&this._scene.getEngine().setDepthFunction(this._cachedDepthFunctionState),this.disableDepthWrite&&this._scene.getEngine().setDepthWrite(this._cachedDepthWriteState),this.disableColorWrite&&this._scene.getEngine().setColorWrite(this._cachedColorWriteState)}getAnimatables(){return this._eventInfo.animatables=[],this._callbackPluginEventGeneric(256,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(512,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(1024,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}_clonePlugins(e,t){let i={};if(this._serializePlugins(i),n._ParsePlugins(i,e,this._scene,t),this.pluginManager)for(let r of this.pluginManager._plugins){let s=e.pluginManager.getPlugin(r.name);s&&r.copyTo(s)}}getBindedMeshes(){if(this.meshMap){let e=[];for(let t in this.meshMap){let i=this.meshMap[t];i&&e.push(i)}return e}else return this._scene.meshes.filter(t=>t.material===this)}forceCompilation(e,t,i,r){let s={clipPlane:!1,useInstances:!1,...i},a=this.getScene(),o=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;let l=()=>{if(!this._scene||!this._scene.getEngine())return;let c=a.clipPlane;if(s.clipPlane&&(a.clipPlane=new to(0,0,0,1)),this._storeEffectOnSubMeshes){let f=!0,h=null;if(e.subMeshes){let d=new xs(0,0,0,0,0,e,void 0,!1,!1);d.materialDefines&&(d.materialDefines._renderId=-1),this.isReadyForSubMesh(e,d,s.useInstances)||(d.effect&&d.effect.getCompilationError()&&d.effect.allFallbacksProcessed()?h=d.effect.getCompilationError():(f=!1,setTimeout(l,16)))}f&&(this.allowShaderHotSwapping=o,h&&r&&r(h),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=o,t&&t(this)):setTimeout(l,16);s.clipPlane&&(a.clipPlane=c)};l()}async forceCompilationAsync(e,t){return await new Promise((i,r)=>{this.forceCompilation(e,()=>{i()},t,s=>{r(s)})})}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(n._DirtyCallbackArray.length=0,e&n.ImageProcessingDirtyFlag&&n._DirtyCallbackArray.push(n._ImageProcessingDirtyCallBack),e&n.TextureDirtyFlag&&n._DirtyCallbackArray.push(n._TextureDirtyCallBack),e&n.LightDirtyFlag&&n._DirtyCallbackArray.push(n._LightsDirtyCallBack),e&n.FresnelDirtyFlag&&n._DirtyCallbackArray.push(n._FresnelDirtyCallBack),e&n.AttributesDirtyFlag&&n._DirtyCallbackArray.push(n._AttributeDirtyCallBack),e&n.MiscDirtyFlag&&n._DirtyCallbackArray.push(n._MiscDirtyCallBack),e&n.PrePassDirtyFlag&&n._DirtyCallbackArray.push(n._PrePassDirtyCallBack),n._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(n._RunDirtyCallBacks),this.getScene().resetCachedMaterial())}resetDrawCache(){let e=this.getScene().meshes;for(let t of e)if(t.subMeshes)for(let i of t.subMeshes)i.getMaterial()===this&&i.resetDrawCache()}_markAllSubMeshesAsDirty(e){let t=this.getScene();if(t.blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;let i=t.meshes;for(let r of i)if(r.subMeshes){for(let s of r.subMeshes)if((s.getMaterial()||(t._hasDefaultMaterial?t.defaultMaterial:null))===this)for(let o of s._drawWrappers)!o||!o.defines||!o.defines.markAllAsDirty||this._materialContext===o.materialContext&&e(o.defines)}}_markScenePrePassDirty(){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;let e=this.getScene().enablePrePassRenderer();e&&e.markAsDirty()}_markAllSubMeshesAsAllDirty(){this._markAllSubMeshesAsDirty(n._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(n._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(n._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(n._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(n._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(n._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(n._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(n._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(n._PrePassDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(n._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(this._scene.performancePriority!==0){this.checkReadyOnlyOnce=!0;let e=this._scene.onScenePerformancePriorityChangedObservable.addOnce(()=>{this.checkReadyOnlyOnce=!1});this.onDisposeObservable.add(()=>{this._scene.onScenePerformancePriorityChangedObservable.remove(e)})}}setPrePassRenderer(e){return!1}dispose(e,t,i){let r=this.getScene();if(r.stopAnimation(this),r.freeProcessedMaterials(),r.removeMaterial(this),this._eventInfo.forceDisposeTextures=t,this._callbackPluginEventGeneric(2,this._eventInfo),this._parentContainer){let s=this._parentContainer.materials.indexOf(this);s>-1&&this._parentContainer.materials.splice(s,1),this._parentContainer=null}if(i!==!0)if(this.meshMap)for(let s in this.meshMap){let a=this.meshMap[s];this._disposeMeshResources(a)}else{let s=r.meshes;for(let a of s)this._disposeMeshResources(a)}this._uniformBuffer.dispose(),this._drawWrapper.effect&&(this._storeEffectOnSubMeshes||this._drawWrapper.effect.dispose(),this._drawWrapper.effect=null),this.metadata=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._onBindObservable&&this._onBindObservable.clear(),this._onUnBindObservable&&this._onUnBindObservable.clear(),this._onEffectCreatedObservable&&this._onEffectCreatedObservable.clear(),this._eventInfo&&(this._eventInfo={})}_disposeMeshResources(e){var r;if(!e)return;let t=e.geometry,i=e._internalAbstractMeshDataInfo._materialForRenderPass;if(this._storeEffectOnSubMeshes){if(e.subMeshes&&i)for(let s of e.subMeshes){let a=s._drawWrappers;for(let o=0;on.markAllAsDirty();Ee._ImageProcessingDirtyCallBack=n=>n.markAsImageProcessingDirty();Ee._TextureDirtyCallBack=n=>n.markAsTexturesDirty();Ee._FresnelDirtyCallBack=n=>n.markAsFresnelDirty();Ee._MiscDirtyCallBack=n=>n.markAsMiscDirty();Ee._PrePassDirtyCallBack=n=>n.markAsPrePassDirty();Ee._LightsDirtyCallBack=n=>n.markAsLightDirty();Ee._AttributeDirtyCallBack=n=>n.markAsAttributesDirty();Ee._FresnelAndMiscDirtyCallBack=n=>{Ee._FresnelDirtyCallBack(n),Ee._MiscDirtyCallBack(n)};Ee._TextureAndMiscDirtyCallBack=n=>{Ee._TextureDirtyCallBack(n),Ee._MiscDirtyCallBack(n)};Ee._DirtyCallbackArray=[];Ee._RunDirtyCallBacks=n=>{for(let e of Ee._DirtyCallbackArray)e(n)};P([w()],Ee.prototype,"id",void 0);P([w()],Ee.prototype,"uniqueId",void 0);P([w()],Ee.prototype,"name",void 0);P([w()],Ee.prototype,"metadata",void 0);P([w()],Ee.prototype,"checkReadyOnEveryCall",void 0);P([w()],Ee.prototype,"checkReadyOnlyOnce",void 0);P([w()],Ee.prototype,"state",void 0);P([w("alpha")],Ee.prototype,"_alpha",void 0);P([w("backFaceCulling")],Ee.prototype,"_backFaceCulling",void 0);P([w("cullBackFaces")],Ee.prototype,"_cullBackFaces",void 0);P([w()],Ee.prototype,"sideOrientation",void 0);P([w()],Ee.prototype,"_alphaMode",void 0);P([w()],Ee.prototype,"_needDepthPrePass",void 0);P([w()],Ee.prototype,"disableDepthWrite",void 0);P([w()],Ee.prototype,"disableColorWrite",void 0);P([w()],Ee.prototype,"forceDepthWrite",void 0);P([w()],Ee.prototype,"depthFunction",void 0);P([w()],Ee.prototype,"separateCullingPass",void 0);P([w("fogEnabled")],Ee.prototype,"_fogEnabled",void 0);P([w()],Ee.prototype,"pointSize",void 0);P([w()],Ee.prototype,"zOffset",void 0);P([w()],Ee.prototype,"zOffsetUnits",void 0);P([w()],Ee.prototype,"pointsCloud",null);P([w()],Ee.prototype,"fillMode",null);P([w()],Ee.prototype,"useLogarithmicDepth",null);P([w()],Ee.prototype,"_isVertexOutputInvariant",void 0);P([w()],Ee.prototype,"transparencyMode",null)});var Nm,vG=C(()=>{Vn();df();Hi();Nm=class n extends Ee{get subMaterials(){return this._subMaterials}set subMaterials(e){this._subMaterials=e,this._hookArray(e)}getChildren(){return this.subMaterials}constructor(e,t){super(e,t,!0),this._waitingSubMaterialsUniqueIds=[],this.getScene().addMultiMaterial(this),this.subMaterials=[],this._storeEffectOnSubMeshes=!0}_hookArray(e){let t=e.push;e.push=(...r)=>{let s=t.apply(e,r);return this._markAllSubMeshesAsTexturesDirty(),s};let i=e.splice;e.splice=(r,s)=>{let a=i.call(e,r,s!=null?s:e.length);return this._markAllSubMeshesAsTexturesDirty(),a}}getSubMaterial(e){return e<0||e>=this.subMaterials.length?this.getScene().defaultMaterial:this.subMaterials[e]}getActiveTextures(){return super.getActiveTextures().concat(...this.subMaterials.map(e=>e?e.getActiveTextures():[]))}hasTexture(e){var t;if(super.hasTexture(e))return!0;for(let i=0;i=0&&r.multiMaterials.splice(s,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){let i=new n(e.name,t);if(i.id=e.id,i._loadedUniqueId=e.uniqueId,Zt&&Zt.AddTagsTo(i,e.tags),e.materialsUniqueIds)i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds;else for(let r of e.materials)i.subMaterials.push(t.getLastMaterialById(r));return i}};Ft("BABYLON.MultiMaterial",Nm)});var OA,EG=C(()=>{OA=class{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}});var wm,NA,Ay,wA,xy,Ry,cl,q,Mi=C(()=>{di();Ii();W_();df();py();sl();Ge();zt();js();ki();dr();yA();_m();hg();Vn();vG();CA();Tr();Pt();Hi();hn();am();EG();wm=class{},NA=class{constructor(){this.batchCache=new wA(this),this.batchCacheReplacementModeInFrozenMode=new wA(this),this.instancesBufferSize=512*4}},Ay=class{constructor(){this.renderPasses={}}},wA=class{constructor(e){this.parent=e,this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=[],this.hardwareInstancedRendering=[]}},xy=class{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=512,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}},Ry=class{constructor(){this._areNormalsFrozen=!1,this._source=null,this.meshMap=null,this._preActivateId=-1,this._LODLevels=new Array,this._useLODScreenCoverage=!1,this._effectiveMaterial=null,this._forcedInstanceCount=0,this._overrideRenderingFillMode=null}},cl={source:null,parent:null,doNotCloneChildren:!1,clonePhysicsImpostor:!0,cloneThinInstances:!1},q=class n extends vr{static _GetDefaultSideOrientation(e){return e||n.FRONTSIDE}get useLODScreenCoverage(){return this._internalMeshDataInfo._useLODScreenCoverage}set useLODScreenCoverage(e){this._internalMeshDataInfo._useLODScreenCoverage=e,this._sortLODLevels()}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(e&&this._internalMeshDataInfo._sourcePositions&&(this.setVerticesData(L.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(L.NormalKind,this._internalMeshDataInfo._sourceNormals,!0),this._internalMeshDataInfo._sourcePositions=null,this._internalMeshDataInfo._sourceNormals=null),this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get onBeforeRenderObservable(){return this._internalMeshDataInfo._onBeforeRenderObservable||(this._internalMeshDataInfo._onBeforeRenderObservable=new ie),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new ie),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new ie),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new ie),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new ie),this._internalMeshDataInfo._onBeforeDrawObservable}set onBeforeDraw(e){this._onBeforeDrawObserver&&this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver),this._onBeforeDrawObserver=this.onBeforeDrawObservable.add(e)}get hasInstances(){return this.instances.length>0}get hasThinInstances(){return(this.forcedInstanceCount||this._thinInstanceDataStorage.instancesCount||0)>0}get forcedInstanceCount(){return this._internalMeshDataInfo._forcedInstanceCount}set forcedInstanceCount(e){this._internalMeshDataInfo._forcedInstanceCount=e}get sideOrientation(){return this._internalMeshDataInfo._sideOrientation}set sideOrientation(e){this._internalMeshDataInfo._sideOrientation=e,this._internalAbstractMeshDataInfo._sideOrientationHint=this._scene.useRightHandedSystem&&e===1||!this._scene.useRightHandedSystem&&e===0}get _effectiveSideOrientation(){return this._internalMeshDataInfo._effectiveSideOrientation}get overrideMaterialSideOrientation(){return this.sideOrientation}set overrideMaterialSideOrientation(e){this.sideOrientation=e,this.material&&(this.material.sideOrientation=null)}get overrideRenderingFillMode(){return this._internalMeshDataInfo._overrideRenderingFillMode}set overrideRenderingFillMode(e){this._internalMeshDataInfo._overrideRenderingFillMode=e}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){e&&(this.material&&this.material.sideOrientation===null||this._internalAbstractMeshDataInfo._sideOrientationHint)&&(e.sideOrientation=null),this._setMaterial(e)}get source(){return this._internalMeshDataInfo._source}get cloneMeshMap(){return this._internalMeshDataInfo.meshMap}get isUnIndexed(){return this._unIndexed}set isUnIndexed(e){this._unIndexed!==e&&(this._unIndexed=e,this._markSubMeshesAsAttributesDirty())}get worldMatrixInstancedBuffer(){let e=this._instanceDataStorage.useMonoDataStorageRenderPass?this._instanceDataStorage.dataStorageRenderPass:this._instanceDataStorage.renderPasses[this._instanceDataStorage.engine.currentRenderPassId];return e?e.instancesData:void 0}get previousWorldMatrixInstancedBuffer(){let e=this._instanceDataStorage.useMonoDataStorageRenderPass?this._instanceDataStorage.dataStorageRenderPass:this._instanceDataStorage.renderPasses[this._instanceDataStorage.engine.currentRenderPassId];return e?e.instancesPreviousData:void 0}get manualUpdateOfWorldMatrixInstancedBuffer(){return this._instanceDataStorage.manualUpdate}set manualUpdateOfWorldMatrixInstancedBuffer(e){this._instanceDataStorage.manualUpdate=e}get manualUpdateOfPreviousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.previousManualUpdate}set manualUpdateOfPreviousWorldMatrixInstancedBuffer(e){this._instanceDataStorage.previousManualUpdate=e}get forceWorldMatrixInstancedBufferUpdate(){return this._instanceDataStorage.forceMatrixUpdates}set forceWorldMatrixInstancedBufferUpdate(e){this._instanceDataStorage.forceMatrixUpdates=e}_copySource(e,t,i=!0,r=!1){var a,o;let s=this.getScene();if(e._geometry&&e._geometry.applyToMesh(this),tl.DeepCopy(e,this,["name","material","skeleton","instances","parent","uniqueId","source","metadata","morphTargetManager","hasInstances","worldMatrixInstancedBuffer","previousWorldMatrixInstancedBuffer","hasLODLevels","geometry","isBlocked","areNormalsFrozen","facetNb","isFacetDataEnabled","lightSources","useBones","isAnInstance","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","cloneMeshMap","hasBoundingInfo","physicsBody","physicsImpostor"],["_poseMatrix"]),this._internalMeshDataInfo._source=e,s.useClonedMeshMap&&(e._internalMeshDataInfo.meshMap||(e._internalMeshDataInfo.meshMap={}),e._internalMeshDataInfo.meshMap[this.uniqueId]=this),this._originalBuilderSideOrientation=e._originalBuilderSideOrientation,this._creationDataStorage=e._creationDataStorage,e._ranges){let l=e._ranges;for(let c in l)Object.prototype.hasOwnProperty.call(l,c)&&l[c]&&this.createAnimationRange(c,l[c].from,l[c].to)}if(e.metadata&&e.metadata.clone?this.metadata=e.metadata.clone():this.metadata=e.metadata,this._internalMetadata=e._internalMetadata,Zt&&Zt.HasTags(e)&&Zt.AddTagsTo(this,Zt.GetTags(e,!0)),this.setEnabled(e.isEnabled(!1)),this.parent=e.parent,this.setPivotMatrix(e.getPivotMatrix(),this._postMultiplyPivotMatrix),this.id=this.name+"."+e.id,this.material=e.material,!t){let l=e.getDescendants(!0);for(let c=0;c{m&&_&&(this._uniformBuffer?this.transferToEffect(p):_.bindOnlyWorldMatrix(p))};let o,l=!1;if(i&&i._addToSceneRootNodes===void 0){let m=i;o=(c=m.parent)!=null?c:null,r=(f=m.source)!=null?f:null,s=(h=m.doNotCloneChildren)!=null?h:!1,a=(d=m.clonePhysicsImpostor)!=null?d:!0,l=(u=m.cloneThinInstances)!=null?u:!1}else o=i;r&&this._copySource(r,s,a,l),o!==null&&(this.parent=o),this._instanceDataStorage.hardwareInstancedRendering=this.getEngine().getCaps().instancedArrays,this._internalMeshDataInfo._onMeshReadyObserverAdded=m=>{m.unregisterOnNextCall=!0,this.isReady(!0)?this.onMeshReadyObservable.notifyObservers(this):this._internalMeshDataInfo._checkReadinessObserver||(this._internalMeshDataInfo._checkReadinessObserver=this._scene.onBeforeRenderObservable.add(()=>{this.isReady(!0)&&(this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),this._internalMeshDataInfo._checkReadinessObserver=null,this.onMeshReadyObservable.notifyObservers(this))}))},this.onMeshReadyObservable=new ie(this._internalMeshDataInfo._onMeshReadyObserverAdded),r&&r.onClonedObservable.notifyObservers(this)}instantiateHierarchy(e=null,t,i){let r=this.getTotalVertices()===0||t&&t.doNotInstantiate&&(t.doNotInstantiate===!0||t.doNotInstantiate(this))?this.clone("Clone of "+(this.name||this.id),e||this.parent,!0):this.createInstance("instance of "+(this.name||this.id));r.parent=e||this.parent,r.position=this.position.clone(),r.scaling=this.scaling.clone(),this.rotationQuaternion?r.rotationQuaternion=this.rotationQuaternion.clone():r.rotation=this.rotation.clone(),i&&i(this,r);for(let s of this.getChildTransformNodes(!0))s.getClassName()==="InstancedMesh"&&r.getClassName()==="Mesh"&&s.sourceMesh===this?s.instantiateHierarchy(r,{doNotInstantiate:t&&t.doNotInstantiate||!1,newSourcedMesh:r},i):s.instantiateHierarchy(r,t,i);return r}getClassName(){return"Mesh"}get _isMesh(){return!0}toString(e){let t=super.toString(e);if(t+=", n vertices: "+this.getTotalVertices(),t+=", parent: "+(this._waitingParentId?this._waitingParentId:this.parent?this.parent.name:"NONE"),this.animations)for(let i=0;i0}getLODLevels(){return this._internalMeshDataInfo._LODLevels}_sortLODLevels(){let e=this._internalMeshDataInfo._useLODScreenCoverage?-1:1;this._internalMeshDataInfo._LODLevels.sort((t,i)=>t.distanceOrScreenCoveragei.distanceOrScreenCoverage?-e:0)}addLODLevel(e,t){if(t&&t._masterMesh)return te.Warn("You cannot use a mesh as LOD level twice"),this;let i=new OA(e,t);return this._internalMeshDataInfo._LODLevels.push(i),t&&(t._masterMesh=this),this._sortLODLevels(),this}getLODLevelAtDistance(e){let t=this._internalMeshDataInfo;for(let i=0;io*a)return this.onLODLevelSelection&&this.onLODLevelSelection(a,this,this),this;for(let l=0;l0||this.hasThinInstances);this.computeWorldMatrix();let a=this.material||r.defaultMaterial;if(a){if(a._storeEffectOnSubMeshes)for(let p of this.subMeshes){let _=p.getMaterial();if(_){if(_._storeEffectOnSubMeshes){if(!_.isReadyForSubMesh(this,p,s))return!1}else if(!_.isReady(this,s))return!1}}else if(!a.isReady(this,s))return!1}let o=i.currentRenderPassId;for(let p of this.lightSources){let _=p.getShadowGenerators();if(!_)continue;let g=_.values();for(let v=g.next();v.done!==!0;v=g.next()){let x=v.value;if(x&&(!((l=x.getShadowMap())!=null&&l.renderList)||(c=x.getShadowMap())!=null&&c.renderList&&((h=(f=x.getShadowMap())==null?void 0:f.renderList)==null?void 0:h.indexOf(this))!==-1)){let S=(d=x.getShadowMap().renderPassIds)!=null?d:[i.currentRenderPassId];for(let E=0;E0){let i=this.getIndices();if(!i)return null;let r=i.length,s=!1;if(e)s=!0;else for(let a of this.subMeshes){if(a.indexStart+a.indexCount>r){s=!0;break}if(a.verticesStart+a.verticesCount>t){s=!0;break}}if(!s)return this.subMeshes[0]}return this.releaseSubMeshes(),new xs(0,0,t,0,this.getTotalIndices()||(this.isUnIndexed?t:0),this)}subdivide(e){if(e<1)return;let t=this.getTotalIndices(),i=t/e|0,r=0;for(;i%3!==0;)i++;this.releaseSubMeshes();for(let s=0;s=t);s++)xs.CreateFromIndices(0,r,r+i>=t?t-r:i,this,void 0,!1),r+=i;this.refreshBoundingInfo(),this.synchronizeInstances()}setVerticesData(e,t,i=!1,r){if(this._geometry)this._geometry.setVerticesData(e,t,i,r);else{let s=new Ce;s.set(t,e);let a=this.getScene();new mn(mn.RandomId(),a,s,i,this)}return this}removeVerticesData(e){this._geometry&&this._geometry.removeVerticesData(e)}markVerticesDataAsUpdatable(e,t=!0){let i=this.getVertexBuffer(e);!i||i.isUpdatable()===t||this.setVerticesData(e,this.getVerticesData(e),t)}setVerticesBuffer(e,t=!0,i=null){return this._geometry||(this._geometry=mn.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(e,i,t),this}updateVerticesData(e,t,i,r){return this._geometry?(r?(this.makeGeometryUnique(),this.updateVerticesData(e,t,i,!1)):this._geometry.updateVerticesData(e,t,i),this):this}updateMeshPositions(e,t=!0){let i=this.getVerticesData(L.PositionKind);if(!i)return this;if(e(i),this.updateVerticesData(L.PositionKind,i,!1,!1),t){let r=this.getIndices(),s=this.getVerticesData(L.NormalKind);if(!s)return this;Ce.ComputeNormals(i,r,s),this.updateVerticesData(L.NormalKind,s,!1,!1)}return this}makeGeometryUnique(){if(!this._geometry)return this;if(this._geometry.meshes.length===1)return this;let e=this._geometry,t=this._geometry.copy(mn.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndexBuffer(e,t,i,r=null){let s=this._geometry;s||(s=new mn(mn.RandomId(),this.getScene(),void 0,void 0,this)),s.setIndexBuffer(e,t,i,r)}setIndices(e,t=null,i=!1,r=!1){if(this._geometry)this._geometry.setIndices(e,t,i,r);else{let s=new Ce;s.indices=e;let a=this.getScene();new mn(mn.RandomId(),a,s,i,this,t)}return this}updateIndices(e,t,i=!1){return this._geometry?(this._geometry.updateIndices(e,t,i),this):this}toLeftHanded(){return this._geometry?(this._geometry.toLeftHanded(),this):this}_bind(e,t,i,r=!0){if(!this._geometry)return this;let s=this.getScene().getEngine(),a;if(this._unIndexed)this._getRenderingFillMode(i)===Ee.WireFrameFillMode?a=e._getLinesIndexBuffer(this.getIndices(),s):a=null;else switch(this._getRenderingFillMode(i)){case Ee.PointFillMode:a=null;break;case Ee.WireFrameFillMode:a=e._getLinesIndexBuffer(this.getIndices(),s);break;default:case Ee.TriangleFillMode:a=this._geometry.getIndexBuffer();break}return this._bindDirect(t,a,r)}_bindDirect(e,t,i=!0){if(!this._geometry)return this;if(this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(e),!i||!this._userInstancedBuffersStorage||this.hasThinInstances)this._geometry._bind(e,t);else{if(!this._instanceDataStorage.useMonoDataStorageRenderPass&&this._userInstancedBuffersStorage.renderPasses&&this._userInstancedBuffersStorage.renderPasses[this._instanceDataStorage.engine.currentRenderPassId]){let r=this._userInstancedBuffersStorage.renderPasses[this._instanceDataStorage.engine.currentRenderPassId];for(let s in r)this._userInstancedBuffersStorage.vertexBuffers[s]=r[s]}this._geometry._bind(e,t,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects)}return this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this._internalMeshDataInfo._onBeforeDrawObservable&&this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);let s=this.getScene().getEngine(),a=s._currentMaterialContext,o=a&&a.useVertexPulling;return this._unIndexed&&t!==Ee.WireFrameFillMode||t==Ee.PointFillMode?s.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||i):t==Ee.WireFrameFillMode?s.drawElementsType(t,0,e._linesIndexCount,this.forcedInstanceCount||i):o?s.drawArraysType(t,e.indexStart,e.indexCount,this.forcedInstanceCount||i):s.drawElementsType(t,e.indexStart,e.indexCount,this.forcedInstanceCount||i),this}registerBeforeRender(e){return this.onBeforeRenderObservable.add(e),this}unregisterBeforeRender(e){return this.onBeforeRenderObservable.removeCallback(e),this}registerAfterRender(e){return this.onAfterRenderObservable.add(e),this}unregisterAfterRender(e){return this.onAfterRenderObservable.removeCallback(e),this}_getInstancesRenderList(e,t=!1){let i=this._instanceDataStorage.useMonoDataStorageRenderPass?this._instanceDataStorage.dataStorageRenderPass:this._getInstanceDataStorage();if(this._instanceDataStorage.isFrozen){if(t)return i.batchCacheReplacementModeInFrozenMode.hardwareInstancedRendering[e]=!1,i.batchCacheReplacementModeInFrozenMode.renderSelf[e]=!0,i.batchCacheReplacementModeInFrozenMode;if(i.previousBatch)return i.previousBatch}let r=this.getScene(),s=r._isInIntermediateRendering(),a=s?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,o=i.batchCache;if(o.mustReturn=!1,o.renderSelf[e]=t||!a&&this.isEnabled()&&this.isVisible,o.visibleInstances[e]=null,i.visibleInstances&&!t){let l=i.visibleInstances,c=r.getRenderId(),f=s?l.intermediateDefaultRenderId:l.defaultRenderId;o.visibleInstances[e]=l[c],!o.visibleInstances[e]&&f&&(o.visibleInstances[e]=l[f])}return o.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&o.visibleInstances[e]!==null&&o.visibleInstances[e]!==void 0,i.previousBatch=o,o}_updateInstancedBuffers(e,t,i,r,s,a){var v;let o=t.visibleInstances[e._id],l=o?o.length:0,c=t.parent,f=this._instanceDataStorage,h=c.instancesBuffer,d=c.instancesPreviousBuffer,u=0,m=0,p=t.renderSelf[e._id],_=this._scene.floatingOriginOffset,g=!h||i!==c.instancesBufferSize||this._scene.needsPreviousWorldMatrices&&!c.instancesPreviousBuffer;if(!this._instanceDataStorage.manualUpdate&&(!f.isFrozen||g)){let x=this.getWorldMatrix();if(p){this._scene.needsPreviousWorldMatrices&&(f.masterMeshPreviousWorldMatrix?(f.masterMeshPreviousWorldMatrix.copyToArray(c.instancesPreviousData,u),f.masterMeshPreviousWorldMatrix.copyFrom(x)):(f.masterMeshPreviousWorldMatrix=x.clone(),f.masterMeshPreviousWorldMatrix.copyToArray(c.instancesPreviousData,u))),x.copyToArray(c.instancesData,u);let A=x.asArray();c.instancesData[u+12]=A[12]-_.x,c.instancesData[u+13]=A[13]-_.y,c.instancesData[u+14]=A[14]-_.z,u+=16,m++}if(o){if(n.INSTANCEDMESH_SORT_TRANSPARENT&&this._scene.activeCamera&&((v=e.getMaterial())!=null&&v.needAlphaBlendingForMesh(e.getRenderingMesh()))){let A=this._scene.activeCamera.globalPosition;for(let S=0;SS._distanceToCamera>E._distanceToCamera?-1:S._distanceToCamera1&&r.activeCamera===r.activeCameras[0]||a<=1,l=this._occlusionDataStorage&&this._occlusionDataStorage.occlusionForRenderPassId!==-1&&this._occlusionDataStorage.occlusionForRenderPassId!==s.currentRenderPassId;if(o&&this._checkOcclusionQuery(l)&&!this._occlusionDataStorage.forceRenderingWhenOccluded)return this;let c=this._getInstancesRenderList(e._id,!!i);if(c.mustReturn)return this;if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;let f=0,h=null;this.ignoreCameraMaxZ&&r.activeCamera&&!r._isInIntermediateRendering()&&(f=r.activeCamera.maxZ,h=r.activeCamera,r.activeCamera.maxZ=0,r.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);let d=e.getRenderingMesh(),u=c.hardwareInstancedRendering[e._id]||d.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,m=this._instanceDataStorage,p=e.getMaterial();if(!p)return h&&(h.maxZ=f,r.updateTransformMatrix(!0)),this;if(!m.isFrozen||!this._internalMeshDataInfo._effectiveMaterial||this._internalMeshDataInfo._effectiveMaterial!==p){if(p._storeEffectOnSubMeshes){if(!p.isReadyForSubMesh(this,e,u))return h&&(h.maxZ=f,r.updateTransformMatrix(!0)),this}else if(!p.isReady(this,u))return h&&(h.maxZ=f,r.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=p}else if(p._storeEffectOnSubMeshes&&!((M=e._drawWrapper)!=null&&M._wasPreviouslyReady)||!p._storeEffectOnSubMeshes&&!p._getDrawWrapper()._wasPreviouslyReady)return h&&(h.maxZ=f,r.updateTransformMatrix(!0)),this;if(t){let O=this._internalMeshDataInfo._effectiveMaterial;if(O.alphaModes.length===1)s.setAlphaMode(O.alphaMode);else for(let V=0;Vg&&r++,S!==0&&x++,v+=S,g=S}if(c[x]++,x>a&&(a=x),v===0)s++;else{let A=1/v,S=0;for(let E=0;Ef&&o++}}let h=this.skeleton.bones.length,d=this.getVerticesData(L.MatricesIndicesKind),u=this.getVerticesData(L.MatricesIndicesExtraKind),m=0;for(let _=0;_=h||v<0)&&m++}let p="Number of Weights = "+i/4+` Maximum influences = `+a+` Missing Weights = `+s+` Not Sorted = `+r+` Not Normalized = `+o+` WeightCounts = [`+c+`] Number of bones = `+h+` -Bad Bone Indices = `+m;return{skinned:!0,valid:s===0&&o===0&&m===0,report:p}}_checkDelayState(){let e=this.getScene();return this._geometry?this._geometry.load(e):this.delayLoadState===4&&(this.delayLoadState=2,this._queueLoad(e)),this}_queueLoad(e){e.addPendingData(this);let t=this.delayLoadingFile.indexOf(".babylonbinarymeshdata")!==-1;return pe.LoadFile(this.delayLoadingFile,i=>{i instanceof ArrayBuffer?this._delayLoadingFunction(i,this):this._delayLoadingFunction(JSON.parse(i),this);for(let r of this.instances)r.refreshBoundingInfo(),r._syncSubMeshes();this.delayLoadState=1,e.removePendingData(this)},()=>{},e.offlineProvider,t),this}isInFrustum(e){return this.delayLoadState===2||!super.isInFrustum(e)?!1:(this._checkDelayState(),!0)}setMaterialById(e){let t=this.getScene().materials,i;for(i=t.length-1;i>-1;i--)if(t[i].id===e)return this.material=t[i],this;let r=this.getScene().multiMaterials;for(i=r.length-1;i>-1;i--)if(r[i].id===e)return this.material=r[i],this;return this}getAnimatables(){let e=[];return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e}bakeTransformIntoVertices(e){if(!this.isVerticesDataPresent(L.PositionKind))return this;let t=this.subMeshes.splice(0);this._resetPointsArrayCache();let i=this.getVerticesData(L.PositionKind),r=b.Zero(),s;for(s=0;s{let d=h.width,u=h.height,p=this.getEngine().createCanvas(d,u).getContext("2d");p.drawImage(h,0,0);let _=p.getImageData(0,0,d,u).data;this.applyDisplacementMapFromBuffer(_,d,u,t,i,s,a,o),r&&r(this)};return pe.LoadImage(e,f,l||(()=>{}),c.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,i,r,s,a,o,l=!1){if(!this.isVerticesDataPresent(L.PositionKind)||!this.isVerticesDataPresent(L.NormalKind)||!this.isVerticesDataPresent(L.UVKind))return te.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;let c=this.getVerticesData(L.PositionKind,!0,!0),f=this.getVerticesData(L.NormalKind),h=this.getVerticesData(L.UVKind),d=b.Zero(),u=b.Zero(),m=we.Zero();a=a||we.Zero(),o=o||new we(1,1);for(let p=0;p{var c;return!((c=this.getVertexBuffer(l))!=null&&c.getIsInstanced())}),i=this.getIndices(!1,!0),r={},s=(l,c)=>{let f=new Float32Array(i.length*c),h=0;for(let d=0;d{let o=r.length-1-a,l=r[o];for(let c=0;c{for(let o=0;o-1&&(r._waitingMorphTargetManagerId=e.morphTargetManagerId),e.skeletonId!==void 0&&e.skeletonId!==null&&(r.skeleton=t.getLastSkeletonById(e.skeletonId),r._waitingSkeletonId=e.skeletonId,e.numBoneInfluencers&&(r.numBoneInfluencers=e.numBoneInfluencers)),e.skeletonUniqueId!==void 0&&e.skeletonUniqueId!==null&&(r._waitingSkeletonUniqueId=e.skeletonUniqueId),e.animations){for(let a=0;a4,c=l?this.getVerticesData(L.MatricesIndicesExtraKind):null,f=l?this.getVerticesData(L.MatricesWeightsExtraKind):null,h=e.getTransformMatrices(this),d=b.Zero(),u=new j,m=new j,p=0,_;for(let g=0;g0&&(j.FromFloat32ArrayToRefScaled(h,Math.floor(a[p+_]*16),v,m),u.addToSelf(m));if(l)for(_=0;_<4;_++)v=f[p+_],v>0&&(j.FromFloat32ArrayToRefScaled(h,Math.floor(c[p+_]*16),v,m),u.addToSelf(m));b.TransformCoordinatesFromFloatsToRef(i._sourcePositions[g],i._sourcePositions[g+1],i._sourcePositions[g+2],u,d),d.toArray(r,g),t&&(b.TransformNormalFromFloatsToRef(i._sourceNormals[g],i._sourceNormals[g+1],i._sourceNormals[g+2],u,d),d.toArray(s,g)),u.reset()}return this.updateVerticesData(L.PositionKind,r),t&&this.updateVerticesData(L.NormalKind,s),this}static MinMax(e){let t=null,i=null;for(let r of e){let a=r.getBoundingInfo().boundingBox;!t||!i?(t=a.minimumWorld.clone(),i=a.maximumWorld.clone()):(t.minimizeInPlace(a.minimumWorld),i.maximizeInPlace(a.maximumWorld))}return!t||!i?{min:b.Zero(),max:b.Zero()}:{min:t,max:i}}static Center(e){let t=e instanceof Array?n.MinMax(e):e;return b.Center(t.min,t.max)}static MergeMeshes(e,t=!0,i,r,s,a){return fg(n._MergeMeshesCoroutine(e,t,i,r,s,a,!1))}static async MergeMeshesAsync(e,t=!0,i,r,s,a){return await rG(n._MergeMeshesCoroutine(e,t,i,r,s,a,!0),tG())}static*_MergeMeshesCoroutine(e,t=!0,i,r,s,a,o){if(e=e.filter(Boolean),e.length===0)return null;let l;if(!i){let R=0;for(l=0;l=65536)return te.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}let c=e[0];a&&(s=!1,e.sort((R,I)=>{var y,M,D,O;return((M=(y=R.material)==null?void 0:y.uniqueId)!=null?M:-1)-((O=(D=I.material)==null?void 0:D.uniqueId)!=null?O:-1)}));let f=new Array,h=new Array,d=new Array,u=e[0].sideOrientation;for(l=0;lMath.max(y,M.start+M.count),0);if(a)if(R.material){let y=R.material;if(y instanceof wm){for(let M=0;M1){let R=0;for(let I=1;I{let I=R.computeWorldMatrix(!0);return{vertexData:Me.ExtractFromMesh(R,!1,!1),transform:I}},{vertexData:p,transform:_}=m(e[0]);o&&(yield);let g=new Array(e.length-1);for(let R=1;R{throw Ze("GroundMesh")};Z._GoldbergMeshParser=(n,e)=>{throw Ze("GoldbergMesh")};Z._LinesMeshParser=(n,e)=>{throw Ze("LinesMesh")};Z._GreasedLineMeshParser=(n,e)=>{throw Ze("GreasedLineMesh")};Z._GreasedLineRibbonMeshParser=(n,e)=>{throw Ze("GreasedLineRibbonMesh")};Z._TrailMeshParser=(n,e)=>{throw Ze("TrailMesh")};Z._GaussianSplattingMeshParser=(n,e)=>{throw Ze("GaussianSplattingMesh")};Z._GaussianSplattingPartProxyMeshParser=(n,e)=>{throw Ze("GaussianSplattingPartProxyMesh")};Z._GaussianSplattingCompoundMeshParser=(n,e)=>{throw Ze("GaussianSplattingCompoundMesh")};wt("BABYLON.Mesh",Z)});var Bm,by=C(()=>{oo();Fl();Dn();Bm=class{constructor(){this._zoomStopsAnimation=!1,this._idleRotationSpeed=.05,this._idleRotationWaitTime=2e3,this._idleRotationSpinupTime=2e3,this.targetAlpha=null,this._attachedCamera=null,this._isPointerDown=!1,this._lastFrameTime=null,this._lastInteractionTime=-1/0,this._cameraRotationSpeed=0,this._lastFrameRadius=0}get name(){return"AutoRotation"}set zoomStopsAnimation(e){this._zoomStopsAnimation=e}get zoomStopsAnimation(){return this._zoomStopsAnimation}set idleRotationSpeed(e){this._idleRotationSpeed=e}get idleRotationSpeed(){return this._idleRotationSpeed}set idleRotationWaitTime(e){this._idleRotationWaitTime=e}get idleRotationWaitTime(){return this._idleRotationWaitTime}set idleRotationSpinupTime(e){this._idleRotationSpinupTime=e}get idleRotationSpinupTime(){return this._idleRotationSpinupTime}get rotationInProgress(){return Math.abs(this._cameraRotationSpeed)>0}get attachedNode(){return this._attachedCamera}init(){}attach(e){this._attachedCamera=e;let t=this._attachedCamera.getScene();this._onPrePointerObservableObserver=t.onPrePointerObservable.add(i=>{if(i.type===st.POINTERDOWN){this._isPointerDown=!0;return}i.type===st.POINTERUP&&(this._isPointerDown=!1)}),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{if(this._reachTargetAlpha())return;let i=mr.Now,r=0;this._lastFrameTime!=null&&(r=i-this._lastFrameTime),this._lastFrameTime=i,this._applyUserInteraction();let s=i-this._lastInteractionTime-this._idleRotationWaitTime,a=Math.max(Math.min(s/this._idleRotationSpinupTime,1),0);this._cameraRotationSpeed=this._idleRotationSpeed*a,this._attachedCamera&&(this._attachedCamera.alpha-=this._cameraRotationSpeed*(r/1e3))})}detach(){if(!this._attachedCamera)return;let e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._attachedCamera=null,this._lastFrameTime=null}resetLastInteractionTime(e){this._lastInteractionTime=e!=null?e:mr.Now}_reachTargetAlpha(){return this._attachedCamera&&this.targetAlpha?Math.abs(this._attachedCamera.alpha-this.targetAlpha){Fh();po=class n{constructor(){this._easingMode=n.EASINGMODE_EASEIN}setEasingMode(e){let t=Math.min(Math.max(e,0),2);this._easingMode=t}getEasingMode(){return this._easingMode}easeInCore(e){throw new Error("You must implement this method")}ease(e){switch(this._easingMode){case n.EASINGMODE_EASEIN:return this.easeInCore(e);case n.EASINGMODE_EASEOUT:return 1-this.easeInCore(1-e)}return e>=.5?(1-this.easeInCore((1-e)*2))*.5+.5:this.easeInCore(e*2)*.5}};po.EASINGMODE_EASEIN=0;po.EASINGMODE_EASEOUT=1;po.EASINGMODE_EASEINOUT=2;wA=class extends po{constructor(e=1){super(),this.amplitude=e}easeInCore(e){let t=Math.max(0,this.amplitude);return Math.pow(e,3)-e*t*Math.sin(3.141592653589793*e)}},FA=class extends po{constructor(e=2){super(),this.exponent=e}easeInCore(e){return this.exponent<=0?e:(Math.exp(this.exponent*e)-1)/(Math.exp(this.exponent)-1)}}});var If,My=C(()=>{If=class n{constructor(e,t,i){this.name=e,this.from=t,this.to=i}clone(){return new n(this.name,this.from,this.to)}}});var Cy,yy,Py,Dy,Ly,Oy,_o,ft,Mf=C(()=>{Ve();zt();Ln();Hi();My();qs();FT();Bh();Tr();Cy=Object.freeze(new Ye(0,0,0,0)),yy=Object.freeze(b.Zero()),Py=Object.freeze(we.Zero()),Dy=Object.freeze(Vl.Zero()),Ly=Object.freeze(ge.Black()),Oy=Object.freeze(new lt(0,0,0,0)),_o={key:0,repeatCount:0,loopMode:2},ft=class n{static _PrepareAnimation(e,t,i,r,s,a,o,l){let c;if(!isNaN(parseFloat(s))&&isFinite(s)?c=n.ANIMATIONTYPE_FLOAT:s instanceof Ye?c=n.ANIMATIONTYPE_QUATERNION:s instanceof b?c=n.ANIMATIONTYPE_VECTOR3:s instanceof we?c=n.ANIMATIONTYPE_VECTOR2:s instanceof ge?c=n.ANIMATIONTYPE_COLOR3:s instanceof lt?c=n.ANIMATIONTYPE_COLOR4:s instanceof Vl&&(c=n.ANIMATIONTYPE_SIZE),c==null)return null;let f=new n(e,t,i,c,o),h=[{frame:0,value:s},{frame:r,value:a}];return f.setKeys(h),l!==void 0&&f.setEasingFunction(l),f}static CreateAnimation(e,t,i,r){let s=new n(e+"Animation",e,i,t,n.ANIMATIONLOOPMODE_CONSTANT);return s.setEasingFunction(r),s}static CreateAndStartAnimation(e,t,i,r,s,a,o,l,c,f,h){let d=n._PrepareAnimation(e,i,r,s,a,o,l,c);return!d||(t.getScene&&(h=t.getScene()),!h)?null:h.beginDirectAnimation(t,[d],0,s,d.loopMode!==n.ANIMATIONLOOPMODE_CONSTANT,1,f)}static CreateAndStartHierarchyAnimation(e,t,i,r,s,a,o,l,c,f,h){let d=n._PrepareAnimation(e,r,s,a,o,l,c,f);return d?t.getScene().beginDirectHierarchyAnimation(t,i,[d],0,a,d.loopMode===1,1,h):null}static CreateMergeAndStartAnimation(e,t,i,r,s,a,o,l,c,f){let h=n._PrepareAnimation(e,i,r,s,a,o,l,c);return h?(t.animations.push(h),t.getScene().beginAnimation(t,0,s,h.loopMode===1,1,f)):null}static MakeAnimationAdditive(e,t,i,r=!1,s){var v,x;let a;typeof t=="object"?a=t:a={referenceFrame:t!=null?t:0,range:i,cloneOriginalAnimation:r,clonedAnimationName:s};let o=e;if(a.cloneOriginalAnimation&&(o=e.clone(),o.name=a.clonedAnimationName||o.name),!o._keys.length)return o;let l=a.referenceFrame&&a.referenceFrame>=0?a.referenceFrame:0,c=0,f=o._keys[0],h=o._keys.length-1,d=o._keys[h],u={referenceValue:f.value,referencePosition:$.Vector3[0],referenceQuaternion:$.Quaternion[0],referenceScaling:$.Vector3[1],keyPosition:$.Vector3[2],keyQuaternion:$.Quaternion[1],keyScaling:$.Vector3[3]},m=f.frame,p=d.frame;if(a.range){let A=o.getRange(a.range);A&&(m=A.from,p=A.to)}else m=(v=a.fromFrame)!=null?v:m,p=(x=a.toFrame)!=null?x:p;if(m!==f.frame&&(c=o.createKeyForFrame(m)),p!==d.frame&&(h=o.createKeyForFrame(p)),o._keys.length===1){let A=o._getKeyValue(o._keys[0]);u.referenceValue=A.clone?A.clone():A}else if(l<=f.frame){let A=o._getKeyValue(f.value);u.referenceValue=A.clone?A.clone():A}else if(l>=d.frame){let A=o._getKeyValue(d.value);u.referenceValue=A.clone?A.clone():A}else{_o.key=0;let A=o._interpolate(l,_o);u.referenceValue=A.clone?A.clone():A}o.dataType===n.ANIMATIONTYPE_QUATERNION?u.referenceValue.normalize().conjugateInPlace():o.dataType===n.ANIMATIONTYPE_MATRIX&&(u.referenceValue.decompose(u.referenceScaling,u.referenceQuaternion,u.referencePosition),u.referenceQuaternion.normalize().conjugateInPlace());let _=Number.MAX_VALUE,g=a.clipKeys?[]:null;for(let A=c;A<=h;A++){let S=o._keys[A];if((g||a.cloneOriginalAnimation)&&(S={frame:S.frame,value:S.value.clone?S.value.clone():S.value,inTangent:S.inTangent,outTangent:S.outTangent,interpolation:S.interpolation,lockedTangent:S.lockedTangent,easingFunction:S.easingFunction},g&&(_===Number.MAX_VALUE&&(_=S.frame),S.frame-=_,g.push(S))),!(A&&o.dataType!==n.ANIMATIONTYPE_FLOAT&&S.value===f.value))switch(o.dataType){case n.ANIMATIONTYPE_MATRIX:S.value.decompose(u.keyScaling,u.keyQuaternion,u.keyPosition),u.keyPosition.subtractInPlace(u.referencePosition),u.keyScaling.divideInPlace(u.referenceScaling),u.referenceQuaternion.multiplyToRef(u.keyQuaternion,u.keyQuaternion),j.ComposeToRef(u.keyScaling,u.keyQuaternion,u.keyPosition,S.value);break;case n.ANIMATIONTYPE_QUATERNION:u.referenceValue.multiplyToRef(S.value,S.value);break;case n.ANIMATIONTYPE_VECTOR2:case n.ANIMATIONTYPE_VECTOR3:case n.ANIMATIONTYPE_COLOR3:case n.ANIMATIONTYPE_COLOR4:S.value.subtractToRef(u.referenceValue,S.value);break;case n.ANIMATIONTYPE_SIZE:S.value.width-=u.referenceValue.width,S.value.height-=u.referenceValue.height;break;default:S.value-=u.referenceValue}}return g&&o.setKeys(g,!0),o}static TransitionTo(e,t,i,r,s,a,o,l=null,c=!0,f){if(o<=0)return i[e]=t,l&&l(),null;let h=s*(o/1e3);return a.setKeys(f!=null?f:[{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:h,value:t}]),i.animations||(i.animations=[]),i.animations.push(a),r.beginAnimation(i,0,h,!1,1,l!=null?l:void 0,void 0,c)}get runtimeAnimations(){return this._runtimeAnimations}get hasRunningRuntimeAnimations(){for(let e of this._runtimeAnimations)if(!e.isStopped())return!0;return!1}constructor(e,t,i,r,s,a){this.name=e,this.targetProperty=t,this.framePerSecond=i,this.dataType=r,this.loopMode=s,this.enableBlending=a,this._easingFunction=null,this._runtimeAnimations=new Array,this._events=new Array,this.blendingSpeed=.01,this._ranges={},this._coreAnimation=null,this.targetPropertyPath=t.split("."),this.dataType=r,this.loopMode=s===void 0?n.ANIMATIONLOOPMODE_CYCLE:s,this.uniqueId=n._UniqueIdGenerator++}toString(e){let t="Name: "+this.name+", property: "+this.targetProperty;if(t+=", datatype: "+["Float","Vector3","Quaternion","Matrix","Color3","Vector2"][this.dataType],t+=", nKeys: "+(this._keys?this._keys.length:"none"),t+=", nRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";let i=!0;for(let r in this._ranges)i||(t+=", "),i=!1,t+=r;t+="}"}return t}addEvent(e){this._events.push(e),this._events.sort((t,i)=>t.frame-i.frame)}removeEvents(e){for(let t=0;t=0;a--)this._keys[a].frame>=r&&this._keys[a].frame<=s&&this._keys.splice(a,1)}this._ranges[e]=null}}getRange(e){return this._ranges[e]}getKeys(){return this._keys}getHighestFrame(){let e=0;for(let t=0,i=this._keys.length;t0)return t.highLimitValue.clone?t.highLimitValue.clone():t.highLimitValue;let r=this._keys,s;if(this._coreAnimation)s=this._coreAnimation._key;else{let p=r.length;for(s=t.key;s>=0&&e=r[s+1].frame;)++s;if(t.key=s,s<0)return i?void 0:this._getKeyValue(r[0].value);if(s+1>p-1)return i?void 0:this._getKeyValue(r[p-1].value);this._key=s}let a=r[s],o=r[s+1];if(i&&(e===a.frame||e===o.frame))return;let l=this._getKeyValue(a.value),c=this._getKeyValue(o.value);if(a.interpolation===1)return o.frame>e?l:c;let f=a.outTangent!==void 0&&o.inTangent!==void 0,h=o.frame-a.frame,d=(e-a.frame)/h,u=a.easingFunction||this.getEasingFunction();switch(u&&(d=u.ease(d)),this.dataType){case n.ANIMATIONTYPE_FLOAT:{let p=f?this.floatInterpolateFunctionWithTangents(l,a.outTangent*h,c,o.inTangent*h,d):this.floatInterpolateFunction(l,c,d);switch(t.loopMode){case n.ANIMATIONLOOPMODE_CYCLE:case n.ANIMATIONLOOPMODE_CONSTANT:case n.ANIMATIONLOOPMODE_YOYO:return p;case n.ANIMATIONLOOPMODE_RELATIVE:case n.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return((m=t.offsetValue)!=null?m:0)*t.repeatCount+p}break}case n.ANIMATIONTYPE_QUATERNION:{let p=f?this.quaternionInterpolateFunctionWithTangents(l,a.outTangent.scale(h),c,o.inTangent.scale(h),d):this.quaternionInterpolateFunction(l,c,d);switch(t.loopMode){case n.ANIMATIONLOOPMODE_CYCLE:case n.ANIMATIONLOOPMODE_CONSTANT:case n.ANIMATIONLOOPMODE_YOYO:return p;case n.ANIMATIONLOOPMODE_RELATIVE:case n.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return p.addInPlace((t.offsetValue||Cy).scale(t.repeatCount))}return p}case n.ANIMATIONTYPE_VECTOR3:{let p=f?this.vector3InterpolateFunctionWithTangents(l,a.outTangent.scale(h),c,o.inTangent.scale(h),d):this.vector3InterpolateFunction(l,c,d);switch(t.loopMode){case n.ANIMATIONLOOPMODE_CYCLE:case n.ANIMATIONLOOPMODE_CONSTANT:case n.ANIMATIONLOOPMODE_YOYO:return p;case n.ANIMATIONLOOPMODE_RELATIVE:case n.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return p.add((t.offsetValue||yy).scale(t.repeatCount))}break}case n.ANIMATIONTYPE_VECTOR2:{let p=f?this.vector2InterpolateFunctionWithTangents(l,a.outTangent.scale(h),c,o.inTangent.scale(h),d):this.vector2InterpolateFunction(l,c,d);switch(t.loopMode){case n.ANIMATIONLOOPMODE_CYCLE:case n.ANIMATIONLOOPMODE_CONSTANT:case n.ANIMATIONLOOPMODE_YOYO:return p;case n.ANIMATIONLOOPMODE_RELATIVE:case n.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return p.add((t.offsetValue||Py).scale(t.repeatCount))}break}case n.ANIMATIONTYPE_SIZE:{switch(t.loopMode){case n.ANIMATIONLOOPMODE_CYCLE:case n.ANIMATIONLOOPMODE_CONSTANT:case n.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(l,c,d);case n.ANIMATIONLOOPMODE_RELATIVE:case n.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return this.sizeInterpolateFunction(l,c,d).add((t.offsetValue||Dy).scale(t.repeatCount))}break}case n.ANIMATIONTYPE_COLOR3:{let p=f?this.color3InterpolateFunctionWithTangents(l,a.outTangent.scale(h),c,o.inTangent.scale(h),d):this.color3InterpolateFunction(l,c,d);switch(t.loopMode){case n.ANIMATIONLOOPMODE_CYCLE:case n.ANIMATIONLOOPMODE_CONSTANT:case n.ANIMATIONLOOPMODE_YOYO:return p;case n.ANIMATIONLOOPMODE_RELATIVE:case n.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return p.add((t.offsetValue||Ly).scale(t.repeatCount))}break}case n.ANIMATIONTYPE_COLOR4:{let p=f?this.color4InterpolateFunctionWithTangents(l,a.outTangent.scale(h),c,o.inTangent.scale(h),d):this.color4InterpolateFunction(l,c,d);switch(t.loopMode){case n.ANIMATIONLOOPMODE_CYCLE:case n.ANIMATIONLOOPMODE_CONSTANT:case n.ANIMATIONLOOPMODE_YOYO:return p;case n.ANIMATIONLOOPMODE_RELATIVE:case n.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return p.add((t.offsetValue||Oy).scale(t.repeatCount))}break}case n.ANIMATIONTYPE_MATRIX:{switch(t.loopMode){case n.ANIMATIONLOOPMODE_CYCLE:case n.ANIMATIONLOOPMODE_CONSTANT:case n.ANIMATIONLOOPMODE_YOYO:return n.AllowMatricesInterpolation?this.matrixInterpolateFunction(l,c,d,t.workValue):l;case n.ANIMATIONLOOPMODE_RELATIVE:case n.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return l}break}}return 0}matrixInterpolateFunction(e,t,i,r){return n.AllowMatrixDecomposeForInterpolation?r?(j.DecomposeLerpToRef(e,t,i,r),r):j.DecomposeLerp(e,t,i):r?(j.LerpToRef(e,t,i,r),r):j.Lerp(e,t,i)}clone(e=!1){let t=new n(this.name,this.targetPropertyPath.join("."),this.framePerSecond,this.dataType,this.loopMode);if(t.enableBlending=this.enableBlending,t.blendingSpeed=this.blendingSpeed,this._keys&&t.setKeys(this._keys,!1,e),this._ranges){t._ranges={};for(let i in this._ranges){let r=this._ranges[i];r&&(t._ranges[i]=r.clone())}}return t}setKeys(e,t=!1,i=!1){if(t)this._keys=e;else if(this._keys=e.slice(0),i)for(let r=0;r=2&&(l=o.values[1]),o.values.length>=3&&(c=o.values[2]),o.values.length>=4&&(f=o.values[3]);break;case n.ANIMATIONTYPE_QUATERNION:if(s=Ye.FromArray(o.values),o.values.length>=8){let d=Ye.FromArray(o.values.slice(4,8));d.equals(Ye.Zero())||(l=d)}if(o.values.length>=12){let d=Ye.FromArray(o.values.slice(8,12));d.equals(Ye.Zero())||(c=d)}o.values.length>=13&&(f=o.values[12]);break;case n.ANIMATIONTYPE_MATRIX:s=j.FromArray(o.values),o.values.length>=17&&(f=o.values[16]);break;case n.ANIMATIONTYPE_COLOR3:s=ge.FromArray(o.values),o.values[3]&&(l=ge.FromArray(o.values[3])),o.values[4]&&(c=ge.FromArray(o.values[4])),o.values[5]&&(f=o.values[5]);break;case n.ANIMATIONTYPE_COLOR4:s=lt.FromArray(o.values),o.values[4]&&(l=lt.FromArray(o.values[4])),o.values[5]&&(c=lt.FromArray(o.values[5])),o.values[6]&&(f=lt.FromArray(o.values[6]));break;case n.ANIMATIONTYPE_VECTOR3:default:s=b.FromArray(o.values),o.values[3]&&(l=b.FromArray(o.values[3])),o.values[4]&&(c=b.FromArray(o.values[4])),o.values[5]&&(f=o.values[5]);break}let h={};h.frame=o.frame,h.value=s,l!=null&&(h.inTangent=l),c!=null&&(h.outTangent=c),f!=null&&(h.interpolation=f),r.push(h)}if(t.setKeys(r),e.ranges)for(a=0;a{let s=new Ir;s.addEventListener("readystatechange",()=>{if(s.readyState==4)if(s.status==200){let a=JSON.parse(s.responseText);if(a.animations&&(a=a.animations),a.length){let o=[];for(let l of a)o.push(this.Parse(l));i(o)}else{let o=this.Parse(a);e&&(o.name=e),i(o)}}else r("Unable to load the animation")}),s.open("GET",t),s.send()})}static async ParseFromSnippetAsync(e){return await new Promise((t,i)=>{let r=new Ir;r.addEventListener("readystatechange",()=>{if(r.readyState==4)if(r.status==200){let s=JSON.parse(JSON.parse(r.responseText).jsonPayload);if(s.animations){let a=JSON.parse(s.animations),o=[];for(let l of a.animations){let c=this.Parse(l);c.snippetId=e,o.push(c)}t(o)}else{let a=JSON.parse(s.animation),o=this.Parse(a);o.snippetId=e,t(o)}}else i("Unable to load the snippet "+e)}),r.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),r.send()})}};ft._UniqueIdGenerator=0;ft.AllowMatricesInterpolation=!1;ft.AllowMatrixDecomposeForInterpolation=!0;ft.InheritOriginalValueFromActiveAnimations=!1;ft.SnippetUrl="https://snippet.babylonjs.com";ft.ANIMATIONTYPE_FLOAT=0;ft.ANIMATIONTYPE_VECTOR3=1;ft.ANIMATIONTYPE_QUATERNION=2;ft.ANIMATIONTYPE_MATRIX=3;ft.ANIMATIONTYPE_COLOR3=4;ft.ANIMATIONTYPE_COLOR4=7;ft.ANIMATIONTYPE_VECTOR2=5;ft.ANIMATIONTYPE_SIZE=6;ft.ANIMATIONLOOPMODE_RELATIVE=0;ft.ANIMATIONLOOPMODE_CYCLE=1;ft.ANIMATIONLOOPMODE_CONSTANT=2;ft.ANIMATIONLOOPMODE_YOYO=4;ft.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT=5;ft.CreateFromSnippetAsync=ft.ParseFromSnippetAsync;wt("BABYLON.Animation",ft);_i._AnimationRangeFactory=(n,e,t)=>new If(n,e,t)});var Um,SG=C(()=>{Iy();Mf();Um=class n{constructor(){this.transitionDuration=450,this.lowerRadiusTransitionRange=2,this.upperRadiusTransitionRange=-2,this._autoTransitionRange=!1,this._attachedCamera=null,this._radiusIsAnimating=!1,this._radiusBounceTransition=null,this._animatables=new Array}get name(){return"Bouncing"}get autoTransitionRange(){return this._autoTransitionRange}set autoTransitionRange(e){if(this._autoTransitionRange===e)return;this._autoTransitionRange=e;let t=this._attachedCamera;t&&(e?this._onMeshTargetChangedObserver=t.onMeshTargetChangedObservable.add(i=>{if(i&&(i.computeWorldMatrix(!0),i.getBoundingInfo)){let r=i.getBoundingInfo().diagonalLength;this.lowerRadiusTransitionRange=r*.05,this.upperRadiusTransitionRange=r*.05}}):this._onMeshTargetChangedObserver&&t.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver))}get attachedNode(){return this._attachedCamera}init(){}attach(e){this._attachedCamera=e,this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{this._attachedCamera&&(this._isRadiusAtLimit(this._attachedCamera.lowerRadiusLimit)&&this._applyBoundRadiusAnimation(this.lowerRadiusTransitionRange),this._isRadiusAtLimit(this._attachedCamera.upperRadiusLimit)&&this._applyBoundRadiusAnimation(this.upperRadiusTransitionRange))})}detach(){this._attachedCamera&&(this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null)}_isRadiusAtLimit(e){return this._attachedCamera?this._attachedCamera.radius===e&&!this._radiusIsAnimating:!1}_applyBoundRadiusAnimation(e){if(!this._attachedCamera)return;this._radiusBounceTransition||(n.EasingFunction.setEasingMode(n.EasingMode),this._radiusBounceTransition=ft.CreateAnimation("radius",ft.ANIMATIONTYPE_FLOAT,60,n.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;let t=ft.TransitionTo("radius",this._attachedCamera.radius+e,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusBounceTransition,this.transitionDuration,()=>this._clearAnimationLocks());t&&this._animatables.push(t)}_clearAnimationLocks(){this._radiusIsAnimating=!1,this._attachedCamera&&(this._attachedCamera.wheelPrecision=this._cachedWheelPrecision)}stopAllAnimations(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0].onAnimationEnd=null,this._animatables[0].stop(),this._animatables.shift()}};Um.EasingFunction=new wA(.3);Um.EasingMode=po.EASINGMODE_EASEOUT});var Cf,TG=C(()=>{Iy();hi();oo();Fl();Ve();Mf();Cf=class n{constructor(){this.onTargetFramingAnimationEndObservable=new ie,this._mode=n.FitFrustumSidesMode,this._radiusScale=1,this._positionScale=.5,this._defaultElevation=.3,this._elevationReturnTime=1500,this._elevationReturnWaitTime=1e3,this._zoomStopsAnimation=!1,this._framingTime=1500,this.autoCorrectCameraLimitsAndSensibility=!0,this._attachedCamera=null,this._isPointerDown=!1,this._lastInteractionTime=-1/0,this._animatables=new Array,this._betaIsAnimating=!1}get name(){return"Framing"}set mode(e){this._mode=e}get mode(){return this._mode}set radiusScale(e){this._radiusScale=e}get radiusScale(){return this._radiusScale}set positionScale(e){this._positionScale=e}get positionScale(){return this._positionScale}set defaultElevation(e){this._defaultElevation=e}get defaultElevation(){return this._defaultElevation}set elevationReturnTime(e){this._elevationReturnTime=e}get elevationReturnTime(){return this._elevationReturnTime}set elevationReturnWaitTime(e){this._elevationReturnWaitTime=e}get elevationReturnWaitTime(){return this._elevationReturnWaitTime}set zoomStopsAnimation(e){this._zoomStopsAnimation=e}get zoomStopsAnimation(){return this._zoomStopsAnimation}set framingTime(e){this._framingTime=e}get framingTime(){return this._framingTime}get attachedNode(){return this._attachedCamera}init(){}attach(e){this._attachedCamera=e;let t=this._attachedCamera.getScene();n.EasingFunction.setEasingMode(n.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add(i=>{if(i.type===st.POINTERDOWN){this._isPointerDown=!0;return}i.type===st.POINTERUP&&(this._isPointerDown=!1)}),this._onMeshTargetChangedObserver=e.onMeshTargetChangedObservable.add(i=>{i&&i.getBoundingInfo&&this.zoomOnMesh(i,void 0,()=>{this.onTargetFramingAnimationEndObservable.notifyObservers()})}),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{this._applyUserInteraction(),this._maintainCameraAboveGround()})}detach(){if(!this._attachedCamera)return;let e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null}zoomOnMesh(e,t=!1,i=null){e.computeWorldMatrix(!0);let r=e.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(r.minimumWorld,r.maximumWorld,t,i)}zoomOnMeshHierarchy(e,t=!1,i=null){e.computeWorldMatrix(!0);let r=e.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(r.min,r.max,t,i)}zoomOnMeshesHierarchy(e,t=!1,i=null){let r=new b(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),s=new b(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let a=0;a{this.stopAllAnimations(),r&&r(),this._attachedCamera&&this._attachedCamera.useInputToRestoreState&&this._attachedCamera.storeState()}),f&&this._animatables.push(f),!0}_calculateLowerRadiusFromModelBoundingSphere(e,t){let i=this._attachedCamera;if(!i)return 0;let r=i._calculateLowerRadiusFromModelBoundingSphere(e,t,this._radiusScale);return i.lowerRadiusLimit&&this._mode===n.IgnoreBoundsSizeMode&&(r=ri.upperRadiusLimit?i.upperRadiusLimit:r),r}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;let e=mr.Now-this._lastInteractionTime,t=Math.PI*.5-this._defaultElevation,i=Math.PI*.5;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>i&&e>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=ft.CreateAnimation("beta",ft.ANIMATIONTYPE_FLOAT,60,n.EasingFunction));let r=ft.TransitionTo("beta",t,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,()=>{this._clearAnimationLocks(),this.stopAllAnimations()});r&&this._animatables.push(r)}}_clearAnimationLocks(){this._betaIsAnimating=!1}_applyUserInteraction(){this.isUserIsMoving&&(this._lastInteractionTime=mr.Now,this.stopAllAnimations(),this._clearAnimationLocks())}stopAllAnimations(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0]&&(this._animatables[0].onAnimationEnd=null,this._animatables[0].stop()),this._animatables.shift()}get isUserIsMoving(){return this._attachedCamera?this._attachedCamera.inertialAlphaOffset!==0||this._attachedCamera.inertialBetaOffset!==0||this._attachedCamera.inertialRadiusOffset!==0||this._attachedCamera.inertialPanningX!==0||this._attachedCamera.inertialPanningY!==0||this._isPointerDown:!1}};Cf.EasingFunction=new FA;Cf.EasingMode=po.EASINGMODE_EASEINOUT;Cf.IgnoreBoundsSizeMode=0;Cf.FitFrustumSidesMode=1});var BA,Ny,Is,wy=C(()=>{Gt();Ut();sl();Ve();Dn();Xu();qs();_i.AddNodeConstructor("TargetCamera",(n,e)=>()=>new Is(n,b.Zero(),e));BA=j.Zero(),Ny=Ye.Identity(),Is=class n extends ut{constructor(e,t,i,r=!0){super(e,t,i,r),this.cameraDirection=new b(0,0,0),this.cameraRotation=new we(0,0),this.updateUpVectorFromRotation=!1,this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this._panningEpsilon=Ot,this._rotationEpsilon=Ot,this.lockedTarget=null,this._currentTarget=b.Zero(),this._initialFocalDistance=1,this._viewMatrix=j.Zero(),this._cameraTransformMatrix=j.Zero(),this._cameraRotationMatrix=j.Zero(),this._transformedReferencePoint=b.Zero(),this._deferredPositionUpdate=new b,this._deferredRotationQuaternionUpdate=new Ye,this._deferredRotationUpdate=new b,this._deferredUpdated=!1,this._deferOnly=!1,this._cachedRotationZ=0,this._cachedQuaternionRotationZ=0,this._referencePoint=b.Forward(this.getScene().useRightHandedSystem),this.rotation=new b(0,this.getScene().useRightHandedSystem?Math.PI:0,0)}getFrontPosition(e){this.getWorldMatrix();let t=$.Vector3[0],i=$.Vector3[1];return i.set(0,0,this._scene.useRightHandedSystem?-1:1),this.getDirectionToRef(i,t),t.scaleInPlace(e),this.globalPosition.add(t)}_getLockedTargetPosition(){if(!this.lockedTarget)return null;if(this.lockedTarget.absolutePosition){let e=this.lockedTarget;e.computeWorldMatrix().getTranslationToRef(e.absolutePosition)}return this.lockedTarget.absolutePosition||this.lockedTarget}storeState(){return this._storedPosition=this.position.clone(),this._storedRotation=this.rotation.clone(),this.rotationQuaternion&&(this._storedRotationQuaternion=this.rotationQuaternion.clone()),super.storeState()}_restoreStateValues(){return super._restoreStateValues()?(this.position=this._storedPosition.clone(),this.rotation=this._storedRotation.clone(),this.rotationQuaternion&&this._storedRotationQuaternion&&(this.rotationQuaternion=this._storedRotationQuaternion.clone()),this.cameraDirection.copyFromFloats(0,0,0),this.cameraRotation.copyFromFloats(0,0),!0):!1}_initCache(){super._initCache(),this._cache.lockedTarget=new b(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new b(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new Ye(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)}_updateCache(e){e||super._updateCache();let t=this._getLockedTargetPosition();t?this._cache.lockedTarget?this._cache.lockedTarget.copyFrom(t):this._cache.lockedTarget=t.clone():this._cache.lockedTarget=null,this._cache.rotation.copyFrom(this.rotation),this.rotationQuaternion&&this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion)}_isSynchronizedViewMatrix(){if(!super._isSynchronizedViewMatrix())return!1;let e=this._getLockedTargetPosition();return(this._cache.lockedTarget?this._cache.lockedTarget.equals(e):!e)&&(this.rotationQuaternion?this.rotationQuaternion.equals(this._cache.rotationQuaternion):this._cache.rotation.equals(this.rotation))}_computeLocalCameraSpeed(){let e=this.getEngine();return this.speed*Math.sqrt(e.getDeltaTime()/(e.getFps()*100))}setTarget(e){this.upVector.normalize(),this._initialFocalDistance=e.subtract(this.position).length(),this.position.z===e.z&&(this.position.z+=Ot),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),this.getScene().useRightHandedSystem?j.LookAtRHToRef(this.position,e,b.UpReadOnly,BA):j.LookAtLHToRef(this.position,e,b.UpReadOnly,BA),BA.invert();let t=this.rotationQuaternion||Ny;Ye.FromRotationMatrixToRef(BA,t),t.toEulerAnglesToRef(this.rotation),this.rotation.z=0}get target(){return this.getTarget()}set target(e){this.setTarget(e)}getTarget(){return this._currentTarget}_decideIfNeedsToMove(){return Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){if(this.parent){this.parent.getWorldMatrix().invertToRef($.Matrix[0]),b.TransformNormalToRef(this.cameraDirection,$.Matrix[0],$.Vector3[0]),this._deferredPositionUpdate.addInPlace($.Vector3[0]),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate);return}this._deferredPositionUpdate.addInPlace(this.cameraDirection),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate)}_checkInputs(){let e=this.invertRotation?-this.inverseRotationSpeed:1,t=this._decideIfNeedsToMove(),i=this.cameraRotation.x||this.cameraRotation.y;this._deferredUpdated=!1,this._deferredRotationUpdate.copyFrom(this.rotation),this._deferredPositionUpdate.copyFrom(this.position),this.rotationQuaternion&&this._deferredRotationQuaternionUpdate.copyFrom(this.rotationQuaternion),t&&this._updatePosition(),i&&(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this._deferredRotationUpdate),this._deferredRotationUpdate.x+=this.cameraRotation.x*e,this._deferredRotationUpdate.y+=this.cameraRotation.y*e,this.noRotationConstraint||(this._deferredRotationUpdate.x>1.570796&&(this._deferredRotationUpdate.x=1.570796),this._deferredRotationUpdate.x<-1.570796&&(this._deferredRotationUpdate.x=-1.570796)),this._deferOnly?this._deferredUpdated=!0:this.rotation.copyFrom(this._deferredRotationUpdate),this.rotationQuaternion&&this._deferredRotationUpdate.lengthSquared()&&(Ye.RotationYawPitchRollToRef(this._deferredRotationUpdate.y,this._deferredRotationUpdate.x,this._deferredRotationUpdate.z,this._deferredRotationQuaternionUpdate),this._deferOnly?this._deferredUpdated=!0:this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate)));let r=this.speed*this._panningEpsilon,s=this.speed*this._rotationEpsilon;t&&(Math.abs(this.cameraDirection.x){yt();Tr();sl();Gn={},Vm=class{constructor(e){this.attachedToElement=!1,this.attached={},this.camera=e,this.checkInputs=()=>{}}add(e){let t=e.getSimpleName();if(this.attached[t]){te.Warn("camera input of type "+t+" already exists on camera");return}this.attached[t]=e,e.camera=this.camera,e.checkInputs&&(this.checkInputs=this._addCheckInputs(e.checkInputs.bind(e))),this.attachedToElement&&e.attachControl(this.noPreventDefault)}remove(e){for(let t in this.attached){let i=this.attached[t];if(i===e){i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck();return}}}removeByType(e){for(let t in this.attached){let i=this.attached[t];i.getClassName()===e&&(i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck())}}_addCheckInputs(e){let t=this.checkInputs;return()=>{t(),e()}}attachInput(e){this.attachedToElement&&e.attachControl(this.noPreventDefault)}attachElement(e=!1){if(!this.attachedToElement){e=ut.ForceAttachControlToAlwaysPreventDefault?!1:e,this.attachedToElement=!0,this.noPreventDefault=e;for(let t in this.attached)this.attached[t].attachControl(e)}}detachElement(e=!1){for(let t in this.attached)this.attached[t].detachControl(),e&&(this.attached[t].camera=null);this.attachedToElement=!1}rebuildInputCheck(){this.checkInputs=()=>{};for(let e in this.attached){let t=this.attached[e];t.checkInputs&&(this.checkInputs=this._addCheckInputs(t.checkInputs.bind(t)))}}clear(){this.attachedToElement&&this.detachElement(!0),this.attached={},this.attachedToElement=!1,this.checkInputs=()=>{}}serialize(e){let t={};for(let i in this.attached){let r=this.attached[i],s=it.Serialize(r);t[r.getClassName()]=s}e.inputsmgr=t}parse(e){let t=e.inputsmgr;if(t){this.clear();for(let i in t){let r=Gn[i];if(r){let s=t[i],a=it.Parse(()=>new r,s,null);this.add(a)}}}else for(let i in this.attached){let r=Gn[this.attached[i].getClassName()];if(r){let s=it.Parse(()=>new r,e,null);this.remove(this.attached[i]),this.add(s)}}}}});var ug,AG=C(()=>{Gt();Ut();bi();oo();ug=class{constructor(){this._currentMousePointerIdDown=-1,this.buttons=[0,1,2]}attachControl(e){e=pe.BackCompatCameraNoPreventDefault(arguments);let t=this.camera.getEngine(),i=t.getInputElement(),r=0,s=null;this._pointA=null,this._pointB=null,this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._pointerInput=o=>{var h,d;let l=o.event,c=l.pointerType==="touch";if(o.type!==st.POINTERMOVE&&this.buttons.indexOf(l.button)===-1)return;let f=l.target;if(this._altKey=l.altKey,this._ctrlKey=l.ctrlKey,this._metaKey=l.metaKey,this._shiftKey=l.shiftKey,this._buttonsPressed=l.buttons,t.isPointerLock){let u=l.movementX,m=l.movementY;this.onTouch(null,u,m),this._pointA=null,this._pointB=null}else{if(o.type!==st.POINTERDOWN&&o.type!==st.POINTERDOUBLETAP&&c&&((h=this._pointA)==null?void 0:h.pointerId)!==l.pointerId&&((d=this._pointB)==null?void 0:d.pointerId)!==l.pointerId)return;if(o.type===st.POINTERDOWN&&(this._currentMousePointerIdDown===-1||c)){try{f==null||f.setPointerCapture(l.pointerId)}catch(u){}if(this._pointA===null)this._pointA={x:l.clientX,y:l.clientY,pointerId:l.pointerId,type:l.pointerType,button:l.button};else if(this._pointB===null)this._pointB={x:l.clientX,y:l.clientY,pointerId:l.pointerId,type:l.pointerType,button:l.button};else return;this._currentMousePointerIdDown===-1&&!c&&(this._currentMousePointerIdDown=l.pointerId),this.onButtonDown(l),e||(l.preventDefault(),i&&i.focus())}else if(o.type===st.POINTERDOUBLETAP)this.onDoubleTap(l.pointerType);else if(o.type===st.POINTERUP&&(this._currentMousePointerIdDown===l.pointerId||c)){try{f==null||f.releasePointerCapture(l.pointerId)}catch(u){}c||(this._pointB=null),t._badOS?this._pointA=this._pointB=null:this._pointB&&this._pointA&&this._pointA.pointerId==l.pointerId?(this._pointA=this._pointB,this._pointB=null):this._pointA&&this._pointB&&this._pointB.pointerId==l.pointerId?this._pointB=null:this._pointA=this._pointB=null,(r!==0||s)&&(this.onMultiTouch(this._pointA,this._pointB,r,0,s,null),r=0,s=null),this._currentMousePointerIdDown=-1,this.onButtonUp(l),e||l.preventDefault()}else if(o.type===st.POINTERMOVE){if(e||l.preventDefault(),this._pointA&&this._pointB===null){let u=l.clientX-this._pointA.x,m=l.clientY-this._pointA.y;this._pointA.x=l.clientX,this._pointA.y=l.clientY,this.onTouch(this._pointA,u,m)}else if(this._pointA&&this._pointB){let u=this._pointA.pointerId===l.pointerId?this._pointA:this._pointB;u.x=l.clientX,u.y=l.clientY;let m=this._pointA.x-this._pointB.x,p=this._pointA.y-this._pointB.y,_=m*m+p*p,g={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:l.pointerId,type:o.type};this.onMultiTouch(this._pointA,this._pointB,r,_,s,g),s=g,r=_}}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,st.POINTERDOWN|st.POINTERUP|st.POINTERMOVE|st.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,r=0,s=null,this.onLostFocus()},this._contextMenuBind=o=>this.onContextMenu(o),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);let a=this.camera.getScene().getEngine().getHostWindow();a&&pe.RegisterTopRootEvents(a,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){let e=this.camera.getScene().getEngine().getHostWindow();e&&pe.UnregisterTopRootEvents(e,[{name:"blur",handler:this._onLostFocus}])}if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._contextMenuBind){let e=this.camera.getScene().getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this._onLostFocus=null}this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._currentMousePointerIdDown=-1}getClassName(){return"BaseCameraPointersInput"}getSimpleName(){return"pointers"}onDoubleTap(e){}onTouch(e,t,i){}onMultiTouch(e,t,i,r,s,a){}onContextMenu(e){e.preventDefault()}onButtonDown(e){}onButtonUp(e){}onLostFocus(){}};P([w()],ug.prototype,"buttons",void 0)});var $h,xG=C(()=>{Gt();Ut();AG();$h=class extends ug{constructor(){super(...arguments),this.pinchZoom=!0,this.multiTouchPanning=!0,this.multiTouchPanAndZoom=!0,this._isPinching=!1,this._twoFingerActivityCount=0,this._shouldStartPinchZoom=!1}_computePinchZoom(e,t){}_computeMultiTouchPanning(e,t){}onMultiTouch(e,t,i,r,s,a){i===0&&s===null||r===0&&a===null||(this.multiTouchPanAndZoom?(this._computePinchZoom(i,r),this._computeMultiTouchPanning(s,a)):this.multiTouchPanning&&this.pinchZoom?(this._twoFingerActivityCount++,this._isPinching||this._shouldStartPinchZoom?(this._computePinchZoom(i,r),this._isPinching=!0):this._computeMultiTouchPanning(s,a)):this.multiTouchPanning?this._computeMultiTouchPanning(s,a):this.pinchZoom&&this._computePinchZoom(i,r))}onButtonUp(e){this._twoFingerActivityCount=0,this._isPinching=!1}onLostFocus(){this._twoFingerActivityCount=0,this._isPinching=!1}};P([w()],$h.prototype,"pinchZoom",void 0);P([w()],$h.prototype,"multiTouchPanning",void 0);P([w()],$h.prototype,"multiTouchPanAndZoom",void 0)});var Zs,RG=C(()=>{Gt();Ut();fl();xG();Zs=class n extends $h{constructor(){super(...arguments),this.buttons=[0,1,2],this.angularSensibilityX=1e3,this.angularSensibilityY=1e3,this.pinchPrecision=12,this.pinchDeltaPercentage=0,this.useNaturalPinchZoom=!1,this.panningSensibility=1e3,this.pinchInwards=!0,this._isPanClick=!1}getClassName(){return"ArcRotateCameraPointersInput"}_computeMultiTouchPanning(e,t){if(this.panningSensibility!==0&&e&&t){let i=t.x-e.x,r=t.y-e.y;this.camera.inertialPanningX+=-i/this.panningSensibility,this.camera.inertialPanningY+=r/this.panningSensibility}}_computePinchZoom(e,t){let i=this.camera.radius||n.MinimumRadiusForPinch;this.useNaturalPinchZoom?this.camera.radius=i*Math.sqrt(e)/Math.sqrt(t):this.pinchDeltaPercentage?this.camera.inertialRadiusOffset+=(t-e)*.001*i*this.pinchDeltaPercentage:this.camera.inertialRadiusOffset+=(t-e)/(this.pinchPrecision*(this.pinchInwards?1:-1)*(this.angularSensibilityX+this.angularSensibilityY)/2)}onTouch(e,t,i){this.panningSensibility!==0&&(this._ctrlKey&&this.camera._useCtrlForPanning||this._isPanClick)?(this.camera.inertialPanningX+=-t/this.panningSensibility,this.camera.inertialPanningY+=i/this.panningSensibility):(this.camera.inertialAlphaOffset-=t/this.angularSensibilityX,this.camera.inertialBetaOffset-=i/this.angularSensibilityY)}onDoubleTap(){this.camera.useInputToRestoreState&&this.camera.restoreState()}onMultiTouch(e,t,i,r,s,a){this._shouldStartPinchZoom=this._twoFingerActivityCount<20&&Math.abs(Math.sqrt(r)-Math.sqrt(i))>this.camera.pinchToPanMaxDistance,super.onMultiTouch(e,t,i,r,s,a)}onButtonDown(e){this._isPanClick=e.button===this.camera._panningMouseButton,super.onButtonDown(e)}onButtonUp(e){super.onButtonUp(e)}onLostFocus(){this._isPanClick=!1,super.onLostFocus()}};Zs.MinimumRadiusForPinch=.001;P([w()],Zs.prototype,"buttons",void 0);P([w()],Zs.prototype,"angularSensibilityX",void 0);P([w()],Zs.prototype,"angularSensibilityY",void 0);P([w()],Zs.prototype,"pinchPrecision",void 0);P([w()],Zs.prototype,"pinchDeltaPercentage",void 0);P([w()],Zs.prototype,"useNaturalPinchZoom",void 0);P([w()],Zs.prototype,"panningSensibility",void 0);Gn.ArcRotateCameraPointersInput=Zs});var Ms,bG=C(()=>{Gt();Ut();fl();oA();bi();Ms=class{constructor(){this.keysUp=[38],this.keysDown=[40],this.keysLeft=[37],this.keysRight=[39],this.keysReset=[220],this.panningSensibility=50,this.zoomingSensibility=25,this.useAltToZoom=!0,this.angularSpeed=.01,this._keys=new Array}attachControl(e){e=pe.BackCompatCameraNoPreventDefault(arguments),!this._onCanvasBlurObserver&&(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add(()=>{this._keys.length=0}),this._onKeyboardObserver=this._scene.onKeyboardObservable.add(t=>{let i=t.event;if(!i.metaKey){if(t.type===lo.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,(this.keysUp.indexOf(i.keyCode)!==-1||this.keysDown.indexOf(i.keyCode)!==-1||this.keysLeft.indexOf(i.keyCode)!==-1||this.keysRight.indexOf(i.keyCode)!==-1||this.keysReset.indexOf(i.keyCode)!==-1)&&(this._keys.indexOf(i.keyCode)===-1&&this._keys.push(i.keyCode),i.preventDefault&&(e||i.preventDefault()));else if(this.keysUp.indexOf(i.keyCode)!==-1||this.keysDown.indexOf(i.keyCode)!==-1||this.keysLeft.indexOf(i.keyCode)!==-1||this.keysRight.indexOf(i.keyCode)!==-1||this.keysReset.indexOf(i.keyCode)!==-1){let r=this._keys.indexOf(i.keyCode);r>=0&&this._keys.splice(r,1),i.preventDefault&&(e||i.preventDefault())}}}))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){if(this._onKeyboardObserver){let e=this.camera;for(let t=0;t{Gt();Ut();fl();oo();Zu();Ve();Dn();lA();Ln();bi();yse=40,yf=class{constructor(){this.wheelPrecision=3,this.zoomToMouseLocation=!1,this.wheelDeltaPercentage=0,this.customComputeDeltaFromMouseWheel=null,this._viewOffset=new b(0,0,0),this._globalOffset=new b(0,0,0),this._inertialPanning=b.Zero()}_computeDeltaFromMouseWheelLegacyEvent(e,t){let i,r=e*.01*this.wheelDeltaPercentage*t;return e>0?i=r/(1+this.wheelDeltaPercentage):i=r*(1+this.wheelDeltaPercentage),i}attachControl(e){e=pe.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==st.POINTERWHEEL)return;let i=t.event,r,s=i.deltaMode===co.DOM_DELTA_LINE?yse:1,a=-(i.deltaY*s);if(this.customComputeDeltaFromMouseWheel)r=this.customComputeDeltaFromMouseWheel(a,this,i);else if(this.wheelDeltaPercentage){if(r=this._computeDeltaFromMouseWheelLegacyEvent(a,this.camera.radius),r>0){let o=this.camera.radius,l=this.camera.inertialRadiusOffset+r;for(let c=0;c<20&&!(o<=l||Math.abs(l*this.camera.inertia)<.001);c++)o-=l,l*=this.camera.inertia;o=Nt(o,0,Number.MAX_VALUE),r=this._computeDeltaFromMouseWheelLegacyEvent(a,o)}}else r=a/(this.wheelPrecision*40);r&&(this.zoomToMouseLocation?(this._hitPlane||this._updateHitPlane(),this._zoomToMouse(r)):this.camera.inertialRadiusOffset+=r),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,st.POINTERWHEEL),this.zoomToMouseLocation&&this._inertialPanning.setAll(0)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}checkInputs(){if(!this.zoomToMouseLocation)return;let e=this.camera;0+e.inertialAlphaOffset+e.inertialBetaOffset+e.inertialRadiusOffset&&(this._updateHitPlane(),e.target.addInPlace(this._inertialPanning),this._inertialPanning.scaleInPlace(e.inertia),this._zeroIfClose(this._inertialPanning))}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}_updateHitPlane(){let e=this.camera,t=e.target.subtract(e.position);this._hitPlane=to.FromPositionAndNormal(e.target,t)}_getPosition(){var s;let e=this.camera,t=e.getScene(),i=t.createPickingRay(t.pointerX,t.pointerY,j.Identity(),e,!1);(e.targetScreenOffset.x!==0||e.targetScreenOffset.y!==0)&&(this._viewOffset.set(e.targetScreenOffset.x,e.targetScreenOffset.y,0),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),this._globalOffset=b.TransformNormal(this._viewOffset,e._cameraTransformMatrix),i.origin.addInPlace(this._globalOffset));let r=0;return this._hitPlane&&(r=(s=i.intersectsPlane(this._hitPlane))!=null?s:0),i.origin.addInPlace(i.direction.scaleInPlace(r))}_zoomToMouse(e){var l,c;let t=this.camera,i=1-t.inertia;if(t.lowerRadiusLimit){let f=(l=t.lowerRadiusLimit)!=null?l:0;t.radius-(t.inertialRadiusOffset+e)/if&&(e=(t.radius-f)*i-t.inertialRadiusOffset)}let s=e/i/t.radius,a=this._getPosition(),o=$.Vector3[6];a.subtractToRef(t.target,o),o.scaleInPlace(s),o.scaleInPlace(i),this._inertialPanning.addInPlace(o),t.inertialRadiusOffset+=e}_zeroIfClose(e){Math.abs(e.x){RG();bG();IG();fl();UA=class extends Vm{constructor(e){super(e)}addMouseWheel(){return this.add(new yf),this}addPointers(){return this.add(new Zs),this}addKeyboard(){return this.add(new Ms),this}}});function Pse(n){let e=Math.PI/2;return n.x===0&&n.z===0||(e=Math.acos(n.x/Math.sqrt(Math.pow(n.x,2)+Math.pow(n.z,2)))),n.z<0&&(e=2*Math.PI-e),e}function Dse(n,e){return Math.acos(n/e)}function kn(n,e){return isNaN(n)?e:n}var gi,VA=C(()=>{Gt();Ut();hi();Ve();Ln();qs();Ii();by();SG();TG();sl();wy();MG();Dn();bi();Hi();_i.AddNodeConstructor("ArcRotateCamera",(n,e)=>()=>new gi(n,0,0,1,b.Zero(),e));gi=class n extends Is{get target(){return this._target}set target(e){this.setTarget(e)}get targetHost(){return this._targetHost}set targetHost(e){e&&this.setTarget(e)}getTarget(){return this.target}get position(){return this._position}set position(e){this.setPosition(e)}set upVector(e){this._upToYMatrix||(this._yToUpMatrix=new j,this._upToYMatrix=new j,this._upVector=b.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){j.RotationAlignToRef(b.UpReadOnly,this._upVector,this._yToUpMatrix),j.RotationAlignToRef(this._upVector,b.UpReadOnly,this._upToYMatrix)}get angularSensibilityX(){let e=this.inputs.attached.pointers;return e?e.angularSensibilityX:0}set angularSensibilityX(e){let t=this.inputs.attached.pointers;t&&(t.angularSensibilityX=e)}get angularSensibilityY(){let e=this.inputs.attached.pointers;return e?e.angularSensibilityY:0}set angularSensibilityY(e){let t=this.inputs.attached.pointers;t&&(t.angularSensibilityY=e)}get pinchPrecision(){let e=this.inputs.attached.pointers;return e?e.pinchPrecision:0}set pinchPrecision(e){let t=this.inputs.attached.pointers;t&&(t.pinchPrecision=e)}get pinchDeltaPercentage(){let e=this.inputs.attached.pointers;return e?e.pinchDeltaPercentage:0}set pinchDeltaPercentage(e){let t=this.inputs.attached.pointers;t&&(t.pinchDeltaPercentage=e)}get useNaturalPinchZoom(){let e=this.inputs.attached.pointers;return e?e.useNaturalPinchZoom:!1}set useNaturalPinchZoom(e){let t=this.inputs.attached.pointers;t&&(t.useNaturalPinchZoom=e)}get panningSensibility(){let e=this.inputs.attached.pointers;return e?e.panningSensibility:0}set panningSensibility(e){let t=this.inputs.attached.pointers;t&&(t.panningSensibility=e)}get keysUp(){let e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){let t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){let e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){let t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){let e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){let t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){let e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){let t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}get wheelPrecision(){let e=this.inputs.attached.mousewheel;return e?e.wheelPrecision:0}set wheelPrecision(e){let t=this.inputs.attached.mousewheel;t&&(t.wheelPrecision=e)}get zoomToMouseLocation(){let e=this.inputs.attached.mousewheel;return e?e.zoomToMouseLocation:!1}set zoomToMouseLocation(e){let t=this.inputs.attached.mousewheel;t&&(t.zoomToMouseLocation=e)}get wheelDeltaPercentage(){let e=this.inputs.attached.mousewheel;return e?e.wheelDeltaPercentage:0}set wheelDeltaPercentage(e){let t=this.inputs.attached.mousewheel;t&&(t.wheelDeltaPercentage=e)}get isInterpolating(){return this._isInterpolating}get bouncingBehavior(){return this._bouncingBehavior}get useBouncingBehavior(){return this._bouncingBehavior!=null}set useBouncingBehavior(e){e!==this.useBouncingBehavior&&(e?(this._bouncingBehavior=new Um,this.addBehavior(this._bouncingBehavior)):this._bouncingBehavior&&(this.removeBehavior(this._bouncingBehavior),this._bouncingBehavior=null))}get framingBehavior(){return this._framingBehavior}get useFramingBehavior(){return this._framingBehavior!=null}set useFramingBehavior(e){e!==this.useFramingBehavior&&(e?(this._framingBehavior=new Cf,this.addBehavior(this._framingBehavior)):this._framingBehavior&&(this.removeBehavior(this._framingBehavior),this._framingBehavior=null))}get autoRotationBehavior(){return this._autoRotationBehavior}get useAutoRotationBehavior(){return this._autoRotationBehavior!=null}set useAutoRotationBehavior(e){e!==this.useAutoRotationBehavior&&(e?(this._autoRotationBehavior=new Bm,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,i,r,s,a,o=!0){super(e,b.Zero(),a,o),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.lowerAlphaLimit=null,this.upperAlphaLimit=null,this.lowerBetaLimit=.01,this.upperBetaLimit=Math.PI-.01,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.lowerTargetYLimit=-1/0,this.inertialPanningX=0,this.inertialPanningY=0,this.pinchToPanMaxDistance=20,this.panningDistanceLimit=null,this.panningOriginTarget=b.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=we.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this.restoreStateInterpolationFactor=0,this._currentInterpolationFactor=0,this._viewMatrix=new j,this.panningAxis=new b(1,1,0),this._transformedDirection=new b,this.mapPanning=!1,this._isInterpolating=!1,this.onMeshTargetChangedObservable=new ie,this.checkCollisions=!1,this.collisionRadius=new b(.5,.5,.5),this._previousPosition=b.Zero(),this._collisionVelocity=b.Zero(),this._newPosition=b.Zero(),this._computationVector=b.Zero(),this._goalAlpha=NaN,this._goalBeta=NaN,this._goalRadius=NaN,this._goalTarget=new b(NaN,NaN,NaN),this._goalTargetScreenOffset=new we(NaN,NaN),this._onCollisionPositionChange=(l,c,f=null)=>{f?(this.setPosition(c),this.onCollide&&this.onCollide(f)):this._previousPosition.copyFrom(this._position);let h=Math.cos(this.alpha),d=Math.sin(this.alpha),u=Math.cos(this.beta),m=Math.sin(this.beta);m===0&&(m=1e-4);let p=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*h*m,this.radius*u,this.radius*d*m),p.addToRef(this._computationVector,this._newPosition),this._position.copyFrom(this._newPosition);let _=this.upVector;this.allowUpsideDown&&this.beta<0&&(_=_.clone(),_=_.negate()),this._computeViewMatrix(this._position,p,_),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=b.Zero(),s&&this.setTarget(s),this.alpha=t,this.beta=i,this.radius=r,this.getViewMatrix(),this.inputs=new UA(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_initCache(){super._initCache(),this._cache._target=new b(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.alpha=void 0,this._cache.beta=void 0,this._cache.radius=void 0,this._cache.targetScreenOffset=we.Zero()}_updateCache(e){e||super._updateCache(),this._cache._target.copyFrom(this._getTargetPosition()),this._cache.alpha=this.alpha,this._cache.beta=this.beta,this._cache.radius=this.radius,this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset)}_getTargetPosition(){if(this._targetHost&&this._targetHost.getAbsolutePosition){let t=this._targetHost.getAbsolutePosition();this._targetBoundingCenter?t.addToRef(this._targetBoundingCenter,this._target):this._target.copyFrom(t)}let e=this._getLockedTargetPosition();return e||this._target}storeState(){return this._storedAlpha=this.alpha,this._storedBeta=this.beta,this._storedRadius=this.radius,this._storedTarget=this._getTargetPosition().clone(),this._storedTargetScreenOffset=this.targetScreenOffset.clone(),super.storeState()}_restoreStateValues(){return this.hasStateStored()&&this.restoreStateInterpolationFactor>Ot&&this.restoreStateInterpolationFactor<1?(this.interpolateTo(this._storedAlpha,this._storedBeta,this._storedRadius,this._storedTarget,this._storedTargetScreenOffset,this.restoreStateInterpolationFactor),!0):super._restoreStateValues()?(this.setTarget(this._storedTarget.clone()),this.alpha=this._storedAlpha,this.beta=this._storedBeta,this.radius=this._storedRadius,this.targetScreenOffset=this._storedTargetScreenOffset.clone(),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,!0):!1}stopInterpolation(){this._goalAlpha=NaN,this._goalBeta=NaN,this._goalRadius=NaN,this._goalTarget.set(NaN,NaN,NaN),this._goalTargetScreenOffset.set(NaN,NaN)}interpolateTo(e=this.alpha,t=this.beta,i=this.radius,r=this.target,s=this.targetScreenOffset,a){var o,l,c,f,h,d,u;this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,a!=null?this._currentInterpolationFactor=a:this.restoreStateInterpolationFactor!==0?this._currentInterpolationFactor=this.restoreStateInterpolationFactor:this._currentInterpolationFactor=.1,this._goalAlpha=kn(e,this._goalAlpha),this._goalBeta=kn(t,this._goalBeta),this._goalRadius=kn(i,this._goalRadius),this._goalTarget.set(kn(r.x,this._goalTarget.x),kn(r.y,this._goalTarget.y),kn(r.z,this._goalTarget.z)),this._goalTargetScreenOffset.set(kn(s.x,this._goalTargetScreenOffset.x),kn(s.y,this._goalTargetScreenOffset.y)),this._goalAlpha=Nt(this._goalAlpha,(o=this.lowerAlphaLimit)!=null?o:-1/0,(l=this.upperAlphaLimit)!=null?l:1/0),this._goalBeta=Nt(this._goalBeta,(c=this.lowerBetaLimit)!=null?c:-1/0,(f=this.upperBetaLimit)!=null?f:1/0),this._goalRadius=Nt(this._goalRadius,(h=this.lowerRadiusLimit)!=null?h:-1/0,(d=this.upperRadiusLimit)!=null?d:1/0),this._goalTarget.y=Nt(this._goalTarget.y,(u=this.lowerTargetYLimit)!=null?u:-1/0,1/0),this._isInterpolating=!0}_isSynchronizedViewMatrix(){return super._isSynchronizedViewMatrix()?this._cache._target.equals(this._getTargetPosition())&&this._cache.alpha===this.alpha&&this._cache.beta===this.beta&&this._cache.radius===this.radius&&this._cache.targetScreenOffset.equals(this.targetScreenOffset):!1}attachControl(e,t,i=!0,r=2){let s=arguments;t=pe.BackCompatCameraNoPreventDefault(s),this._useCtrlForPanning=i,this._panningMouseButton=r,typeof s[0]=="boolean"&&(s.length>1&&(this._useCtrlForPanning=s[1]),s.length>2&&(this._panningMouseButton=s[2])),this.inputs.attachElement(t),this._reset=()=>{this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){if(this._collisionTriggered)return;this.inputs.checkInputs();let e=!1;if(this.inertialAlphaOffset!==0||this.inertialBetaOffset!==0||this.inertialRadiusOffset!==0){e=!0;let t=this.invertRotation?-1:1,i=this._calculateHandednessMultiplier(),r=this.inertialAlphaOffset*i;this.beta<0&&(r*=-1),this.alpha+=r*t,this.beta+=this.inertialBetaOffset*t,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,Math.abs(this.inertialAlphaOffset)Math.PI&&(this.beta=this.beta-2*Math.PI):this.betathis.upperBetaLimit&&(this.beta=this.upperBetaLimit),this.lowerAlphaLimit!==null&&this.alphathis.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),this.lowerRadiusLimit!==null&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit,this.inertialRadiusOffset=0),this.target.y=Math.max(this.target.y,this.lowerTargetYLimit)}rebuildAnglesAndRadius(){this._position.subtractToRef(this._getTargetPosition(),this._computationVector),(this._upVector.x!==0||this._upVector.y!==1||this._upVector.z!==0)&&b.TransformCoordinatesToRef(this._computationVector,this._upToYMatrix,this._computationVector),this.radius=this._computationVector.length(),this.radius===0&&(this.radius=1e-4);let e=this.alpha;this.alpha=Pse(this._computationVector),this.beta=Dse(this._computationVector.y,this.radius);let t=Math.round((e-this.alpha)/(2*Math.PI));this.alpha+=t*2*Math.PI,this._checkLimits()}setPosition(e){this._position.equals(e)||(this._position.copyFrom(e),this.rebuildAnglesAndRadius())}setTarget(e,t=!1,i=!1,r=!1){var s;if(r=(s=this.overrideCloneAlphaBetaRadius)!=null?s:r,e.computeWorldMatrix)t&&e.getBoundingInfo?this._targetBoundingCenter=e.getBoundingInfo().boundingBox.centerWorld.clone():this._targetBoundingCenter=null,e.computeWorldMatrix(),this._targetHost=e,this._target=this._getTargetPosition(),this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);else{let a=e,o=this._getTargetPosition();if(o&&!i&&o.equals(a))return;this._targetHost=null,this._target=a,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}r||this.rebuildAnglesAndRadius()}_getViewMatrix(){let e=Math.cos(this.alpha),t=Math.sin(this.alpha),i=Math.cos(this.beta),r=Math.sin(this.beta);r===0&&(r=1e-4),this.radius===0&&(this.radius=1e-4);let s=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*r,this.radius*i,this.radius*t*r),(this._upVector.x!==0||this._upVector.y!==1||this._upVector.z!==0)&&b.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),s.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){let a=this.getScene().collisionCoordinator;this._collider||(this._collider=a.createCollider()),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this._position,this._collisionVelocity),this._collisionTriggered=!0,a.getNewPosition(this._position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}else{this._position.copyFrom(this._newPosition);let a=this.upVector;this.allowUpsideDown&&r<0&&(a=a.negate()),this._computeViewMatrix(this._position,s,a),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget.copyFrom(s),this._viewMatrix}zoomOn(e,t=!1){e=e||this.getScene().meshes;let i=Z.MinMax(e),r=this._calculateLowerRadiusFromModelBoundingSphere(i.min,i.max);if(r=Math.max(Math.min(r,this.upperRadiusLimit||Number.MAX_VALUE),this.lowerRadiusLimit||0),this.radius=r*this.zoomOnFactor,this.mode===ut.ORTHOGRAPHIC_CAMERA){let s=this.getScene().getEngine().getAspectRatio(this),a=r*this.zoomOnFactor/2;this.orthoLeft=-a*s,this.orthoRight=a*s,this.orthoBottom=-a,this.orthoTop=a}this.focusOn({min:i.min,max:i.max,distance:r},t)}focusOn(e,t=!1){let i,r;if(e.min===void 0){let s=e||this.getScene().meshes;i=Z.MinMax(s),r=b.Distance(i.min,i.max)}else{let s=e;i=s,r=s.distance}this._target=Z.Center(i),t||(this.maxZ=r*2)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case ut.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case ut.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case ut.RIG_MODE_STEREOSCOPIC_OVERUNDER:case ut.RIG_MODE_STEREOSCOPIC_INTERLACED:case ut.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(t===0?1:-1);break;case ut.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(t===0?-1:1);break}let r=new n(e,this.alpha+i,this.beta,this.radius,this._target,this.getScene());return r._cameraRigParams={},r.isRigCamera=!0,r.rigParent=this,r.upVector=this.upVector,r.mode=this.mode,r.orthoLeft=this.orthoLeft,r.orthoRight=this.orthoRight,r.orthoBottom=this.orthoBottom,r.orthoTop=this.orthoTop,r}_updateRigCameras(){let e=this._rigCameras[0],t=this._rigCameras[1];switch(e.beta=t.beta=this.beta,this.cameraRigMode){case ut.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case ut.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case ut.RIG_MODE_STEREOSCOPIC_OVERUNDER:case ut.RIG_MODE_STEREOSCOPIC_INTERLACED:case ut.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case ut.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:e.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle;break}super._updateRigCameras()}_calculateLowerRadiusFromModelBoundingSphere(e,t,i=1){let r=b.Distance(e,t),a=this.getScene().getEngine().getAspectRatio(this),o=Math.tan(this.fov/2),l=o*a,f=r*.5*i,h=f*Math.sqrt(1+1/(l*l)),d=f*Math.sqrt(1+1/(o*o));return Math.max(h,d)}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"ArcRotateCamera"}};P([w()],gi.prototype,"alpha",void 0);P([w()],gi.prototype,"beta",void 0);P([w()],gi.prototype,"radius",void 0);P([w()],gi.prototype,"overrideCloneAlphaBetaRadius",void 0);P([Hr("target")],gi.prototype,"_target",void 0);P([GT("targetHost")],gi.prototype,"_targetHost",void 0);P([w()],gi.prototype,"inertialAlphaOffset",void 0);P([w()],gi.prototype,"inertialBetaOffset",void 0);P([w()],gi.prototype,"inertialRadiusOffset",void 0);P([w()],gi.prototype,"lowerAlphaLimit",void 0);P([w()],gi.prototype,"upperAlphaLimit",void 0);P([w()],gi.prototype,"lowerBetaLimit",void 0);P([w()],gi.prototype,"upperBetaLimit",void 0);P([w()],gi.prototype,"lowerRadiusLimit",void 0);P([w()],gi.prototype,"upperRadiusLimit",void 0);P([w()],gi.prototype,"lowerTargetYLimit",void 0);P([w()],gi.prototype,"inertialPanningX",void 0);P([w()],gi.prototype,"inertialPanningY",void 0);P([w()],gi.prototype,"pinchToPanMaxDistance",void 0);P([w()],gi.prototype,"panningDistanceLimit",void 0);P([Hr()],gi.prototype,"panningOriginTarget",void 0);P([w()],gi.prototype,"panningInertia",void 0);P([w()],gi.prototype,"zoomToMouseLocation",null);P([w()],gi.prototype,"zoomOnFactor",void 0);P([tm()],gi.prototype,"targetScreenOffset",void 0);P([w()],gi.prototype,"allowUpsideDown",void 0);P([w()],gi.prototype,"useInputToRestoreState",void 0);P([w()],gi.prototype,"restoreStateInterpolationFactor",void 0);wt("BABYLON.ArcRotateCamera",gi)});var Xt,Pf=C(()=>{Gt();Ut();Ve();zt();qs();pf();Hi();z_();Tr();Xt=class n extends _i{get range(){return this._range}set range(e){this._range=e,this._inverseSquaredRange=1/(this.range*this.range)}get intensityMode(){return this._intensityMode}set intensityMode(e){this._intensityMode=e,this._computePhotometricScale()}get radius(){return this._radius}set radius(e){this._radius=e,this._computePhotometricScale()}get shadowEnabled(){return this._shadowEnabled}set shadowEnabled(e){this._shadowEnabled!==e&&(this._shadowEnabled=e,this._markMeshesAsLightDirty())}get includedOnlyMeshes(){return this._includedOnlyMeshes}set includedOnlyMeshes(e){this._includedOnlyMeshes=e,this._hookArrayForIncludedOnly(e)}get excludedMeshes(){return this._excludedMeshes}set excludedMeshes(e){this._excludedMeshes=e,this._hookArrayForExcluded(e)}get excludeWithLayerMask(){return this._excludeWithLayerMask}set excludeWithLayerMask(e){this._excludeWithLayerMask=e,this._resyncMeshes()}get includeOnlyWithLayerMask(){return this._includeOnlyWithLayerMask}set includeOnlyWithLayerMask(e){this._includeOnlyWithLayerMask=e,this._resyncMeshes()}get lightmapMode(){return this._lightmapMode}set lightmapMode(e){this._lightmapMode!==e&&(this._lightmapMode=e,this._markMeshesAsLightDirty())}getViewMatrix(e){return null}getProjectionMatrix(e,t){return null}constructor(e,t,i){super(e,t,!1),this.diffuse=new ge(1,1,1),this.specular=new ge(1,1,1),this.falloffType=n.FALLOFF_DEFAULT,this.intensity=1,this._range=Number.MAX_VALUE,this._inverseSquaredRange=0,this._photometricScale=1,this._intensityMode=n.INTENSITYMODE_AUTOMATIC,this._radius=1e-5,this.renderPriority=0,this._shadowEnabled=!0,this._excludeWithLayerMask=0,this._includeOnlyWithLayerMask=0,this._lightmapMode=0,this._shadowGenerators=null,this._excludedMeshesIds=new Array,this._includedOnlyMeshesIds=new Array,this._currentViewDepth=0,this._clusteredContainer=null,this._isLight=!0,i||this.getScene().addLight(this),this._uniformBuffer=new fr(this.getScene().getEngine(),void 0,void 0,e),this._buildUniformLayout(),this.includedOnlyMeshes=[],this.excludedMeshes=[],i||this._resyncMeshes()}transferTexturesToEffect(e,t){return this}_bindLight(e,t,i,r,s=!0){var l;let a=e.toString(),o=!1;if(this._uniformBuffer.bindToEffect(i,"Light"+a),this._renderId!==t.getRenderId()||this._lastUseSpecular!==r||!this._uniformBuffer.useUbo){this._renderId=t.getRenderId(),this._lastUseSpecular=r;let c=this.getScaledIntensity();this.transferToEffect(i,a),this.diffuse.scaleToRef(c,En.Color3[0]),this._uniformBuffer.updateColor4("vLightDiffuse",En.Color3[0],this.range,a),r&&(this.specular.scaleToRef(c,En.Color3[1]),this._uniformBuffer.updateColor4("vLightSpecular",En.Color3[1],this.radius,a)),o=!0}if(this.transferTexturesToEffect(i,a),t.shadowsEnabled&&this.shadowEnabled&&s){let c=(l=this.getShadowGenerator(t.activeCamera))!=null?l:this.getShadowGenerator();c&&(c.bindShadowLight(a,i),o=!0)}o?this._uniformBuffer.update():this._uniformBuffer.bindUniformBuffer()}getClassName(){return"Light"}toString(e){let t="Name: "+this.name;if(t+=", type: "+["Point","Directional","Spot","Hemispheric","Clustered"][this.getTypeID()],this.animations)for(let i=0;i0&&this.includedOnlyMeshes.indexOf(e)===-1||this.excludedMeshes&&this.excludedMeshes.length>0&&this.excludedMeshes.indexOf(e)!==-1||this.includeOnlyWithLayerMask!==0&&(this.includeOnlyWithLayerMask&e.layerMask)===0||this.excludeWithLayerMask!==0&&this.excludeWithLayerMask&e.layerMask):!0}dispose(e,t=!1){if(this._shadowGenerators){let i=this._shadowGenerators.values();for(let r=i.next();r.done!==!0;r=i.next())r.value.dispose();this._shadowGenerators=null}if(this.getScene().stopAnimation(this),this._parentContainer){let i=this._parentContainer.lights.indexOf(this);i>-1&&this._parentContainer.lights.splice(i,1),this._parentContainer=null}for(let i of this.getScene().meshes)i._removeLightSource(this,!0);this._uniformBuffer.dispose(),this.getScene().removeLight(this),super.dispose(e,t)}getTypeID(){return 0}getScaledIntensity(){return this._photometricScale*this.intensity}clone(e,t=null){let i=n.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;let r=it.Clone(i,this);return e&&(r.name=e),t&&(r.parent=t),r.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(r),r}serialize(){let e=it.Serialize(this);if(e.uniqueId=this.uniqueId,e.type=this.getTypeID(),this.parent&&this.parent._serializeAsParent(e),this.excludedMeshes.length>0){e.excludedMeshesIds=[];for(let t of this.excludedMeshes)e.excludedMeshesIds.push(t.id)}if(this.includedOnlyMeshes.length>0){e.includedOnlyMeshesIds=[];for(let t of this.includedOnlyMeshes)e.includedOnlyMeshesIds.push(t.id)}return it.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){let r=_i.Construct("Light_Type_"+e,t,i);return r||null}static Parse(e,t){let i=n.GetConstructorFromName(e.type,e.name,t);if(!i)return null;let r=it.Parse(i,e,t);if(e.excludedMeshesIds&&(r._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(r._includedOnlyMeshesIds=e.includedOnlyMeshesIds),e.parentId!==void 0&&(r._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),e.falloffType!==void 0&&(r.falloffType=e.falloffType),e.lightmapMode!==void 0&&(r.lightmapMode=e.lightmapMode),e.animations){for(let s=0;s{let s=t.apply(e,r);if(this._clusteredContainer)return s;for(let a of r)a._resyncLightSource(this);return s};let i=e.splice;if(e.splice=(r,s)=>{let a=i.call(e,r,s!=null?s:e.length);if(this._clusteredContainer)return a;for(let o of a)o._resyncLightSource(this);return a},!this._clusteredContainer)for(let r of e)r._resyncLightSource(this)}_hookArrayForIncludedOnly(e){let t=e.push;e.push=(...r)=>{let s=t.apply(e,r);return this._resyncMeshes(),s};let i=e.splice;e.splice=(r,s)=>{let a=i.call(e,r,s!=null?s:e.length);return this._resyncMeshes(),a},this._resyncMeshes()}_resyncMeshes(){if(!this._clusteredContainer)for(let e of this.getScene().meshes)e._resyncLightSource(this)}_markMeshesAsLightDirty(){for(let e of this.getScene().meshes)e.lightSources.indexOf(this)!==-1&&e._markSubMeshesAsLightDirty()}_computePhotometricScale(){this._photometricScale=this._getPhotometricScale(),this.getScene().resetCachedMaterial()}_getPhotometricScale(){let e=0,t=this.getTypeID(),i=this.intensityMode;switch(i===n.INTENSITYMODE_AUTOMATIC&&(t===n.LIGHTTYPEID_DIRECTIONALLIGHT?i=n.INTENSITYMODE_ILLUMINANCE:i=n.INTENSITYMODE_LUMINOUSINTENSITY),t){case n.LIGHTTYPEID_POINTLIGHT:case n.LIGHTTYPEID_SPOTLIGHT:switch(i){case n.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case n.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case n.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius;break}break;case n.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case n.INTENSITYMODE_ILLUMINANCE:e=1;break;case n.INTENSITYMODE_LUMINANCE:{let r=this.radius;r=Math.max(r,.001),e=2*Math.PI*(1-Math.cos(r));break}}break;case n.LIGHTTYPEID_HEMISPHERICLIGHT:e=1;break}return e}_reorderLightsInScene(){let e=this.getScene();this._renderPriority!=0&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}areLightTexturesReady(){return!0}_isReady(){return!0}};Xt.FALLOFF_DEFAULT=Yt.FALLOFF_DEFAULT;Xt.FALLOFF_PHYSICAL=Yt.FALLOFF_PHYSICAL;Xt.FALLOFF_GLTF=Yt.FALLOFF_GLTF;Xt.FALLOFF_STANDARD=Yt.FALLOFF_STANDARD;Xt.LIGHTMAP_DEFAULT=Yt.LIGHTMAP_DEFAULT;Xt.LIGHTMAP_SPECULAR=Yt.LIGHTMAP_SPECULAR;Xt.LIGHTMAP_SHADOWSONLY=Yt.LIGHTMAP_SHADOWSONLY;Xt.INTENSITYMODE_AUTOMATIC=Yt.INTENSITYMODE_AUTOMATIC;Xt.INTENSITYMODE_LUMINOUSPOWER=Yt.INTENSITYMODE_LUMINOUSPOWER;Xt.INTENSITYMODE_LUMINOUSINTENSITY=Yt.INTENSITYMODE_LUMINOUSINTENSITY;Xt.INTENSITYMODE_ILLUMINANCE=Yt.INTENSITYMODE_ILLUMINANCE;Xt.INTENSITYMODE_LUMINANCE=Yt.INTENSITYMODE_LUMINANCE;Xt.LIGHTTYPEID_POINTLIGHT=Yt.LIGHTTYPEID_POINTLIGHT;Xt.LIGHTTYPEID_DIRECTIONALLIGHT=Yt.LIGHTTYPEID_DIRECTIONALLIGHT;Xt.LIGHTTYPEID_SPOTLIGHT=Yt.LIGHTTYPEID_SPOTLIGHT;Xt.LIGHTTYPEID_HEMISPHERICLIGHT=Yt.LIGHTTYPEID_HEMISPHERICLIGHT;Xt.LIGHTTYPEID_RECT_AREALIGHT=Yt.LIGHTTYPEID_RECT_AREALIGHT;P([_r()],Xt.prototype,"diffuse",void 0);P([_r()],Xt.prototype,"specular",void 0);P([w()],Xt.prototype,"falloffType",void 0);P([w()],Xt.prototype,"intensity",void 0);P([w()],Xt.prototype,"range",null);P([w()],Xt.prototype,"intensityMode",null);P([w()],Xt.prototype,"radius",null);P([w()],Xt.prototype,"_renderPriority",void 0);P([oe("_reorderLightsInScene")],Xt.prototype,"renderPriority",void 0);P([w("shadowEnabled")],Xt.prototype,"_shadowEnabled",void 0);P([w("excludeWithLayerMask")],Xt.prototype,"_excludeWithLayerMask",void 0);P([w("includeOnlyWithLayerMask")],Xt.prototype,"_includeOnlyWithLayerMask",void 0);P([w("lightmapMode")],Xt.prototype,"_lightmapMode",void 0)});var Qs,GA=C(()=>{Gt();Ut();Ve();zt();qs();Pf();Hi();_i.AddNodeConstructor("Light_Type_3",(n,e)=>()=>new Qs(n,b.Zero(),e));Qs=class extends Xt{constructor(e,t,i,r){super(e,i,r),this.groundColor=new ge(0,0,0),this.direction=t||b.Up()}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightGround",3),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}getClassName(){return"HemisphericLight"}setDirectionToTarget(e){return this.direction=b.Normalize(e.subtract(b.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){let i=b.Normalize(this.direction);return this._uniformBuffer.updateFloat4("vLightData",i.x,i.y,i.z,0,t),this._uniformBuffer.updateColor3("vLightGround",this.groundColor.scale(this.intensity),t),this}transferToNodeMaterialEffect(e,t){let i=b.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=j.Identity()),this._worldMatrix}getTypeID(){return Xt.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}};P([_r()],Qs.prototype,"groundColor",void 0);P([Hr()],Qs.prototype,"direction",void 0);wt("BABYLON.HemisphericLight",Qs)});var La,kA=C(()=>{Gt();Ut();Ve();Pf();Xu();La=class extends Xt{constructor(){super(...arguments),this._needProjectionMatrixCompute=!0,this._viewMatrix=j.Identity(),this._projectionMatrix=j.Identity()}_setPosition(e){this._position=e}get position(){return this._position}set position(e){this._setPosition(e)}_setDirection(e){this._direction=e}get direction(){return this._direction}set direction(e){this._setDirection(e)}get shadowMinZ(){return this._shadowMinZ}set shadowMinZ(e){this._shadowMinZ=e,this.forceProjectionMatrixCompute()}get shadowMaxZ(){return this._shadowMaxZ}set shadowMaxZ(e){this._shadowMaxZ=e,this.forceProjectionMatrixCompute()}computeTransformedInformation(){return this.parent&&this.parent.getWorldMatrix?(this.transformedPosition||(this.transformedPosition=b.Zero()),b.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=b.Zero()),b.TransformNormalToRef(this.direction,this.parent.getWorldMatrix(),this.transformedDirection)),!0):!1}getDepthScale(){return 50}getShadowDirection(e){return this.transformedDirection?this.transformedDirection:this.direction}getAbsolutePosition(){return this.transformedPosition?this.transformedPosition:this.position}setDirectionToTarget(e){return this.direction=b.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();let e=b.Cross(this.direction,Ss.Y),t=b.Cross(e,this.direction);return b.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=b.Zero()}_isSynchronized(){return!!this._cache.position.equals(this.position)}computeWorldMatrix(e){return!e&&this.isSynchronized()?(this._currentRenderId=this.getScene().getRenderId(),this._worldMatrix):(this._updateCache(),this._cache.position.copyFrom(this.position),this._worldMatrix||(this._worldMatrix=j.Identity()),j.TranslationToRef(this.position.x,this.position.y,this.position.z,this._worldMatrix),this.parent&&this.parent.getWorldMatrix&&(this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(),this._worldMatrix),this._markSyncedWithParent()),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix)}getDepthMinZ(e){return this.shadowMinZ!==void 0?this.shadowMinZ:(e==null?void 0:e.minZ)||0}getDepthMaxZ(e){return this.shadowMaxZ!==void 0?this.shadowMaxZ:(e==null?void 0:e.maxZ)||1e4}setShadowProjectionMatrix(e,t,i){return this.customProjectionMatrixBuilder?this.customProjectionMatrixBuilder(t,i,e):this._setDefaultShadowProjectionMatrix(e,t,i),this}_syncParentEnabledState(){super._syncParentEnabledState(),(!this.parent||!this.parent.getWorldMatrix)&&(this.transformedPosition=null,this.transformedDirection=null)}getViewMatrix(e){let t=$.Vector3[0],i=this.position;this.computeTransformedInformation()&&(i=this.transformedPosition),b.NormalizeToRef(this.getShadowDirection(e),t),Math.abs(b.Dot(t,b.Up()))===1&&(t.z=1e-13);let r=$.Vector3[1];return i.addToRef(t,r),j.LookAtLHToRef(i,r,b.Up(),this._viewMatrix),this._viewMatrix}getProjectionMatrix(e,t){return this.setShadowProjectionMatrix(this._projectionMatrix,e!=null?e:this._viewMatrix,t!=null?t:[]),this._projectionMatrix}};P([Hr()],La.prototype,"position",null);P([Hr()],La.prototype,"direction",null);P([w()],La.prototype,"shadowMinZ",null);P([w()],La.prototype,"shadowMaxZ",null)});var Cs,CG=C(()=>{Gt();Ut();Ve();qs();Pf();kA();Hi();_i.AddNodeConstructor("Light_Type_1",(n,e)=>()=>new Cs(n,b.Zero(),e));Cs=class extends La{get shadowFrustumSize(){return this._shadowFrustumSize}set shadowFrustumSize(e){this._shadowFrustumSize=e,this.forceProjectionMatrixCompute()}get shadowOrthoScale(){return this._shadowOrthoScale}set shadowOrthoScale(e){this._shadowOrthoScale=e,this.forceProjectionMatrixCompute()}get orthoLeft(){return this._orthoLeft}set orthoLeft(e){this._orthoLeft=e}get orthoRight(){return this._orthoRight}set orthoRight(e){this._orthoRight=e}get orthoTop(){return this._orthoTop}set orthoTop(e){this._orthoTop=e}get orthoBottom(){return this._orthoBottom}set orthoBottom(e){this._orthoBottom=e}constructor(e,t,i,r){super(e,i,r),this._shadowFrustumSize=0,this._shadowOrthoScale=.1,this.autoUpdateExtends=!0,this.autoCalcShadowZBounds=!1,this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE,this.position=t.scale(-1),this.direction=t}getClassName(){return"DirectionalLight"}getTypeID(){return Xt.LIGHTTYPEID_DIRECTIONALLIGHT}_setDefaultShadowProjectionMatrix(e,t,i){this.shadowFrustumSize>0?this._setDefaultFixedFrustumShadowProjectionMatrix(e):this._setDefaultAutoExtendShadowProjectionMatrix(e,t,i)}_setDefaultFixedFrustumShadowProjectionMatrix(e){let t=this.getScene().activeCamera;j.OrthoLHToRef(this.shadowFrustumSize,this.shadowFrustumSize,this.shadowMinZ!==void 0?this.shadowMinZ:t?t.minZ:0,this.shadowMaxZ!==void 0?this.shadowMaxZ:t?t.maxZ:1e4,e,this.getScene().getEngine().isNDCHalfZRange)}_setDefaultAutoExtendShadowProjectionMatrix(e,t,i){let r=this.getScene().activeCamera;if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){let f=b.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=-Number.MAX_VALUE,this._orthoTop=-Number.MAX_VALUE,this._orthoBottom=Number.MAX_VALUE;let h=Number.MAX_VALUE,d=-Number.MAX_VALUE;for(let u=0;uthis._orthoRight&&(this._orthoRight=f.x),f.y>this._orthoTop&&(this._orthoTop=f.y),this.autoCalcShadowZBounds&&(f.zd&&(d=f.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=h,this._shadowMaxZ=d)}let s=this._orthoRight-this._orthoLeft,a=this._orthoTop-this._orthoBottom,o=this.shadowMinZ!==void 0?this.shadowMinZ:(r==null?void 0:r.minZ)||0,l=this.shadowMaxZ!==void 0?this.shadowMaxZ:(r==null?void 0:r.maxZ)||1e4,c=this.getScene().getEngine().useReverseDepthBuffer;j.OrthoOffCenterLHToRef(this._orthoLeft-s*this.shadowOrthoScale,this._orthoRight+s*this.shadowOrthoScale,this._orthoBottom-a*this.shadowOrthoScale,this._orthoTop+a*this.shadowOrthoScale,c?l:o,c?o:l,e,this.getScene().getEngine().isNDCHalfZRange)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z,1,t),this):(this._uniformBuffer.updateFloat4("vLightData",this.direction.x,this.direction.y,this.direction.z,1,t),this)}transferToNodeMaterialEffect(e,t){return this.computeTransformedInformation()?(e.setFloat3(t,this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z),this):(e.setFloat3(t,this.direction.x,this.direction.y,this.direction.z),this)}getDepthMinZ(e){let t=this._scene.getEngine();return!t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}getDepthMaxZ(e){let t=this._scene.getEngine();return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}prepareLightSpecificDefines(e,t){e["DIRLIGHT"+t]=!0}};P([w()],Cs.prototype,"shadowFrustumSize",null);P([w()],Cs.prototype,"shadowOrthoScale",null);P([w()],Cs.prototype,"autoUpdateExtends",void 0);P([w()],Cs.prototype,"autoCalcShadowZBounds",void 0);P([w("orthoLeft")],Cs.prototype,"_orthoLeft",void 0);P([w("orthoRight")],Cs.prototype,"_orthoRight",void 0);P([w("orthoTop")],Cs.prototype,"_orthoTop",void 0);P([w("orthoBottom")],Cs.prototype,"_orthoBottom",void 0);wt("BABYLON.DirectionalLight",Cs)});var Df,yG=C(()=>{Gt();Ut();Ve();qs();Pf();kA();Hi();_i.AddNodeConstructor("Light_Type_0",(n,e)=>()=>new Df(n,b.Zero(),e));Df=class extends La{get shadowAngle(){return this._shadowAngle}set shadowAngle(e){this._shadowAngle=e,this.forceProjectionMatrixCompute()}get direction(){return this._direction}set direction(e){let t=this.needCube();if(this._direction=e,this.needCube()!==t&&this._shadowGenerators){let i=this._shadowGenerators.values();for(let r=i.next();r.done!==!0;r=i.next())r.value.recreateShadowMap()}}constructor(e,t,i,r){super(e,i,r),this._shadowAngle=Math.PI/2,this.position=t}getClassName(){return"PointLight"}getTypeID(){return Xt.LIGHTTYPEID_POINTLIGHT}needCube(){return!this.direction}getShadowDirection(e){if(this.direction)return super.getShadowDirection(e);switch(e){case 0:return new b(1,0,0);case 1:return new b(-1,0,0);case 2:return new b(0,-1,0);case 3:return new b(0,1,0);case 4:return new b(0,0,1);case 5:return new b(0,0,-1)}return b.Zero()}_setDefaultShadowProjectionMatrix(e,t,i){let r=this.getScene().activeCamera,s=this.getDepthMinZ(r),a=this.getDepthMaxZ(r),o=this.getScene().getEngine().useReverseDepthBuffer;j.PerspectiveFovLHToRef(this.shadowAngle,1,o?a:s,o?s:a,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,o)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){let i=this._scene.floatingOriginOffset;return this.computeTransformedInformation()?this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x-i.x,this.transformedPosition.y-i.y,this.transformedPosition.z-i.z,0,t):this._uniformBuffer.updateFloat4("vLightData",this.position.x-i.x,this.position.y-i.y,this.position.z-i.z,0,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,0,0,t),this}transferToNodeMaterialEffect(e,t){let i=this._scene.floatingOriginOffset;return this.computeTransformedInformation()?e.setFloat3(t,this.transformedPosition.x-i.x,this.transformedPosition.y-i.y,this.transformedPosition.z-i.z):e.setFloat3(t,this.position.x-i.x,this.position.y-i.y,this.position.z-i.z),this}prepareLightSpecificDefines(e,t){e["POINTLIGHT"+t]=!0}};P([w()],Df.prototype,"shadowAngle",null);wt("BABYLON.PointLight",Df)});var Ur,Fy=C(()=>{Gt();Ut();Ve();qs();Pf();kA();Fr();Hi();_i.AddNodeConstructor("Light_Type_2",(n,e)=>()=>new Ur(n,b.Zero(),b.Zero(),0,0,e));Ur=class n extends La{get iesProfileTexture(){return this._iesProfileTexture}set iesProfileTexture(e){this._iesProfileTexture!==e&&(this._iesProfileTexture=e,this._iesProfileTexture&&n._IsTexture(this._iesProfileTexture)&&this._iesProfileTexture.onLoadObservable.addOnce(()=>{this._markMeshesAsLightDirty()}))}get angle(){return this._angle}set angle(e){this._angle=e,this._cosHalfAngle=Math.cos(e*.5),this._projectionTextureProjectionLightDirty=!0,this.forceProjectionMatrixCompute(),this._computeAngleValues()}get innerAngle(){return this._innerAngle}set innerAngle(e){this._innerAngle=e,this._computeAngleValues()}get shadowAngleScale(){return this._shadowAngleScale}set shadowAngleScale(e){this._shadowAngleScale=e,this.forceProjectionMatrixCompute()}get projectionTextureMatrix(){return this._projectionTextureMatrix}get projectionTextureLightNear(){return this._projectionTextureLightNear}set projectionTextureLightNear(e){this._projectionTextureLightNear=e,this._projectionTextureProjectionLightDirty=!0}get projectionTextureLightFar(){return this._projectionTextureLightFar}set projectionTextureLightFar(e){this._projectionTextureLightFar=e,this._projectionTextureProjectionLightDirty=!0}get projectionTextureUpDirection(){return this._projectionTextureUpDirection}set projectionTextureUpDirection(e){this._projectionTextureUpDirection=e,this._projectionTextureProjectionLightDirty=!0}get projectionTexture(){return this._projectionTexture}set projectionTexture(e){this._projectionTexture!==e&&(this._projectionTexture=e,this._projectionTextureDirty=!0,this._projectionTexture&&!this._projectionTexture.isReady()&&(n._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled(()=>{this._markMeshesAsLightDirty()}):n._IsTexture(this._projectionTexture)&&this._projectionTexture.onLoadObservable.addOnce(()=>{this._markMeshesAsLightDirty()})))}static _IsProceduralTexture(e){return e.onGeneratedObservable!==void 0}static _IsTexture(e){return e.onLoadObservable!==void 0}get projectionTextureProjectionLightMatrix(){return this._projectionTextureProjectionLightMatrix}set projectionTextureProjectionLightMatrix(e){this._projectionTextureProjectionLightMatrix=e,this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0}constructor(e,t,i,r,s,a,o){super(e,a,o),this._innerAngle=0,this._iesProfileTexture=null,this._projectionTextureMatrix=j.Zero(),this._projectionTextureLightNear=1e-6,this._projectionTextureLightFar=1e3,this._projectionTextureUpDirection=b.Up(),this._projectionTextureViewLightDirty=!0,this._projectionTextureProjectionLightDirty=!0,this._projectionTextureDirty=!0,this._projectionTextureViewTargetVector=b.Zero(),this._projectionTextureViewLightMatrix=j.Zero(),this._projectionTextureProjectionLightMatrix=j.Zero(),this._projectionTextureScalingMatrix=j.FromValues(.5,0,0,0,0,.5,0,0,0,0,.5,0,.5,.5,.5,1),this.position=t,this.direction=i,this.angle=r,this.exponent=s}getClassName(){return"SpotLight"}getTypeID(){return Xt.LIGHTTYPEID_SPOTLIGHT}_setDirection(e){super._setDirection(e),this._projectionTextureViewLightDirty=!0}_setPosition(e){super._setPosition(e),this._projectionTextureViewLightDirty=!0}_setDefaultShadowProjectionMatrix(e,t,i){let r=this.getScene().activeCamera;if(!r)return;this._shadowAngleScale=this._shadowAngleScale||1;let s=this._shadowAngleScale*this._angle,a=this.shadowMinZ!==void 0?this.shadowMinZ:r.minZ,o=this.shadowMaxZ!==void 0?this.shadowMaxZ:r.maxZ,l=this.getScene().getEngine().useReverseDepthBuffer;j.PerspectiveFovLHToRef(s,1,l?o:a,l?a:o,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,l)}_computeProjectionTextureViewLightMatrix(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.getAbsolutePosition().addToRef(this.getShadowDirection(),this._projectionTextureViewTargetVector),j.LookAtLHToRef(this.getAbsolutePosition(),this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)}_computeProjectionTextureProjectionLightMatrix(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;let e=this.projectionTextureLightFar,t=this.projectionTextureLightNear,i=e/(e-t),r=-i*t,s=1/Math.tan(this._angle/2);j.FromValuesToRef(s/1,0,0,0,0,s,0,0,0,0,i,1,0,0,r,0,this._projectionTextureProjectionLightMatrix)}_computeProjectionTextureMatrix(){if(this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTexture instanceof _e){let e=this._projectionTexture.uScale/2,t=this._projectionTexture.vScale/2;j.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,.5,0,.5,.5,.5,1,this._projectionTextureScalingMatrix)}this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix,this._projectionTextureMatrix)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightDirection",3),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}_computeAngleValues(){this._lightAngleScale=1/Math.max(.001,Math.cos(this._innerAngle*.5)-this._cosHalfAngle),this._lightAngleOffset=-this._cosHalfAngle*this._lightAngleScale}transferTexturesToEffect(e,t){return this.projectionTexture&&this.projectionTexture.isReady()&&(this._projectionTextureViewLightDirty&&this._computeProjectionTextureViewLightMatrix(),this._projectionTextureProjectionLightDirty&&this._computeProjectionTextureProjectionLightMatrix(),this._projectionTextureDirty&&this._computeProjectionTextureMatrix(),e.setMatrix("textureProjectionMatrix"+t,this._projectionTextureMatrix),e.setTexture("projectionLightTexture"+t,this.projectionTexture)),this._iesProfileTexture&&this._iesProfileTexture.isReady()&&e.setTexture("iesLightTexture"+t,this._iesProfileTexture),this}transferToEffect(e,t){let i,r=this._scene.floatingOriginOffset;return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x-r.x,this.transformedPosition.y-r.y,this.transformedPosition.z-r.z,this.exponent,t),i=b.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x-r.x,this.position.y-r.y,this.position.z-r.z,this.exponent,t),i=b.Normalize(this.direction)),this._uniformBuffer.updateFloat4("vLightDirection",i.x,i.y,i.z,this._cosHalfAngle,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,this._lightAngleScale,this._lightAngleOffset,t),this}transferToNodeMaterialEffect(e,t){let i;return this.computeTransformedInformation()?i=b.Normalize(this.transformedDirection):i=b.Normalize(this.direction),this.getScene().useRightHandedSystem?e.setFloat3(t,-i.x,-i.y,-i.z):e.setFloat3(t,i.x,i.y,i.z),this}dispose(){super.dispose(),this._projectionTexture&&this._projectionTexture.dispose(),this._iesProfileTexture&&(this._iesProfileTexture.dispose(),this._iesProfileTexture=null)}getDepthMinZ(e){var r;let t=this._scene.getEngine(),i=this.shadowMinZ!==void 0?this.shadowMinZ:(r=e==null?void 0:e.minZ)!=null?r:0;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?i:this._scene.getEngine().isNDCHalfZRange?0:i}getDepthMaxZ(e){var r;let t=this._scene.getEngine(),i=this.shadowMaxZ!==void 0?this.shadowMaxZ:(r=e==null?void 0:e.maxZ)!=null?r:1e4;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:i}areLightTexturesReady(){return!(this._projectionTexture&&!this._projectionTexture.isReadyOrNotBlocking()||this._iesProfileTexture&&!this._iesProfileTexture.isReadyOrNotBlocking())}prepareLightSpecificDefines(e,t){e["SPOTLIGHT"+t]=!0,e["PROJECTEDLIGHTTEXTURE"+t]=!!(this.projectionTexture&&this.projectionTexture.isReady()),e["IESLIGHTTEXTURE"+t]=!!(this._iesProfileTexture&&this._iesProfileTexture.isReady())}};P([w()],Ur.prototype,"angle",null);P([w()],Ur.prototype,"innerAngle",null);P([w()],Ur.prototype,"shadowAngleScale",null);P([w()],Ur.prototype,"exponent",void 0);P([w()],Ur.prototype,"projectionTextureLightNear",null);P([w()],Ur.prototype,"projectionTextureLightFar",null);P([w()],Ur.prototype,"projectionTextureUpDirection",null);P([Bt("projectedLightTexture")],Ur.prototype,"_projectionTexture",void 0);wt("BABYLON.SpotLight",Ur)});function PG(n){let e=n.pathArray,t=n.closeArray||!1,i=n.closePath||!1,r=n.invertUV||!1,s=Math.floor(e[0].length/2),a=n.offset||s;a=a>s?s:Math.floor(a);let o=n.sideOrientation===0?0:n.sideOrientation||Me.DEFAULTSIDE,l=n.uvs,c=n.colors,f=[],h=[],d=[],u=[],m=[],p=[],_=[],g=[],v,x=[],A=[],S,E,R;if(e.length<2){let be=[],Xe=[];for(E=0;E0&&(V=D[R].subtract(D[R-1]).length(),N=V+_[S],m[S].push(N),_[S]=N),R++;i&&(R--,f.push(D[0].x,D[0].y,D[0].z),V=D[R].subtract(D[0]).length(),N=V+_[S],m[S].push(N),_[S]=N),x[S]=O+y,A[S]=I,I+=O+y}let F,U,k,ee;for(E=0;E{let m=i[0].length,p=o,_=0,g=p._originalBuilderSideOrientation===Z.DOUBLESIDE?2:1;for(let v=1;v<=g;++v)for(let x=0;x{Ve();Ii();Gi();hr();en();Me.CreateRibbon=PG;Z.CreateRibbon=(n,e,t=!1,i,r,s,a=!1,o,l)=>go(n,{pathArray:e,closeArray:t,closePath:i,offset:r,updatable:a,sideOrientation:o,instance:l},s)});function DG(n){let e=[],t=[],i=[],r=[],s=n.radius||.5,a=n.tessellation||64,o=n.arc&&(n.arc<=0||n.arc>1)?1:n.arc||1,l=n.sideOrientation===0?0:n.sideOrientation||Me.DEFAULTSIDE;e.push(0,0,0),r.push(.5,.5);let c=Math.PI*2*o,f=o===1?c/a:c/(a-1),h=0;for(let m=0;m{Ii();hr();en();Me.CreateDisc=DG;Z.CreateDisc=(n,e,t,i=null,r,s)=>By(n,{radius:e,tessellation:t,sideOrientation:s,updatable:r},i)});var Gm,OG=C(()=>{Ve();Gi();Ii();Z._GroundMeshParser=(n,e)=>Gm.Parse(n,e);Gm=class n extends Z{constructor(e,t){super(e,t),this.generateOctree=!1}getClassName(){return"GroundMesh"}get subdivisions(){return Math.min(this._subdivisionsX,this._subdivisionsY)}get subdivisionsX(){return this._subdivisionsX}get subdivisionsY(){return this._subdivisionsY}optimize(e,t=32){this._subdivisionsX=e,this._subdivisionsY=e,this.subdivide(e);let i=this;i.createOrUpdateSubmeshesOctree&&i.createOrUpdateSubmeshesOctree(t)}getHeightAtCoordinates(e,t){let i=this.getWorldMatrix(),r=$.Matrix[5];i.invertToRef(r);let s=$.Vector3[8];if(b.TransformCoordinatesFromFloatsToRef(e,0,t,r,s),e=s.x,t=s.z,e=this._maxX||t<=this._minZ||t>this._maxZ)return this.position.y;(!this._heightQuads||this._heightQuads.length==0)&&(this._initHeightQuads(),this._computeHeightQuads());let a=this._getFacetAt(e,t),o=-(a.x*e+a.z*t+a.w)/a.y;return b.TransformCoordinatesFromFloatsToRef(0,o,0,i,s),s.y}getNormalAtCoordinates(e,t){let i=new b(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){let r=this.getWorldMatrix(),s=$.Matrix[5];r.invertToRef(s);let a=$.Vector3[8];if(b.TransformCoordinatesFromFloatsToRef(e,0,t,s,a),e=a.x,t=a.z,ethis._maxX||tthis._maxZ)return this;(!this._heightQuads||this._heightQuads.length==0)&&(this._initHeightQuads(),this._computeHeightQuads());let o=this._getFacetAt(e,t);return b.TransformNormalFromFloatsToRef(o.x,o.y,o.z,r,i),this}updateCoordinateHeights(){return(!this._heightQuads||this._heightQuads.length==0)&&this._initHeightQuads(),this._computeHeightQuads(),this}_getFacetAt(e,t){let i=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),r=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),s=this._heightQuads[r*this._subdivisionsX+i],a;return tn.maxHeight){c=!0;let h=n.maxHeight;n.maxHeight=n.minHeight,n.minHeight=h}for(s=0;s<=n.subdivisions;s++)for(a=0;a<=n.subdivisions;a++){let h=new b(a*n.width/n.subdivisions-n.width/2,0,(n.subdivisions-s)*n.height/n.subdivisions-n.height/2),d=(h.x+n.width/2)/n.width*(n.bufferWidth-1)|0,u=(1-(h.z+n.height/2)/n.height)*(n.bufferHeight-1)|0,m=(d+u*n.bufferWidth)*4,p=n.buffer[m]/255,_=n.buffer[m+1]/255,g=n.buffer[m+2]/255,v=n.buffer[m+3]/255;c&&(p=1-p,_=1-_,g=1-g);let x=p*o.r+_*o.g+g*o.b;v>=l?h.y=n.minHeight+(n.maxHeight-n.minHeight)*x:h.y=n.minHeight-Ot,n.heightBuffer&&(n.heightBuffer[s*(n.subdivisions+1)+a]=h.y),t.push(h.x,h.y,h.z),i.push(0,0,0),r.push(a/n.subdivisions,1-s/n.subdivisions)}for(s=0;s=n.minHeight,_=t[d*3+1]>=n.minHeight,g=t[u*3+1]>=n.minHeight;p&&_&&g&&(e.push(h),e.push(d),e.push(u)),t[m*3+1]>=n.minHeight&&p&&g&&(e.push(m),e.push(h),e.push(u))}Me.ComputeNormals(t,e,i);let f=new Me;return f.indices=e,f.positions=t,f.normals=i,f.uvs=r,f}function Vy(n,e={},t){let i=new Gm(n,t);return i._setReady(!1),i._subdivisionsX=e.subdivisionsX||e.subdivisions||1,i._subdivisionsY=e.subdivisionsY||e.subdivisions||1,i._width=e.width||1,i._height=e.height||1,i._maxX=i._width/2,i._maxZ=i._height/2,i._minX=-i._maxX,i._minZ=-i._maxZ,Uy(e).applyToMesh(i,e.updatable),i._setReady(!0),i}function Gy(n,e,t=null){let i=new Z(n,t);return NG(e).applyToMesh(i,e.updatable),i}function ky(n,e,t={},i=null){let r=t.width||10,s=t.height||10,a=t.subdivisions||1,o=t.minHeight||0,l=t.maxHeight||1,c=t.colorFilter||new ge(.3,.59,.11),f=t.alphaFilter||0,h=t.updatable,d=t.onReady;i=i||Le.LastCreatedScene;let u=new Gm(n,i);u._subdivisionsX=a,u._subdivisionsY=a,u._width=r,u._height=s,u._maxX=u._width/2,u._maxZ=u._height/2,u._minX=-u._maxX,u._minZ=-u._maxZ,u._setReady(!1);let m;t.passHeightBufferInCallback&&(m=new Float32Array((a+1)*(a+1)));let p=(_,g,v)=>{wG({width:r,height:s,subdivisions:a,minHeight:o,maxHeight:l,colorFilter:c,buffer:_,bufferWidth:g,bufferHeight:v,alphaFilter:f,heightBuffer:m}).applyToMesh(u,h),d&&d(u,m),u._setReady(!0)};if(typeof e=="string"){i.addPendingData(u);let _=v=>{let x=v.width,A=v.height;if(i.isDisposed){i.removePendingData(u);return}let S=i==null?void 0:i.getEngine().resizeImageBitmap(v,x,A);p(S,x,A),i.removePendingData(u)},g=(v,x)=>{i.removePendingData(u),t.onError&&t.onError(v,x)};pe.LoadImage(e,_,g,i.offlineProvider)}else p(e.data,e.width,e.height);return u}var Wy=C(()=>{Ve();zt();Ii();hr();OG();bi();Pi();Dn();en();Me.CreateGround=Uy;Me.CreateTiledGround=NG;Me.CreateGroundFromHeightMap=wG;Z.CreateGround=(n,e,t,i,r,s)=>Vy(n,{width:e,height:t,subdivisions:i,updatable:s},r);Z.CreateTiledGround=(n,e,t,i,r,s,a,o,l)=>Gy(n,{xmin:e,zmin:t,xmax:i,zmax:r,subdivisions:s,precision:a,updatable:l},o);Z.CreateGroundFromHeightMap=(n,e,t,i,r,s,a,o,l,c,f)=>ky(n,e,{width:t,height:i,subdivisions:r,minHeight:s,maxHeight:a,updatable:l,onReady:c,alphaFilter:f},o)});function WA(n){let t=[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23],i=[0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0],r=[],s=n.width||n.size||1,a=n.height||n.size||1,o=n.depth||n.size||1,l=n.wrap||!1,c=n.topBaseAt===void 0?1:n.topBaseAt,f=n.bottomBaseAt===void 0?0:n.bottomBaseAt;c=(c+4)%4,f=(f+4)%4;let h=[2,0,3,1],d=[2,0,1,3],u=h[c],m=d[f],p=[1,-1,1,-1,-1,1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,-1,1,-1,1,1,1,1,-1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,1,1,-1,1,1,1,1,-1,1,1,-1,-1,-1,-1,-1,-1,-1,1];if(l){t=[2,3,0,2,0,1,4,5,6,4,6,7,9,10,11,9,11,8,12,14,15,12,13,14],p=[-1,1,1,1,1,1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,1,1,1,-1,1,-1,-1,1,-1,1,-1,1,-1,-1,1,1,-1,-1,1,-1,-1,-1];let R=[[1,1,1],[-1,1,1],[-1,1,-1],[1,1,-1]],I=[[-1,-1,1],[1,-1,1],[1,-1,-1],[-1,-1,-1]],y=[17,18,19,16],M=[22,23,20,21];for(;u>0;)R.unshift(R.pop()),y.unshift(y.pop()),u--;for(;m>0;)I.unshift(I.pop()),M.unshift(M.pop()),m--;R=R.flat(),I=I.flat(),p=p.concat(R).concat(I),t.push(y[0],y[2],y[3],y[0],y[1],y[2]),t.push(M[0],M[2],M[3],M[0],M[1],M[2])}let _=[s/2,a/2,o/2],g=p.reduce((R,I,y)=>R.concat(I*_[y%3]),[]),v=n.sideOrientation===0?0:n.sideOrientation||Me.DEFAULTSIDE,x=n.faceUV||new Array(6),A=n.faceColors,S=[];for(let R=0;R<6;R++)x[R]===void 0&&(x[R]=new Ri(0,0,1,1)),A&&A[R]===void 0&&(A[R]=new lt(1,1,1,1));for(let R=0;R<6;R++)if(r.push(x[R].z,It?1-x[R].w:x[R].w),r.push(x[R].x,It?1-x[R].w:x[R].w),r.push(x[R].x,It?1-x[R].y:x[R].y),r.push(x[R].z,It?1-x[R].y:x[R].y),A)for(let I=0;I<4;I++)S.push(A[R].r,A[R].g,A[R].b,A[R].a);Me._ComputeSides(v,g,t,i,r,n.frontUVs,n.backUVs);let E=new Me;if(E.indices=t,E.positions=g,E.normals=i,E.uvs=r,A){let R=v===Me.DOUBLESIDE?S.concat(S):S;E.colors=R}return E}function Hy(n,e={},t=null){let i=new Z(n,t);return e.sideOrientation=Z._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,WA(e).applyToMesh(i,e.updatable),i}var zy=C(()=>{Ve();zt();Ii();hr();en();Wy();Me.CreateBox=WA;Z.CreateBox=(n,e,t=null,i,r)=>Hy(n,{size:e,sideOrientation:r,updatable:i},t)});function km(n){let e=n.pattern||Z.NO_FLIP,t=n.tileWidth||n.tileSize||1,i=n.tileHeight||n.tileSize||1,r=n.alignHorizontal||0,s=n.alignVertical||0,a=n.width||n.size||1,o=Math.floor(a/t),l=a-o*t,c=n.height||n.size||1,f=Math.floor(c/i),h=c-f*i,d=t*o/2,u=i*f/2,m=0,p=0,_=0,g=0,v=0,x=0;if(l>0||h>0){switch(_=-d,g=-u,v=d,x=u,r){case Z.CENTER:l/=2,_-=l,v+=l;break;case Z.LEFT:v+=l,m=-l/2;break;case Z.RIGHT:_-=l,m=l/2;break}switch(s){case Z.CENTER:h/=2,g-=h,x+=h;break;case Z.BOTTOM:x+=h,p=-h/2;break;case Z.TOP:g-=h,p=h/2;break}}let A=[],S=[],E=[];E[0]=[0,0,1,0,1,1,0,1],E[1]=[0,0,1,0,1,1,0,1],(e===Z.ROTATE_TILE||e===Z.ROTATE_ROW)&&(E[1]=[1,1,0,1,0,0,1,0]),(e===Z.FLIP_TILE||e===Z.FLIP_ROW)&&(E[1]=[1,0,0,0,0,1,1,1]),(e===Z.FLIP_N_ROTATE_TILE||e===Z.FLIP_N_ROTATE_ROW)&&(E[1]=[0,1,1,1,1,0,0,0]);let R=[],I=[],y=[],M=0;for(let N=0;N0||h>0){let N=h>0&&(s===Z.CENTER||s===Z.TOP),F=h>0&&(s===Z.CENTER||s===Z.BOTTOM),U=l>0&&(r===Z.CENTER||r===Z.RIGHT),k=l>0&&(r===Z.CENTER||r===Z.LEFT),ee,q,Q,Y,K;if(N&&U&&(A.push(_+m,g+p,0),A.push(-d+m,g+p,0),A.push(-d+m,g+h+p,0),A.push(_+m,g+h+p,0),y.push(M,M+1,M+3,M+1,M+2,M+3),M+=4,q=1-l/t,Q=1-h/i,Y=1,K=1,ee=[q,Q,Y,Q,Y,K,q,K],e===Z.ROTATE_ROW&&(ee=[1-q,1-Q,1-Y,1-Q,1-Y,1-K,1-q,1-K]),e===Z.FLIP_ROW&&(ee=[1-q,Q,1-Y,Q,1-Y,K,1-q,K]),e===Z.FLIP_N_ROTATE_ROW&&(ee=[q,1-Q,Y,1-Q,Y,1-K,q,1-K]),R=R.concat(ee),I.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),N&&k&&(A.push(d+m,g+p,0),A.push(v+m,g+p,0),A.push(v+m,g+h+p,0),A.push(d+m,g+h+p,0),y.push(M,M+1,M+3,M+1,M+2,M+3),M+=4,q=0,Q=1-h/i,Y=l/t,K=1,ee=[q,Q,Y,Q,Y,K,q,K],(e===Z.ROTATE_ROW||e===Z.ROTATE_TILE&&o%2===0)&&(ee=[1-q,1-Q,1-Y,1-Q,1-Y,1-K,1-q,1-K]),(e===Z.FLIP_ROW||e===Z.FLIP_TILE&&o%2===0)&&(ee=[1-q,Q,1-Y,Q,1-Y,K,1-q,K]),(e===Z.FLIP_N_ROTATE_ROW||e===Z.FLIP_N_ROTATE_TILE&&o%2===0)&&(ee=[q,1-Q,Y,1-Q,Y,1-K,q,1-K]),R=R.concat(ee),I.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),F&&U&&(A.push(_+m,u+p,0),A.push(-d+m,u+p,0),A.push(-d+m,x+p,0),A.push(_+m,x+p,0),y.push(M,M+1,M+3,M+1,M+2,M+3),M+=4,q=1-l/t,Q=0,Y=1,K=h/i,ee=[q,Q,Y,Q,Y,K,q,K],(e===Z.ROTATE_ROW&&f%2===1||e===Z.ROTATE_TILE&&f%1===0)&&(ee=[1-q,1-Q,1-Y,1-Q,1-Y,1-K,1-q,1-K]),(e===Z.FLIP_ROW&&f%2===1||e===Z.FLIP_TILE&&f%2===0)&&(ee=[1-q,Q,1-Y,Q,1-Y,K,1-q,K]),(e===Z.FLIP_N_ROTATE_ROW&&f%2===1||e===Z.FLIP_N_ROTATE_TILE&&f%2===0)&&(ee=[q,1-Q,Y,1-Q,Y,1-K,q,1-K]),R=R.concat(ee),I.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),F&&k&&(A.push(d+m,u+p,0),A.push(v+m,u+p,0),A.push(v+m,x+p,0),A.push(d+m,x+p,0),y.push(M,M+1,M+3,M+1,M+2,M+3),M+=4,q=0,Q=0,Y=l/t,K=h/i,ee=[q,Q,Y,Q,Y,K,q,K],(e===Z.ROTATE_ROW&&f%2===1||e===Z.ROTATE_TILE&&(f+o)%2===1)&&(ee=[1-q,1-Q,1-Y,1-Q,1-Y,1-K,1-q,1-K]),(e===Z.FLIP_ROW&&f%2===1||e===Z.FLIP_TILE&&(f+o)%2===1)&&(ee=[1-q,Q,1-Y,Q,1-Y,K,1-q,K]),(e===Z.FLIP_N_ROTATE_ROW&&f%2===1||e===Z.FLIP_N_ROTATE_TILE&&(f+o)%2===1)&&(ee=[q,1-Q,Y,1-Q,Y,1-K,q,1-K]),R=R.concat(ee),I.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),N){let de=[];q=0,Q=1-h/i,Y=1,K=1,de[0]=[q,Q,Y,Q,Y,K,q,K],de[1]=[q,Q,Y,Q,Y,K,q,K],(e===Z.ROTATE_TILE||e===Z.ROTATE_ROW)&&(de[1]=[1-q,1-Q,1-Y,1-Q,1-Y,1-K,1-q,1-K]),(e===Z.FLIP_TILE||e===Z.FLIP_ROW)&&(de[1]=[1-q,Q,1-Y,Q,1-Y,K,1-q,K]),(e===Z.FLIP_N_ROTATE_TILE||e===Z.FLIP_N_ROTATE_ROW)&&(de[1]=[q,1-Q,Y,1-Q,Y,1-K,q,1-K]);for(let Re=0;Re{Ii();hr();Me.CreateTiledPlane=km});function BG(n){let t=n.faceUV||new Array(6),i=n.faceColors,r=n.pattern||Z.NO_FLIP,s=n.width||n.size||1,a=n.height||n.size||1,o=n.depth||n.size||1,l=n.tileWidth||n.tileSize||1,c=n.tileHeight||n.tileSize||1,f=n.alignHorizontal||0,h=n.alignVertical||0,d=n.sideOrientation===0?0:n.sideOrientation||Me.DEFAULTSIDE;for(let N=0;N<6;N++)t[N]===void 0&&(t[N]=new Ri(0,0,1,1)),i&&i[N]===void 0&&(i[N]=new lt(1,1,1,1));let u=s/2,m=a/2,p=o/2,_=[];for(let N=0;N<2;N++)_[N]=km({pattern:r,tileWidth:l,tileHeight:c,width:s,height:a,alignVertical:h,alignHorizontal:f,sideOrientation:d});for(let N=2;N<4;N++)_[N]=km({pattern:r,tileWidth:l,tileHeight:c,width:o,height:a,alignVertical:h,alignHorizontal:f,sideOrientation:d});let g=h;h===Z.BOTTOM?g=Z.TOP:h===Z.TOP&&(g=Z.BOTTOM);for(let N=4;N<6;N++)_[N]=km({pattern:r,tileWidth:l,tileHeight:c,width:s,height:o,alignVertical:g,alignHorizontal:f,sideOrientation:d});let v=[],x=[],A=[],S=[],E=[],R=[],I=[],y=[],M,D=0;for(let N=0;N<6;N++){let F=_[N].positions.length;R[N]=[],I[N]=[];for(let U=0;UU+D)),D+=R[N].length,i){let U=i[N];for(let k=0;k{Ve();zt();Ii();hr();Xy();en();HA=1,Yy=-1;Me.CreateTiledBox=BG});function GG(n){let e=(n.segments||32)|0,t=n.diameterX||n.diameter||1,i=n.diameterY||n.diameter||1,r=n.diameterZ||n.diameter||1,s=n.arc&&(n.arc<=0||n.arc>1)?1:n.arc||1,a=n.slice&&n.slice<=0?1:n.slice||1,o=n.sideOrientation===0?0:n.sideOrientation||Me.DEFAULTSIDE,l=!!n.dedupTopBottomIndices,c=new b(t/2,i/2,r/2),f=2+e,h=2*f,d=[],u=[],m=[],p=[];for(let g=0;g<=f;g++){let v=g/f,x=v*Math.PI*a;for(let A=0;A<=h;A++){let S=A/h,E=S*Math.PI*2*s,R=j.RotationZ(-x),I=j.RotationY(E),y=b.TransformCoordinates(b.Up(),R),M=b.TransformCoordinates(y,I),D=M.multiply(c),O=M.divide(c).normalize();u.push(D.x,D.y,D.z),m.push(O.x,O.y,O.z),p.push(S,It?1-v:v)}if(g>0){let A=u.length/3;for(let S=A-2*(h+1);S+h+21&&(d.push(S),d.push(S+1),d.push(S+h+1)),(g{Ve();Ii();hr();en();Me.CreateSphere=GG;Z.CreateSphere=(n,e,t,i,r,s)=>Ky(n,{segments:e,diameterX:t,diameterY:t,diameterZ:t,sideOrientation:s,updatable:r},i)});function WG(n){let e=n.height||2,t=n.diameterTop===0?0:n.diameterTop||n.diameter||1,i=n.diameterBottom===0?0:n.diameterBottom||n.diameter||1;t=t||1e-5,i=i||1e-5;let r=(n.tessellation||24)|0,s=(n.subdivisions||1)|0,a=!!n.hasRings,o=!!n.enclose,l=n.cap===0?0:n.cap||Z.CAP_ALL,c=n.arc&&(n.arc<=0||n.arc>1)?1:n.arc||1,f=n.sideOrientation===0?0:n.sideOrientation||Me.DEFAULTSIDE,h=n.faceUV||new Array(3),d=n.faceColors,u=c!==1&&o?2:0,m=a?s:1,p=2+(1+u)*m,_;for(_=0;_{let re=ue?t/2:i/2;if(re===0)return;let he,De,fe,be=ue?h[p-1]:h[0],Xe=null;d&&(Xe=ue?d[p-1]:d[0]);let Et=v.length/3,Ke=ue?e/2:-e/2,qe=new b(0,Ke,0);v.push(qe.x,qe.y,qe.z),x.push(0,ue?1:-1,0);let Qt=be.y+(be.w-be.y)*.5;A.push(be.x+(be.z-be.x)*.5,It?1-Qt:Qt),Xe&&S.push(Xe.r,Xe.g,Xe.b,Xe.a);let Dt=new we(.5,.5);for(fe=0;fe<=r;fe++){he=Math.PI*2*fe*c/r;let Fi=Math.cos(-he),ae=Math.sin(-he);De=new b(Fi*re,Ke,ae*re);let Bi=new we(Fi*Dt.x+.5,ae*Dt.y+.5);v.push(De.x,De.y,De.z),x.push(0,ue?1:-1,0);let ei=be.y+(be.w-be.y)*Bi.y;A.push(be.x+(be.z-be.x)*Bi.x,It?1-ei:ei),Xe&&S.push(Xe.r,Xe.g,Xe.b,Xe.a)}for(fe=0;fe{Ve();zt();Ii();hr();xs();Xu();en();Me.CreateCylinder=WG;Z.CreateCylinder=(n,e,t,i,r,s,a,o,l)=>((a===void 0||!(a instanceof $t))&&(a!==void 0&&(l=o||Z.DEFAULTSIDE,o=a),a=s,s=1),jy(n,{height:e,diameterTop:t,diameterBottom:i,tessellation:r,subdivisions:s,sideOrientation:l,updatable:o},a))});function zG(n){let e=[],t=[],i=[],r=[],s=n.diameter||1,a=n.thickness||.5,o=(n.tessellation||16)|0,l=n.sideOrientation===0?0:n.sideOrientation||Me.DEFAULTSIDE,c=o+1;for(let h=0;h<=o;h++){let d=h/o,u=h*Math.PI*2/o-Math.PI/2,m=j.Translation(s/2,0,0).multiply(j.RotationY(u));for(let p=0;p<=o;p++){let _=1-p/o,g=p*Math.PI*2/o+Math.PI,v=Math.cos(g),x=Math.sin(g),A=new b(v,x,0),S=A.scale(a/2),E=new we(d,_);S=b.TransformCoordinates(S,m),A=b.TransformNormal(A,m),t.push(S.x,S.y,S.z),i.push(A.x,A.y,A.z),r.push(E.x,It?1-E.y:E.y);let R=(h+1)%c,I=(p+1)%c;e.push(h*c+p),e.push(h*c+I),e.push(R*c+p),e.push(h*c+I),e.push(R*c+I),e.push(R*c+p)}}Me._ComputeSides(l,t,e,i,r,n.frontUVs,n.backUVs);let f=new Me;return f.indices=e,f.positions=t,f.normals=i,f.uvs=r,f}function qy(n,e={},t){let i=new Z(n,t);return e.sideOrientation=Z._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,zG(e).applyToMesh(i,e.updatable),i}var XG=C(()=>{Ve();Ii();hr();en();Me.CreateTorus=zG;Z.CreateTorus=(n,e,t,i,r,s,a)=>qy(n,{diameter:e,thickness:t,tessellation:i,sideOrientation:a,updatable:s},r)});function YG(n){let e=[],t=[],i=[],r=[],s=n.radius||2,a=n.tube||.5,o=n.radialSegments||32,l=n.tubularSegments||32,c=n.p||2,f=n.q||3,h=n.sideOrientation===0?0:n.sideOrientation||Me.DEFAULTSIDE,d=_=>{let g=Math.cos(_),v=Math.sin(_),x=f/c*_,A=Math.cos(x),S=s*(2+A)*.5*g,E=s*(2+A)*v*.5,R=s*Math.sin(x)*.5;return new b(S,E,R)},u,m;for(u=0;u<=o;u++){let g=u%o/o*2*c*Math.PI,v=d(g),x=d(g+.01),A=x.subtract(v),S=x.add(v),E=b.Cross(A,S);for(S=b.Cross(E,A),E.normalize(),S.normalize(),m=0;m{Ve();Ii();hr();en();Me.CreateTorusKnot=YG;Z.CreateTorusKnot=(n,e,t,i,r,s,a,o,l,c)=>Zy(n,{radius:e,tube:t,radialSegments:i,tubularSegments:r,p:s,q:a,sideOrientation:c,updatable:l},o)});var ic,Qy=C(()=>{Ve();yt();gm();Ii();W_();qh();Gi();bi();Hi();Z._instancedMeshFactory=(n,e)=>{let t=new ic(n,e);if(e.instancedBuffers){t.instancedBuffers={};for(let i in e.instancedBuffers)t.instancedBuffers[i]=e.instancedBuffers[i]}return t};ic=class extends gr{constructor(e,t){super(e,t.getScene()),this._indexInSourceMeshInstanceArray=-1,this._distanceToCamera=0,t.addInstance(this),this._sourceMesh=t,this._unIndexed=t._unIndexed,this.position.copyFrom(t.position),this.rotation.copyFrom(t.rotation),this.scaling.copyFrom(t.scaling),t.rotationQuaternion&&(this.rotationQuaternion=t.rotationQuaternion.clone()),this.animations=t.animations.slice();for(let i of t.getAnimationRanges())i!=null&&this.createAnimationRange(i.name,i.from,i.to);if(this.infiniteDistance=t.infiniteDistance,this.setPivotMatrix(t.getPivotMatrix()),!t.skeleton&&!t.morphTargetManager&&t.hasBoundingInfo){let i=t.getBoundingInfo();this.buildBoundingInfo(i.minimum,i.maximum)}else this.refreshBoundingInfo(!0,!0);this._syncSubMeshes()}getClassName(){return"InstancedMesh"}get lightSources(){return this._sourceMesh._lightSources}_resyncLightSources(){}_resyncLightSource(){}_removeLightSource(){}get receiveShadows(){return this._sourceMesh.receiveShadows}set receiveShadows(e){var t;((t=this._sourceMesh)==null?void 0:t.receiveShadows)!==e&&pe.Warn("Setting receiveShadows on an instanced mesh has no effect")}get material(){return this._sourceMesh.material}set material(e){var t;((t=this._sourceMesh)==null?void 0:t.material)!==e&&pe.Warn("Setting material on an instanced mesh has no effect")}get visibility(){return this._sourceMesh.visibility}set visibility(e){var t;((t=this._sourceMesh)==null?void 0:t.visibility)!==e&&pe.Warn("Setting visibility on an instanced mesh has no effect")}get skeleton(){return this._sourceMesh.skeleton}set skeleton(e){var t;((t=this._sourceMesh)==null?void 0:t.skeleton)!==e&&pe.Warn("Setting skeleton on an instanced mesh has no effect")}get renderingGroupId(){return this._sourceMesh.renderingGroupId}set renderingGroupId(e){!this._sourceMesh||e===this._sourceMesh.renderingGroupId||te.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene")}getTotalVertices(){return this._sourceMesh?this._sourceMesh.getTotalVertices():0}getTotalIndices(){return this._sourceMesh.getTotalIndices()}get sourceMesh(){return this._sourceMesh}get geometry(){return this._sourceMesh._geometry}createInstance(e){return this._sourceMesh.createInstance(e)}isReady(e=!1){return this._sourceMesh.isReady(e,!0)}getVerticesData(e,t,i){return this._sourceMesh.getVerticesData(e,t,i)}copyVerticesData(e,t){this._sourceMesh.copyVerticesData(e,t)}getVertexBuffer(e,t){return this._sourceMesh.getVertexBuffer(e,t)}setVerticesData(e,t,i,r){return this.sourceMesh&&this.sourceMesh.setVerticesData(e,t,i,r),this.sourceMesh}updateVerticesData(e,t,i,r){return this.sourceMesh&&this.sourceMesh.updateVerticesData(e,t,i,r),this.sourceMesh}setIndices(e,t=null){return this.sourceMesh&&this.sourceMesh.setIndices(e,t),this.sourceMesh}isVerticesDataPresent(e){return this._sourceMesh.isVerticesDataPresent(e)}getIndices(){return this._sourceMesh.getIndices()}get _positions(){return this._sourceMesh._positions}refreshBoundingInfo(e=!1,t=!1){if(this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;let i;typeof e=="object"?i=e:i={applySkeleton:e,applyMorph:t};let r=this._sourceMesh.geometry?this._sourceMesh.geometry.boundingBias:null;return this._refreshBoundingInfo(this._sourceMesh._getData(i,null,L.PositionKind),r),this}_preActivate(){return this._currentLOD&&this._currentLOD._preActivate(),this}_activate(e,t){if(super._activate(e,t),this._sourceMesh.subMeshes||te.Warn("Instances should only be created for meshes with geometry."),this._currentLOD){if(this._currentLOD._getWorldMatrixDeterminant()>=0!=this._getWorldMatrixDeterminant()>=0)return this._internalAbstractMeshDataInfo._actAsRegularMesh=!0,!0;if(this._internalAbstractMeshDataInfo._actAsRegularMesh=!1,this._currentLOD._registerInstanceForRenderId(this,e),t){if(!this._currentLOD._internalAbstractMeshDataInfo._isActiveIntermediate)return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstancesIntermediate=!0,!0}else if(!this._currentLOD._internalAbstractMeshDataInfo._isActive)return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstances=!0,!0}return!1}_postActivate(){this._sourceMesh.edgesShareWithInstances&&this._sourceMesh._edgesRenderer&&this._sourceMesh._edgesRenderer.isEnabled&&this._sourceMesh._renderingGroup?(this._sourceMesh._renderingGroup._edgesRenderers.pushNoDuplicate(this._sourceMesh._edgesRenderer),this._sourceMesh._edgesRenderer.customInstances.push(this.getWorldMatrix())):this._edgesRenderer&&this._edgesRenderer.isEnabled&&this._sourceMesh._renderingGroup&&this._sourceMesh._renderingGroup._edgesRenderers.push(this._edgesRenderer)}getWorldMatrix(){if(this._currentLOD&&this._currentLOD!==this._sourceMesh&&this._currentLOD.billboardMode!==Jt.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new j);let e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,$.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom($.Vector3[7]),this._currentLOD._masterMesh=e,this._billboardWorldMatrix}return super.getWorldMatrix()}get isAnInstance(){return!0}getLOD(e){if(!e)return this;let t=this.sourceMesh.getLODLevels();if(!t||t.length===0)this._currentLOD=this.sourceMesh;else{let i=this.getBoundingInfo();this._currentLOD=this.sourceMesh.getLOD(e,i.boundingSphere)}return this._currentLOD}_preActivateForIntermediateRendering(e){return this.sourceMesh._preActivateForIntermediateRendering(e)}_syncSubMeshes(){if(this.releaseSubMeshes(),this._sourceMesh.subMeshes)for(let e=0;e{Wn=class{constructor(){this._defines={},this._currentRank=32,this._maxRank=-1,this._mesh=null}unBindMesh(){this._mesh=null}addFallback(e,t){this._defines[e]||(ethis._maxRank&&(this._maxRank=e),this._defines[e]=new Array),this._defines[e].push(t)}addCPUSkinningFallback(e,t){this._mesh=t,ethis._maxRank&&(this._maxRank=e)}get hasMoreFallbacks(){return this._currentRank<=this._maxRank}reduce(e,t){if(this._mesh&&this._mesh.computeBonesUsingShaders&&this._mesh.numBoneInfluencers>0){this._mesh.computeBonesUsingShaders=!1,e=e.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),t._bonesComputationForcedToCPU=!0;let i=this._mesh.getScene();for(let r=0;r0&&(s.computeBonesUsingShaders=!1);continue}if(!(!s.computeBonesUsingShaders||s.numBoneInfluencers===0)){if(s.material.getEffect()===t)s.computeBonesUsingShaders=!1;else if(s.subMeshes){for(let a of s.subMeshes)if(a.effect===t){s.computeBonesUsingShaders=!1;break}}}}}else{let i=this._defines[this._currentRank];if(i)for(let r=0;r{Ve();Vn();hl=class extends Ee{constructor(e,t,i=!0,r=!1){super(e,t,void 0,r),this._normalMatrix=new j,this._storeEffectOnSubMeshes=i}getEffect(){return this._storeEffectOnSubMeshes?this._activeEffect:super.getEffect()}isReady(e,t){return e?!this._storeEffectOnSubMeshes||!e.subMeshes||e.subMeshes.length===0?!0:this.isReadyForSubMesh(e,e.subMeshes[0],t):!1}_isReadyForSubMesh(e){let t=e.materialDefines;return!!(!this.checkReadyOnEveryCall&&e.effect&&t&&t._renderId===this.getScene().getRenderId())}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindOnlyNormalMatrix(e){this._activeEffect.setMatrix("normalMatrix",e)}bind(e,t){t&&this.bindForSubMesh(e,t,t.subMeshes[0])}_afterBind(e,t=null,i){super._afterBind(e,t,i),this.getScene()._cachedEffect=t,i?i._drawWrapper._forceRebindOnNextCall=!1:this._drawWrapper._forceRebindOnNextCall=!1}_mustRebind(e,t,i,r=1){return i._drawWrapper._forceRebindOnNextCall||e.isCachedMaterialInvalid(this,t,r)}dispose(e,t,i){this._activeEffect=void 0,super.dispose(e,t,i)}}});function Of(n){let e=n.getVertexBuffers();if(!e)return null;let t=jG.get(n);if(!t)t=new Map,jG.set(n,t);else{let i=!1;for(let r in e)if(!t.has(r)){i=!0;break}if(!i)return t}for(let i in e){let r=e[i];if(r){let s=r.byteOffset,a=r.byteStride,o=r.type,l=r.normalized;t.set(i,{offset:s,stride:a,type:o,normalized:l})}}return t}function Nf(n,e){e.forEach((t,i)=>{let r=`vp_${i}_info`;n.setFloat4(r,t.offset,t.stride,t.type,t.normalized?1:0)})}var jG,_g=C(()=>{jG=new WeakMap});var $y,vo,Jy=C(()=>{Tr();xs();Ve();Gi();Fr();Hi();Lf();Bh();pg();Pi();ol();Un();_g();$y={effect:null,subMesh:null},vo=class n extends hl{constructor(e,t,i,r={},s=!0){super(e,t,s),this._textures={},this._internalTextures={},this._textureArrays={},this._externalTextures={},this._floats={},this._ints={},this._uints={},this._floatsArrays={},this._colors3={},this._colors3Arrays={},this._colors4={},this._colors4Arrays={},this._vectors2={},this._vectors3={},this._vectors4={},this._quaternions={},this._quaternionsArrays={},this._matrices={},this._matrixArrays={},this._matrices3x3={},this._matrices2x2={},this._vectors2Arrays={},this._vectors3Arrays={},this._vectors4Arrays={},this._uniformBuffers={},this._textureSamplers={},this._storageBuffers={},this._cachedWorldViewMatrix=new j,this._cachedWorldViewProjectionMatrix=new j,this._multiview=!1,this._vertexPullingMetadata=null,this._materialHelperNeedsPreviousMatrices=!1,this._shaderPath=i,this._options={needAlphaBlending:!1,needAlphaTesting:!1,attributes:["position","normal","uv"],uniforms:["worldViewProjection"],uniformBuffers:[],samplers:[],externalTextures:[],samplerObjects:[],storageBuffers:[],defines:[],useClipPlane:!1,...r}}get shaderPath(){return this._shaderPath}set shaderPath(e){this._shaderPath=e}get options(){return this._options}get isMultiview(){return this._multiview}getClassName(){return"ShaderMaterial"}needAlphaBlending(){return this.alpha<1||this._options.needAlphaBlending}needAlphaTesting(){return this._options.needAlphaTesting}_checkUniform(e){this._options.uniforms.indexOf(e)===-1&&this._options.uniforms.push(e)}setTexture(e,t){return this._options.samplers.indexOf(e)===-1&&this._options.samplers.push(e),this._textures[e]=t,this}setInternalTexture(e,t){return this._options.samplers.indexOf(e)===-1&&this._options.samplers.push(e),this._internalTextures[e]=t,this}removeTexture(e){delete this._textures[e]}setTextureArray(e,t){return this._options.samplers.indexOf(e)===-1&&this._options.samplers.push(e),this._checkUniform(e),this._textureArrays[e]=t,this}setExternalTexture(e,t){return this._options.externalTextures.indexOf(e)===-1&&this._options.externalTextures.push(e),this._externalTextures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setUInt(e,t){return this._checkUniform(e),this._uints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor3Array(e,t){return this._checkUniform(e),this._colors3Arrays[e]=t.reduce((i,r)=>(i.push(r.r,r.g,r.b),i),[]),this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setColor4Array(e,t){return this._checkUniform(e),this._colors4Arrays[e]=t.reduce((i,r)=>(i.push(r.r,r.g,r.b,r.a),i),[]),this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setVector4(e,t){return this._checkUniform(e),this._vectors4[e]=t,this}setQuaternion(e,t){return this._checkUniform(e),this._quaternions[e]=t,this}setQuaternionArray(e,t){return this._checkUniform(e),this._quaternionsArrays[e]=t.reduce((i,r)=>(r.toArray(i,i.length),i),[]),this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}setMatrices(e,t){this._checkUniform(e);let i=new Float32Array(t.length*16);for(let r=0;rs===e||s.startsWith(i));return r>=0&&this.options.defines.splice(r,1),(typeof t!="boolean"||t)&&this.options.defines.push(i+t),this}isReadyForSubMesh(e,t,i){return this.isReady(e,i,t)}isReady(e,t,i){var E,R,I,y;let r=i&&this._storeEffectOnSubMeshes;if(this.isFrozen){let M=r?i._drawWrapper:this._drawWrapper;if(M.effect&&M._wasPreviouslyReady&&M._wasPreviouslyUsingInstances===t)return!0}let s=this.getScene(),a=s.getEngine(),o=[],l=[],c=null,f=this._shaderPath,h=this._options.uniforms,d=this._options.uniformBuffers,u=this._options.samplers;a.getCaps().multiview&&s.activeCamera&&s.activeCamera.outputRenderTarget&&s.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,o.push("#define MULTIVIEW"),h.indexOf("viewProjection")!==-1&&h.indexOf("viewProjectionR")===-1&&h.push("viewProjectionR"));for(let M=0;M4&&(l.push(L.MatricesIndicesExtraKind),l.push(L.MatricesWeightsExtraKind));let M=e.skeleton;o.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),c=new Wn,c.addCPUSkinningFallback(0,e),M.isUsingTextureForMatrices?(o.push("#define BONETEXTURE"),h.indexOf("boneTextureInfo")===-1&&h.push("boneTextureInfo"),this._options.samplers.indexOf("boneSampler")===-1&&this._options.samplers.push("boneSampler")):(o.push("#define BonesPerMesh "+(M.bones.length+1)),h.indexOf("mBones")===-1&&h.push("mBones"))}else o.push("#define NUM_BONE_INFLUENCERS 0");let m=0,p=e?e.morphTargetManager:null;if(p){let M=o.indexOf("#define UV1")!==-1,D=o.indexOf("#define UV2")!==-1,O=o.indexOf("#define TANGENT")!==-1,V=o.indexOf("#define NORMAL")!==-1,N=o.indexOf("#define VERTEXCOLOR")!==-1;m=ll(p,o,l,e,!0,V,O,M,D,N),p.isUsingTextureForTargets&&(h.indexOf("morphTargetTextureIndices")===-1&&h.push("morphTargetTextureIndices"),this._options.samplers.indexOf("morphTargets")===-1&&this._options.samplers.push("morphTargets")),m>0&&(h=h.slice(),h.push("morphTargetInfluences"),h.push("morphTargetCount"),h.push("morphTargetTextureInfo"),h.push("morphTargetTextureIndices"))}else o.push("#define NUM_MORPH_INFLUENCERS 0");if(e){let M=e.bakedVertexAnimationManager;M&&M.isEnabled&&(o.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),h.indexOf("bakedVertexAnimationSettings")===-1&&h.push("bakedVertexAnimationSettings"),h.indexOf("bakedVertexAnimationTextureSizeInverted")===-1&&h.push("bakedVertexAnimationTextureSizeInverted"),h.indexOf("bakedVertexAnimationTime")===-1&&h.push("bakedVertexAnimationTime"),this._options.samplers.indexOf("bakedVertexAnimationTexture")===-1&&this._options.samplers.push("bakedVertexAnimationTexture"),t&&l.push("bakedVertexAnimationSettingsInstanced"))}for(let M in this._textures)if(!this._textures[M].isReady())return!1;for(let M in this._internalTextures)if(!this._internalTextures[M].isReady)return!1;e&&this.needAlphaTestingForMesh(e)&&o.push("#define ALPHATEST"),this._options.useClipPlane!==!1&&(wn(h),al(this,s,o)),s.fogEnabled&&(e!=null&&e.applyFog)&&s.fogMode!==$t.FOGMODE_NONE&&(o.push("#define FOG"),h.indexOf("view")===-1&&h.push("view"),h.indexOf("vFogInfos")===-1&&h.push("vFogInfos"),h.indexOf("vFogColor")===-1&&h.push("vFogColor")),this._useLogarithmicDepth&&(o.push("#define LOGARITHMICDEPTH"),h.indexOf("logarithmicDepthConstant")===-1&&h.push("logarithmicDepthConstant"));let _=i?i.getRenderingMesh():e;if(_&&this.useVertexPulling){let M=_.geometry;M&&(this._vertexPullingMetadata=Of(M),this._vertexPullingMetadata&&this._vertexPullingMetadata.forEach((O,V)=>{h.push(`vp_${V}_info`)})),o.push("#define USE_VERTEX_PULLING");let D=(E=_.geometry)==null?void 0:E.getIndexBuffer();D&&!_.isUnIndexed&&(o.push("#define VERTEX_PULLING_USE_INDEX_BUFFER"),D.is32Bits&&o.push("#define VERTEX_PULLING_INDEX_BUFFER_32BITS"))}this.customShaderNameResolve&&(h=h.slice(),d=d.slice(),u=u.slice(),f=this.customShaderNameResolve(this.name,h,d,u,o,l));let g=r?i._getDrawWrapper(void 0,!0):this._drawWrapper,v=(R=g==null?void 0:g.effect)!=null?R:null,x=(I=g==null?void 0:g.defines)!=null?I:null,A=o.join(` -`),S=v;return x!==A&&(S=a.createEffect(f,{attributes:l,uniformsNames:h,uniformBuffersNames:d,samplers:u,defines:A,fallbacks:c,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:m},shaderLanguage:this._options.shaderLanguage,extraInitializationsAsync:this._options.extraInitializationsAsync},a),r?i.setEffect(S,A,this._materialContext):g&&g.setEffect(S,A),this._onEffectCreatedObservable&&($y.effect=S,$y.subMesh=(y=i!=null?i:e==null?void 0:e.subMeshes[0])!=null?y:null,this._onEffectCreatedObservable.notifyObservers($y))),g._wasPreviouslyUsingInstances=!!t,S!=null&&S.isReady()?(v!==S&&s.resetCachedMaterial(),g._wasPreviouslyReady=!0,!0):!1}bindOnlyWorldMatrix(e,t){let i=t!=null?t:this.getEffect();if(!i)return;let r=this._options.uniforms;r.indexOf("world")!==-1&&i.setMatrix("world",e);let s=this.getScene();r.indexOf("worldView")!==-1&&(e.multiplyToRef(s.getViewMatrix(),this._cachedWorldViewMatrix),i.setMatrix("worldView",this._cachedWorldViewMatrix)),r.indexOf("worldViewProjection")!==-1&&(e.multiplyToRef(s.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),i.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)),r.indexOf("view")!==-1&&i.setMatrix("view",s.getViewMatrix())}bindForSubMesh(e,t,i){var r;this.bind(e,t,(r=i._drawWrapperOverride)==null?void 0:r.effect,i)}bind(e,t,i,r){var h;let s=r&&this._storeEffectOnSubMeshes,a=i!=null?i:s?r.effect:this.getEffect();if(!a)return;let o=this.getScene();this._activeEffect=a,this.bindOnlyWorldMatrix(e,i);let l=this._options.uniformBuffers,c=!1;if(a&&l&&l.length>0&&o.getEngine().supportsUniformBuffers)for(let d=0;dnew n(e,this.getScene(),this._shaderPath,this._options,this._storeEffectOnSubMeshes),this);t.name=e,t.id=e,typeof t._shaderPath=="object"&&(t._shaderPath={...t._shaderPath}),this._options={...this._options};let i=Object.keys(this._options);for(let r of i){let s=this._options[r];Array.isArray(s)&&(this._options[r]=s.slice(0))}this.stencil.copyTo(t.stencil);for(let r in this._textures)t.setTexture(r,this._textures[r]);for(let r in this._internalTextures)t.setInternalTexture(r,this._internalTextures[r]);for(let r in this._textureArrays)t.setTextureArray(r,this._textureArrays[r]);for(let r in this._externalTextures)t.setExternalTexture(r,this._externalTextures[r]);for(let r in this._ints)t.setInt(r,this._ints[r]);for(let r in this._uints)t.setUInt(r,this._uints[r]);for(let r in this._floats)t.setFloat(r,this._floats[r]);for(let r in this._floatsArrays)t.setFloats(r,this._floatsArrays[r]);for(let r in this._colors3)t.setColor3(r,this._colors3[r]);for(let r in this._colors3Arrays)t._colors3Arrays[r]=this._colors3Arrays[r];for(let r in this._colors4)t.setColor4(r,this._colors4[r]);for(let r in this._colors4Arrays)t._colors4Arrays[r]=this._colors4Arrays[r];for(let r in this._vectors2)t.setVector2(r,this._vectors2[r]);for(let r in this._vectors3)t.setVector3(r,this._vectors3[r]);for(let r in this._vectors4)t.setVector4(r,this._vectors4[r]);for(let r in this._quaternions)t.setQuaternion(r,this._quaternions[r]);for(let r in this._quaternionsArrays)t._quaternionsArrays[r]=this._quaternionsArrays[r];for(let r in this._matrices)t.setMatrix(r,this._matrices[r]);for(let r in this._matrixArrays)t._matrixArrays[r]=this._matrixArrays[r].slice();for(let r in this._matrices3x3)t.setMatrix3x3(r,this._matrices3x3[r]);for(let r in this._matrices2x2)t.setMatrix2x2(r,this._matrices2x2[r]);for(let r in this._vectors2Arrays)t.setArray2(r,this._vectors2Arrays[r]);for(let r in this._vectors3Arrays)t.setArray3(r,this._vectors3Arrays[r]);for(let r in this._vectors4Arrays)t.setArray4(r,this._vectors4Arrays[r]);for(let r in this._uniformBuffers)t.setUniformBuffer(r,this._uniformBuffers[r]);for(let r in this._textureSamplers)t.setTextureSampler(r,this._textureSamplers[r]);for(let r in this._storageBuffers)t.setStorageBuffer(r,this._storageBuffers[r]);return t}dispose(e,t,i){if(t){let r;for(r in this._textures)this._textures[r].dispose();for(r in this._internalTextures)this._internalTextures[r].dispose();for(r in this._textureArrays){let s=this._textureArrays[r];for(let a=0;anew n(e.name,t,e.shaderPath,e.options,e.storeEffectOnSubMeshes),e,t,i),s;e.stencil&&r.stencil.parse(e.stencil,t,i);for(s in e.textures)r.setTexture(s,_e.Parse(e.textures[s],t,i));for(s in e.textureArrays){let a=e.textureArrays[s],o=[];for(let l=0;l(c%3===0?o.push([l]):o[o.length-1].push(l),o),[]).map(o=>({r:o[0],g:o[1],b:o[2]}));r.setColor3Array(s,a)}for(s in e.colors4){let a=e.colors4[s];r.setColor4(s,{r:a[0],g:a[1],b:a[2],a:a[3]})}for(s in e.colors4Arrays){let a=e.colors4Arrays[s].reduce((o,l,c)=>(c%4===0?o.push([l]):o[o.length-1].push(l),o),[]).map(o=>({r:o[0],g:o[1],b:o[2],a:o[3]}));r.setColor4Array(s,a)}for(s in e.vectors2){let a=e.vectors2[s];r.setVector2(s,{x:a[0],y:a[1]})}for(s in e.vectors3){let a=e.vectors3[s];r.setVector3(s,{x:a[0],y:a[1],z:a[2]})}for(s in e.vectors4){let a=e.vectors4[s];r.setVector4(s,{x:a[0],y:a[1],z:a[2],w:a[3]})}for(s in e.quaternions)r.setQuaternion(s,Ye.FromArray(e.quaternions[s]));for(s in e.matrices)r.setMatrix(s,j.FromArray(e.matrices[s]));for(s in e.matrixArray)r._matrixArrays[s]=new Float32Array(e.matrixArray[s]);for(s in e.matrices3x3)r.setMatrix3x3(s,e.matrices3x3[s]);for(s in e.matrices2x2)r.setMatrix2x2(s,e.matrices2x2[s]);for(s in e.vectors2Arrays)r.setArray2(s,e.vectors2Arrays[s]);for(s in e.vectors3Arrays)r.setArray3(s,e.vectors3Arrays[s]);for(s in e.vectors4Arrays)r.setArray4(s,e.vectors4Arrays[s]);for(s in e.quaternionsArrays)r.setArray4(s,e.quaternionsArrays[s]);return r}static async ParseFromFileAsync(e,t,i,r=""){return await new Promise((s,a)=>{let o=new Ir;o.addEventListener("readystatechange",()=>{if(o.readyState==4)if(o.status==200){let l=JSON.parse(o.responseText),c=this.Parse(l,i||Le.LastCreatedScene,r);e&&(c.name=e),s(c)}else a("Unable to load the ShaderMaterial")}),o.open("GET",t),o.send()})}static async ParseFromSnippetAsync(e,t,i=""){return await new Promise((r,s)=>{let a=new Ir;a.addEventListener("readystatechange",()=>{if(a.readyState==4)if(a.status==200){let o=JSON.parse(JSON.parse(a.responseText).jsonPayload),l=JSON.parse(o.shaderMaterial),c=this.Parse(l,t||Le.LastCreatedScene,i);c.snippetId=e,r(c)}else s("Unable to load the snippet "+e)}),a.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),a.send()})}};vo.SnippetUrl="https://snippet.babylonjs.com";vo.CreateFromSnippetAsync=vo.ParseFromSnippetAsync;wt("BABYLON.ShaderMaterial",vo)});var qG,Lse,rc=C(()=>{W();qG="bonesDeclaration",Lse=`#if NUM_BONE_INFLUENCERS>0 +Bad Bone Indices = `+m;return{skinned:!0,valid:s===0&&o===0&&m===0,report:p}}_checkDelayState(){let e=this.getScene();return this._geometry?this._geometry.load(e):this.delayLoadState===4&&(this.delayLoadState=2,this._queueLoad(e)),this}_queueLoad(e){e.addPendingData(this);let t=this.delayLoadingFile.indexOf(".babylonbinarymeshdata")!==-1;return _e.LoadFile(this.delayLoadingFile,i=>{i instanceof ArrayBuffer?this._delayLoadingFunction(i,this):this._delayLoadingFunction(JSON.parse(i),this);for(let r of this.instances)r.refreshBoundingInfo(),r._syncSubMeshes();this.delayLoadState=1,e.removePendingData(this)},()=>{},e.offlineProvider,t),this}isInFrustum(e){return this.delayLoadState===2||!super.isInFrustum(e)?!1:(this._checkDelayState(),!0)}setMaterialById(e){let t=this.getScene().materials,i;for(i=t.length-1;i>-1;i--)if(t[i].id===e)return this.material=t[i],this;let r=this.getScene().multiMaterials;for(i=r.length-1;i>-1;i--)if(r[i].id===e)return this.material=r[i],this;return this}getAnimatables(){let e=[];return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e}bakeTransformIntoVertices(e){if(!this.isVerticesDataPresent(L.PositionKind))return this;let t=this.subMeshes.splice(0);this._resetPointsArrayCache();let i=this.getVerticesData(L.PositionKind),r=b.Zero(),s;for(s=0;s{let d=h.width,u=h.height,p=this.getEngine().createCanvas(d,u).getContext("2d");p.drawImage(h,0,0);let _=p.getImageData(0,0,d,u).data;this.applyDisplacementMapFromBuffer(_,d,u,t,i,s,a,o),r&&r(this)};return _e.LoadImage(e,f,l||(()=>{}),c.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,i,r,s,a,o,l=!1){if(!this.isVerticesDataPresent(L.PositionKind)||!this.isVerticesDataPresent(L.NormalKind)||!this.isVerticesDataPresent(L.UVKind))return te.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;let c=this.getVerticesData(L.PositionKind,!0,!0),f=this.getVerticesData(L.NormalKind),h=this.getVerticesData(L.UVKind),d=b.Zero(),u=b.Zero(),m=we.Zero();a=a||we.Zero(),o=o||new we(1,1);for(let p=0;p{var c;return!((c=this.getVertexBuffer(l))!=null&&c.getIsInstanced())}),i=this.getIndices(!1,!0),r={},s=(l,c)=>{let f=new Float32Array(i.length*c),h=0;for(let d=0;d{let o=r.length-1-a,l=r[o];for(let c=0;c{for(let o=0;o-1&&(r._waitingMorphTargetManagerId=e.morphTargetManagerId),e.skeletonId!==void 0&&e.skeletonId!==null&&(r.skeleton=t.getLastSkeletonById(e.skeletonId),r._waitingSkeletonId=e.skeletonId,e.numBoneInfluencers&&(r.numBoneInfluencers=e.numBoneInfluencers)),e.skeletonUniqueId!==void 0&&e.skeletonUniqueId!==null&&(r._waitingSkeletonUniqueId=e.skeletonUniqueId),e.animations){for(let a=0;a4,c=l?this.getVerticesData(L.MatricesIndicesExtraKind):null,f=l?this.getVerticesData(L.MatricesWeightsExtraKind):null,h=e.getTransformMatrices(this),d=b.Zero(),u=new K,m=new K,p=0,_;for(let g=0;g0&&(K.FromFloat32ArrayToRefScaled(h,Math.floor(a[p+_]*16),v,m),u.addToSelf(m));if(l)for(_=0;_<4;_++)v=f[p+_],v>0&&(K.FromFloat32ArrayToRefScaled(h,Math.floor(c[p+_]*16),v,m),u.addToSelf(m));b.TransformCoordinatesFromFloatsToRef(i._sourcePositions[g],i._sourcePositions[g+1],i._sourcePositions[g+2],u,d),d.toArray(r,g),t&&(b.TransformNormalFromFloatsToRef(i._sourceNormals[g],i._sourceNormals[g+1],i._sourceNormals[g+2],u,d),d.toArray(s,g)),u.reset()}return this.updateVerticesData(L.PositionKind,r),t&&this.updateVerticesData(L.NormalKind,s),this}static MinMax(e){let t=null,i=null;for(let r of e){let a=r.getBoundingInfo().boundingBox;!t||!i?(t=a.minimumWorld.clone(),i=a.maximumWorld.clone()):(t.minimizeInPlace(a.minimumWorld),i.maximizeInPlace(a.maximumWorld))}return!t||!i?{min:b.Zero(),max:b.Zero()}:{min:t,max:i}}static Center(e){let t=e instanceof Array?n.MinMax(e):e;return b.Center(t.min,t.max)}static MergeMeshes(e,t=!0,i,r,s,a){return fg(n._MergeMeshesCoroutine(e,t,i,r,s,a,!1))}static async MergeMeshesAsync(e,t=!0,i,r,s,a){return await rG(n._MergeMeshesCoroutine(e,t,i,r,s,a,!0),tG())}static*_MergeMeshesCoroutine(e,t=!0,i,r,s,a,o){if(e=e.filter(Boolean),e.length===0)return null;let l;if(!i){let R=0;for(l=0;l=65536)return te.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}let c=e[0];a&&(s=!1,e.sort((R,I)=>{var y,M,D,O;return((M=(y=R.material)==null?void 0:y.uniqueId)!=null?M:-1)-((O=(D=I.material)==null?void 0:D.uniqueId)!=null?O:-1)}));let f=new Array,h=new Array,d=new Array,u=e[0].sideOrientation;for(l=0;lMath.max(y,M.start+M.count),0);if(a)if(R.material){let y=R.material;if(y instanceof Nm){for(let M=0;M1){let R=0;for(let I=1;I{let I=R.computeWorldMatrix(!0);return{vertexData:Ce.ExtractFromMesh(R,!1,!1),transform:I}},{vertexData:p,transform:_}=m(e[0]);o&&(yield);let g=new Array(e.length-1);for(let R=1;R{throw qe("GroundMesh")};q._GoldbergMeshParser=(n,e)=>{throw qe("GoldbergMesh")};q._LinesMeshParser=(n,e)=>{throw qe("LinesMesh")};q._GreasedLineMeshParser=(n,e)=>{throw qe("GreasedLineMesh")};q._GreasedLineRibbonMeshParser=(n,e)=>{throw qe("GreasedLineRibbonMesh")};q._TrailMeshParser=(n,e)=>{throw qe("TrailMesh")};q._GaussianSplattingMeshParser=(n,e)=>{throw qe("GaussianSplattingMesh")};q._GaussianSplattingPartProxyMeshParser=(n,e)=>{throw qe("GaussianSplattingPartProxyMesh")};q._GaussianSplattingCompoundMeshParser=(n,e)=>{throw qe("GaussianSplattingCompoundMesh")};Ft("BABYLON.Mesh",q)});var Fm,by=C(()=>{oo();wl();Dn();Fm=class{constructor(){this._zoomStopsAnimation=!1,this._idleRotationSpeed=.05,this._idleRotationWaitTime=2e3,this._idleRotationSpinupTime=2e3,this.targetAlpha=null,this._attachedCamera=null,this._isPointerDown=!1,this._lastFrameTime=null,this._lastInteractionTime=-1/0,this._cameraRotationSpeed=0,this._lastFrameRadius=0}get name(){return"AutoRotation"}set zoomStopsAnimation(e){this._zoomStopsAnimation=e}get zoomStopsAnimation(){return this._zoomStopsAnimation}set idleRotationSpeed(e){this._idleRotationSpeed=e}get idleRotationSpeed(){return this._idleRotationSpeed}set idleRotationWaitTime(e){this._idleRotationWaitTime=e}get idleRotationWaitTime(){return this._idleRotationWaitTime}set idleRotationSpinupTime(e){this._idleRotationSpinupTime=e}get idleRotationSpinupTime(){return this._idleRotationSpinupTime}get rotationInProgress(){return Math.abs(this._cameraRotationSpeed)>0}get attachedNode(){return this._attachedCamera}init(){}attach(e){this._attachedCamera=e;let t=this._attachedCamera.getScene();this._onPrePointerObservableObserver=t.onPrePointerObservable.add(i=>{if(i.type===st.POINTERDOWN){this._isPointerDown=!0;return}i.type===st.POINTERUP&&(this._isPointerDown=!1)}),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{if(this._reachTargetAlpha())return;let i=pr.Now,r=0;this._lastFrameTime!=null&&(r=i-this._lastFrameTime),this._lastFrameTime=i,this._applyUserInteraction();let s=i-this._lastInteractionTime-this._idleRotationWaitTime,a=Math.max(Math.min(s/this._idleRotationSpinupTime,1),0);this._cameraRotationSpeed=this._idleRotationSpeed*a,this._attachedCamera&&(this._attachedCamera.alpha-=this._cameraRotationSpeed*(r/1e3))})}detach(){if(!this._attachedCamera)return;let e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._attachedCamera=null,this._lastFrameTime=null}resetLastInteractionTime(e){this._lastInteractionTime=e!=null?e:pr.Now}_reachTargetAlpha(){return this._attachedCamera&&this.targetAlpha?Math.abs(this._attachedCamera.alpha-this.targetAlpha){Fh();po=class n{constructor(){this._easingMode=n.EASINGMODE_EASEIN}setEasingMode(e){let t=Math.min(Math.max(e,0),2);this._easingMode=t}getEasingMode(){return this._easingMode}easeInCore(e){throw new Error("You must implement this method")}ease(e){switch(this._easingMode){case n.EASINGMODE_EASEIN:return this.easeInCore(e);case n.EASINGMODE_EASEOUT:return 1-this.easeInCore(1-e)}return e>=.5?(1-this.easeInCore((1-e)*2))*.5+.5:this.easeInCore(e*2)*.5}};po.EASINGMODE_EASEIN=0;po.EASINGMODE_EASEOUT=1;po.EASINGMODE_EASEINOUT=2;FA=class extends po{constructor(e=1){super(),this.amplitude=e}easeInCore(e){let t=Math.max(0,this.amplitude);return Math.pow(e,3)-e*t*Math.sin(3.141592653589793*e)}},BA=class extends po{constructor(e=2){super(),this.exponent=e}easeInCore(e){return this.exponent<=0?e:(Math.exp(this.exponent*e)-1)/(Math.exp(this.exponent)-1)}}});var bf,My=C(()=>{bf=class n{constructor(e,t,i){this.name=e,this.from=t,this.to=i}clone(){return new n(this.name,this.from,this.to)}}});var Cy,yy,Py,Dy,Ly,Oy,_o,ht,If=C(()=>{Ge();zt();Ln();Hi();My();js();BT();Bh();Tr();Cy=Object.freeze(new Xe(0,0,0,0)),yy=Object.freeze(b.Zero()),Py=Object.freeze(we.Zero()),Dy=Object.freeze(Ul.Zero()),Ly=Object.freeze(ve.Black()),Oy=Object.freeze(new lt(0,0,0,0)),_o={key:0,repeatCount:0,loopMode:2},ht=class n{static _PrepareAnimation(e,t,i,r,s,a,o,l){let c;if(!isNaN(parseFloat(s))&&isFinite(s)?c=n.ANIMATIONTYPE_FLOAT:s instanceof Xe?c=n.ANIMATIONTYPE_QUATERNION:s instanceof b?c=n.ANIMATIONTYPE_VECTOR3:s instanceof we?c=n.ANIMATIONTYPE_VECTOR2:s instanceof ve?c=n.ANIMATIONTYPE_COLOR3:s instanceof lt?c=n.ANIMATIONTYPE_COLOR4:s instanceof Ul&&(c=n.ANIMATIONTYPE_SIZE),c==null)return null;let f=new n(e,t,i,c,o),h=[{frame:0,value:s},{frame:r,value:a}];return f.setKeys(h),l!==void 0&&f.setEasingFunction(l),f}static CreateAnimation(e,t,i,r){let s=new n(e+"Animation",e,i,t,n.ANIMATIONLOOPMODE_CONSTANT);return s.setEasingFunction(r),s}static CreateAndStartAnimation(e,t,i,r,s,a,o,l,c,f,h){let d=n._PrepareAnimation(e,i,r,s,a,o,l,c);return!d||(t.getScene&&(h=t.getScene()),!h)?null:h.beginDirectAnimation(t,[d],0,s,d.loopMode!==n.ANIMATIONLOOPMODE_CONSTANT,1,f)}static CreateAndStartHierarchyAnimation(e,t,i,r,s,a,o,l,c,f,h){let d=n._PrepareAnimation(e,r,s,a,o,l,c,f);return d?t.getScene().beginDirectHierarchyAnimation(t,i,[d],0,a,d.loopMode===1,1,h):null}static CreateMergeAndStartAnimation(e,t,i,r,s,a,o,l,c,f){let h=n._PrepareAnimation(e,i,r,s,a,o,l,c);return h?(t.animations.push(h),t.getScene().beginAnimation(t,0,s,h.loopMode===1,1,f)):null}static MakeAnimationAdditive(e,t,i,r=!1,s){var v,x;let a;typeof t=="object"?a=t:a={referenceFrame:t!=null?t:0,range:i,cloneOriginalAnimation:r,clonedAnimationName:s};let o=e;if(a.cloneOriginalAnimation&&(o=e.clone(),o.name=a.clonedAnimationName||o.name),!o._keys.length)return o;let l=a.referenceFrame&&a.referenceFrame>=0?a.referenceFrame:0,c=0,f=o._keys[0],h=o._keys.length-1,d=o._keys[h],u={referenceValue:f.value,referencePosition:$.Vector3[0],referenceQuaternion:$.Quaternion[0],referenceScaling:$.Vector3[1],keyPosition:$.Vector3[2],keyQuaternion:$.Quaternion[1],keyScaling:$.Vector3[3]},m=f.frame,p=d.frame;if(a.range){let A=o.getRange(a.range);A&&(m=A.from,p=A.to)}else m=(v=a.fromFrame)!=null?v:m,p=(x=a.toFrame)!=null?x:p;if(m!==f.frame&&(c=o.createKeyForFrame(m)),p!==d.frame&&(h=o.createKeyForFrame(p)),o._keys.length===1){let A=o._getKeyValue(o._keys[0]);u.referenceValue=A.clone?A.clone():A}else if(l<=f.frame){let A=o._getKeyValue(f.value);u.referenceValue=A.clone?A.clone():A}else if(l>=d.frame){let A=o._getKeyValue(d.value);u.referenceValue=A.clone?A.clone():A}else{_o.key=0;let A=o._interpolate(l,_o);u.referenceValue=A.clone?A.clone():A}o.dataType===n.ANIMATIONTYPE_QUATERNION?u.referenceValue.normalize().conjugateInPlace():o.dataType===n.ANIMATIONTYPE_MATRIX&&(u.referenceValue.decompose(u.referenceScaling,u.referenceQuaternion,u.referencePosition),u.referenceQuaternion.normalize().conjugateInPlace());let _=Number.MAX_VALUE,g=a.clipKeys?[]:null;for(let A=c;A<=h;A++){let S=o._keys[A];if((g||a.cloneOriginalAnimation)&&(S={frame:S.frame,value:S.value.clone?S.value.clone():S.value,inTangent:S.inTangent,outTangent:S.outTangent,interpolation:S.interpolation,lockedTangent:S.lockedTangent,easingFunction:S.easingFunction},g&&(_===Number.MAX_VALUE&&(_=S.frame),S.frame-=_,g.push(S))),!(A&&o.dataType!==n.ANIMATIONTYPE_FLOAT&&S.value===f.value))switch(o.dataType){case n.ANIMATIONTYPE_MATRIX:S.value.decompose(u.keyScaling,u.keyQuaternion,u.keyPosition),u.keyPosition.subtractInPlace(u.referencePosition),u.keyScaling.divideInPlace(u.referenceScaling),u.referenceQuaternion.multiplyToRef(u.keyQuaternion,u.keyQuaternion),K.ComposeToRef(u.keyScaling,u.keyQuaternion,u.keyPosition,S.value);break;case n.ANIMATIONTYPE_QUATERNION:u.referenceValue.multiplyToRef(S.value,S.value);break;case n.ANIMATIONTYPE_VECTOR2:case n.ANIMATIONTYPE_VECTOR3:case n.ANIMATIONTYPE_COLOR3:case n.ANIMATIONTYPE_COLOR4:S.value.subtractToRef(u.referenceValue,S.value);break;case n.ANIMATIONTYPE_SIZE:S.value.width-=u.referenceValue.width,S.value.height-=u.referenceValue.height;break;default:S.value-=u.referenceValue}}return g&&o.setKeys(g,!0),o}static TransitionTo(e,t,i,r,s,a,o,l=null,c=!0,f){if(o<=0)return i[e]=t,l&&l(),null;let h=s*(o/1e3);return a.setKeys(f!=null?f:[{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:h,value:t}]),i.animations||(i.animations=[]),i.animations.push(a),r.beginAnimation(i,0,h,!1,1,l!=null?l:void 0,void 0,c)}get runtimeAnimations(){return this._runtimeAnimations}get hasRunningRuntimeAnimations(){for(let e of this._runtimeAnimations)if(!e.isStopped())return!0;return!1}constructor(e,t,i,r,s,a){this.name=e,this.targetProperty=t,this.framePerSecond=i,this.dataType=r,this.loopMode=s,this.enableBlending=a,this._easingFunction=null,this._runtimeAnimations=new Array,this._events=new Array,this.blendingSpeed=.01,this._ranges={},this._coreAnimation=null,this.targetPropertyPath=t.split("."),this.dataType=r,this.loopMode=s===void 0?n.ANIMATIONLOOPMODE_CYCLE:s,this.uniqueId=n._UniqueIdGenerator++}toString(e){let t="Name: "+this.name+", property: "+this.targetProperty;if(t+=", datatype: "+["Float","Vector3","Quaternion","Matrix","Color3","Vector2"][this.dataType],t+=", nKeys: "+(this._keys?this._keys.length:"none"),t+=", nRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";let i=!0;for(let r in this._ranges)i||(t+=", "),i=!1,t+=r;t+="}"}return t}addEvent(e){this._events.push(e),this._events.sort((t,i)=>t.frame-i.frame)}removeEvents(e){for(let t=0;t=0;a--)this._keys[a].frame>=r&&this._keys[a].frame<=s&&this._keys.splice(a,1)}this._ranges[e]=null}}getRange(e){return this._ranges[e]}getKeys(){return this._keys}getHighestFrame(){let e=0;for(let t=0,i=this._keys.length;t0)return t.highLimitValue.clone?t.highLimitValue.clone():t.highLimitValue;let r=this._keys,s;if(this._coreAnimation)s=this._coreAnimation._key;else{let p=r.length;for(s=t.key;s>=0&&e=r[s+1].frame;)++s;if(t.key=s,s<0)return i?void 0:this._getKeyValue(r[0].value);if(s+1>p-1)return i?void 0:this._getKeyValue(r[p-1].value);this._key=s}let a=r[s],o=r[s+1];if(i&&(e===a.frame||e===o.frame))return;let l=this._getKeyValue(a.value),c=this._getKeyValue(o.value);if(a.interpolation===1)return o.frame>e?l:c;let f=a.outTangent!==void 0&&o.inTangent!==void 0,h=o.frame-a.frame,d=(e-a.frame)/h,u=a.easingFunction||this.getEasingFunction();switch(u&&(d=u.ease(d)),this.dataType){case n.ANIMATIONTYPE_FLOAT:{let p=f?this.floatInterpolateFunctionWithTangents(l,a.outTangent*h,c,o.inTangent*h,d):this.floatInterpolateFunction(l,c,d);switch(t.loopMode){case n.ANIMATIONLOOPMODE_CYCLE:case n.ANIMATIONLOOPMODE_CONSTANT:case n.ANIMATIONLOOPMODE_YOYO:return p;case n.ANIMATIONLOOPMODE_RELATIVE:case n.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return((m=t.offsetValue)!=null?m:0)*t.repeatCount+p}break}case n.ANIMATIONTYPE_QUATERNION:{let p=f?this.quaternionInterpolateFunctionWithTangents(l,a.outTangent.scale(h),c,o.inTangent.scale(h),d):this.quaternionInterpolateFunction(l,c,d);switch(t.loopMode){case n.ANIMATIONLOOPMODE_CYCLE:case n.ANIMATIONLOOPMODE_CONSTANT:case n.ANIMATIONLOOPMODE_YOYO:return p;case n.ANIMATIONLOOPMODE_RELATIVE:case n.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return p.addInPlace((t.offsetValue||Cy).scale(t.repeatCount))}return p}case n.ANIMATIONTYPE_VECTOR3:{let p=f?this.vector3InterpolateFunctionWithTangents(l,a.outTangent.scale(h),c,o.inTangent.scale(h),d):this.vector3InterpolateFunction(l,c,d);switch(t.loopMode){case n.ANIMATIONLOOPMODE_CYCLE:case n.ANIMATIONLOOPMODE_CONSTANT:case n.ANIMATIONLOOPMODE_YOYO:return p;case n.ANIMATIONLOOPMODE_RELATIVE:case n.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return p.add((t.offsetValue||yy).scale(t.repeatCount))}break}case n.ANIMATIONTYPE_VECTOR2:{let p=f?this.vector2InterpolateFunctionWithTangents(l,a.outTangent.scale(h),c,o.inTangent.scale(h),d):this.vector2InterpolateFunction(l,c,d);switch(t.loopMode){case n.ANIMATIONLOOPMODE_CYCLE:case n.ANIMATIONLOOPMODE_CONSTANT:case n.ANIMATIONLOOPMODE_YOYO:return p;case n.ANIMATIONLOOPMODE_RELATIVE:case n.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return p.add((t.offsetValue||Py).scale(t.repeatCount))}break}case n.ANIMATIONTYPE_SIZE:{switch(t.loopMode){case n.ANIMATIONLOOPMODE_CYCLE:case n.ANIMATIONLOOPMODE_CONSTANT:case n.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(l,c,d);case n.ANIMATIONLOOPMODE_RELATIVE:case n.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return this.sizeInterpolateFunction(l,c,d).add((t.offsetValue||Dy).scale(t.repeatCount))}break}case n.ANIMATIONTYPE_COLOR3:{let p=f?this.color3InterpolateFunctionWithTangents(l,a.outTangent.scale(h),c,o.inTangent.scale(h),d):this.color3InterpolateFunction(l,c,d);switch(t.loopMode){case n.ANIMATIONLOOPMODE_CYCLE:case n.ANIMATIONLOOPMODE_CONSTANT:case n.ANIMATIONLOOPMODE_YOYO:return p;case n.ANIMATIONLOOPMODE_RELATIVE:case n.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return p.add((t.offsetValue||Ly).scale(t.repeatCount))}break}case n.ANIMATIONTYPE_COLOR4:{let p=f?this.color4InterpolateFunctionWithTangents(l,a.outTangent.scale(h),c,o.inTangent.scale(h),d):this.color4InterpolateFunction(l,c,d);switch(t.loopMode){case n.ANIMATIONLOOPMODE_CYCLE:case n.ANIMATIONLOOPMODE_CONSTANT:case n.ANIMATIONLOOPMODE_YOYO:return p;case n.ANIMATIONLOOPMODE_RELATIVE:case n.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return p.add((t.offsetValue||Oy).scale(t.repeatCount))}break}case n.ANIMATIONTYPE_MATRIX:{switch(t.loopMode){case n.ANIMATIONLOOPMODE_CYCLE:case n.ANIMATIONLOOPMODE_CONSTANT:case n.ANIMATIONLOOPMODE_YOYO:return n.AllowMatricesInterpolation?this.matrixInterpolateFunction(l,c,d,t.workValue):l;case n.ANIMATIONLOOPMODE_RELATIVE:case n.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return l}break}}return 0}matrixInterpolateFunction(e,t,i,r){return n.AllowMatrixDecomposeForInterpolation?r?(K.DecomposeLerpToRef(e,t,i,r),r):K.DecomposeLerp(e,t,i):r?(K.LerpToRef(e,t,i,r),r):K.Lerp(e,t,i)}clone(e=!1){let t=new n(this.name,this.targetPropertyPath.join("."),this.framePerSecond,this.dataType,this.loopMode);if(t.enableBlending=this.enableBlending,t.blendingSpeed=this.blendingSpeed,this._keys&&t.setKeys(this._keys,!1,e),this._ranges){t._ranges={};for(let i in this._ranges){let r=this._ranges[i];r&&(t._ranges[i]=r.clone())}}return t}setKeys(e,t=!1,i=!1){if(t)this._keys=e;else if(this._keys=e.slice(0),i)for(let r=0;r=2&&(l=o.values[1]),o.values.length>=3&&(c=o.values[2]),o.values.length>=4&&(f=o.values[3]);break;case n.ANIMATIONTYPE_QUATERNION:if(s=Xe.FromArray(o.values),o.values.length>=8){let d=Xe.FromArray(o.values.slice(4,8));d.equals(Xe.Zero())||(l=d)}if(o.values.length>=12){let d=Xe.FromArray(o.values.slice(8,12));d.equals(Xe.Zero())||(c=d)}o.values.length>=13&&(f=o.values[12]);break;case n.ANIMATIONTYPE_MATRIX:s=K.FromArray(o.values),o.values.length>=17&&(f=o.values[16]);break;case n.ANIMATIONTYPE_COLOR3:s=ve.FromArray(o.values),o.values[3]&&(l=ve.FromArray(o.values[3])),o.values[4]&&(c=ve.FromArray(o.values[4])),o.values[5]&&(f=o.values[5]);break;case n.ANIMATIONTYPE_COLOR4:s=lt.FromArray(o.values),o.values[4]&&(l=lt.FromArray(o.values[4])),o.values[5]&&(c=lt.FromArray(o.values[5])),o.values[6]&&(f=lt.FromArray(o.values[6]));break;case n.ANIMATIONTYPE_VECTOR3:default:s=b.FromArray(o.values),o.values[3]&&(l=b.FromArray(o.values[3])),o.values[4]&&(c=b.FromArray(o.values[4])),o.values[5]&&(f=o.values[5]);break}let h={};h.frame=o.frame,h.value=s,l!=null&&(h.inTangent=l),c!=null&&(h.outTangent=c),f!=null&&(h.interpolation=f),r.push(h)}if(t.setKeys(r),e.ranges)for(a=0;a{let s=new Ir;s.addEventListener("readystatechange",()=>{if(s.readyState==4)if(s.status==200){let a=JSON.parse(s.responseText);if(a.animations&&(a=a.animations),a.length){let o=[];for(let l of a)o.push(this.Parse(l));i(o)}else{let o=this.Parse(a);e&&(o.name=e),i(o)}}else r("Unable to load the animation")}),s.open("GET",t),s.send()})}static async ParseFromSnippetAsync(e){return await new Promise((t,i)=>{let r=new Ir;r.addEventListener("readystatechange",()=>{if(r.readyState==4)if(r.status==200){let s=JSON.parse(JSON.parse(r.responseText).jsonPayload);if(s.animations){let a=JSON.parse(s.animations),o=[];for(let l of a.animations){let c=this.Parse(l);c.snippetId=e,o.push(c)}t(o)}else{let a=JSON.parse(s.animation),o=this.Parse(a);o.snippetId=e,t(o)}}else i("Unable to load the snippet "+e)}),r.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),r.send()})}};ht._UniqueIdGenerator=0;ht.AllowMatricesInterpolation=!1;ht.AllowMatrixDecomposeForInterpolation=!0;ht.InheritOriginalValueFromActiveAnimations=!1;ht.SnippetUrl="https://snippet.babylonjs.com";ht.ANIMATIONTYPE_FLOAT=0;ht.ANIMATIONTYPE_VECTOR3=1;ht.ANIMATIONTYPE_QUATERNION=2;ht.ANIMATIONTYPE_MATRIX=3;ht.ANIMATIONTYPE_COLOR3=4;ht.ANIMATIONTYPE_COLOR4=7;ht.ANIMATIONTYPE_VECTOR2=5;ht.ANIMATIONTYPE_SIZE=6;ht.ANIMATIONLOOPMODE_RELATIVE=0;ht.ANIMATIONLOOPMODE_CYCLE=1;ht.ANIMATIONLOOPMODE_CONSTANT=2;ht.ANIMATIONLOOPMODE_YOYO=4;ht.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT=5;ht.CreateFromSnippetAsync=ht.ParseFromSnippetAsync;Ft("BABYLON.Animation",ht);_i._AnimationRangeFactory=(n,e,t)=>new bf(n,e,t)});var Bm,SG=C(()=>{Iy();If();Bm=class n{constructor(){this.transitionDuration=450,this.lowerRadiusTransitionRange=2,this.upperRadiusTransitionRange=-2,this._autoTransitionRange=!1,this._attachedCamera=null,this._radiusIsAnimating=!1,this._radiusBounceTransition=null,this._animatables=new Array}get name(){return"Bouncing"}get autoTransitionRange(){return this._autoTransitionRange}set autoTransitionRange(e){if(this._autoTransitionRange===e)return;this._autoTransitionRange=e;let t=this._attachedCamera;t&&(e?this._onMeshTargetChangedObserver=t.onMeshTargetChangedObservable.add(i=>{if(i&&(i.computeWorldMatrix(!0),i.getBoundingInfo)){let r=i.getBoundingInfo().diagonalLength;this.lowerRadiusTransitionRange=r*.05,this.upperRadiusTransitionRange=r*.05}}):this._onMeshTargetChangedObserver&&t.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver))}get attachedNode(){return this._attachedCamera}init(){}attach(e){this._attachedCamera=e,this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{this._attachedCamera&&(this._isRadiusAtLimit(this._attachedCamera.lowerRadiusLimit)&&this._applyBoundRadiusAnimation(this.lowerRadiusTransitionRange),this._isRadiusAtLimit(this._attachedCamera.upperRadiusLimit)&&this._applyBoundRadiusAnimation(this.upperRadiusTransitionRange))})}detach(){this._attachedCamera&&(this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null)}_isRadiusAtLimit(e){return this._attachedCamera?this._attachedCamera.radius===e&&!this._radiusIsAnimating:!1}_applyBoundRadiusAnimation(e){if(!this._attachedCamera)return;this._radiusBounceTransition||(n.EasingFunction.setEasingMode(n.EasingMode),this._radiusBounceTransition=ht.CreateAnimation("radius",ht.ANIMATIONTYPE_FLOAT,60,n.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;let t=ht.TransitionTo("radius",this._attachedCamera.radius+e,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusBounceTransition,this.transitionDuration,()=>this._clearAnimationLocks());t&&this._animatables.push(t)}_clearAnimationLocks(){this._radiusIsAnimating=!1,this._attachedCamera&&(this._attachedCamera.wheelPrecision=this._cachedWheelPrecision)}stopAllAnimations(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0].onAnimationEnd=null,this._animatables[0].stop(),this._animatables.shift()}};Bm.EasingFunction=new FA(.3);Bm.EasingMode=po.EASINGMODE_EASEOUT});var Mf,TG=C(()=>{Iy();di();oo();wl();Ge();If();Mf=class n{constructor(){this.onTargetFramingAnimationEndObservable=new ie,this._mode=n.FitFrustumSidesMode,this._radiusScale=1,this._positionScale=.5,this._defaultElevation=.3,this._elevationReturnTime=1500,this._elevationReturnWaitTime=1e3,this._zoomStopsAnimation=!1,this._framingTime=1500,this.autoCorrectCameraLimitsAndSensibility=!0,this._attachedCamera=null,this._isPointerDown=!1,this._lastInteractionTime=-1/0,this._animatables=new Array,this._betaIsAnimating=!1}get name(){return"Framing"}set mode(e){this._mode=e}get mode(){return this._mode}set radiusScale(e){this._radiusScale=e}get radiusScale(){return this._radiusScale}set positionScale(e){this._positionScale=e}get positionScale(){return this._positionScale}set defaultElevation(e){this._defaultElevation=e}get defaultElevation(){return this._defaultElevation}set elevationReturnTime(e){this._elevationReturnTime=e}get elevationReturnTime(){return this._elevationReturnTime}set elevationReturnWaitTime(e){this._elevationReturnWaitTime=e}get elevationReturnWaitTime(){return this._elevationReturnWaitTime}set zoomStopsAnimation(e){this._zoomStopsAnimation=e}get zoomStopsAnimation(){return this._zoomStopsAnimation}set framingTime(e){this._framingTime=e}get framingTime(){return this._framingTime}get attachedNode(){return this._attachedCamera}init(){}attach(e){this._attachedCamera=e;let t=this._attachedCamera.getScene();n.EasingFunction.setEasingMode(n.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add(i=>{if(i.type===st.POINTERDOWN){this._isPointerDown=!0;return}i.type===st.POINTERUP&&(this._isPointerDown=!1)}),this._onMeshTargetChangedObserver=e.onMeshTargetChangedObservable.add(i=>{i&&i.getBoundingInfo&&this.zoomOnMesh(i,void 0,()=>{this.onTargetFramingAnimationEndObservable.notifyObservers()})}),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{this._applyUserInteraction(),this._maintainCameraAboveGround()})}detach(){if(!this._attachedCamera)return;let e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null}zoomOnMesh(e,t=!1,i=null){e.computeWorldMatrix(!0);let r=e.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(r.minimumWorld,r.maximumWorld,t,i)}zoomOnMeshHierarchy(e,t=!1,i=null){e.computeWorldMatrix(!0);let r=e.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(r.min,r.max,t,i)}zoomOnMeshesHierarchy(e,t=!1,i=null){let r=new b(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),s=new b(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let a=0;a{this.stopAllAnimations(),r&&r(),this._attachedCamera&&this._attachedCamera.useInputToRestoreState&&this._attachedCamera.storeState()}),f&&this._animatables.push(f),!0}_calculateLowerRadiusFromModelBoundingSphere(e,t){let i=this._attachedCamera;if(!i)return 0;let r=i._calculateLowerRadiusFromModelBoundingSphere(e,t,this._radiusScale);return i.lowerRadiusLimit&&this._mode===n.IgnoreBoundsSizeMode&&(r=ri.upperRadiusLimit?i.upperRadiusLimit:r),r}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;let e=pr.Now-this._lastInteractionTime,t=Math.PI*.5-this._defaultElevation,i=Math.PI*.5;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>i&&e>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=ht.CreateAnimation("beta",ht.ANIMATIONTYPE_FLOAT,60,n.EasingFunction));let r=ht.TransitionTo("beta",t,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,()=>{this._clearAnimationLocks(),this.stopAllAnimations()});r&&this._animatables.push(r)}}_clearAnimationLocks(){this._betaIsAnimating=!1}_applyUserInteraction(){this.isUserIsMoving&&(this._lastInteractionTime=pr.Now,this.stopAllAnimations(),this._clearAnimationLocks())}stopAllAnimations(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0]&&(this._animatables[0].onAnimationEnd=null,this._animatables[0].stop()),this._animatables.shift()}get isUserIsMoving(){return this._attachedCamera?this._attachedCamera.inertialAlphaOffset!==0||this._attachedCamera.inertialBetaOffset!==0||this._attachedCamera.inertialRadiusOffset!==0||this._attachedCamera.inertialPanningX!==0||this._attachedCamera.inertialPanningY!==0||this._isPointerDown:!1}};Mf.EasingFunction=new BA;Mf.EasingMode=po.EASINGMODE_EASEINOUT;Mf.IgnoreBoundsSizeMode=0;Mf.FitFrustumSidesMode=1});var UA,Ny,bs,wy=C(()=>{Gt();Vt();sl();Ge();Dn();zu();js();_i.AddNodeConstructor("TargetCamera",(n,e)=>()=>new bs(n,b.Zero(),e));UA=K.Zero(),Ny=Xe.Identity(),bs=class n extends mt{constructor(e,t,i,r=!0){super(e,t,i,r),this.cameraDirection=new b(0,0,0),this.cameraRotation=new we(0,0),this.updateUpVectorFromRotation=!1,this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this._panningEpsilon=Nt,this._rotationEpsilon=Nt,this.lockedTarget=null,this._currentTarget=b.Zero(),this._initialFocalDistance=1,this._viewMatrix=K.Zero(),this._cameraTransformMatrix=K.Zero(),this._cameraRotationMatrix=K.Zero(),this._transformedReferencePoint=b.Zero(),this._deferredPositionUpdate=new b,this._deferredRotationQuaternionUpdate=new Xe,this._deferredRotationUpdate=new b,this._deferredUpdated=!1,this._deferOnly=!1,this._cachedRotationZ=0,this._cachedQuaternionRotationZ=0,this._referencePoint=b.Forward(this.getScene().useRightHandedSystem),this.rotation=new b(0,this.getScene().useRightHandedSystem?Math.PI:0,0)}getFrontPosition(e){this.getWorldMatrix();let t=$.Vector3[0],i=$.Vector3[1];return i.set(0,0,this._scene.useRightHandedSystem?-1:1),this.getDirectionToRef(i,t),t.scaleInPlace(e),this.globalPosition.add(t)}_getLockedTargetPosition(){if(!this.lockedTarget)return null;if(this.lockedTarget.absolutePosition){let e=this.lockedTarget;e.computeWorldMatrix().getTranslationToRef(e.absolutePosition)}return this.lockedTarget.absolutePosition||this.lockedTarget}storeState(){return this._storedPosition=this.position.clone(),this._storedRotation=this.rotation.clone(),this.rotationQuaternion&&(this._storedRotationQuaternion=this.rotationQuaternion.clone()),super.storeState()}_restoreStateValues(){return super._restoreStateValues()?(this.position=this._storedPosition.clone(),this.rotation=this._storedRotation.clone(),this.rotationQuaternion&&this._storedRotationQuaternion&&(this.rotationQuaternion=this._storedRotationQuaternion.clone()),this.cameraDirection.copyFromFloats(0,0,0),this.cameraRotation.copyFromFloats(0,0),!0):!1}_initCache(){super._initCache(),this._cache.lockedTarget=new b(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new b(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new Xe(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)}_updateCache(e){e||super._updateCache();let t=this._getLockedTargetPosition();t?this._cache.lockedTarget?this._cache.lockedTarget.copyFrom(t):this._cache.lockedTarget=t.clone():this._cache.lockedTarget=null,this._cache.rotation.copyFrom(this.rotation),this.rotationQuaternion&&this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion)}_isSynchronizedViewMatrix(){if(!super._isSynchronizedViewMatrix())return!1;let e=this._getLockedTargetPosition();return(this._cache.lockedTarget?this._cache.lockedTarget.equals(e):!e)&&(this.rotationQuaternion?this.rotationQuaternion.equals(this._cache.rotationQuaternion):this._cache.rotation.equals(this.rotation))}_computeLocalCameraSpeed(){let e=this.getEngine();return this.speed*Math.sqrt(e.getDeltaTime()/(e.getFps()*100))}setTarget(e){this.upVector.normalize(),this._initialFocalDistance=e.subtract(this.position).length(),this.position.z===e.z&&(this.position.z+=Nt),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),this.getScene().useRightHandedSystem?K.LookAtRHToRef(this.position,e,b.UpReadOnly,UA):K.LookAtLHToRef(this.position,e,b.UpReadOnly,UA),UA.invert();let t=this.rotationQuaternion||Ny;Xe.FromRotationMatrixToRef(UA,t),t.toEulerAnglesToRef(this.rotation),this.rotation.z=0}get target(){return this.getTarget()}set target(e){this.setTarget(e)}getTarget(){return this._currentTarget}_decideIfNeedsToMove(){return Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){if(this.parent){this.parent.getWorldMatrix().invertToRef($.Matrix[0]),b.TransformNormalToRef(this.cameraDirection,$.Matrix[0],$.Vector3[0]),this._deferredPositionUpdate.addInPlace($.Vector3[0]),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate);return}this._deferredPositionUpdate.addInPlace(this.cameraDirection),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate)}_checkInputs(){let e=this.invertRotation?-this.inverseRotationSpeed:1,t=this._decideIfNeedsToMove(),i=this.cameraRotation.x||this.cameraRotation.y;this._deferredUpdated=!1,this._deferredRotationUpdate.copyFrom(this.rotation),this._deferredPositionUpdate.copyFrom(this.position),this.rotationQuaternion&&this._deferredRotationQuaternionUpdate.copyFrom(this.rotationQuaternion),t&&this._updatePosition(),i&&(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this._deferredRotationUpdate),this._deferredRotationUpdate.x+=this.cameraRotation.x*e,this._deferredRotationUpdate.y+=this.cameraRotation.y*e,this.noRotationConstraint||(this._deferredRotationUpdate.x>1.570796&&(this._deferredRotationUpdate.x=1.570796),this._deferredRotationUpdate.x<-1.570796&&(this._deferredRotationUpdate.x=-1.570796)),this._deferOnly?this._deferredUpdated=!0:this.rotation.copyFrom(this._deferredRotationUpdate),this.rotationQuaternion&&this._deferredRotationUpdate.lengthSquared()&&(Xe.RotationYawPitchRollToRef(this._deferredRotationUpdate.y,this._deferredRotationUpdate.x,this._deferredRotationUpdate.z,this._deferredRotationQuaternionUpdate),this._deferOnly?this._deferredUpdated=!0:this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate)));let r=this.speed*this._panningEpsilon,s=this.speed*this._rotationEpsilon;t&&(Math.abs(this.cameraDirection.x){Pt();Tr();sl();Gn={},Um=class{constructor(e){this.attachedToElement=!1,this.attached={},this.camera=e,this.checkInputs=()=>{}}add(e){let t=e.getSimpleName();if(this.attached[t]){te.Warn("camera input of type "+t+" already exists on camera");return}this.attached[t]=e,e.camera=this.camera,e.checkInputs&&(this.checkInputs=this._addCheckInputs(e.checkInputs.bind(e))),this.attachedToElement&&e.attachControl(this.noPreventDefault)}remove(e){for(let t in this.attached){let i=this.attached[t];if(i===e){i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck();return}}}removeByType(e){for(let t in this.attached){let i=this.attached[t];i.getClassName()===e&&(i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck())}}_addCheckInputs(e){let t=this.checkInputs;return()=>{t(),e()}}attachInput(e){this.attachedToElement&&e.attachControl(this.noPreventDefault)}attachElement(e=!1){if(!this.attachedToElement){e=mt.ForceAttachControlToAlwaysPreventDefault?!1:e,this.attachedToElement=!0,this.noPreventDefault=e;for(let t in this.attached)this.attached[t].attachControl(e)}}detachElement(e=!1){for(let t in this.attached)this.attached[t].detachControl(),e&&(this.attached[t].camera=null);this.attachedToElement=!1}rebuildInputCheck(){this.checkInputs=()=>{};for(let e in this.attached){let t=this.attached[e];t.checkInputs&&(this.checkInputs=this._addCheckInputs(t.checkInputs.bind(t)))}}clear(){this.attachedToElement&&this.detachElement(!0),this.attached={},this.attachedToElement=!1,this.checkInputs=()=>{}}serialize(e){let t={};for(let i in this.attached){let r=this.attached[i],s=it.Serialize(r);t[r.getClassName()]=s}e.inputsmgr=t}parse(e){let t=e.inputsmgr;if(t){this.clear();for(let i in t){let r=Gn[i];if(r){let s=t[i],a=it.Parse(()=>new r,s,null);this.add(a)}}}else for(let i in this.attached){let r=Gn[this.attached[i].getClassName()];if(r){let s=it.Parse(()=>new r,e,null);this.remove(this.attached[i]),this.add(s)}}}}});var ug,AG=C(()=>{Gt();Vt();Ii();oo();ug=class{constructor(){this._currentMousePointerIdDown=-1,this.buttons=[0,1,2]}attachControl(e){e=_e.BackCompatCameraNoPreventDefault(arguments);let t=this.camera.getEngine(),i=t.getInputElement(),r=0,s=null;this._pointA=null,this._pointB=null,this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._pointerInput=o=>{var h,d;let l=o.event,c=l.pointerType==="touch";if(o.type!==st.POINTERMOVE&&this.buttons.indexOf(l.button)===-1)return;let f=l.target;if(this._altKey=l.altKey,this._ctrlKey=l.ctrlKey,this._metaKey=l.metaKey,this._shiftKey=l.shiftKey,this._buttonsPressed=l.buttons,t.isPointerLock){let u=l.movementX,m=l.movementY;this.onTouch(null,u,m),this._pointA=null,this._pointB=null}else{if(o.type!==st.POINTERDOWN&&o.type!==st.POINTERDOUBLETAP&&c&&((h=this._pointA)==null?void 0:h.pointerId)!==l.pointerId&&((d=this._pointB)==null?void 0:d.pointerId)!==l.pointerId)return;if(o.type===st.POINTERDOWN&&(this._currentMousePointerIdDown===-1||c)){try{f==null||f.setPointerCapture(l.pointerId)}catch(u){}if(this._pointA===null)this._pointA={x:l.clientX,y:l.clientY,pointerId:l.pointerId,type:l.pointerType,button:l.button};else if(this._pointB===null)this._pointB={x:l.clientX,y:l.clientY,pointerId:l.pointerId,type:l.pointerType,button:l.button};else return;this._currentMousePointerIdDown===-1&&!c&&(this._currentMousePointerIdDown=l.pointerId),this.onButtonDown(l),e||(l.preventDefault(),i&&i.focus())}else if(o.type===st.POINTERDOUBLETAP)this.onDoubleTap(l.pointerType);else if(o.type===st.POINTERUP&&(this._currentMousePointerIdDown===l.pointerId||c)){try{f==null||f.releasePointerCapture(l.pointerId)}catch(u){}c||(this._pointB=null),t._badOS?this._pointA=this._pointB=null:this._pointB&&this._pointA&&this._pointA.pointerId==l.pointerId?(this._pointA=this._pointB,this._pointB=null):this._pointA&&this._pointB&&this._pointB.pointerId==l.pointerId?this._pointB=null:this._pointA=this._pointB=null,(r!==0||s)&&(this.onMultiTouch(this._pointA,this._pointB,r,0,s,null),r=0,s=null),this._currentMousePointerIdDown=-1,this.onButtonUp(l),e||l.preventDefault()}else if(o.type===st.POINTERMOVE){if(e||l.preventDefault(),this._pointA&&this._pointB===null){let u=l.clientX-this._pointA.x,m=l.clientY-this._pointA.y;this._pointA.x=l.clientX,this._pointA.y=l.clientY,this.onTouch(this._pointA,u,m)}else if(this._pointA&&this._pointB){let u=this._pointA.pointerId===l.pointerId?this._pointA:this._pointB;u.x=l.clientX,u.y=l.clientY;let m=this._pointA.x-this._pointB.x,p=this._pointA.y-this._pointB.y,_=m*m+p*p,g={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:l.pointerId,type:o.type};this.onMultiTouch(this._pointA,this._pointB,r,_,s,g),s=g,r=_}}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,st.POINTERDOWN|st.POINTERUP|st.POINTERMOVE|st.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,r=0,s=null,this.onLostFocus()},this._contextMenuBind=o=>this.onContextMenu(o),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);let a=this.camera.getScene().getEngine().getHostWindow();a&&_e.RegisterTopRootEvents(a,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){let e=this.camera.getScene().getEngine().getHostWindow();e&&_e.UnregisterTopRootEvents(e,[{name:"blur",handler:this._onLostFocus}])}if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._contextMenuBind){let e=this.camera.getScene().getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this._onLostFocus=null}this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._currentMousePointerIdDown=-1}getClassName(){return"BaseCameraPointersInput"}getSimpleName(){return"pointers"}onDoubleTap(e){}onTouch(e,t,i){}onMultiTouch(e,t,i,r,s,a){}onContextMenu(e){e.preventDefault()}onButtonDown(e){}onButtonUp(e){}onLostFocus(){}};P([w()],ug.prototype,"buttons",void 0)});var $h,xG=C(()=>{Gt();Vt();AG();$h=class extends ug{constructor(){super(...arguments),this.pinchZoom=!0,this.multiTouchPanning=!0,this.multiTouchPanAndZoom=!0,this._isPinching=!1,this._twoFingerActivityCount=0,this._shouldStartPinchZoom=!1}_computePinchZoom(e,t){}_computeMultiTouchPanning(e,t){}onMultiTouch(e,t,i,r,s,a){i===0&&s===null||r===0&&a===null||(this.multiTouchPanAndZoom?(this._computePinchZoom(i,r),this._computeMultiTouchPanning(s,a)):this.multiTouchPanning&&this.pinchZoom?(this._twoFingerActivityCount++,this._isPinching||this._shouldStartPinchZoom?(this._computePinchZoom(i,r),this._isPinching=!0):this._computeMultiTouchPanning(s,a)):this.multiTouchPanning?this._computeMultiTouchPanning(s,a):this.pinchZoom&&this._computePinchZoom(i,r))}onButtonUp(e){this._twoFingerActivityCount=0,this._isPinching=!1}onLostFocus(){this._twoFingerActivityCount=0,this._isPinching=!1}};P([w()],$h.prototype,"pinchZoom",void 0);P([w()],$h.prototype,"multiTouchPanning",void 0);P([w()],$h.prototype,"multiTouchPanAndZoom",void 0)});var qs,RG=C(()=>{Gt();Vt();fl();xG();qs=class n extends $h{constructor(){super(...arguments),this.buttons=[0,1,2],this.angularSensibilityX=1e3,this.angularSensibilityY=1e3,this.pinchPrecision=12,this.pinchDeltaPercentage=0,this.useNaturalPinchZoom=!1,this.panningSensibility=1e3,this.pinchInwards=!0,this._isPanClick=!1}getClassName(){return"ArcRotateCameraPointersInput"}_computeMultiTouchPanning(e,t){if(this.panningSensibility!==0&&e&&t){let i=t.x-e.x,r=t.y-e.y;this.camera.inertialPanningX+=-i/this.panningSensibility,this.camera.inertialPanningY+=r/this.panningSensibility}}_computePinchZoom(e,t){let i=this.camera.radius||n.MinimumRadiusForPinch;this.useNaturalPinchZoom?this.camera.radius=i*Math.sqrt(e)/Math.sqrt(t):this.pinchDeltaPercentage?this.camera.inertialRadiusOffset+=(t-e)*.001*i*this.pinchDeltaPercentage:this.camera.inertialRadiusOffset+=(t-e)/(this.pinchPrecision*(this.pinchInwards?1:-1)*(this.angularSensibilityX+this.angularSensibilityY)/2)}onTouch(e,t,i){this.panningSensibility!==0&&(this._ctrlKey&&this.camera._useCtrlForPanning||this._isPanClick)?(this.camera.inertialPanningX+=-t/this.panningSensibility,this.camera.inertialPanningY+=i/this.panningSensibility):(this.camera.inertialAlphaOffset-=t/this.angularSensibilityX,this.camera.inertialBetaOffset-=i/this.angularSensibilityY)}onDoubleTap(){this.camera.useInputToRestoreState&&this.camera.restoreState()}onMultiTouch(e,t,i,r,s,a){this._shouldStartPinchZoom=this._twoFingerActivityCount<20&&Math.abs(Math.sqrt(r)-Math.sqrt(i))>this.camera.pinchToPanMaxDistance,super.onMultiTouch(e,t,i,r,s,a)}onButtonDown(e){this._isPanClick=e.button===this.camera._panningMouseButton,super.onButtonDown(e)}onButtonUp(e){super.onButtonUp(e)}onLostFocus(){this._isPanClick=!1,super.onLostFocus()}};qs.MinimumRadiusForPinch=.001;P([w()],qs.prototype,"buttons",void 0);P([w()],qs.prototype,"angularSensibilityX",void 0);P([w()],qs.prototype,"angularSensibilityY",void 0);P([w()],qs.prototype,"pinchPrecision",void 0);P([w()],qs.prototype,"pinchDeltaPercentage",void 0);P([w()],qs.prototype,"useNaturalPinchZoom",void 0);P([w()],qs.prototype,"panningSensibility",void 0);Gn.ArcRotateCameraPointersInput=qs});var Is,bG=C(()=>{Gt();Vt();fl();lA();Ii();Is=class{constructor(){this.keysUp=[38],this.keysDown=[40],this.keysLeft=[37],this.keysRight=[39],this.keysReset=[220],this.panningSensibility=50,this.zoomingSensibility=25,this.useAltToZoom=!0,this.angularSpeed=.01,this._keys=new Array}attachControl(e){e=_e.BackCompatCameraNoPreventDefault(arguments),!this._onCanvasBlurObserver&&(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add(()=>{this._keys.length=0}),this._onKeyboardObserver=this._scene.onKeyboardObservable.add(t=>{let i=t.event;if(!i.metaKey){if(t.type===lo.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,(this.keysUp.indexOf(i.keyCode)!==-1||this.keysDown.indexOf(i.keyCode)!==-1||this.keysLeft.indexOf(i.keyCode)!==-1||this.keysRight.indexOf(i.keyCode)!==-1||this.keysReset.indexOf(i.keyCode)!==-1)&&(this._keys.indexOf(i.keyCode)===-1&&this._keys.push(i.keyCode),i.preventDefault&&(e||i.preventDefault()));else if(this.keysUp.indexOf(i.keyCode)!==-1||this.keysDown.indexOf(i.keyCode)!==-1||this.keysLeft.indexOf(i.keyCode)!==-1||this.keysRight.indexOf(i.keyCode)!==-1||this.keysReset.indexOf(i.keyCode)!==-1){let r=this._keys.indexOf(i.keyCode);r>=0&&this._keys.splice(r,1),i.preventDefault&&(e||i.preventDefault())}}}))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){if(this._onKeyboardObserver){let e=this.camera;for(let t=0;t{Gt();Vt();fl();oo();qu();Ge();Dn();cA();Ln();Ii();yse=40,Cf=class{constructor(){this.wheelPrecision=3,this.zoomToMouseLocation=!1,this.wheelDeltaPercentage=0,this.customComputeDeltaFromMouseWheel=null,this._viewOffset=new b(0,0,0),this._globalOffset=new b(0,0,0),this._inertialPanning=b.Zero()}_computeDeltaFromMouseWheelLegacyEvent(e,t){let i,r=e*.01*this.wheelDeltaPercentage*t;return e>0?i=r/(1+this.wheelDeltaPercentage):i=r*(1+this.wheelDeltaPercentage),i}attachControl(e){e=_e.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==st.POINTERWHEEL)return;let i=t.event,r,s=i.deltaMode===co.DOM_DELTA_LINE?yse:1,a=-(i.deltaY*s);if(this.customComputeDeltaFromMouseWheel)r=this.customComputeDeltaFromMouseWheel(a,this,i);else if(this.wheelDeltaPercentage){if(r=this._computeDeltaFromMouseWheelLegacyEvent(a,this.camera.radius),r>0){let o=this.camera.radius,l=this.camera.inertialRadiusOffset+r;for(let c=0;c<20&&!(o<=l||Math.abs(l*this.camera.inertia)<.001);c++)o-=l,l*=this.camera.inertia;o=wt(o,0,Number.MAX_VALUE),r=this._computeDeltaFromMouseWheelLegacyEvent(a,o)}}else r=a/(this.wheelPrecision*40);r&&(this.zoomToMouseLocation?(this._hitPlane||this._updateHitPlane(),this._zoomToMouse(r)):this.camera.inertialRadiusOffset+=r),i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,st.POINTERWHEEL),this.zoomToMouseLocation&&this._inertialPanning.setAll(0)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}checkInputs(){if(!this.zoomToMouseLocation)return;let e=this.camera;0+e.inertialAlphaOffset+e.inertialBetaOffset+e.inertialRadiusOffset&&(this._updateHitPlane(),e.target.addInPlace(this._inertialPanning),this._inertialPanning.scaleInPlace(e.inertia),this._zeroIfClose(this._inertialPanning))}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}_updateHitPlane(){let e=this.camera,t=e.target.subtract(e.position);this._hitPlane=to.FromPositionAndNormal(e.target,t)}_getPosition(){var s;let e=this.camera,t=e.getScene(),i=t.createPickingRay(t.pointerX,t.pointerY,K.Identity(),e,!1);(e.targetScreenOffset.x!==0||e.targetScreenOffset.y!==0)&&(this._viewOffset.set(e.targetScreenOffset.x,e.targetScreenOffset.y,0),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),this._globalOffset=b.TransformNormal(this._viewOffset,e._cameraTransformMatrix),i.origin.addInPlace(this._globalOffset));let r=0;return this._hitPlane&&(r=(s=i.intersectsPlane(this._hitPlane))!=null?s:0),i.origin.addInPlace(i.direction.scaleInPlace(r))}_zoomToMouse(e){var l,c;let t=this.camera,i=1-t.inertia;if(t.lowerRadiusLimit){let f=(l=t.lowerRadiusLimit)!=null?l:0;t.radius-(t.inertialRadiusOffset+e)/if&&(e=(t.radius-f)*i-t.inertialRadiusOffset)}let s=e/i/t.radius,a=this._getPosition(),o=$.Vector3[6];a.subtractToRef(t.target,o),o.scaleInPlace(s),o.scaleInPlace(i),this._inertialPanning.addInPlace(o),t.inertialRadiusOffset+=e}_zeroIfClose(e){Math.abs(e.x){RG();bG();IG();fl();VA=class extends Um{constructor(e){super(e)}addMouseWheel(){return this.add(new Cf),this}addPointers(){return this.add(new qs),this}addKeyboard(){return this.add(new Is),this}}});function Pse(n){let e=Math.PI/2;return n.x===0&&n.z===0||(e=Math.acos(n.x/Math.sqrt(Math.pow(n.x,2)+Math.pow(n.z,2)))),n.z<0&&(e=2*Math.PI-e),e}function Dse(n,e){return Math.acos(n/e)}function kn(n,e){return isNaN(n)?e:n}var gi,GA=C(()=>{Gt();Vt();di();Ge();Ln();js();Mi();by();SG();TG();sl();wy();MG();Dn();Ii();Hi();_i.AddNodeConstructor("ArcRotateCamera",(n,e)=>()=>new gi(n,0,0,1,b.Zero(),e));gi=class n extends bs{get target(){return this._target}set target(e){this.setTarget(e)}get targetHost(){return this._targetHost}set targetHost(e){e&&this.setTarget(e)}getTarget(){return this.target}get position(){return this._position}set position(e){this.setPosition(e)}set upVector(e){this._upToYMatrix||(this._yToUpMatrix=new K,this._upToYMatrix=new K,this._upVector=b.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){K.RotationAlignToRef(b.UpReadOnly,this._upVector,this._yToUpMatrix),K.RotationAlignToRef(this._upVector,b.UpReadOnly,this._upToYMatrix)}get angularSensibilityX(){let e=this.inputs.attached.pointers;return e?e.angularSensibilityX:0}set angularSensibilityX(e){let t=this.inputs.attached.pointers;t&&(t.angularSensibilityX=e)}get angularSensibilityY(){let e=this.inputs.attached.pointers;return e?e.angularSensibilityY:0}set angularSensibilityY(e){let t=this.inputs.attached.pointers;t&&(t.angularSensibilityY=e)}get pinchPrecision(){let e=this.inputs.attached.pointers;return e?e.pinchPrecision:0}set pinchPrecision(e){let t=this.inputs.attached.pointers;t&&(t.pinchPrecision=e)}get pinchDeltaPercentage(){let e=this.inputs.attached.pointers;return e?e.pinchDeltaPercentage:0}set pinchDeltaPercentage(e){let t=this.inputs.attached.pointers;t&&(t.pinchDeltaPercentage=e)}get useNaturalPinchZoom(){let e=this.inputs.attached.pointers;return e?e.useNaturalPinchZoom:!1}set useNaturalPinchZoom(e){let t=this.inputs.attached.pointers;t&&(t.useNaturalPinchZoom=e)}get panningSensibility(){let e=this.inputs.attached.pointers;return e?e.panningSensibility:0}set panningSensibility(e){let t=this.inputs.attached.pointers;t&&(t.panningSensibility=e)}get keysUp(){let e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){let t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){let e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){let t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){let e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){let t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){let e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){let t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}get wheelPrecision(){let e=this.inputs.attached.mousewheel;return e?e.wheelPrecision:0}set wheelPrecision(e){let t=this.inputs.attached.mousewheel;t&&(t.wheelPrecision=e)}get zoomToMouseLocation(){let e=this.inputs.attached.mousewheel;return e?e.zoomToMouseLocation:!1}set zoomToMouseLocation(e){let t=this.inputs.attached.mousewheel;t&&(t.zoomToMouseLocation=e)}get wheelDeltaPercentage(){let e=this.inputs.attached.mousewheel;return e?e.wheelDeltaPercentage:0}set wheelDeltaPercentage(e){let t=this.inputs.attached.mousewheel;t&&(t.wheelDeltaPercentage=e)}get isInterpolating(){return this._isInterpolating}get bouncingBehavior(){return this._bouncingBehavior}get useBouncingBehavior(){return this._bouncingBehavior!=null}set useBouncingBehavior(e){e!==this.useBouncingBehavior&&(e?(this._bouncingBehavior=new Bm,this.addBehavior(this._bouncingBehavior)):this._bouncingBehavior&&(this.removeBehavior(this._bouncingBehavior),this._bouncingBehavior=null))}get framingBehavior(){return this._framingBehavior}get useFramingBehavior(){return this._framingBehavior!=null}set useFramingBehavior(e){e!==this.useFramingBehavior&&(e?(this._framingBehavior=new Mf,this.addBehavior(this._framingBehavior)):this._framingBehavior&&(this.removeBehavior(this._framingBehavior),this._framingBehavior=null))}get autoRotationBehavior(){return this._autoRotationBehavior}get useAutoRotationBehavior(){return this._autoRotationBehavior!=null}set useAutoRotationBehavior(e){e!==this.useAutoRotationBehavior&&(e?(this._autoRotationBehavior=new Fm,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,i,r,s,a,o=!0){super(e,b.Zero(),a,o),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.lowerAlphaLimit=null,this.upperAlphaLimit=null,this.lowerBetaLimit=.01,this.upperBetaLimit=Math.PI-.01,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.lowerTargetYLimit=-1/0,this.inertialPanningX=0,this.inertialPanningY=0,this.pinchToPanMaxDistance=20,this.panningDistanceLimit=null,this.panningOriginTarget=b.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=we.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this.restoreStateInterpolationFactor=0,this._currentInterpolationFactor=0,this._viewMatrix=new K,this.panningAxis=new b(1,1,0),this._transformedDirection=new b,this.mapPanning=!1,this._isInterpolating=!1,this.onMeshTargetChangedObservable=new ie,this.checkCollisions=!1,this.collisionRadius=new b(.5,.5,.5),this._previousPosition=b.Zero(),this._collisionVelocity=b.Zero(),this._newPosition=b.Zero(),this._computationVector=b.Zero(),this._goalAlpha=NaN,this._goalBeta=NaN,this._goalRadius=NaN,this._goalTarget=new b(NaN,NaN,NaN),this._goalTargetScreenOffset=new we(NaN,NaN),this._onCollisionPositionChange=(l,c,f=null)=>{f?(this.setPosition(c),this.onCollide&&this.onCollide(f)):this._previousPosition.copyFrom(this._position);let h=Math.cos(this.alpha),d=Math.sin(this.alpha),u=Math.cos(this.beta),m=Math.sin(this.beta);m===0&&(m=1e-4);let p=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*h*m,this.radius*u,this.radius*d*m),p.addToRef(this._computationVector,this._newPosition),this._position.copyFrom(this._newPosition);let _=this.upVector;this.allowUpsideDown&&this.beta<0&&(_=_.clone(),_=_.negate()),this._computeViewMatrix(this._position,p,_),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=b.Zero(),s&&this.setTarget(s),this.alpha=t,this.beta=i,this.radius=r,this.getViewMatrix(),this.inputs=new VA(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_initCache(){super._initCache(),this._cache._target=new b(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.alpha=void 0,this._cache.beta=void 0,this._cache.radius=void 0,this._cache.targetScreenOffset=we.Zero()}_updateCache(e){e||super._updateCache(),this._cache._target.copyFrom(this._getTargetPosition()),this._cache.alpha=this.alpha,this._cache.beta=this.beta,this._cache.radius=this.radius,this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset)}_getTargetPosition(){if(this._targetHost&&this._targetHost.getAbsolutePosition){let t=this._targetHost.getAbsolutePosition();this._targetBoundingCenter?t.addToRef(this._targetBoundingCenter,this._target):this._target.copyFrom(t)}let e=this._getLockedTargetPosition();return e||this._target}storeState(){return this._storedAlpha=this.alpha,this._storedBeta=this.beta,this._storedRadius=this.radius,this._storedTarget=this._getTargetPosition().clone(),this._storedTargetScreenOffset=this.targetScreenOffset.clone(),super.storeState()}_restoreStateValues(){return this.hasStateStored()&&this.restoreStateInterpolationFactor>Nt&&this.restoreStateInterpolationFactor<1?(this.interpolateTo(this._storedAlpha,this._storedBeta,this._storedRadius,this._storedTarget,this._storedTargetScreenOffset,this.restoreStateInterpolationFactor),!0):super._restoreStateValues()?(this.setTarget(this._storedTarget.clone()),this.alpha=this._storedAlpha,this.beta=this._storedBeta,this.radius=this._storedRadius,this.targetScreenOffset=this._storedTargetScreenOffset.clone(),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,!0):!1}stopInterpolation(){this._goalAlpha=NaN,this._goalBeta=NaN,this._goalRadius=NaN,this._goalTarget.set(NaN,NaN,NaN),this._goalTargetScreenOffset.set(NaN,NaN)}interpolateTo(e=this.alpha,t=this.beta,i=this.radius,r=this.target,s=this.targetScreenOffset,a){var o,l,c,f,h,d,u;this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,a!=null?this._currentInterpolationFactor=a:this.restoreStateInterpolationFactor!==0?this._currentInterpolationFactor=this.restoreStateInterpolationFactor:this._currentInterpolationFactor=.1,this._goalAlpha=kn(e,this._goalAlpha),this._goalBeta=kn(t,this._goalBeta),this._goalRadius=kn(i,this._goalRadius),this._goalTarget.set(kn(r.x,this._goalTarget.x),kn(r.y,this._goalTarget.y),kn(r.z,this._goalTarget.z)),this._goalTargetScreenOffset.set(kn(s.x,this._goalTargetScreenOffset.x),kn(s.y,this._goalTargetScreenOffset.y)),this._goalAlpha=wt(this._goalAlpha,(o=this.lowerAlphaLimit)!=null?o:-1/0,(l=this.upperAlphaLimit)!=null?l:1/0),this._goalBeta=wt(this._goalBeta,(c=this.lowerBetaLimit)!=null?c:-1/0,(f=this.upperBetaLimit)!=null?f:1/0),this._goalRadius=wt(this._goalRadius,(h=this.lowerRadiusLimit)!=null?h:-1/0,(d=this.upperRadiusLimit)!=null?d:1/0),this._goalTarget.y=wt(this._goalTarget.y,(u=this.lowerTargetYLimit)!=null?u:-1/0,1/0),this._isInterpolating=!0}_isSynchronizedViewMatrix(){return super._isSynchronizedViewMatrix()?this._cache._target.equals(this._getTargetPosition())&&this._cache.alpha===this.alpha&&this._cache.beta===this.beta&&this._cache.radius===this.radius&&this._cache.targetScreenOffset.equals(this.targetScreenOffset):!1}attachControl(e,t,i=!0,r=2){let s=arguments;t=_e.BackCompatCameraNoPreventDefault(s),this._useCtrlForPanning=i,this._panningMouseButton=r,typeof s[0]=="boolean"&&(s.length>1&&(this._useCtrlForPanning=s[1]),s.length>2&&(this._panningMouseButton=s[2])),this.inputs.attachElement(t),this._reset=()=>{this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){if(this._collisionTriggered)return;this.inputs.checkInputs();let e=!1;if(this.inertialAlphaOffset!==0||this.inertialBetaOffset!==0||this.inertialRadiusOffset!==0){e=!0;let t=this.invertRotation?-1:1,i=this._calculateHandednessMultiplier(),r=this.inertialAlphaOffset*i;this.beta<0&&(r*=-1),this.alpha+=r*t,this.beta+=this.inertialBetaOffset*t,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,Math.abs(this.inertialAlphaOffset)Math.PI&&(this.beta=this.beta-2*Math.PI):this.betathis.upperBetaLimit&&(this.beta=this.upperBetaLimit),this.lowerAlphaLimit!==null&&this.alphathis.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),this.lowerRadiusLimit!==null&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit,this.inertialRadiusOffset=0),this.target.y=Math.max(this.target.y,this.lowerTargetYLimit)}rebuildAnglesAndRadius(){this._position.subtractToRef(this._getTargetPosition(),this._computationVector),(this._upVector.x!==0||this._upVector.y!==1||this._upVector.z!==0)&&b.TransformCoordinatesToRef(this._computationVector,this._upToYMatrix,this._computationVector),this.radius=this._computationVector.length(),this.radius===0&&(this.radius=1e-4);let e=this.alpha;this.alpha=Pse(this._computationVector),this.beta=Dse(this._computationVector.y,this.radius);let t=Math.round((e-this.alpha)/(2*Math.PI));this.alpha+=t*2*Math.PI,this._checkLimits()}setPosition(e){this._position.equals(e)||(this._position.copyFrom(e),this.rebuildAnglesAndRadius())}setTarget(e,t=!1,i=!1,r=!1){var s;if(r=(s=this.overrideCloneAlphaBetaRadius)!=null?s:r,e.computeWorldMatrix)t&&e.getBoundingInfo?this._targetBoundingCenter=e.getBoundingInfo().boundingBox.centerWorld.clone():this._targetBoundingCenter=null,e.computeWorldMatrix(),this._targetHost=e,this._target=this._getTargetPosition(),this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);else{let a=e,o=this._getTargetPosition();if(o&&!i&&o.equals(a))return;this._targetHost=null,this._target=a,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}r||this.rebuildAnglesAndRadius()}_getViewMatrix(){let e=Math.cos(this.alpha),t=Math.sin(this.alpha),i=Math.cos(this.beta),r=Math.sin(this.beta);r===0&&(r=1e-4),this.radius===0&&(this.radius=1e-4);let s=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*r,this.radius*i,this.radius*t*r),(this._upVector.x!==0||this._upVector.y!==1||this._upVector.z!==0)&&b.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),s.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){let a=this.getScene().collisionCoordinator;this._collider||(this._collider=a.createCollider()),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this._position,this._collisionVelocity),this._collisionTriggered=!0,a.getNewPosition(this._position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}else{this._position.copyFrom(this._newPosition);let a=this.upVector;this.allowUpsideDown&&r<0&&(a=a.negate()),this._computeViewMatrix(this._position,s,a),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget.copyFrom(s),this._viewMatrix}zoomOn(e,t=!1){e=e||this.getScene().meshes;let i=q.MinMax(e),r=this._calculateLowerRadiusFromModelBoundingSphere(i.min,i.max);if(r=Math.max(Math.min(r,this.upperRadiusLimit||Number.MAX_VALUE),this.lowerRadiusLimit||0),this.radius=r*this.zoomOnFactor,this.mode===mt.ORTHOGRAPHIC_CAMERA){let s=this.getScene().getEngine().getAspectRatio(this),a=r*this.zoomOnFactor/2;this.orthoLeft=-a*s,this.orthoRight=a*s,this.orthoBottom=-a,this.orthoTop=a}this.focusOn({min:i.min,max:i.max,distance:r},t)}focusOn(e,t=!1){let i,r;if(e.min===void 0){let s=e||this.getScene().meshes;i=q.MinMax(s),r=b.Distance(i.min,i.max)}else{let s=e;i=s,r=s.distance}this._target=q.Center(i),t||(this.maxZ=r*2)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case mt.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case mt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case mt.RIG_MODE_STEREOSCOPIC_OVERUNDER:case mt.RIG_MODE_STEREOSCOPIC_INTERLACED:case mt.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(t===0?1:-1);break;case mt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(t===0?-1:1);break}let r=new n(e,this.alpha+i,this.beta,this.radius,this._target,this.getScene());return r._cameraRigParams={},r.isRigCamera=!0,r.rigParent=this,r.upVector=this.upVector,r.mode=this.mode,r.orthoLeft=this.orthoLeft,r.orthoRight=this.orthoRight,r.orthoBottom=this.orthoBottom,r.orthoTop=this.orthoTop,r}_updateRigCameras(){let e=this._rigCameras[0],t=this._rigCameras[1];switch(e.beta=t.beta=this.beta,this.cameraRigMode){case mt.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case mt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case mt.RIG_MODE_STEREOSCOPIC_OVERUNDER:case mt.RIG_MODE_STEREOSCOPIC_INTERLACED:case mt.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case mt.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:e.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle;break}super._updateRigCameras()}_calculateLowerRadiusFromModelBoundingSphere(e,t,i=1){let r=b.Distance(e,t),a=this.getScene().getEngine().getAspectRatio(this),o=Math.tan(this.fov/2),l=o*a,f=r*.5*i,h=f*Math.sqrt(1+1/(l*l)),d=f*Math.sqrt(1+1/(o*o));return Math.max(h,d)}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"ArcRotateCamera"}};P([w()],gi.prototype,"alpha",void 0);P([w()],gi.prototype,"beta",void 0);P([w()],gi.prototype,"radius",void 0);P([w()],gi.prototype,"overrideCloneAlphaBetaRadius",void 0);P([Hr("target")],gi.prototype,"_target",void 0);P([kT("targetHost")],gi.prototype,"_targetHost",void 0);P([w()],gi.prototype,"inertialAlphaOffset",void 0);P([w()],gi.prototype,"inertialBetaOffset",void 0);P([w()],gi.prototype,"inertialRadiusOffset",void 0);P([w()],gi.prototype,"lowerAlphaLimit",void 0);P([w()],gi.prototype,"upperAlphaLimit",void 0);P([w()],gi.prototype,"lowerBetaLimit",void 0);P([w()],gi.prototype,"upperBetaLimit",void 0);P([w()],gi.prototype,"lowerRadiusLimit",void 0);P([w()],gi.prototype,"upperRadiusLimit",void 0);P([w()],gi.prototype,"lowerTargetYLimit",void 0);P([w()],gi.prototype,"inertialPanningX",void 0);P([w()],gi.prototype,"inertialPanningY",void 0);P([w()],gi.prototype,"pinchToPanMaxDistance",void 0);P([w()],gi.prototype,"panningDistanceLimit",void 0);P([Hr()],gi.prototype,"panningOriginTarget",void 0);P([w()],gi.prototype,"panningInertia",void 0);P([w()],gi.prototype,"zoomToMouseLocation",null);P([w()],gi.prototype,"zoomOnFactor",void 0);P([em()],gi.prototype,"targetScreenOffset",void 0);P([w()],gi.prototype,"allowUpsideDown",void 0);P([w()],gi.prototype,"useInputToRestoreState",void 0);P([w()],gi.prototype,"restoreStateInterpolationFactor",void 0);Ft("BABYLON.ArcRotateCamera",gi)});var Xt,yf=C(()=>{Gt();Vt();Ge();zt();js();mf();Hi();z_();Tr();Xt=class n extends _i{get range(){return this._range}set range(e){this._range=e,this._inverseSquaredRange=1/(this.range*this.range)}get intensityMode(){return this._intensityMode}set intensityMode(e){this._intensityMode=e,this._computePhotometricScale()}get radius(){return this._radius}set radius(e){this._radius=e,this._computePhotometricScale()}get shadowEnabled(){return this._shadowEnabled}set shadowEnabled(e){this._shadowEnabled!==e&&(this._shadowEnabled=e,this._markMeshesAsLightDirty())}get includedOnlyMeshes(){return this._includedOnlyMeshes}set includedOnlyMeshes(e){this._includedOnlyMeshes=e,this._hookArrayForIncludedOnly(e)}get excludedMeshes(){return this._excludedMeshes}set excludedMeshes(e){this._excludedMeshes=e,this._hookArrayForExcluded(e)}get excludeWithLayerMask(){return this._excludeWithLayerMask}set excludeWithLayerMask(e){this._excludeWithLayerMask=e,this._resyncMeshes()}get includeOnlyWithLayerMask(){return this._includeOnlyWithLayerMask}set includeOnlyWithLayerMask(e){this._includeOnlyWithLayerMask=e,this._resyncMeshes()}get lightmapMode(){return this._lightmapMode}set lightmapMode(e){this._lightmapMode!==e&&(this._lightmapMode=e,this._markMeshesAsLightDirty())}getViewMatrix(e){return null}getProjectionMatrix(e,t){return null}constructor(e,t,i){super(e,t,!1),this.diffuse=new ve(1,1,1),this.specular=new ve(1,1,1),this.falloffType=n.FALLOFF_DEFAULT,this.intensity=1,this._range=Number.MAX_VALUE,this._inverseSquaredRange=0,this._photometricScale=1,this._intensityMode=n.INTENSITYMODE_AUTOMATIC,this._radius=1e-5,this.renderPriority=0,this._shadowEnabled=!0,this._excludeWithLayerMask=0,this._includeOnlyWithLayerMask=0,this._lightmapMode=0,this._shadowGenerators=null,this._excludedMeshesIds=new Array,this._includedOnlyMeshesIds=new Array,this._currentViewDepth=0,this._clusteredContainer=null,this._isLight=!0,i||this.getScene().addLight(this),this._uniformBuffer=new hr(this.getScene().getEngine(),void 0,void 0,e),this._buildUniformLayout(),this.includedOnlyMeshes=[],this.excludedMeshes=[],i||this._resyncMeshes()}transferTexturesToEffect(e,t){return this}_bindLight(e,t,i,r,s=!0){var l;let a=e.toString(),o=!1;if(this._uniformBuffer.bindToEffect(i,"Light"+a),this._renderId!==t.getRenderId()||this._lastUseSpecular!==r||!this._uniformBuffer.useUbo){this._renderId=t.getRenderId(),this._lastUseSpecular=r;let c=this.getScaledIntensity();this.transferToEffect(i,a),this.diffuse.scaleToRef(c,En.Color3[0]),this._uniformBuffer.updateColor4("vLightDiffuse",En.Color3[0],this.range,a),r&&(this.specular.scaleToRef(c,En.Color3[1]),this._uniformBuffer.updateColor4("vLightSpecular",En.Color3[1],this.radius,a)),o=!0}if(this.transferTexturesToEffect(i,a),t.shadowsEnabled&&this.shadowEnabled&&s){let c=(l=this.getShadowGenerator(t.activeCamera))!=null?l:this.getShadowGenerator();c&&(c.bindShadowLight(a,i),o=!0)}o?this._uniformBuffer.update():this._uniformBuffer.bindUniformBuffer()}getClassName(){return"Light"}toString(e){let t="Name: "+this.name;if(t+=", type: "+["Point","Directional","Spot","Hemispheric","Clustered"][this.getTypeID()],this.animations)for(let i=0;i0&&this.includedOnlyMeshes.indexOf(e)===-1||this.excludedMeshes&&this.excludedMeshes.length>0&&this.excludedMeshes.indexOf(e)!==-1||this.includeOnlyWithLayerMask!==0&&(this.includeOnlyWithLayerMask&e.layerMask)===0||this.excludeWithLayerMask!==0&&this.excludeWithLayerMask&e.layerMask):!0}dispose(e,t=!1){if(this._shadowGenerators){let i=this._shadowGenerators.values();for(let r=i.next();r.done!==!0;r=i.next())r.value.dispose();this._shadowGenerators=null}if(this.getScene().stopAnimation(this),this._parentContainer){let i=this._parentContainer.lights.indexOf(this);i>-1&&this._parentContainer.lights.splice(i,1),this._parentContainer=null}for(let i of this.getScene().meshes)i._removeLightSource(this,!0);this._uniformBuffer.dispose(),this.getScene().removeLight(this),super.dispose(e,t)}getTypeID(){return 0}getScaledIntensity(){return this._photometricScale*this.intensity}clone(e,t=null){let i=n.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;let r=it.Clone(i,this);return e&&(r.name=e),t&&(r.parent=t),r.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(r),r}serialize(){let e=it.Serialize(this);if(e.uniqueId=this.uniqueId,e.type=this.getTypeID(),this.parent&&this.parent._serializeAsParent(e),this.excludedMeshes.length>0){e.excludedMeshesIds=[];for(let t of this.excludedMeshes)e.excludedMeshesIds.push(t.id)}if(this.includedOnlyMeshes.length>0){e.includedOnlyMeshesIds=[];for(let t of this.includedOnlyMeshes)e.includedOnlyMeshesIds.push(t.id)}return it.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){let r=_i.Construct("Light_Type_"+e,t,i);return r||null}static Parse(e,t){let i=n.GetConstructorFromName(e.type,e.name,t);if(!i)return null;let r=it.Parse(i,e,t);if(e.excludedMeshesIds&&(r._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(r._includedOnlyMeshesIds=e.includedOnlyMeshesIds),e.parentId!==void 0&&(r._waitingParentId=e.parentId),e.parentInstanceIndex!==void 0&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),e.falloffType!==void 0&&(r.falloffType=e.falloffType),e.lightmapMode!==void 0&&(r.lightmapMode=e.lightmapMode),e.animations){for(let s=0;s{let s=t.apply(e,r);if(this._clusteredContainer)return s;for(let a of r)a._resyncLightSource(this);return s};let i=e.splice;if(e.splice=(r,s)=>{let a=i.call(e,r,s!=null?s:e.length);if(this._clusteredContainer)return a;for(let o of a)o._resyncLightSource(this);return a},!this._clusteredContainer)for(let r of e)r._resyncLightSource(this)}_hookArrayForIncludedOnly(e){let t=e.push;e.push=(...r)=>{let s=t.apply(e,r);return this._resyncMeshes(),s};let i=e.splice;e.splice=(r,s)=>{let a=i.call(e,r,s!=null?s:e.length);return this._resyncMeshes(),a},this._resyncMeshes()}_resyncMeshes(){if(!this._clusteredContainer)for(let e of this.getScene().meshes)e._resyncLightSource(this)}_markMeshesAsLightDirty(){for(let e of this.getScene().meshes)e.lightSources.indexOf(this)!==-1&&e._markSubMeshesAsLightDirty()}_computePhotometricScale(){this._photometricScale=this._getPhotometricScale(),this.getScene().resetCachedMaterial()}_getPhotometricScale(){let e=0,t=this.getTypeID(),i=this.intensityMode;switch(i===n.INTENSITYMODE_AUTOMATIC&&(t===n.LIGHTTYPEID_DIRECTIONALLIGHT?i=n.INTENSITYMODE_ILLUMINANCE:i=n.INTENSITYMODE_LUMINOUSINTENSITY),t){case n.LIGHTTYPEID_POINTLIGHT:case n.LIGHTTYPEID_SPOTLIGHT:switch(i){case n.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case n.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case n.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius;break}break;case n.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case n.INTENSITYMODE_ILLUMINANCE:e=1;break;case n.INTENSITYMODE_LUMINANCE:{let r=this.radius;r=Math.max(r,.001),e=2*Math.PI*(1-Math.cos(r));break}}break;case n.LIGHTTYPEID_HEMISPHERICLIGHT:e=1;break}return e}_reorderLightsInScene(){let e=this.getScene();this._renderPriority!=0&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}areLightTexturesReady(){return!0}_isReady(){return!0}};Xt.FALLOFF_DEFAULT=Yt.FALLOFF_DEFAULT;Xt.FALLOFF_PHYSICAL=Yt.FALLOFF_PHYSICAL;Xt.FALLOFF_GLTF=Yt.FALLOFF_GLTF;Xt.FALLOFF_STANDARD=Yt.FALLOFF_STANDARD;Xt.LIGHTMAP_DEFAULT=Yt.LIGHTMAP_DEFAULT;Xt.LIGHTMAP_SPECULAR=Yt.LIGHTMAP_SPECULAR;Xt.LIGHTMAP_SHADOWSONLY=Yt.LIGHTMAP_SHADOWSONLY;Xt.INTENSITYMODE_AUTOMATIC=Yt.INTENSITYMODE_AUTOMATIC;Xt.INTENSITYMODE_LUMINOUSPOWER=Yt.INTENSITYMODE_LUMINOUSPOWER;Xt.INTENSITYMODE_LUMINOUSINTENSITY=Yt.INTENSITYMODE_LUMINOUSINTENSITY;Xt.INTENSITYMODE_ILLUMINANCE=Yt.INTENSITYMODE_ILLUMINANCE;Xt.INTENSITYMODE_LUMINANCE=Yt.INTENSITYMODE_LUMINANCE;Xt.LIGHTTYPEID_POINTLIGHT=Yt.LIGHTTYPEID_POINTLIGHT;Xt.LIGHTTYPEID_DIRECTIONALLIGHT=Yt.LIGHTTYPEID_DIRECTIONALLIGHT;Xt.LIGHTTYPEID_SPOTLIGHT=Yt.LIGHTTYPEID_SPOTLIGHT;Xt.LIGHTTYPEID_HEMISPHERICLIGHT=Yt.LIGHTTYPEID_HEMISPHERICLIGHT;Xt.LIGHTTYPEID_RECT_AREALIGHT=Yt.LIGHTTYPEID_RECT_AREALIGHT;P([gr()],Xt.prototype,"diffuse",void 0);P([gr()],Xt.prototype,"specular",void 0);P([w()],Xt.prototype,"falloffType",void 0);P([w()],Xt.prototype,"intensity",void 0);P([w()],Xt.prototype,"range",null);P([w()],Xt.prototype,"intensityMode",null);P([w()],Xt.prototype,"radius",null);P([w()],Xt.prototype,"_renderPriority",void 0);P([le("_reorderLightsInScene")],Xt.prototype,"renderPriority",void 0);P([w("shadowEnabled")],Xt.prototype,"_shadowEnabled",void 0);P([w("excludeWithLayerMask")],Xt.prototype,"_excludeWithLayerMask",void 0);P([w("includeOnlyWithLayerMask")],Xt.prototype,"_includeOnlyWithLayerMask",void 0);P([w("lightmapMode")],Xt.prototype,"_lightmapMode",void 0)});var Zs,kA=C(()=>{Gt();Vt();Ge();zt();js();yf();Hi();_i.AddNodeConstructor("Light_Type_3",(n,e)=>()=>new Zs(n,b.Zero(),e));Zs=class extends Xt{constructor(e,t,i,r){super(e,i,r),this.groundColor=new ve(0,0,0),this.direction=t||b.Up()}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightGround",3),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}getClassName(){return"HemisphericLight"}setDirectionToTarget(e){return this.direction=b.Normalize(e.subtract(b.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){let i=b.Normalize(this.direction);return this._uniformBuffer.updateFloat4("vLightData",i.x,i.y,i.z,0,t),this._uniformBuffer.updateColor3("vLightGround",this.groundColor.scale(this.intensity),t),this}transferToNodeMaterialEffect(e,t){let i=b.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=K.Identity()),this._worldMatrix}getTypeID(){return Xt.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}};P([gr()],Zs.prototype,"groundColor",void 0);P([Hr()],Zs.prototype,"direction",void 0);Ft("BABYLON.HemisphericLight",Zs)});var Da,WA=C(()=>{Gt();Vt();Ge();yf();zu();Da=class extends Xt{constructor(){super(...arguments),this._needProjectionMatrixCompute=!0,this._viewMatrix=K.Identity(),this._projectionMatrix=K.Identity()}_setPosition(e){this._position=e}get position(){return this._position}set position(e){this._setPosition(e)}_setDirection(e){this._direction=e}get direction(){return this._direction}set direction(e){this._setDirection(e)}get shadowMinZ(){return this._shadowMinZ}set shadowMinZ(e){this._shadowMinZ=e,this.forceProjectionMatrixCompute()}get shadowMaxZ(){return this._shadowMaxZ}set shadowMaxZ(e){this._shadowMaxZ=e,this.forceProjectionMatrixCompute()}computeTransformedInformation(){return this.parent&&this.parent.getWorldMatrix?(this.transformedPosition||(this.transformedPosition=b.Zero()),b.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=b.Zero()),b.TransformNormalToRef(this.direction,this.parent.getWorldMatrix(),this.transformedDirection)),!0):!1}getDepthScale(){return 50}getShadowDirection(e){return this.transformedDirection?this.transformedDirection:this.direction}getAbsolutePosition(){return this.transformedPosition?this.transformedPosition:this.position}setDirectionToTarget(e){return this.direction=b.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();let e=b.Cross(this.direction,Es.Y),t=b.Cross(e,this.direction);return b.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=b.Zero()}_isSynchronized(){return!!this._cache.position.equals(this.position)}computeWorldMatrix(e){return!e&&this.isSynchronized()?(this._currentRenderId=this.getScene().getRenderId(),this._worldMatrix):(this._updateCache(),this._cache.position.copyFrom(this.position),this._worldMatrix||(this._worldMatrix=K.Identity()),K.TranslationToRef(this.position.x,this.position.y,this.position.z,this._worldMatrix),this.parent&&this.parent.getWorldMatrix&&(this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(),this._worldMatrix),this._markSyncedWithParent()),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix)}getDepthMinZ(e){return this.shadowMinZ!==void 0?this.shadowMinZ:(e==null?void 0:e.minZ)||0}getDepthMaxZ(e){return this.shadowMaxZ!==void 0?this.shadowMaxZ:(e==null?void 0:e.maxZ)||1e4}setShadowProjectionMatrix(e,t,i){return this.customProjectionMatrixBuilder?this.customProjectionMatrixBuilder(t,i,e):this._setDefaultShadowProjectionMatrix(e,t,i),this}_syncParentEnabledState(){super._syncParentEnabledState(),(!this.parent||!this.parent.getWorldMatrix)&&(this.transformedPosition=null,this.transformedDirection=null)}getViewMatrix(e){let t=$.Vector3[0],i=this.position;this.computeTransformedInformation()&&(i=this.transformedPosition),b.NormalizeToRef(this.getShadowDirection(e),t),Math.abs(b.Dot(t,b.Up()))===1&&(t.z=1e-13);let r=$.Vector3[1];return i.addToRef(t,r),K.LookAtLHToRef(i,r,b.Up(),this._viewMatrix),this._viewMatrix}getProjectionMatrix(e,t){return this.setShadowProjectionMatrix(this._projectionMatrix,e!=null?e:this._viewMatrix,t!=null?t:[]),this._projectionMatrix}};P([Hr()],Da.prototype,"position",null);P([Hr()],Da.prototype,"direction",null);P([w()],Da.prototype,"shadowMinZ",null);P([w()],Da.prototype,"shadowMaxZ",null)});var Ms,CG=C(()=>{Gt();Vt();Ge();js();yf();WA();Hi();_i.AddNodeConstructor("Light_Type_1",(n,e)=>()=>new Ms(n,b.Zero(),e));Ms=class extends Da{get shadowFrustumSize(){return this._shadowFrustumSize}set shadowFrustumSize(e){this._shadowFrustumSize=e,this.forceProjectionMatrixCompute()}get shadowOrthoScale(){return this._shadowOrthoScale}set shadowOrthoScale(e){this._shadowOrthoScale=e,this.forceProjectionMatrixCompute()}get orthoLeft(){return this._orthoLeft}set orthoLeft(e){this._orthoLeft=e}get orthoRight(){return this._orthoRight}set orthoRight(e){this._orthoRight=e}get orthoTop(){return this._orthoTop}set orthoTop(e){this._orthoTop=e}get orthoBottom(){return this._orthoBottom}set orthoBottom(e){this._orthoBottom=e}constructor(e,t,i,r){super(e,i,r),this._shadowFrustumSize=0,this._shadowOrthoScale=.1,this.autoUpdateExtends=!0,this.autoCalcShadowZBounds=!1,this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE,this.position=t.scale(-1),this.direction=t}getClassName(){return"DirectionalLight"}getTypeID(){return Xt.LIGHTTYPEID_DIRECTIONALLIGHT}_setDefaultShadowProjectionMatrix(e,t,i){this.shadowFrustumSize>0?this._setDefaultFixedFrustumShadowProjectionMatrix(e):this._setDefaultAutoExtendShadowProjectionMatrix(e,t,i)}_setDefaultFixedFrustumShadowProjectionMatrix(e){let t=this.getScene().activeCamera;K.OrthoLHToRef(this.shadowFrustumSize,this.shadowFrustumSize,this.shadowMinZ!==void 0?this.shadowMinZ:t?t.minZ:0,this.shadowMaxZ!==void 0?this.shadowMaxZ:t?t.maxZ:1e4,e,this.getScene().getEngine().isNDCHalfZRange)}_setDefaultAutoExtendShadowProjectionMatrix(e,t,i){let r=this.getScene().activeCamera;if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){let f=b.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=-Number.MAX_VALUE,this._orthoTop=-Number.MAX_VALUE,this._orthoBottom=Number.MAX_VALUE;let h=Number.MAX_VALUE,d=-Number.MAX_VALUE;for(let u=0;uthis._orthoRight&&(this._orthoRight=f.x),f.y>this._orthoTop&&(this._orthoTop=f.y),this.autoCalcShadowZBounds&&(f.zd&&(d=f.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=h,this._shadowMaxZ=d)}let s=this._orthoRight-this._orthoLeft,a=this._orthoTop-this._orthoBottom,o=this.shadowMinZ!==void 0?this.shadowMinZ:(r==null?void 0:r.minZ)||0,l=this.shadowMaxZ!==void 0?this.shadowMaxZ:(r==null?void 0:r.maxZ)||1e4,c=this.getScene().getEngine().useReverseDepthBuffer;K.OrthoOffCenterLHToRef(this._orthoLeft-s*this.shadowOrthoScale,this._orthoRight+s*this.shadowOrthoScale,this._orthoBottom-a*this.shadowOrthoScale,this._orthoTop+a*this.shadowOrthoScale,c?l:o,c?o:l,e,this.getScene().getEngine().isNDCHalfZRange)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z,1,t),this):(this._uniformBuffer.updateFloat4("vLightData",this.direction.x,this.direction.y,this.direction.z,1,t),this)}transferToNodeMaterialEffect(e,t){return this.computeTransformedInformation()?(e.setFloat3(t,this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z),this):(e.setFloat3(t,this.direction.x,this.direction.y,this.direction.z),this)}getDepthMinZ(e){let t=this._scene.getEngine();return!t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}getDepthMaxZ(e){let t=this._scene.getEngine();return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}prepareLightSpecificDefines(e,t){e["DIRLIGHT"+t]=!0}};P([w()],Ms.prototype,"shadowFrustumSize",null);P([w()],Ms.prototype,"shadowOrthoScale",null);P([w()],Ms.prototype,"autoUpdateExtends",void 0);P([w()],Ms.prototype,"autoCalcShadowZBounds",void 0);P([w("orthoLeft")],Ms.prototype,"_orthoLeft",void 0);P([w("orthoRight")],Ms.prototype,"_orthoRight",void 0);P([w("orthoTop")],Ms.prototype,"_orthoTop",void 0);P([w("orthoBottom")],Ms.prototype,"_orthoBottom",void 0);Ft("BABYLON.DirectionalLight",Ms)});var Pf,yG=C(()=>{Gt();Vt();Ge();js();yf();WA();Hi();_i.AddNodeConstructor("Light_Type_0",(n,e)=>()=>new Pf(n,b.Zero(),e));Pf=class extends Da{get shadowAngle(){return this._shadowAngle}set shadowAngle(e){this._shadowAngle=e,this.forceProjectionMatrixCompute()}get direction(){return this._direction}set direction(e){let t=this.needCube();if(this._direction=e,this.needCube()!==t&&this._shadowGenerators){let i=this._shadowGenerators.values();for(let r=i.next();r.done!==!0;r=i.next())r.value.recreateShadowMap()}}constructor(e,t,i,r){super(e,i,r),this._shadowAngle=Math.PI/2,this.position=t}getClassName(){return"PointLight"}getTypeID(){return Xt.LIGHTTYPEID_POINTLIGHT}needCube(){return!this.direction}getShadowDirection(e){if(this.direction)return super.getShadowDirection(e);switch(e){case 0:return new b(1,0,0);case 1:return new b(-1,0,0);case 2:return new b(0,-1,0);case 3:return new b(0,1,0);case 4:return new b(0,0,1);case 5:return new b(0,0,-1)}return b.Zero()}_setDefaultShadowProjectionMatrix(e,t,i){let r=this.getScene().activeCamera,s=this.getDepthMinZ(r),a=this.getDepthMaxZ(r),o=this.getScene().getEngine().useReverseDepthBuffer;K.PerspectiveFovLHToRef(this.shadowAngle,1,o?a:s,o?s:a,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,o)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){let i=this._scene.floatingOriginOffset;return this.computeTransformedInformation()?this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x-i.x,this.transformedPosition.y-i.y,this.transformedPosition.z-i.z,0,t):this._uniformBuffer.updateFloat4("vLightData",this.position.x-i.x,this.position.y-i.y,this.position.z-i.z,0,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,0,0,t),this}transferToNodeMaterialEffect(e,t){let i=this._scene.floatingOriginOffset;return this.computeTransformedInformation()?e.setFloat3(t,this.transformedPosition.x-i.x,this.transformedPosition.y-i.y,this.transformedPosition.z-i.z):e.setFloat3(t,this.position.x-i.x,this.position.y-i.y,this.position.z-i.z),this}prepareLightSpecificDefines(e,t){e["POINTLIGHT"+t]=!0}};P([w()],Pf.prototype,"shadowAngle",null);Ft("BABYLON.PointLight",Pf)});var Ur,Fy=C(()=>{Gt();Vt();Ge();js();yf();WA();Fr();Hi();_i.AddNodeConstructor("Light_Type_2",(n,e)=>()=>new Ur(n,b.Zero(),b.Zero(),0,0,e));Ur=class n extends Da{get iesProfileTexture(){return this._iesProfileTexture}set iesProfileTexture(e){this._iesProfileTexture!==e&&(this._iesProfileTexture=e,this._iesProfileTexture&&n._IsTexture(this._iesProfileTexture)&&this._iesProfileTexture.onLoadObservable.addOnce(()=>{this._markMeshesAsLightDirty()}))}get angle(){return this._angle}set angle(e){this._angle=e,this._cosHalfAngle=Math.cos(e*.5),this._projectionTextureProjectionLightDirty=!0,this.forceProjectionMatrixCompute(),this._computeAngleValues()}get innerAngle(){return this._innerAngle}set innerAngle(e){this._innerAngle=e,this._computeAngleValues()}get shadowAngleScale(){return this._shadowAngleScale}set shadowAngleScale(e){this._shadowAngleScale=e,this.forceProjectionMatrixCompute()}get projectionTextureMatrix(){return this._projectionTextureMatrix}get projectionTextureLightNear(){return this._projectionTextureLightNear}set projectionTextureLightNear(e){this._projectionTextureLightNear=e,this._projectionTextureProjectionLightDirty=!0}get projectionTextureLightFar(){return this._projectionTextureLightFar}set projectionTextureLightFar(e){this._projectionTextureLightFar=e,this._projectionTextureProjectionLightDirty=!0}get projectionTextureUpDirection(){return this._projectionTextureUpDirection}set projectionTextureUpDirection(e){this._projectionTextureUpDirection=e,this._projectionTextureProjectionLightDirty=!0}get projectionTexture(){return this._projectionTexture}set projectionTexture(e){this._projectionTexture!==e&&(this._projectionTexture=e,this._projectionTextureDirty=!0,this._projectionTexture&&!this._projectionTexture.isReady()&&(n._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled(()=>{this._markMeshesAsLightDirty()}):n._IsTexture(this._projectionTexture)&&this._projectionTexture.onLoadObservable.addOnce(()=>{this._markMeshesAsLightDirty()})))}static _IsProceduralTexture(e){return e.onGeneratedObservable!==void 0}static _IsTexture(e){return e.onLoadObservable!==void 0}get projectionTextureProjectionLightMatrix(){return this._projectionTextureProjectionLightMatrix}set projectionTextureProjectionLightMatrix(e){this._projectionTextureProjectionLightMatrix=e,this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0}constructor(e,t,i,r,s,a,o){super(e,a,o),this._innerAngle=0,this._iesProfileTexture=null,this._projectionTextureMatrix=K.Zero(),this._projectionTextureLightNear=1e-6,this._projectionTextureLightFar=1e3,this._projectionTextureUpDirection=b.Up(),this._projectionTextureViewLightDirty=!0,this._projectionTextureProjectionLightDirty=!0,this._projectionTextureDirty=!0,this._projectionTextureViewTargetVector=b.Zero(),this._projectionTextureViewLightMatrix=K.Zero(),this._projectionTextureProjectionLightMatrix=K.Zero(),this._projectionTextureScalingMatrix=K.FromValues(.5,0,0,0,0,.5,0,0,0,0,.5,0,.5,.5,.5,1),this.position=t,this.direction=i,this.angle=r,this.exponent=s}getClassName(){return"SpotLight"}getTypeID(){return Xt.LIGHTTYPEID_SPOTLIGHT}_setDirection(e){super._setDirection(e),this._projectionTextureViewLightDirty=!0}_setPosition(e){super._setPosition(e),this._projectionTextureViewLightDirty=!0}_setDefaultShadowProjectionMatrix(e,t,i){let r=this.getScene().activeCamera;if(!r)return;this._shadowAngleScale=this._shadowAngleScale||1;let s=this._shadowAngleScale*this._angle,a=this.shadowMinZ!==void 0?this.shadowMinZ:r.minZ,o=this.shadowMaxZ!==void 0?this.shadowMaxZ:r.maxZ,l=this.getScene().getEngine().useReverseDepthBuffer;K.PerspectiveFovLHToRef(s,1,l?o:a,l?a:o,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,l)}_computeProjectionTextureViewLightMatrix(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.getAbsolutePosition().addToRef(this.getShadowDirection(),this._projectionTextureViewTargetVector),K.LookAtLHToRef(this.getAbsolutePosition(),this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)}_computeProjectionTextureProjectionLightMatrix(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;let e=this.projectionTextureLightFar,t=this.projectionTextureLightNear,i=e/(e-t),r=-i*t,s=1/Math.tan(this._angle/2);K.FromValuesToRef(s/1,0,0,0,0,s,0,0,0,0,i,1,0,0,r,0,this._projectionTextureProjectionLightMatrix)}_computeProjectionTextureMatrix(){if(this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTexture instanceof ge){let e=this._projectionTexture.uScale/2,t=this._projectionTexture.vScale/2;K.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,.5,0,.5,.5,.5,1,this._projectionTextureScalingMatrix)}this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix,this._projectionTextureMatrix)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightDirection",3),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}_computeAngleValues(){this._lightAngleScale=1/Math.max(.001,Math.cos(this._innerAngle*.5)-this._cosHalfAngle),this._lightAngleOffset=-this._cosHalfAngle*this._lightAngleScale}transferTexturesToEffect(e,t){return this.projectionTexture&&this.projectionTexture.isReady()&&(this._projectionTextureViewLightDirty&&this._computeProjectionTextureViewLightMatrix(),this._projectionTextureProjectionLightDirty&&this._computeProjectionTextureProjectionLightMatrix(),this._projectionTextureDirty&&this._computeProjectionTextureMatrix(),e.setMatrix("textureProjectionMatrix"+t,this._projectionTextureMatrix),e.setTexture("projectionLightTexture"+t,this.projectionTexture)),this._iesProfileTexture&&this._iesProfileTexture.isReady()&&e.setTexture("iesLightTexture"+t,this._iesProfileTexture),this}transferToEffect(e,t){let i,r=this._scene.floatingOriginOffset;return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x-r.x,this.transformedPosition.y-r.y,this.transformedPosition.z-r.z,this.exponent,t),i=b.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x-r.x,this.position.y-r.y,this.position.z-r.z,this.exponent,t),i=b.Normalize(this.direction)),this._uniformBuffer.updateFloat4("vLightDirection",i.x,i.y,i.z,this._cosHalfAngle,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,this._lightAngleScale,this._lightAngleOffset,t),this}transferToNodeMaterialEffect(e,t){let i;return this.computeTransformedInformation()?i=b.Normalize(this.transformedDirection):i=b.Normalize(this.direction),this.getScene().useRightHandedSystem?e.setFloat3(t,-i.x,-i.y,-i.z):e.setFloat3(t,i.x,i.y,i.z),this}dispose(){super.dispose(),this._projectionTexture&&this._projectionTexture.dispose(),this._iesProfileTexture&&(this._iesProfileTexture.dispose(),this._iesProfileTexture=null)}getDepthMinZ(e){var r;let t=this._scene.getEngine(),i=this.shadowMinZ!==void 0?this.shadowMinZ:(r=e==null?void 0:e.minZ)!=null?r:0;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?i:this._scene.getEngine().isNDCHalfZRange?0:i}getDepthMaxZ(e){var r;let t=this._scene.getEngine(),i=this.shadowMaxZ!==void 0?this.shadowMaxZ:(r=e==null?void 0:e.maxZ)!=null?r:1e4;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:i}areLightTexturesReady(){return!(this._projectionTexture&&!this._projectionTexture.isReadyOrNotBlocking()||this._iesProfileTexture&&!this._iesProfileTexture.isReadyOrNotBlocking())}prepareLightSpecificDefines(e,t){e["SPOTLIGHT"+t]=!0,e["PROJECTEDLIGHTTEXTURE"+t]=!!(this.projectionTexture&&this.projectionTexture.isReady()),e["IESLIGHTTEXTURE"+t]=!!(this._iesProfileTexture&&this._iesProfileTexture.isReady())}};P([w()],Ur.prototype,"angle",null);P([w()],Ur.prototype,"innerAngle",null);P([w()],Ur.prototype,"shadowAngleScale",null);P([w()],Ur.prototype,"exponent",void 0);P([w()],Ur.prototype,"projectionTextureLightNear",null);P([w()],Ur.prototype,"projectionTextureLightFar",null);P([w()],Ur.prototype,"projectionTextureUpDirection",null);P([Ut("projectedLightTexture")],Ur.prototype,"_projectionTexture",void 0);Ft("BABYLON.SpotLight",Ur)});function PG(n){let e=n.pathArray,t=n.closeArray||!1,i=n.closePath||!1,r=n.invertUV||!1,s=Math.floor(e[0].length/2),a=n.offset||s;a=a>s?s:Math.floor(a);let o=n.sideOrientation===0?0:n.sideOrientation||Ce.DEFAULTSIDE,l=n.uvs,c=n.colors,f=[],h=[],d=[],u=[],m=[],p=[],_=[],g=[],v,x=[],A=[],S,E,R;if(e.length<2){let Ie=[],ze=[];for(E=0;E0&&(V=D[R].subtract(D[R-1]).length(),N=V+_[S],m[S].push(N),_[S]=N),R++;i&&(R--,f.push(D[0].x,D[0].y,D[0].z),V=D[R].subtract(D[0]).length(),N=V+_[S],m[S].push(N),_[S]=N),x[S]=O+y,A[S]=I,I+=O+y}let F,U,G,ee;for(E=0;E{let m=i[0].length,p=o,_=0,g=p._originalBuilderSideOrientation===q.DOUBLESIDE?2:1;for(let v=1;v<=g;++v)for(let x=0;x{Ge();Mi();ki();dr();en();Ce.CreateRibbon=PG;q.CreateRibbon=(n,e,t=!1,i,r,s,a=!1,o,l)=>go(n,{pathArray:e,closeArray:t,closePath:i,offset:r,updatable:a,sideOrientation:o,instance:l},s)});function DG(n){let e=[],t=[],i=[],r=[],s=n.radius||.5,a=n.tessellation||64,o=n.arc&&(n.arc<=0||n.arc>1)?1:n.arc||1,l=n.sideOrientation===0?0:n.sideOrientation||Ce.DEFAULTSIDE;e.push(0,0,0),r.push(.5,.5);let c=Math.PI*2*o,f=o===1?c/a:c/(a-1),h=0;for(let m=0;m{Mi();dr();en();Ce.CreateDisc=DG;q.CreateDisc=(n,e,t,i=null,r,s)=>By(n,{radius:e,tessellation:t,sideOrientation:s,updatable:r},i)});var Vm,OG=C(()=>{Ge();ki();Mi();q._GroundMeshParser=(n,e)=>Vm.Parse(n,e);Vm=class n extends q{constructor(e,t){super(e,t),this.generateOctree=!1}getClassName(){return"GroundMesh"}get subdivisions(){return Math.min(this._subdivisionsX,this._subdivisionsY)}get subdivisionsX(){return this._subdivisionsX}get subdivisionsY(){return this._subdivisionsY}optimize(e,t=32){this._subdivisionsX=e,this._subdivisionsY=e,this.subdivide(e);let i=this;i.createOrUpdateSubmeshesOctree&&i.createOrUpdateSubmeshesOctree(t)}getHeightAtCoordinates(e,t){let i=this.getWorldMatrix(),r=$.Matrix[5];i.invertToRef(r);let s=$.Vector3[8];if(b.TransformCoordinatesFromFloatsToRef(e,0,t,r,s),e=s.x,t=s.z,e=this._maxX||t<=this._minZ||t>this._maxZ)return this.position.y;(!this._heightQuads||this._heightQuads.length==0)&&(this._initHeightQuads(),this._computeHeightQuads());let a=this._getFacetAt(e,t),o=-(a.x*e+a.z*t+a.w)/a.y;return b.TransformCoordinatesFromFloatsToRef(0,o,0,i,s),s.y}getNormalAtCoordinates(e,t){let i=new b(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){let r=this.getWorldMatrix(),s=$.Matrix[5];r.invertToRef(s);let a=$.Vector3[8];if(b.TransformCoordinatesFromFloatsToRef(e,0,t,s,a),e=a.x,t=a.z,ethis._maxX||tthis._maxZ)return this;(!this._heightQuads||this._heightQuads.length==0)&&(this._initHeightQuads(),this._computeHeightQuads());let o=this._getFacetAt(e,t);return b.TransformNormalFromFloatsToRef(o.x,o.y,o.z,r,i),this}updateCoordinateHeights(){return(!this._heightQuads||this._heightQuads.length==0)&&this._initHeightQuads(),this._computeHeightQuads(),this}_getFacetAt(e,t){let i=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),r=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),s=this._heightQuads[r*this._subdivisionsX+i],a;return tn.maxHeight){c=!0;let h=n.maxHeight;n.maxHeight=n.minHeight,n.minHeight=h}for(s=0;s<=n.subdivisions;s++)for(a=0;a<=n.subdivisions;a++){let h=new b(a*n.width/n.subdivisions-n.width/2,0,(n.subdivisions-s)*n.height/n.subdivisions-n.height/2),d=(h.x+n.width/2)/n.width*(n.bufferWidth-1)|0,u=(1-(h.z+n.height/2)/n.height)*(n.bufferHeight-1)|0,m=(d+u*n.bufferWidth)*4,p=n.buffer[m]/255,_=n.buffer[m+1]/255,g=n.buffer[m+2]/255,v=n.buffer[m+3]/255;c&&(p=1-p,_=1-_,g=1-g);let x=p*o.r+_*o.g+g*o.b;v>=l?h.y=n.minHeight+(n.maxHeight-n.minHeight)*x:h.y=n.minHeight-Nt,n.heightBuffer&&(n.heightBuffer[s*(n.subdivisions+1)+a]=h.y),t.push(h.x,h.y,h.z),i.push(0,0,0),r.push(a/n.subdivisions,1-s/n.subdivisions)}for(s=0;s=n.minHeight,_=t[d*3+1]>=n.minHeight,g=t[u*3+1]>=n.minHeight;p&&_&&g&&(e.push(h),e.push(d),e.push(u)),t[m*3+1]>=n.minHeight&&p&&g&&(e.push(m),e.push(h),e.push(u))}Ce.ComputeNormals(t,e,i);let f=new Ce;return f.indices=e,f.positions=t,f.normals=i,f.uvs=r,f}function Vy(n,e={},t){let i=new Vm(n,t);return i._setReady(!1),i._subdivisionsX=e.subdivisionsX||e.subdivisions||1,i._subdivisionsY=e.subdivisionsY||e.subdivisions||1,i._width=e.width||1,i._height=e.height||1,i._maxX=i._width/2,i._maxZ=i._height/2,i._minX=-i._maxX,i._minZ=-i._maxZ,Uy(e).applyToMesh(i,e.updatable),i._setReady(!0),i}function Gy(n,e,t=null){let i=new q(n,t);return NG(e).applyToMesh(i,e.updatable),i}function ky(n,e,t={},i=null){let r=t.width||10,s=t.height||10,a=t.subdivisions||1,o=t.minHeight||0,l=t.maxHeight||1,c=t.colorFilter||new ve(.3,.59,.11),f=t.alphaFilter||0,h=t.updatable,d=t.onReady;i=i||Oe.LastCreatedScene;let u=new Vm(n,i);u._subdivisionsX=a,u._subdivisionsY=a,u._width=r,u._height=s,u._maxX=u._width/2,u._maxZ=u._height/2,u._minX=-u._maxX,u._minZ=-u._maxZ,u._setReady(!1);let m;t.passHeightBufferInCallback&&(m=new Float32Array((a+1)*(a+1)));let p=(_,g,v)=>{wG({width:r,height:s,subdivisions:a,minHeight:o,maxHeight:l,colorFilter:c,buffer:_,bufferWidth:g,bufferHeight:v,alphaFilter:f,heightBuffer:m}).applyToMesh(u,h),d&&d(u,m),u._setReady(!0)};if(typeof e=="string"){i.addPendingData(u);let _=v=>{let x=v.width,A=v.height;if(i.isDisposed){i.removePendingData(u);return}let S=i==null?void 0:i.getEngine().resizeImageBitmap(v,x,A);p(S,x,A),i.removePendingData(u)},g=(v,x)=>{i.removePendingData(u),t.onError&&t.onError(v,x)};_e.LoadImage(e,_,g,i.offlineProvider)}else p(e.data,e.width,e.height);return u}var Wy=C(()=>{Ge();zt();Mi();dr();OG();Ii();Di();Dn();en();Ce.CreateGround=Uy;Ce.CreateTiledGround=NG;Ce.CreateGroundFromHeightMap=wG;q.CreateGround=(n,e,t,i,r,s)=>Vy(n,{width:e,height:t,subdivisions:i,updatable:s},r);q.CreateTiledGround=(n,e,t,i,r,s,a,o,l)=>Gy(n,{xmin:e,zmin:t,xmax:i,zmax:r,subdivisions:s,precision:a,updatable:l},o);q.CreateGroundFromHeightMap=(n,e,t,i,r,s,a,o,l,c,f)=>ky(n,e,{width:t,height:i,subdivisions:r,minHeight:s,maxHeight:a,updatable:l,onReady:c,alphaFilter:f},o)});function HA(n){let t=[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23],i=[0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0],r=[],s=n.width||n.size||1,a=n.height||n.size||1,o=n.depth||n.size||1,l=n.wrap||!1,c=n.topBaseAt===void 0?1:n.topBaseAt,f=n.bottomBaseAt===void 0?0:n.bottomBaseAt;c=(c+4)%4,f=(f+4)%4;let h=[2,0,3,1],d=[2,0,1,3],u=h[c],m=d[f],p=[1,-1,1,-1,-1,1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,-1,1,-1,1,1,1,1,-1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,1,1,-1,1,1,1,1,-1,1,1,-1,-1,-1,-1,-1,-1,-1,1];if(l){t=[2,3,0,2,0,1,4,5,6,4,6,7,9,10,11,9,11,8,12,14,15,12,13,14],p=[-1,1,1,1,1,1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,1,1,1,-1,1,-1,-1,1,-1,1,-1,1,-1,-1,1,1,-1,-1,1,-1,-1,-1];let R=[[1,1,1],[-1,1,1],[-1,1,-1],[1,1,-1]],I=[[-1,-1,1],[1,-1,1],[1,-1,-1],[-1,-1,-1]],y=[17,18,19,16],M=[22,23,20,21];for(;u>0;)R.unshift(R.pop()),y.unshift(y.pop()),u--;for(;m>0;)I.unshift(I.pop()),M.unshift(M.pop()),m--;R=R.flat(),I=I.flat(),p=p.concat(R).concat(I),t.push(y[0],y[2],y[3],y[0],y[1],y[2]),t.push(M[0],M[2],M[3],M[0],M[1],M[2])}let _=[s/2,a/2,o/2],g=p.reduce((R,I,y)=>R.concat(I*_[y%3]),[]),v=n.sideOrientation===0?0:n.sideOrientation||Ce.DEFAULTSIDE,x=n.faceUV||new Array(6),A=n.faceColors,S=[];for(let R=0;R<6;R++)x[R]===void 0&&(x[R]=new bi(0,0,1,1)),A&&A[R]===void 0&&(A[R]=new lt(1,1,1,1));for(let R=0;R<6;R++)if(r.push(x[R].z,Mt?1-x[R].w:x[R].w),r.push(x[R].x,Mt?1-x[R].w:x[R].w),r.push(x[R].x,Mt?1-x[R].y:x[R].y),r.push(x[R].z,Mt?1-x[R].y:x[R].y),A)for(let I=0;I<4;I++)S.push(A[R].r,A[R].g,A[R].b,A[R].a);Ce._ComputeSides(v,g,t,i,r,n.frontUVs,n.backUVs);let E=new Ce;if(E.indices=t,E.positions=g,E.normals=i,E.uvs=r,A){let R=v===Ce.DOUBLESIDE?S.concat(S):S;E.colors=R}return E}function Hy(n,e={},t=null){let i=new q(n,t);return e.sideOrientation=q._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,HA(e).applyToMesh(i,e.updatable),i}var zy=C(()=>{Ge();zt();Mi();dr();en();Wy();Ce.CreateBox=HA;q.CreateBox=(n,e,t=null,i,r)=>Hy(n,{size:e,sideOrientation:r,updatable:i},t)});function Gm(n){let e=n.pattern||q.NO_FLIP,t=n.tileWidth||n.tileSize||1,i=n.tileHeight||n.tileSize||1,r=n.alignHorizontal||0,s=n.alignVertical||0,a=n.width||n.size||1,o=Math.floor(a/t),l=a-o*t,c=n.height||n.size||1,f=Math.floor(c/i),h=c-f*i,d=t*o/2,u=i*f/2,m=0,p=0,_=0,g=0,v=0,x=0;if(l>0||h>0){switch(_=-d,g=-u,v=d,x=u,r){case q.CENTER:l/=2,_-=l,v+=l;break;case q.LEFT:v+=l,m=-l/2;break;case q.RIGHT:_-=l,m=l/2;break}switch(s){case q.CENTER:h/=2,g-=h,x+=h;break;case q.BOTTOM:x+=h,p=-h/2;break;case q.TOP:g-=h,p=h/2;break}}let A=[],S=[],E=[];E[0]=[0,0,1,0,1,1,0,1],E[1]=[0,0,1,0,1,1,0,1],(e===q.ROTATE_TILE||e===q.ROTATE_ROW)&&(E[1]=[1,1,0,1,0,0,1,0]),(e===q.FLIP_TILE||e===q.FLIP_ROW)&&(E[1]=[1,0,0,0,0,1,1,1]),(e===q.FLIP_N_ROTATE_TILE||e===q.FLIP_N_ROTATE_ROW)&&(E[1]=[0,1,1,1,1,0,0,0]);let R=[],I=[],y=[],M=0;for(let N=0;N0||h>0){let N=h>0&&(s===q.CENTER||s===q.TOP),F=h>0&&(s===q.CENTER||s===q.BOTTOM),U=l>0&&(r===q.CENTER||r===q.RIGHT),G=l>0&&(r===q.CENTER||r===q.LEFT),ee,j,Z,X,Y;if(N&&U&&(A.push(_+m,g+p,0),A.push(-d+m,g+p,0),A.push(-d+m,g+h+p,0),A.push(_+m,g+h+p,0),y.push(M,M+1,M+3,M+1,M+2,M+3),M+=4,j=1-l/t,Z=1-h/i,X=1,Y=1,ee=[j,Z,X,Z,X,Y,j,Y],e===q.ROTATE_ROW&&(ee=[1-j,1-Z,1-X,1-Z,1-X,1-Y,1-j,1-Y]),e===q.FLIP_ROW&&(ee=[1-j,Z,1-X,Z,1-X,Y,1-j,Y]),e===q.FLIP_N_ROTATE_ROW&&(ee=[j,1-Z,X,1-Z,X,1-Y,j,1-Y]),R=R.concat(ee),I.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),N&&G&&(A.push(d+m,g+p,0),A.push(v+m,g+p,0),A.push(v+m,g+h+p,0),A.push(d+m,g+h+p,0),y.push(M,M+1,M+3,M+1,M+2,M+3),M+=4,j=0,Z=1-h/i,X=l/t,Y=1,ee=[j,Z,X,Z,X,Y,j,Y],(e===q.ROTATE_ROW||e===q.ROTATE_TILE&&o%2===0)&&(ee=[1-j,1-Z,1-X,1-Z,1-X,1-Y,1-j,1-Y]),(e===q.FLIP_ROW||e===q.FLIP_TILE&&o%2===0)&&(ee=[1-j,Z,1-X,Z,1-X,Y,1-j,Y]),(e===q.FLIP_N_ROTATE_ROW||e===q.FLIP_N_ROTATE_TILE&&o%2===0)&&(ee=[j,1-Z,X,1-Z,X,1-Y,j,1-Y]),R=R.concat(ee),I.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),F&&U&&(A.push(_+m,u+p,0),A.push(-d+m,u+p,0),A.push(-d+m,x+p,0),A.push(_+m,x+p,0),y.push(M,M+1,M+3,M+1,M+2,M+3),M+=4,j=1-l/t,Z=0,X=1,Y=h/i,ee=[j,Z,X,Z,X,Y,j,Y],(e===q.ROTATE_ROW&&f%2===1||e===q.ROTATE_TILE&&f%1===0)&&(ee=[1-j,1-Z,1-X,1-Z,1-X,1-Y,1-j,1-Y]),(e===q.FLIP_ROW&&f%2===1||e===q.FLIP_TILE&&f%2===0)&&(ee=[1-j,Z,1-X,Z,1-X,Y,1-j,Y]),(e===q.FLIP_N_ROTATE_ROW&&f%2===1||e===q.FLIP_N_ROTATE_TILE&&f%2===0)&&(ee=[j,1-Z,X,1-Z,X,1-Y,j,1-Y]),R=R.concat(ee),I.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),F&&G&&(A.push(d+m,u+p,0),A.push(v+m,u+p,0),A.push(v+m,x+p,0),A.push(d+m,x+p,0),y.push(M,M+1,M+3,M+1,M+2,M+3),M+=4,j=0,Z=0,X=l/t,Y=h/i,ee=[j,Z,X,Z,X,Y,j,Y],(e===q.ROTATE_ROW&&f%2===1||e===q.ROTATE_TILE&&(f+o)%2===1)&&(ee=[1-j,1-Z,1-X,1-Z,1-X,1-Y,1-j,1-Y]),(e===q.FLIP_ROW&&f%2===1||e===q.FLIP_TILE&&(f+o)%2===1)&&(ee=[1-j,Z,1-X,Z,1-X,Y,1-j,Y]),(e===q.FLIP_N_ROTATE_ROW&&f%2===1||e===q.FLIP_N_ROTATE_TILE&&(f+o)%2===1)&&(ee=[j,1-Z,X,1-Z,X,1-Y,j,1-Y]),R=R.concat(ee),I.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),N){let ue=[];j=0,Z=1-h/i,X=1,Y=1,ue[0]=[j,Z,X,Z,X,Y,j,Y],ue[1]=[j,Z,X,Z,X,Y,j,Y],(e===q.ROTATE_TILE||e===q.ROTATE_ROW)&&(ue[1]=[1-j,1-Z,1-X,1-Z,1-X,1-Y,1-j,1-Y]),(e===q.FLIP_TILE||e===q.FLIP_ROW)&&(ue[1]=[1-j,Z,1-X,Z,1-X,Y,1-j,Y]),(e===q.FLIP_N_ROTATE_TILE||e===q.FLIP_N_ROTATE_ROW)&&(ue[1]=[j,1-Z,X,1-Z,X,1-Y,j,1-Y]);for(let Re=0;Re{Mi();dr();Ce.CreateTiledPlane=Gm});function BG(n){let t=n.faceUV||new Array(6),i=n.faceColors,r=n.pattern||q.NO_FLIP,s=n.width||n.size||1,a=n.height||n.size||1,o=n.depth||n.size||1,l=n.tileWidth||n.tileSize||1,c=n.tileHeight||n.tileSize||1,f=n.alignHorizontal||0,h=n.alignVertical||0,d=n.sideOrientation===0?0:n.sideOrientation||Ce.DEFAULTSIDE;for(let N=0;N<6;N++)t[N]===void 0&&(t[N]=new bi(0,0,1,1)),i&&i[N]===void 0&&(i[N]=new lt(1,1,1,1));let u=s/2,m=a/2,p=o/2,_=[];for(let N=0;N<2;N++)_[N]=Gm({pattern:r,tileWidth:l,tileHeight:c,width:s,height:a,alignVertical:h,alignHorizontal:f,sideOrientation:d});for(let N=2;N<4;N++)_[N]=Gm({pattern:r,tileWidth:l,tileHeight:c,width:o,height:a,alignVertical:h,alignHorizontal:f,sideOrientation:d});let g=h;h===q.BOTTOM?g=q.TOP:h===q.TOP&&(g=q.BOTTOM);for(let N=4;N<6;N++)_[N]=Gm({pattern:r,tileWidth:l,tileHeight:c,width:s,height:o,alignVertical:g,alignHorizontal:f,sideOrientation:d});let v=[],x=[],A=[],S=[],E=[],R=[],I=[],y=[],M,D=0;for(let N=0;N<6;N++){let F=_[N].positions.length;R[N]=[],I[N]=[];for(let U=0;UU+D)),D+=R[N].length,i){let U=i[N];for(let G=0;G{Ge();zt();Mi();dr();Xy();en();zA=1,Yy=-1;Ce.CreateTiledBox=BG});function GG(n){let e=(n.segments||32)|0,t=n.diameterX||n.diameter||1,i=n.diameterY||n.diameter||1,r=n.diameterZ||n.diameter||1,s=n.arc&&(n.arc<=0||n.arc>1)?1:n.arc||1,a=n.slice&&n.slice<=0?1:n.slice||1,o=n.sideOrientation===0?0:n.sideOrientation||Ce.DEFAULTSIDE,l=!!n.dedupTopBottomIndices,c=new b(t/2,i/2,r/2),f=2+e,h=2*f,d=[],u=[],m=[],p=[];for(let g=0;g<=f;g++){let v=g/f,x=v*Math.PI*a;for(let A=0;A<=h;A++){let S=A/h,E=S*Math.PI*2*s,R=K.RotationZ(-x),I=K.RotationY(E),y=b.TransformCoordinates(b.Up(),R),M=b.TransformCoordinates(y,I),D=M.multiply(c),O=M.divide(c).normalize();u.push(D.x,D.y,D.z),m.push(O.x,O.y,O.z),p.push(S,Mt?1-v:v)}if(g>0){let A=u.length/3;for(let S=A-2*(h+1);S+h+21&&(d.push(S),d.push(S+1),d.push(S+h+1)),(g{Ge();Mi();dr();en();Ce.CreateSphere=GG;q.CreateSphere=(n,e,t,i,r,s)=>Ky(n,{segments:e,diameterX:t,diameterY:t,diameterZ:t,sideOrientation:s,updatable:r},i)});function WG(n){let e=n.height||2,t=n.diameterTop===0?0:n.diameterTop||n.diameter||1,i=n.diameterBottom===0?0:n.diameterBottom||n.diameter||1;t=t||1e-5,i=i||1e-5;let r=(n.tessellation||24)|0,s=(n.subdivisions||1)|0,a=!!n.hasRings,o=!!n.enclose,l=n.cap===0?0:n.cap||q.CAP_ALL,c=n.arc&&(n.arc<=0||n.arc>1)?1:n.arc||1,f=n.sideOrientation===0?0:n.sideOrientation||Ce.DEFAULTSIDE,h=n.faceUV||new Array(3),d=n.faceColors,u=c!==1&&o?2:0,m=a?s:1,p=2+(1+u)*m,_;for(_=0;_{let re=me?t/2:i/2;if(re===0)return;let de,De,he,Ie=me?h[p-1]:h[0],ze=null;d&&(ze=me?d[p-1]:d[0]);let St=v.length/3,Ye=me?e/2:-e/2,je=new b(0,Ye,0);v.push(je.x,je.y,je.z),x.push(0,me?1:-1,0);let $t=Ie.y+(Ie.w-Ie.y)*.5;A.push(Ie.x+(Ie.z-Ie.x)*.5,Mt?1-$t:$t),ze&&S.push(ze.r,ze.g,ze.b,ze.a);let Lt=new we(.5,.5);for(he=0;he<=r;he++){de=Math.PI*2*he*c/r;let xi=Math.cos(-de),oe=Math.sin(-de);De=new b(xi*re,Ye,oe*re);let Ui=new we(xi*Lt.x+.5,oe*Lt.y+.5);v.push(De.x,De.y,De.z),x.push(0,me?1:-1,0);let ti=Ie.y+(Ie.w-Ie.y)*Ui.y;A.push(Ie.x+(Ie.z-Ie.x)*Ui.x,Mt?1-ti:ti),ze&&S.push(ze.r,ze.g,ze.b,ze.a)}for(he=0;he{Ge();zt();Mi();dr();As();zu();en();Ce.CreateCylinder=WG;q.CreateCylinder=(n,e,t,i,r,s,a,o,l)=>((a===void 0||!(a instanceof Jt))&&(a!==void 0&&(l=o||q.DEFAULTSIDE,o=a),a=s,s=1),jy(n,{height:e,diameterTop:t,diameterBottom:i,tessellation:r,subdivisions:s,sideOrientation:l,updatable:o},a))});function zG(n){let e=[],t=[],i=[],r=[],s=n.diameter||1,a=n.thickness||.5,o=(n.tessellation||16)|0,l=n.sideOrientation===0?0:n.sideOrientation||Ce.DEFAULTSIDE,c=o+1;for(let h=0;h<=o;h++){let d=h/o,u=h*Math.PI*2/o-Math.PI/2,m=K.Translation(s/2,0,0).multiply(K.RotationY(u));for(let p=0;p<=o;p++){let _=1-p/o,g=p*Math.PI*2/o+Math.PI,v=Math.cos(g),x=Math.sin(g),A=new b(v,x,0),S=A.scale(a/2),E=new we(d,_);S=b.TransformCoordinates(S,m),A=b.TransformNormal(A,m),t.push(S.x,S.y,S.z),i.push(A.x,A.y,A.z),r.push(E.x,Mt?1-E.y:E.y);let R=(h+1)%c,I=(p+1)%c;e.push(h*c+p),e.push(h*c+I),e.push(R*c+p),e.push(h*c+I),e.push(R*c+I),e.push(R*c+p)}}Ce._ComputeSides(l,t,e,i,r,n.frontUVs,n.backUVs);let f=new Ce;return f.indices=e,f.positions=t,f.normals=i,f.uvs=r,f}function qy(n,e={},t){let i=new q(n,t);return e.sideOrientation=q._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,zG(e).applyToMesh(i,e.updatable),i}var XG=C(()=>{Ge();Mi();dr();en();Ce.CreateTorus=zG;q.CreateTorus=(n,e,t,i,r,s,a)=>qy(n,{diameter:e,thickness:t,tessellation:i,sideOrientation:a,updatable:s},r)});function YG(n){let e=[],t=[],i=[],r=[],s=n.radius||2,a=n.tube||.5,o=n.radialSegments||32,l=n.tubularSegments||32,c=n.p||2,f=n.q||3,h=n.sideOrientation===0?0:n.sideOrientation||Ce.DEFAULTSIDE,d=_=>{let g=Math.cos(_),v=Math.sin(_),x=f/c*_,A=Math.cos(x),S=s*(2+A)*.5*g,E=s*(2+A)*v*.5,R=s*Math.sin(x)*.5;return new b(S,E,R)},u,m;for(u=0;u<=o;u++){let g=u%o/o*2*c*Math.PI,v=d(g),x=d(g+.01),A=x.subtract(v),S=x.add(v),E=b.Cross(A,S);for(S=b.Cross(E,A),E.normalize(),S.normalize(),m=0;m{Ge();Mi();dr();en();Ce.CreateTorusKnot=YG;q.CreateTorusKnot=(n,e,t,i,r,s,a,o,l,c)=>Zy(n,{radius:e,tube:t,radialSegments:i,tubularSegments:r,p:s,q:a,sideOrientation:c,updatable:l},o)});var tc,Qy=C(()=>{Ge();Pt();_m();Mi();W_();qh();ki();Ii();Hi();q._instancedMeshFactory=(n,e)=>{let t=new tc(n,e);if(e.instancedBuffers){t.instancedBuffers={};for(let i in e.instancedBuffers)t.instancedBuffers[i]=e.instancedBuffers[i]}return t};tc=class extends vr{constructor(e,t){super(e,t.getScene()),this._indexInSourceMeshInstanceArray=-1,this._distanceToCamera=0,t.addInstance(this),this._sourceMesh=t,this._unIndexed=t._unIndexed,this.position.copyFrom(t.position),this.rotation.copyFrom(t.rotation),this.scaling.copyFrom(t.scaling),t.rotationQuaternion&&(this.rotationQuaternion=t.rotationQuaternion.clone()),this.animations=t.animations.slice();for(let i of t.getAnimationRanges())i!=null&&this.createAnimationRange(i.name,i.from,i.to);if(this.infiniteDistance=t.infiniteDistance,this.setPivotMatrix(t.getPivotMatrix()),!t.skeleton&&!t.morphTargetManager&&t.hasBoundingInfo){let i=t.getBoundingInfo();this.buildBoundingInfo(i.minimum,i.maximum)}else this.refreshBoundingInfo(!0,!0);this._syncSubMeshes()}getClassName(){return"InstancedMesh"}get lightSources(){return this._sourceMesh._lightSources}_resyncLightSources(){}_resyncLightSource(){}_removeLightSource(){}get receiveShadows(){return this._sourceMesh.receiveShadows}set receiveShadows(e){var t;((t=this._sourceMesh)==null?void 0:t.receiveShadows)!==e&&_e.Warn("Setting receiveShadows on an instanced mesh has no effect")}get material(){return this._sourceMesh.material}set material(e){var t;((t=this._sourceMesh)==null?void 0:t.material)!==e&&_e.Warn("Setting material on an instanced mesh has no effect")}get visibility(){return this._sourceMesh.visibility}set visibility(e){var t;((t=this._sourceMesh)==null?void 0:t.visibility)!==e&&_e.Warn("Setting visibility on an instanced mesh has no effect")}get skeleton(){return this._sourceMesh.skeleton}set skeleton(e){var t;((t=this._sourceMesh)==null?void 0:t.skeleton)!==e&&_e.Warn("Setting skeleton on an instanced mesh has no effect")}get renderingGroupId(){return this._sourceMesh.renderingGroupId}set renderingGroupId(e){!this._sourceMesh||e===this._sourceMesh.renderingGroupId||te.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene")}getTotalVertices(){return this._sourceMesh?this._sourceMesh.getTotalVertices():0}getTotalIndices(){return this._sourceMesh.getTotalIndices()}get sourceMesh(){return this._sourceMesh}get geometry(){return this._sourceMesh._geometry}createInstance(e){return this._sourceMesh.createInstance(e)}isReady(e=!1){return this._sourceMesh.isReady(e,!0)}getVerticesData(e,t,i){return this._sourceMesh.getVerticesData(e,t,i)}copyVerticesData(e,t){this._sourceMesh.copyVerticesData(e,t)}getVertexBuffer(e,t){return this._sourceMesh.getVertexBuffer(e,t)}setVerticesData(e,t,i,r){return this.sourceMesh&&this.sourceMesh.setVerticesData(e,t,i,r),this.sourceMesh}updateVerticesData(e,t,i,r){return this.sourceMesh&&this.sourceMesh.updateVerticesData(e,t,i,r),this.sourceMesh}setIndices(e,t=null){return this.sourceMesh&&this.sourceMesh.setIndices(e,t),this.sourceMesh}isVerticesDataPresent(e){return this._sourceMesh.isVerticesDataPresent(e)}getIndices(){return this._sourceMesh.getIndices()}get _positions(){return this._sourceMesh._positions}refreshBoundingInfo(e=!1,t=!1){if(this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;let i;typeof e=="object"?i=e:i={applySkeleton:e,applyMorph:t};let r=this._sourceMesh.geometry?this._sourceMesh.geometry.boundingBias:null;return this._refreshBoundingInfo(this._sourceMesh._getData(i,null,L.PositionKind),r),this}_preActivate(){return this._currentLOD&&this._currentLOD._preActivate(),this}_activate(e,t){if(super._activate(e,t),this._sourceMesh.subMeshes||te.Warn("Instances should only be created for meshes with geometry."),this._currentLOD){if(this._currentLOD._getWorldMatrixDeterminant()>=0!=this._getWorldMatrixDeterminant()>=0)return this._internalAbstractMeshDataInfo._actAsRegularMesh=!0,!0;if(this._internalAbstractMeshDataInfo._actAsRegularMesh=!1,this._currentLOD._registerInstanceForRenderId(this,e),t){if(!this._currentLOD._internalAbstractMeshDataInfo._isActiveIntermediate)return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstancesIntermediate=!0,!0}else if(!this._currentLOD._internalAbstractMeshDataInfo._isActive)return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstances=!0,!0}return!1}_postActivate(){this._sourceMesh.edgesShareWithInstances&&this._sourceMesh._edgesRenderer&&this._sourceMesh._edgesRenderer.isEnabled&&this._sourceMesh._renderingGroup?(this._sourceMesh._renderingGroup._edgesRenderers.pushNoDuplicate(this._sourceMesh._edgesRenderer),this._sourceMesh._edgesRenderer.customInstances.push(this.getWorldMatrix())):this._edgesRenderer&&this._edgesRenderer.isEnabled&&this._sourceMesh._renderingGroup&&this._sourceMesh._renderingGroup._edgesRenderers.push(this._edgesRenderer)}getWorldMatrix(){if(this._currentLOD&&this._currentLOD!==this._sourceMesh&&this._currentLOD.billboardMode!==ei.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new K);let e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,$.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom($.Vector3[7]),this._currentLOD._masterMesh=e,this._billboardWorldMatrix}return super.getWorldMatrix()}get isAnInstance(){return!0}getLOD(e){if(!e)return this;let t=this.sourceMesh.getLODLevels();if(!t||t.length===0)this._currentLOD=this.sourceMesh;else{let i=this.getBoundingInfo();this._currentLOD=this.sourceMesh.getLOD(e,i.boundingSphere)}return this._currentLOD}_preActivateForIntermediateRendering(e){return this.sourceMesh._preActivateForIntermediateRendering(e)}_syncSubMeshes(){if(this.releaseSubMeshes(),this._sourceMesh.subMeshes)for(let e=0;e{Wn=class{constructor(){this._defines={},this._currentRank=32,this._maxRank=-1,this._mesh=null}unBindMesh(){this._mesh=null}addFallback(e,t){this._defines[e]||(ethis._maxRank&&(this._maxRank=e),this._defines[e]=new Array),this._defines[e].push(t)}addCPUSkinningFallback(e,t){this._mesh=t,ethis._maxRank&&(this._maxRank=e)}get hasMoreFallbacks(){return this._currentRank<=this._maxRank}reduce(e,t){if(this._mesh&&this._mesh.computeBonesUsingShaders&&this._mesh.numBoneInfluencers>0){this._mesh.computeBonesUsingShaders=!1,e=e.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),t._bonesComputationForcedToCPU=!0;let i=this._mesh.getScene();for(let r=0;r0&&(s.computeBonesUsingShaders=!1);continue}if(!(!s.computeBonesUsingShaders||s.numBoneInfluencers===0)){if(s.material.getEffect()===t)s.computeBonesUsingShaders=!1;else if(s.subMeshes){for(let a of s.subMeshes)if(a.effect===t){s.computeBonesUsingShaders=!1;break}}}}}else{let i=this._defines[this._currentRank];if(i)for(let r=0;r{Ge();Vn();hl=class extends Ee{constructor(e,t,i=!0,r=!1){super(e,t,void 0,r),this._normalMatrix=new K,this._storeEffectOnSubMeshes=i}getEffect(){return this._storeEffectOnSubMeshes?this._activeEffect:super.getEffect()}isReady(e,t){return e?!this._storeEffectOnSubMeshes||!e.subMeshes||e.subMeshes.length===0?!0:this.isReadyForSubMesh(e,e.subMeshes[0],t):!1}_isReadyForSubMesh(e){let t=e.materialDefines;return!!(!this.checkReadyOnEveryCall&&e.effect&&t&&t._renderId===this.getScene().getRenderId())}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindOnlyNormalMatrix(e){this._activeEffect.setMatrix("normalMatrix",e)}bind(e,t){t&&this.bindForSubMesh(e,t,t.subMeshes[0])}_afterBind(e,t=null,i){super._afterBind(e,t,i),this.getScene()._cachedEffect=t,i?i._drawWrapper._forceRebindOnNextCall=!1:this._drawWrapper._forceRebindOnNextCall=!1}_mustRebind(e,t,i,r=1){return i._drawWrapper._forceRebindOnNextCall||e.isCachedMaterialInvalid(this,t,r)}dispose(e,t,i){this._activeEffect=void 0,super.dispose(e,t,i)}}});function Lf(n){let e=n.getVertexBuffers();if(!e)return null;let t=jG.get(n);if(!t)t=new Map,jG.set(n,t);else{let i=!1;for(let r in e)if(!t.has(r)){i=!0;break}if(!i)return t}for(let i in e){let r=e[i];if(r){let s=r.byteOffset,a=r.byteStride,o=r.type,l=r.normalized;t.set(i,{offset:s,stride:a,type:o,normalized:l})}}return t}function Of(n,e){e.forEach((t,i)=>{let r=`vp_${i}_info`;n.setFloat4(r,t.offset,t.stride,t.type,t.normalized?1:0)})}var jG,_g=C(()=>{jG=new WeakMap});var $y,vo,Jy=C(()=>{Tr();As();Ge();ki();Fr();Hi();Df();Bh();pg();Di();ol();Un();_g();$y={effect:null,subMesh:null},vo=class n extends hl{constructor(e,t,i,r={},s=!0){super(e,t,s),this._textures={},this._internalTextures={},this._textureArrays={},this._externalTextures={},this._floats={},this._ints={},this._uints={},this._floatsArrays={},this._colors3={},this._colors3Arrays={},this._colors4={},this._colors4Arrays={},this._vectors2={},this._vectors3={},this._vectors4={},this._quaternions={},this._quaternionsArrays={},this._matrices={},this._matrixArrays={},this._matrices3x3={},this._matrices2x2={},this._vectors2Arrays={},this._vectors3Arrays={},this._vectors4Arrays={},this._uniformBuffers={},this._textureSamplers={},this._storageBuffers={},this._cachedWorldViewMatrix=new K,this._cachedWorldViewProjectionMatrix=new K,this._multiview=!1,this._vertexPullingMetadata=null,this._materialHelperNeedsPreviousMatrices=!1,this._shaderPath=i,this._options={needAlphaBlending:!1,needAlphaTesting:!1,attributes:["position","normal","uv"],uniforms:["worldViewProjection"],uniformBuffers:[],samplers:[],externalTextures:[],samplerObjects:[],storageBuffers:[],defines:[],useClipPlane:!1,...r}}get shaderPath(){return this._shaderPath}set shaderPath(e){this._shaderPath=e}get options(){return this._options}get isMultiview(){return this._multiview}getClassName(){return"ShaderMaterial"}needAlphaBlending(){return this.alpha<1||this._options.needAlphaBlending}needAlphaTesting(){return this._options.needAlphaTesting}_checkUniform(e){this._options.uniforms.indexOf(e)===-1&&this._options.uniforms.push(e)}setTexture(e,t){return this._options.samplers.indexOf(e)===-1&&this._options.samplers.push(e),this._textures[e]=t,this}setInternalTexture(e,t){return this._options.samplers.indexOf(e)===-1&&this._options.samplers.push(e),this._internalTextures[e]=t,this}removeTexture(e){delete this._textures[e]}setTextureArray(e,t){return this._options.samplers.indexOf(e)===-1&&this._options.samplers.push(e),this._checkUniform(e),this._textureArrays[e]=t,this}setExternalTexture(e,t){return this._options.externalTextures.indexOf(e)===-1&&this._options.externalTextures.push(e),this._externalTextures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setUInt(e,t){return this._checkUniform(e),this._uints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor3Array(e,t){return this._checkUniform(e),this._colors3Arrays[e]=t.reduce((i,r)=>(i.push(r.r,r.g,r.b),i),[]),this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setColor4Array(e,t){return this._checkUniform(e),this._colors4Arrays[e]=t.reduce((i,r)=>(i.push(r.r,r.g,r.b,r.a),i),[]),this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setVector4(e,t){return this._checkUniform(e),this._vectors4[e]=t,this}setQuaternion(e,t){return this._checkUniform(e),this._quaternions[e]=t,this}setQuaternionArray(e,t){return this._checkUniform(e),this._quaternionsArrays[e]=t.reduce((i,r)=>(r.toArray(i,i.length),i),[]),this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}setMatrices(e,t){this._checkUniform(e);let i=new Float32Array(t.length*16);for(let r=0;rs===e||s.startsWith(i));return r>=0&&this.options.defines.splice(r,1),(typeof t!="boolean"||t)&&this.options.defines.push(i+t),this}isReadyForSubMesh(e,t,i){return this.isReady(e,i,t)}isReady(e,t,i){var E,R,I,y;let r=i&&this._storeEffectOnSubMeshes;if(this.isFrozen){let M=r?i._drawWrapper:this._drawWrapper;if(M.effect&&M._wasPreviouslyReady&&M._wasPreviouslyUsingInstances===t)return!0}let s=this.getScene(),a=s.getEngine(),o=[],l=[],c=null,f=this._shaderPath,h=this._options.uniforms,d=this._options.uniformBuffers,u=this._options.samplers;a.getCaps().multiview&&s.activeCamera&&s.activeCamera.outputRenderTarget&&s.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,o.push("#define MULTIVIEW"),h.indexOf("viewProjection")!==-1&&h.indexOf("viewProjectionR")===-1&&h.push("viewProjectionR"));for(let M=0;M4&&(l.push(L.MatricesIndicesExtraKind),l.push(L.MatricesWeightsExtraKind));let M=e.skeleton;o.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),c=new Wn,c.addCPUSkinningFallback(0,e),M.isUsingTextureForMatrices?(o.push("#define BONETEXTURE"),h.indexOf("boneTextureInfo")===-1&&h.push("boneTextureInfo"),this._options.samplers.indexOf("boneSampler")===-1&&this._options.samplers.push("boneSampler")):(o.push("#define BonesPerMesh "+(M.bones.length+1)),h.indexOf("mBones")===-1&&h.push("mBones"))}else o.push("#define NUM_BONE_INFLUENCERS 0");let m=0,p=e?e.morphTargetManager:null;if(p){let M=o.indexOf("#define UV1")!==-1,D=o.indexOf("#define UV2")!==-1,O=o.indexOf("#define TANGENT")!==-1,V=o.indexOf("#define NORMAL")!==-1,N=o.indexOf("#define VERTEXCOLOR")!==-1;m=ll(p,o,l,e,!0,V,O,M,D,N),p.isUsingTextureForTargets&&(h.indexOf("morphTargetTextureIndices")===-1&&h.push("morphTargetTextureIndices"),this._options.samplers.indexOf("morphTargets")===-1&&this._options.samplers.push("morphTargets")),m>0&&(h=h.slice(),h.push("morphTargetInfluences"),h.push("morphTargetCount"),h.push("morphTargetTextureInfo"),h.push("morphTargetTextureIndices"))}else o.push("#define NUM_MORPH_INFLUENCERS 0");if(e){let M=e.bakedVertexAnimationManager;M&&M.isEnabled&&(o.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),h.indexOf("bakedVertexAnimationSettings")===-1&&h.push("bakedVertexAnimationSettings"),h.indexOf("bakedVertexAnimationTextureSizeInverted")===-1&&h.push("bakedVertexAnimationTextureSizeInverted"),h.indexOf("bakedVertexAnimationTime")===-1&&h.push("bakedVertexAnimationTime"),this._options.samplers.indexOf("bakedVertexAnimationTexture")===-1&&this._options.samplers.push("bakedVertexAnimationTexture"),t&&l.push("bakedVertexAnimationSettingsInstanced"))}for(let M in this._textures)if(!this._textures[M].isReady())return!1;for(let M in this._internalTextures)if(!this._internalTextures[M].isReady)return!1;e&&this.needAlphaTestingForMesh(e)&&o.push("#define ALPHATEST"),this._options.useClipPlane!==!1&&(wn(h),al(this,s,o)),s.fogEnabled&&(e!=null&&e.applyFog)&&s.fogMode!==Jt.FOGMODE_NONE&&(o.push("#define FOG"),h.indexOf("view")===-1&&h.push("view"),h.indexOf("vFogInfos")===-1&&h.push("vFogInfos"),h.indexOf("vFogColor")===-1&&h.push("vFogColor")),this._useLogarithmicDepth&&(o.push("#define LOGARITHMICDEPTH"),h.indexOf("logarithmicDepthConstant")===-1&&h.push("logarithmicDepthConstant"));let _=i?i.getRenderingMesh():e;if(_&&this.useVertexPulling){let M=_.geometry;M&&(this._vertexPullingMetadata=Lf(M),this._vertexPullingMetadata&&this._vertexPullingMetadata.forEach((O,V)=>{h.push(`vp_${V}_info`)})),o.push("#define USE_VERTEX_PULLING");let D=(E=_.geometry)==null?void 0:E.getIndexBuffer();D&&!_.isUnIndexed&&(o.push("#define VERTEX_PULLING_USE_INDEX_BUFFER"),D.is32Bits&&o.push("#define VERTEX_PULLING_INDEX_BUFFER_32BITS"))}this.customShaderNameResolve&&(h=h.slice(),d=d.slice(),u=u.slice(),f=this.customShaderNameResolve(this.name,h,d,u,o,l));let g=r?i._getDrawWrapper(void 0,!0):this._drawWrapper,v=(R=g==null?void 0:g.effect)!=null?R:null,x=(I=g==null?void 0:g.defines)!=null?I:null,A=o.join(` +`),S=v;return x!==A&&(S=a.createEffect(f,{attributes:l,uniformsNames:h,uniformBuffersNames:d,samplers:u,defines:A,fallbacks:c,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:m},shaderLanguage:this._options.shaderLanguage,extraInitializationsAsync:this._options.extraInitializationsAsync},a),r?i.setEffect(S,A,this._materialContext):g&&g.setEffect(S,A),this._onEffectCreatedObservable&&($y.effect=S,$y.subMesh=(y=i!=null?i:e==null?void 0:e.subMeshes[0])!=null?y:null,this._onEffectCreatedObservable.notifyObservers($y))),g._wasPreviouslyUsingInstances=!!t,S!=null&&S.isReady()?(v!==S&&s.resetCachedMaterial(),g._wasPreviouslyReady=!0,!0):!1}bindOnlyWorldMatrix(e,t){let i=t!=null?t:this.getEffect();if(!i)return;let r=this._options.uniforms;r.indexOf("world")!==-1&&i.setMatrix("world",e);let s=this.getScene();r.indexOf("worldView")!==-1&&(e.multiplyToRef(s.getViewMatrix(),this._cachedWorldViewMatrix),i.setMatrix("worldView",this._cachedWorldViewMatrix)),r.indexOf("worldViewProjection")!==-1&&(e.multiplyToRef(s.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),i.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)),r.indexOf("view")!==-1&&i.setMatrix("view",s.getViewMatrix())}bindForSubMesh(e,t,i){var r;this.bind(e,t,(r=i._drawWrapperOverride)==null?void 0:r.effect,i)}bind(e,t,i,r){var h;let s=r&&this._storeEffectOnSubMeshes,a=i!=null?i:s?r.effect:this.getEffect();if(!a)return;let o=this.getScene();this._activeEffect=a,this.bindOnlyWorldMatrix(e,i);let l=this._options.uniformBuffers,c=!1;if(a&&l&&l.length>0&&o.getEngine().supportsUniformBuffers)for(let d=0;dnew n(e,this.getScene(),this._shaderPath,this._options,this._storeEffectOnSubMeshes),this);t.name=e,t.id=e,typeof t._shaderPath=="object"&&(t._shaderPath={...t._shaderPath}),this._options={...this._options};let i=Object.keys(this._options);for(let r of i){let s=this._options[r];Array.isArray(s)&&(this._options[r]=s.slice(0))}this.stencil.copyTo(t.stencil);for(let r in this._textures)t.setTexture(r,this._textures[r]);for(let r in this._internalTextures)t.setInternalTexture(r,this._internalTextures[r]);for(let r in this._textureArrays)t.setTextureArray(r,this._textureArrays[r]);for(let r in this._externalTextures)t.setExternalTexture(r,this._externalTextures[r]);for(let r in this._ints)t.setInt(r,this._ints[r]);for(let r in this._uints)t.setUInt(r,this._uints[r]);for(let r in this._floats)t.setFloat(r,this._floats[r]);for(let r in this._floatsArrays)t.setFloats(r,this._floatsArrays[r]);for(let r in this._colors3)t.setColor3(r,this._colors3[r]);for(let r in this._colors3Arrays)t._colors3Arrays[r]=this._colors3Arrays[r];for(let r in this._colors4)t.setColor4(r,this._colors4[r]);for(let r in this._colors4Arrays)t._colors4Arrays[r]=this._colors4Arrays[r];for(let r in this._vectors2)t.setVector2(r,this._vectors2[r]);for(let r in this._vectors3)t.setVector3(r,this._vectors3[r]);for(let r in this._vectors4)t.setVector4(r,this._vectors4[r]);for(let r in this._quaternions)t.setQuaternion(r,this._quaternions[r]);for(let r in this._quaternionsArrays)t._quaternionsArrays[r]=this._quaternionsArrays[r];for(let r in this._matrices)t.setMatrix(r,this._matrices[r]);for(let r in this._matrixArrays)t._matrixArrays[r]=this._matrixArrays[r].slice();for(let r in this._matrices3x3)t.setMatrix3x3(r,this._matrices3x3[r]);for(let r in this._matrices2x2)t.setMatrix2x2(r,this._matrices2x2[r]);for(let r in this._vectors2Arrays)t.setArray2(r,this._vectors2Arrays[r]);for(let r in this._vectors3Arrays)t.setArray3(r,this._vectors3Arrays[r]);for(let r in this._vectors4Arrays)t.setArray4(r,this._vectors4Arrays[r]);for(let r in this._uniformBuffers)t.setUniformBuffer(r,this._uniformBuffers[r]);for(let r in this._textureSamplers)t.setTextureSampler(r,this._textureSamplers[r]);for(let r in this._storageBuffers)t.setStorageBuffer(r,this._storageBuffers[r]);return t}dispose(e,t,i){if(t){let r;for(r in this._textures)this._textures[r].dispose();for(r in this._internalTextures)this._internalTextures[r].dispose();for(r in this._textureArrays){let s=this._textureArrays[r];for(let a=0;anew n(e.name,t,e.shaderPath,e.options,e.storeEffectOnSubMeshes),e,t,i),s;e.stencil&&r.stencil.parse(e.stencil,t,i);for(s in e.textures)r.setTexture(s,ge.Parse(e.textures[s],t,i));for(s in e.textureArrays){let a=e.textureArrays[s],o=[];for(let l=0;l(c%3===0?o.push([l]):o[o.length-1].push(l),o),[]).map(o=>({r:o[0],g:o[1],b:o[2]}));r.setColor3Array(s,a)}for(s in e.colors4){let a=e.colors4[s];r.setColor4(s,{r:a[0],g:a[1],b:a[2],a:a[3]})}for(s in e.colors4Arrays){let a=e.colors4Arrays[s].reduce((o,l,c)=>(c%4===0?o.push([l]):o[o.length-1].push(l),o),[]).map(o=>({r:o[0],g:o[1],b:o[2],a:o[3]}));r.setColor4Array(s,a)}for(s in e.vectors2){let a=e.vectors2[s];r.setVector2(s,{x:a[0],y:a[1]})}for(s in e.vectors3){let a=e.vectors3[s];r.setVector3(s,{x:a[0],y:a[1],z:a[2]})}for(s in e.vectors4){let a=e.vectors4[s];r.setVector4(s,{x:a[0],y:a[1],z:a[2],w:a[3]})}for(s in e.quaternions)r.setQuaternion(s,Xe.FromArray(e.quaternions[s]));for(s in e.matrices)r.setMatrix(s,K.FromArray(e.matrices[s]));for(s in e.matrixArray)r._matrixArrays[s]=new Float32Array(e.matrixArray[s]);for(s in e.matrices3x3)r.setMatrix3x3(s,e.matrices3x3[s]);for(s in e.matrices2x2)r.setMatrix2x2(s,e.matrices2x2[s]);for(s in e.vectors2Arrays)r.setArray2(s,e.vectors2Arrays[s]);for(s in e.vectors3Arrays)r.setArray3(s,e.vectors3Arrays[s]);for(s in e.vectors4Arrays)r.setArray4(s,e.vectors4Arrays[s]);for(s in e.quaternionsArrays)r.setArray4(s,e.quaternionsArrays[s]);return r}static async ParseFromFileAsync(e,t,i,r=""){return await new Promise((s,a)=>{let o=new Ir;o.addEventListener("readystatechange",()=>{if(o.readyState==4)if(o.status==200){let l=JSON.parse(o.responseText),c=this.Parse(l,i||Oe.LastCreatedScene,r);e&&(c.name=e),s(c)}else a("Unable to load the ShaderMaterial")}),o.open("GET",t),o.send()})}static async ParseFromSnippetAsync(e,t,i=""){return await new Promise((r,s)=>{let a=new Ir;a.addEventListener("readystatechange",()=>{if(a.readyState==4)if(a.status==200){let o=JSON.parse(JSON.parse(a.responseText).jsonPayload),l=JSON.parse(o.shaderMaterial),c=this.Parse(l,t||Oe.LastCreatedScene,i);c.snippetId=e,r(c)}else s("Unable to load the snippet "+e)}),a.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),a.send()})}};vo.SnippetUrl="https://snippet.babylonjs.com";vo.CreateFromSnippetAsync=vo.ParseFromSnippetAsync;Ft("BABYLON.ShaderMaterial",vo)});var qG,Lse,ic=C(()=>{k();qG="bonesDeclaration",Lse=`#if NUM_BONE_INFLUENCERS>0 #ifndef USE_VERTEX_PULLING attribute matricesIndices : vec4f;attribute matricesWeights : vec4f; #if NUM_BONE_INFLUENCERS>4 @@ -4461,7 +4461,7 @@ let textureWidth=i32(uniforms.boneTextureInfo.x);let y=offset/textureWidth;let x #endif #endif #endif -`;T.IncludesShadersStoreWGSL[qG]||(T.IncludesShadersStoreWGSL[qG]=Lse)});var ZG,Ose,nc=C(()=>{W();ZG="bakedVertexAnimationDeclaration",Ose=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE +`;T.IncludesShadersStoreWGSL[qG]||(T.IncludesShadersStoreWGSL[qG]=Lse)});var ZG,Ose,rc=C(()=>{k();ZG="bakedVertexAnimationDeclaration",Ose=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE uniform bakedVertexAnimationTime: f32;uniform bakedVertexAnimationSettings: vec4;var bakedVertexAnimationTexture : texture_2d; #ifdef INSTANCES attribute bakedVertexAnimationSettingsInstanced : vec4; @@ -4469,7 +4469,7 @@ attribute bakedVertexAnimationSettingsInstanced : vec4; fn readMatrixFromRawSamplerVAT(smp : texture_2d,index : f32,frame : f32)->mat4x4 {let offset=i32(index)*4;let frameUV=i32(frame);let m0=textureLoad(smp,vec2(offset+0,frameUV),0);let m1=textureLoad(smp,vec2(offset+1,frameUV),0);let m2=textureLoad(smp,vec2(offset+2,frameUV),0);let m3=textureLoad(smp,vec2(offset+3,frameUV),0);return mat4x4(m0,m1,m2,m3);} #endif -`;T.IncludesShadersStoreWGSL[ZG]||(T.IncludesShadersStoreWGSL[ZG]=Ose)});var QG,Nse,sc=C(()=>{W();QG="clipPlaneVertexDeclaration",Nse=`#ifdef CLIPPLANE +`;T.IncludesShadersStoreWGSL[ZG]||(T.IncludesShadersStoreWGSL[ZG]=Ose)});var QG,Nse,nc=C(()=>{k();QG="clipPlaneVertexDeclaration",Nse=`#ifdef CLIPPLANE uniform vClipPlane: vec4;varying fClipDistance: f32; #endif #ifdef CLIPPLANE2 @@ -4487,10 +4487,10 @@ uniform vClipPlane5: vec4;varying fClipDistance5: f32; #ifdef CLIPPLANE6 uniform vClipPlane6: vec4;varying fClipDistance6: f32; #endif -`;T.IncludesShadersStoreWGSL[QG]||(T.IncludesShadersStoreWGSL[QG]=Nse)});var $G,wse,gg=C(()=>{W();$G="fogVertexDeclaration",wse=`#ifdef FOG +`;T.IncludesShadersStoreWGSL[QG]||(T.IncludesShadersStoreWGSL[QG]=Nse)});var $G,wse,gg=C(()=>{k();$G="fogVertexDeclaration",wse=`#ifdef FOG varying vFogDistance: vec3f; #endif -`;T.IncludesShadersStoreWGSL[$G]||(T.IncludesShadersStoreWGSL[$G]=wse)});var JG,Fse,wf=C(()=>{W();JG="instancesDeclaration",Fse=`#ifdef INSTANCES +`;T.IncludesShadersStoreWGSL[$G]||(T.IncludesShadersStoreWGSL[$G]=wse)});var JG,Fse,Nf=C(()=>{k();JG="instancesDeclaration",Fse=`#ifdef INSTANCES attribute world0 : vec4;attribute world1 : vec4;attribute world2 : vec4;attribute world3 : vec4; #ifdef INSTANCESCOLOR attribute instanceColor : vec4; @@ -4512,7 +4512,7 @@ uniform world : mat4x4; uniform previousWorld : mat4x4; #endif #endif -`;T.IncludesShadersStoreWGSL[JG]||(T.IncludesShadersStoreWGSL[JG]=Fse)});var ek,Bse,ac=C(()=>{W();ek="instancesVertex",Bse=`#ifdef INSTANCES +`;T.IncludesShadersStoreWGSL[JG]||(T.IncludesShadersStoreWGSL[JG]=Fse)});var ek,Bse,sc=C(()=>{k();ek="instancesVertex",Bse=`#ifdef INSTANCES var finalWorld=mat4x4(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3); #if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR) var finalPreviousWorld=mat4x4( @@ -4539,7 +4539,7 @@ var finalWorld=mesh.world; var finalPreviousWorld=uniforms.previousWorld; #endif #endif -`;T.IncludesShadersStoreWGSL[ek]||(T.IncludesShadersStoreWGSL[ek]=Bse)});var tk,Use,oc=C(()=>{W();tk="bonesVertex",Use=`#ifndef BAKED_VERTEX_ANIMATION_TEXTURE +`;T.IncludesShadersStoreWGSL[ek]||(T.IncludesShadersStoreWGSL[ek]=Bse)});var tk,Use,ac=C(()=>{k();tk="bonesVertex",Use=`#ifndef BAKED_VERTEX_ANIMATION_TEXTURE #if NUM_BONE_INFLUENCERS>0 var influence : mat4x4; #ifdef BONETEXTURE @@ -4592,7 +4592,7 @@ influence=influence+uniforms.mBones[i32(vertexInputs.matricesIndicesExtra[3])]*v finalWorld=finalWorld*influence; #endif #endif -`;T.IncludesShadersStoreWGSL[tk]||(T.IncludesShadersStoreWGSL[tk]=Use)});var ik,Vse,lc=C(()=>{W();ik="bakedVertexAnimation",Vse=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE +`;T.IncludesShadersStoreWGSL[tk]||(T.IncludesShadersStoreWGSL[tk]=Use)});var ik,Vse,oc=C(()=>{k();ik="bakedVertexAnimation",Vse=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE { #ifdef INSTANCES let VATStartFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.x;let VATEndFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.y;let VATOffsetFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.z;let VATSpeed: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.w; @@ -4623,7 +4623,7 @@ VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTextur #endif finalWorld=finalWorld*VATInfluence;} #endif -`;T.IncludesShadersStoreWGSL[ik]||(T.IncludesShadersStoreWGSL[ik]=Vse)});var rk,Gse,cc=C(()=>{W();rk="clipPlaneVertex",Gse=`#ifdef CLIPPLANE +`;T.IncludesShadersStoreWGSL[ik]||(T.IncludesShadersStoreWGSL[ik]=Vse)});var rk,Gse,lc=C(()=>{k();rk="clipPlaneVertex",Gse=`#ifdef CLIPPLANE vertexOutputs.fClipDistance=dot(worldPos,uniforms.vClipPlane); #endif #ifdef CLIPPLANE2 @@ -4641,14 +4641,14 @@ vertexOutputs.fClipDistance5=dot(worldPos,uniforms.vClipPlane5); #ifdef CLIPPLANE6 vertexOutputs.fClipDistance6=dot(worldPos,uniforms.vClipPlane6); #endif -`;T.IncludesShadersStoreWGSL[rk]||(T.IncludesShadersStoreWGSL[rk]=Gse)});var nk,kse,vg=C(()=>{W();nk="fogVertex",kse=`#ifdef FOG +`;T.IncludesShadersStoreWGSL[rk]||(T.IncludesShadersStoreWGSL[rk]=Gse)});var nk,kse,vg=C(()=>{k();nk="fogVertex",kse=`#ifdef FOG #ifdef SCENE_UBO vertexOutputs.vFogDistance=(scene.view*worldPos).xyz; #else vertexOutputs.vFogDistance=(uniforms.view*worldPos).xyz; #endif #endif -`;T.IncludesShadersStoreWGSL[nk]||(T.IncludesShadersStoreWGSL[nk]=kse)});var sk,Wse,Eg=C(()=>{W();sk="vertexColorMixing",Wse=`#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +`;T.IncludesShadersStoreWGSL[nk]||(T.IncludesShadersStoreWGSL[nk]=kse)});var sk,Wse,Eg=C(()=>{k();sk="vertexColorMixing",Wse=`#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) vertexOutputs.vColor=vec4f(1.0); #ifdef VERTEXCOLOR #ifdef VERTEXALPHA @@ -4661,7 +4661,7 @@ vertexOutputs.vColor=vec4f(vertexOutputs.vColor.rgb*colorUpdated.rgb,vertexOutpu vertexOutputs.vColor*=vertexInputs.instanceColor; #endif #endif -`;T.IncludesShadersStoreWGSL[sk]||(T.IncludesShadersStoreWGSL[sk]=Wse)});var ok={};tt(ok,{colorVertexShaderWGSL:()=>Hse});var eP,ak,Hse,lk=C(()=>{W();rc();nc();sc();gg();wf();ac();oc();lc();cc();vg();Eg();eP="colorVertexShader",ak=`attribute position: vec3f; +`;T.IncludesShadersStoreWGSL[sk]||(T.IncludesShadersStoreWGSL[sk]=Wse)});var ok={};tt(ok,{colorVertexShaderWGSL:()=>Hse});var eP,ak,Hse,lk=C(()=>{k();ic();rc();nc();gg();Nf();sc();ac();oc();lc();vg();Eg();eP="colorVertexShader",ak=`attribute position: vec3f; #ifdef VERTEXCOLOR attribute color: vec4f; #endif @@ -4692,7 +4692,7 @@ var worldPos: vec4f=finalWorld* vec4f(vertexInputs.position,1.0);vertexOutputs.p #include #include #define CUSTOM_VERTEX_MAIN_END -}`;T.ShadersStoreWGSL[eP]||(T.ShadersStoreWGSL[eP]=ak);Hse={name:eP,shader:ak}});var ck,zse,fc=C(()=>{W();ck="clipPlaneFragmentDeclaration",zse=`#ifdef CLIPPLANE +}`;T.ShadersStoreWGSL[eP]||(T.ShadersStoreWGSL[eP]=ak);Hse={name:eP,shader:ak}});var ck,zse,cc=C(()=>{k();ck="clipPlaneFragmentDeclaration",zse=`#ifdef CLIPPLANE varying fClipDistance: f32; #endif #ifdef CLIPPLANE2 @@ -4710,7 +4710,7 @@ varying fClipDistance5: f32; #ifdef CLIPPLANE6 varying fClipDistance6: f32; #endif -`;T.IncludesShadersStoreWGSL[ck]||(T.IncludesShadersStoreWGSL[ck]=zse)});var fk,Xse,Sg=C(()=>{W();fk="fogFragmentDeclaration",Xse=`#ifdef FOG +`;T.IncludesShadersStoreWGSL[ck]||(T.IncludesShadersStoreWGSL[ck]=zse)});var fk,Xse,Sg=C(()=>{k();fk="fogFragmentDeclaration",Xse=`#ifdef FOG #define FOGMODE_NONE 0. #define FOGMODE_EXP 1. #define FOGMODE_EXP2 2. @@ -4724,7 +4724,7 @@ else if (FOGMODE_EXP2==uniforms.vFogInfos.x) {fogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);} return clamp(fogCoeff,0.0,1.0);} #endif -`;T.IncludesShadersStoreWGSL[fk]||(T.IncludesShadersStoreWGSL[fk]=Xse)});var hk,Yse,hc=C(()=>{W();hk="clipPlaneFragment",Yse=`#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) +`;T.IncludesShadersStoreWGSL[fk]||(T.IncludesShadersStoreWGSL[fk]=Xse)});var hk,Yse,fc=C(()=>{k();hk="clipPlaneFragment",Yse=`#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) if (false) {} #endif #ifdef CLIPPLANE @@ -4751,14 +4751,14 @@ else if (fragmentInputs.fClipDistance5>0.0) else if (fragmentInputs.fClipDistance6>0.0) {discard;} #endif -`;T.IncludesShadersStoreWGSL[hk]||(T.IncludesShadersStoreWGSL[hk]=Yse)});var dk,Kse,Tg=C(()=>{W();dk="fogFragment",Kse=`#ifdef FOG +`;T.IncludesShadersStoreWGSL[hk]||(T.IncludesShadersStoreWGSL[hk]=Yse)});var dk,Kse,Tg=C(()=>{k();dk="fogFragment",Kse=`#ifdef FOG var fog: f32=CalcFogFactor(); #ifdef PBR fog=toLinearSpace(fog); #endif color= vec4f(mix(uniforms.vFogColor,color.rgb,fog),color.a); #endif -`;T.IncludesShadersStoreWGSL[dk]||(T.IncludesShadersStoreWGSL[dk]=Kse)});var mk={};tt(mk,{colorPixelShaderWGSL:()=>jse});var tP,uk,jse,pk=C(()=>{W();fc();Sg();hc();Tg();tP="colorPixelShader",uk=`#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +`;T.IncludesShadersStoreWGSL[dk]||(T.IncludesShadersStoreWGSL[dk]=Kse)});var mk={};tt(mk,{colorPixelShaderWGSL:()=>jse});var tP,uk,jse,pk=C(()=>{k();cc();Sg();fc();Tg();tP="colorPixelShader",uk=`#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) #define VERTEXCOLOR varying vColor: vec4f; #else @@ -4778,7 +4778,7 @@ fragmentOutputs.color=uniforms.color; #endif #include(color,fragmentOutputs.color) #define CUSTOM_FRAGMENT_MAIN_END -}`;T.ShadersStoreWGSL[tP]||(T.ShadersStoreWGSL[tP]=uk);jse={name:tP,shader:uk}});var _k,qse,dc=C(()=>{W();_k="bonesDeclaration",qse=`#if NUM_BONE_INFLUENCERS>0 +}`;T.ShadersStoreWGSL[tP]||(T.ShadersStoreWGSL[tP]=uk);jse={name:tP,shader:uk}});var _k,qse,hc=C(()=>{k();_k="bonesDeclaration",qse=`#if NUM_BONE_INFLUENCERS>0 attribute vec4 matricesIndices;attribute vec4 matricesWeights; #if NUM_BONE_INFLUENCERS>4 attribute vec4 matricesIndicesExtra;attribute vec4 matricesWeightsExtra; @@ -4807,7 +4807,7 @@ return mat4(m0,m1,m2,m3); #endif #endif #endif -`;T.IncludesShadersStore[_k]||(T.IncludesShadersStore[_k]=qse)});var gk,Zse,uc=C(()=>{W();gk="bakedVertexAnimationDeclaration",Zse=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE +`;T.IncludesShadersStore[_k]||(T.IncludesShadersStore[_k]=qse)});var gk,Zse,dc=C(()=>{k();gk="bakedVertexAnimationDeclaration",Zse=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE uniform float bakedVertexAnimationTime; #if !defined(WEBGL2) && !defined(WEBGPU) uniform vec2 bakedVertexAnimationTextureSizeInverted; @@ -4826,7 +4826,7 @@ float offset=index*4.0;float frameUV=(frame+0.5)*bakedVertexAnimationTextureSize #endif } #endif -`;T.IncludesShadersStore[gk]||(T.IncludesShadersStore[gk]=Zse)});var vk,Qse,mc=C(()=>{W();vk="clipPlaneVertexDeclaration",Qse=`#ifdef CLIPPLANE +`;T.IncludesShadersStore[gk]||(T.IncludesShadersStore[gk]=Zse)});var vk,Qse,uc=C(()=>{k();vk="clipPlaneVertexDeclaration",Qse=`#ifdef CLIPPLANE uniform vec4 vClipPlane;varying float fClipDistance; #endif #ifdef CLIPPLANE2 @@ -4844,10 +4844,10 @@ uniform vec4 vClipPlane5;varying float fClipDistance5; #ifdef CLIPPLANE6 uniform vec4 vClipPlane6;varying float fClipDistance6; #endif -`;T.IncludesShadersStore[vk]||(T.IncludesShadersStore[vk]=Qse)});var Ek,$se,Ag=C(()=>{W();Ek="fogVertexDeclaration",$se=`#ifdef FOG +`;T.IncludesShadersStore[vk]||(T.IncludesShadersStore[vk]=Qse)});var Ek,$se,Ag=C(()=>{k();Ek="fogVertexDeclaration",$se=`#ifdef FOG varying vec3 vFogDistance; #endif -`;T.IncludesShadersStore[Ek]||(T.IncludesShadersStore[Ek]=$se)});var Sk,Jse,Ff=C(()=>{W();Sk="instancesDeclaration",Jse=`#ifdef INSTANCES +`;T.IncludesShadersStore[Ek]||(T.IncludesShadersStore[Ek]=$se)});var Sk,Jse,wf=C(()=>{k();Sk="instancesDeclaration",Jse=`#ifdef INSTANCES attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3; #ifdef INSTANCESCOLOR attribute vec4 instanceColor; @@ -4869,7 +4869,7 @@ uniform mat4 world; uniform mat4 previousWorld; #endif #endif -`;T.IncludesShadersStore[Sk]||(T.IncludesShadersStore[Sk]=Jse)});var Tk,eae,pc=C(()=>{W();Tk="instancesVertex",eae=`#ifdef INSTANCES +`;T.IncludesShadersStore[Sk]||(T.IncludesShadersStore[Sk]=Jse)});var Tk,eae,mc=C(()=>{k();Tk="instancesVertex",eae=`#ifdef INSTANCES mat4 finalWorld=mat4(world0,world1,world2,world3); #if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR) mat4 finalPreviousWorld=mat4(previousWorld0,previousWorld1, @@ -4887,7 +4887,7 @@ mat4 finalWorld=world; mat4 finalPreviousWorld=previousWorld; #endif #endif -`;T.IncludesShadersStore[Tk]||(T.IncludesShadersStore[Tk]=eae)});var Ak,tae,_c=C(()=>{W();Ak="bonesVertex",tae=`#ifndef BAKED_VERTEX_ANIMATION_TEXTURE +`;T.IncludesShadersStore[Tk]||(T.IncludesShadersStore[Tk]=eae)});var Ak,tae,pc=C(()=>{k();Ak="bonesVertex",tae=`#ifndef BAKED_VERTEX_ANIMATION_TEXTURE #if NUM_BONE_INFLUENCERS>0 mat4 influence; #ifdef BONETEXTURE @@ -4940,7 +4940,7 @@ influence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; finalWorld=finalWorld*influence; #endif #endif -`;T.IncludesShadersStore[Ak]||(T.IncludesShadersStore[Ak]=tae)});var xk,iae,gc=C(()=>{W();xk="bakedVertexAnimation",iae=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE +`;T.IncludesShadersStore[Ak]||(T.IncludesShadersStore[Ak]=tae)});var xk,iae,_c=C(()=>{k();xk="bakedVertexAnimation",iae=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE { #ifdef INSTANCES #define BVASNAME bakedVertexAnimationSettingsInstanced @@ -4971,7 +4971,7 @@ VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIn #endif finalWorld=finalWorld*VATInfluence;} #endif -`;T.IncludesShadersStore[xk]||(T.IncludesShadersStore[xk]=iae)});var Rk,rae,vc=C(()=>{W();Rk="clipPlaneVertex",rae=`#ifdef CLIPPLANE +`;T.IncludesShadersStore[xk]||(T.IncludesShadersStore[xk]=iae)});var Rk,rae,gc=C(()=>{k();Rk="clipPlaneVertex",rae=`#ifdef CLIPPLANE fClipDistance=dot(worldPos,vClipPlane); #endif #ifdef CLIPPLANE2 @@ -4989,10 +4989,10 @@ fClipDistance5=dot(worldPos,vClipPlane5); #ifdef CLIPPLANE6 fClipDistance6=dot(worldPos,vClipPlane6); #endif -`;T.IncludesShadersStore[Rk]||(T.IncludesShadersStore[Rk]=rae)});var bk,nae,xg=C(()=>{W();bk="fogVertex",nae=`#ifdef FOG +`;T.IncludesShadersStore[Rk]||(T.IncludesShadersStore[Rk]=rae)});var bk,nae,xg=C(()=>{k();bk="fogVertex",nae=`#ifdef FOG vFogDistance=(view*worldPos).xyz; #endif -`;T.IncludesShadersStore[bk]||(T.IncludesShadersStore[bk]=nae)});var Ik,sae,Rg=C(()=>{W();Ik="vertexColorMixing",sae=`#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +`;T.IncludesShadersStore[bk]||(T.IncludesShadersStore[bk]=nae)});var Ik,sae,Rg=C(()=>{k();Ik="vertexColorMixing",sae=`#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) vColor=vec4(1.0); #ifdef VERTEXCOLOR #ifdef VERTEXALPHA @@ -5005,7 +5005,7 @@ vColor.rgb*=colorUpdated.rgb; vColor*=instanceColor; #endif #endif -`;T.IncludesShadersStore[Ik]||(T.IncludesShadersStore[Ik]=sae)});var Ck={};tt(Ck,{colorVertexShader:()=>aae});var iP,Mk,aae,yk=C(()=>{W();dc();uc();mc();Ag();Ff();pc();_c();gc();vc();xg();Rg();iP="colorVertexShader",Mk=`attribute vec3 position; +`;T.IncludesShadersStore[Ik]||(T.IncludesShadersStore[Ik]=sae)});var Ck={};tt(Ck,{colorVertexShader:()=>aae});var iP,Mk,aae,yk=C(()=>{k();hc();dc();uc();Ag();wf();mc();pc();_c();gc();xg();Rg();iP="colorVertexShader",Mk=`attribute vec3 position; #ifdef VERTEXCOLOR attribute vec4 color; #endif @@ -5043,7 +5043,7 @@ gl_Position=viewProjection*worldPos; #include #include #define CUSTOM_VERTEX_MAIN_END -}`;T.ShadersStore[iP]||(T.ShadersStore[iP]=Mk);aae={name:iP,shader:Mk}});var Pk,oae,Ec=C(()=>{W();Pk="clipPlaneFragmentDeclaration",oae=`#ifdef CLIPPLANE +}`;T.ShadersStore[iP]||(T.ShadersStore[iP]=Mk);aae={name:iP,shader:Mk}});var Pk,oae,vc=C(()=>{k();Pk="clipPlaneFragmentDeclaration",oae=`#ifdef CLIPPLANE varying float fClipDistance; #endif #ifdef CLIPPLANE2 @@ -5061,7 +5061,7 @@ varying float fClipDistance5; #ifdef CLIPPLANE6 varying float fClipDistance6; #endif -`;T.IncludesShadersStore[Pk]||(T.IncludesShadersStore[Pk]=oae)});var Dk,lae,bg=C(()=>{W();Dk="fogFragmentDeclaration",lae=`#ifdef FOG +`;T.IncludesShadersStore[Pk]||(T.IncludesShadersStore[Pk]=oae)});var Dk,lae,bg=C(()=>{k();Dk="fogFragmentDeclaration",lae=`#ifdef FOG #define FOGMODE_NONE 0. #define FOGMODE_EXP 1. #define FOGMODE_EXP2 2. @@ -5076,7 +5076,7 @@ else if (FOGMODE_EXP2==vFogInfos.x) {fogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);} return clamp(fogCoeff,0.0,1.0);} #endif -`;T.IncludesShadersStore[Dk]||(T.IncludesShadersStore[Dk]=lae)});var Lk,cae,Sc=C(()=>{W();Lk="clipPlaneFragment",cae=`#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) +`;T.IncludesShadersStore[Dk]||(T.IncludesShadersStore[Dk]=lae)});var Lk,cae,Ec=C(()=>{k();Lk="clipPlaneFragment",cae=`#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) if (false) {} #endif #ifdef CLIPPLANE @@ -5103,14 +5103,14 @@ else if (fClipDistance5>0.0) else if (fClipDistance6>0.0) {discard;} #endif -`;T.IncludesShadersStore[Lk]||(T.IncludesShadersStore[Lk]=cae)});var Ok,fae,Ig=C(()=>{W();Ok="fogFragment",fae=`#ifdef FOG +`;T.IncludesShadersStore[Lk]||(T.IncludesShadersStore[Lk]=cae)});var Ok,fae,Ig=C(()=>{k();Ok="fogFragment",fae=`#ifdef FOG float fog=CalcFogFactor(); #ifdef PBR fog=toLinearSpace(fog); #endif color.rgb=mix(vFogColor,color.rgb,fog); #endif -`;T.IncludesShadersStore[Ok]||(T.IncludesShadersStore[Ok]=fae)});var wk={};tt(wk,{colorPixelShader:()=>hae});var rP,Nk,hae,Fk=C(()=>{W();Ec();bg();Sc();Ig();rP="colorPixelShader",Nk=`#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +`;T.IncludesShadersStore[Ok]||(T.IncludesShadersStore[Ok]=fae)});var wk={};tt(wk,{colorPixelShader:()=>hae});var rP,Nk,hae,Fk=C(()=>{k();vc();bg();Ec();Ig();rP="colorPixelShader",Nk=`#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) #define VERTEXCOLOR varying vec4 vColor; #else @@ -5129,10 +5129,10 @@ gl_FragColor=color; #endif #include(color,gl_FragColor) #define CUSTOM_FRAGMENT_MAIN_END -}`;T.ShadersStore[rP]||(T.ShadersStore[rP]=Nk);hae={name:rP,shader:Nk}});var Jh,nP,Bk=C(()=>{zt();Gi();Ii();Qy();Vn();Jy();Z._LinesMeshParser=(n,e)=>Jh.Parse(n,e);Jh=class n extends Z{_isShaderMaterial(e){return e?e.getClassName()==="ShaderMaterial":!1}constructor(e,t=null,i=null,r=null,s,a,o,l){super(e,t,i,r,s),this.useVertexColor=a,this.useVertexAlpha=o,this.color=new ge(1,1,1),this.alpha=1,this._shaderLanguage=0,this._ownsMaterial=!1,r&&(this.color=r.color.clone(),this.alpha=r.alpha,this.useVertexColor=r.useVertexColor,this.useVertexAlpha=r.useVertexAlpha),this.intersectionThreshold=.1;let c=[],f={attributes:[L.PositionKind],uniforms:["world","viewProjection"],needAlphaBlending:!0,defines:c,useClipPlane:null,shaderLanguage:0};if(this.useVertexAlpha?f.defines.push("#define VERTEXALPHA"):f.needAlphaBlending=!1,this.useVertexColor?(f.defines.push("#define VERTEXCOLOR"),f.attributes.push(L.ColorKind)):(f.uniforms.push("color"),this._color4=new lt),l)this.material=l;else{this.getScene().getEngine().isWebGPU&&!n.ForceGLSL&&(this._shaderLanguage=1),f.shaderLanguage=this._shaderLanguage,f.extraInitializationsAsync=async()=>{this._shaderLanguage===1?await Promise.all([Promise.resolve().then(()=>(lk(),ok)),Promise.resolve().then(()=>(pk(),mk))]):await Promise.all([Promise.resolve().then(()=>(yk(),Ck)),Promise.resolve().then(()=>(Fk(),wk))])};let d=new vo("colorShader",this.getScene(),"color",f,!1);d.doNotSerialize=!0,this._ownsMaterial=!0,this._setInternalMaterial(d)}}getClassName(){return"LinesMesh"}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){let t=this.material;if(t===e)return;let i=t&&this._ownsMaterial;this._ownsMaterial=!1,this._setInternalMaterial(e),i&&(t==null||t.dispose())}_setInternalMaterial(e){this._setMaterial(e),this.material&&(this.material.fillMode=Ee.LineListDrawMode,this.material.disableLighting=!0)}get checkCollisions(){return!1}set checkCollisions(e){}_bind(e,t){if(!this._geometry)return this;let i=this.isUnIndexed?null:this._geometry.getIndexBuffer();if(!this._userInstancedBuffersStorage||this.hasThinInstances?this._geometry._bind(t,i):this._geometry._bind(t,i,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects),!this.useVertexColor&&this._isShaderMaterial(this.material)){let{r,g:s,b:a}=this.color;this._color4.set(r,s,a,this.alpha),this.material.setColor4("color",this._color4)}return this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;let r=this.getScene().getEngine();return this._unIndexed?r.drawArraysType(Ee.LineListDrawMode,e.verticesStart,e.verticesCount,i):r.drawElementsType(Ee.LineListDrawMode,e.indexStart,e.indexCount,i),this}dispose(e,t=!1,i){var r,s;i||(this._ownsMaterial?(r=this.material)==null||r.dispose(!1,!1,!0):t&&((s=this.material)==null||s.dispose(!1,!1,!0))),super.dispose(e)}clone(e,t=null,i){if(t&&t._addToSceneRootNodes===void 0){let r=t;return r.source=this,new n(e,this.getScene(),r.parent,r.source,r.doNotCloneChildren)}return new n(e,this.getScene(),t,this,i)}createInstance(e){let t=new nP(e,this);if(this.instancedBuffers){t.instancedBuffers={};for(let i in this.instancedBuffers)t.instancedBuffers[i]=this.instancedBuffers[i]}return t}serialize(e){super.serialize(e),e.color=this.color.asArray(),e.alpha=this.alpha}static Parse(e,t){let i=new n(e.name,t);return i.color=ge.FromArray(e.color),i.alpha=e.alpha,i}};Jh.ForceGLSL=!1;nP=class extends ic{constructor(e,t){super(e,t),this.intersectionThreshold=t.intersectionThreshold}getClassName(){return"InstancedLinesMesh"}}});function Uk(n){let e=[],t=[],i=n.lines,r=n.colors,s=[],a=0;for(let l=0;l0&&(e.push(a-1),e.push(a)),a++}}let o=new Me;return o.indices=e,o.positions=t,r&&(o.colors=s),o}function Vk(n){let e=n.dashSize||3,t=n.gapSize||1,i=n.dashNb||200,r=n.points,s=[],a=[],o=b.Zero(),l=0,c,f,h=0,d;for(d=0;d{let h=b.Zero(),d=f.length/6,u=0,m,p,_=0,g,v;for(g=0;g{Ve();Ii();hr();Bk();Gi();yt();Me.CreateLineSystem=Uk;Me.CreateDashedLines=Vk;Z.CreateLines=(n,e,t=null,i=!1,r=null)=>aP(n,{points:e,updatable:i,instance:r},t);Z.CreateDashedLines=(n,e,t,i,r,s=null,a,o)=>oP(n,{points:e,dashSize:t,gapSize:i,dashNb:r,updatable:a,instance:o},s)});var lP,Mg,zA,kk=C(()=>{yt();Ve();Gi();Ii();hr();Fh();Dn();Pi();lP=class extends we{constructor(e,t){super(e.x,e.y),this.index=t}},Mg=class{constructor(){this.elements=[]}add(e){let t=[];for(let i of e){let r=new lP(i,this.elements.length);t.push(r),this.elements.push(r)}return t}computeBounds(){let e=new we(this.elements[0].x,this.elements[0].y),t=new we(this.elements[0].x,this.elements[0].y);for(let i of this.elements)i.xt.x&&(t.x=i.x),i.yt.y&&(t.y=i.y);return{min:e,max:t,width:t.x-e.x,height:t.y-e.y}}},zA=class{_addToepoint(e){for(let t of e)this._epoints.push(t.x,t.y)}constructor(e,t,i,r=earcut){this._points=new Mg,this._outlinepoints=new Mg,this._holes=new Array,this._epoints=new Array,this._eholes=new Array,this.bjsEarcut=r,this._name=e,this._scene=i||Le.LastCreatedScene;let s;t instanceof $u?s=t.getPoints():s=t,this._addToepoint(s),this._points.add(s),this._outlinepoints.add(s),typeof this.bjsEarcut=="undefined"&&te.Warn("Earcut was not found, the polygon will not be built.")}addHole(e){this._points.add(e);let t=new Mg;return t.add(e),this._holes.push(t),this._eholes.push(this._epoints.length/2),this._addToepoint(e),this}build(e=!1,t=0,i=2){let r=new Z(this._name,this._scene),s=this.buildVertexData(t,i);return r.setVerticesData(L.PositionKind,s.positions,e),r.setVerticesData(L.NormalKind,s.normals,e),r.setVerticesData(L.UVKind,s.uvs,e),r.setIndices(s.indices),r}buildVertexData(e=0,t=2){let i=new Me,r=[],s=[],a=[],o=this._points.computeBounds();for(let f of this._points.elements)r.push(0,1,0),s.push(f.x,0,f.y),a.push((f.x-o.min.x)/o.width,(f.y-o.min.y)/o.height);let l=[],c=this.bjsEarcut(this._epoints,this._eholes,2);for(let f=0;f0){let f=s.length/3;for(let d of this._points.elements)r.push(0,-1,0),s.push(d.x,-e,d.y),a.push(1-(d.x-o.min.x)/o.width,1-(d.y-o.min.y)/o.height);let h=l.length;for(let d=0;dc?Rc?I{Ve();zt();Ii();hr();kk();Gi();Pi();en();Me.CreatePolygon=Wk;Z.CreatePolygon=(n,e,t,i,r,s,a=earcut)=>XA(n,{shape:e,holes:i,updatable:r,sideOrientation:s},t,a);Z.ExtrudePolygon=(n,e,t,i,r,s,a,o=earcut)=>Cg(n,{shape:e,holes:r,depth:t,updatable:s,sideOrientation:a},i,o)});function fP(n,e,t=null){let i=e.path,r=e.shape,s=e.scale||1,a=e.rotation||0,o=e.cap===0?0:e.cap||Z.NO_CAP,l=e.updatable,c=Z._GetDefaultSideOrientation(e.sideOrientation),f=e.instance||null,h=e.invertUV||!1,d=e.closeShape||!1,u=e.closePath||!1,m=e.capFunction||null;return Hk(n,r,i,s,a,null,null,u,d,o,!1,t,!!l,c,f,h,e.frontUVs||null,e.backUVs||null,e.firstNormal||null,!!e.adjustFrame,m)}function hP(n,e,t=null){var v;let i=e.path,r=e.shape,s=b.Zero(),a=(x,A)=>{var E,R;let S=(R=(E=e.scaleFunction)==null?void 0:E.call(e,x,A))!=null?R:1;return s.copyFromFloats(S,S,S)},o=e.rotationFunction||(()=>0),l=e.closePath||e.ribbonCloseArray||!1,c=e.closeShape||e.ribbonClosePath||!1,f=e.cap===0?0:e.cap||Z.NO_CAP,h=e.updatable,d=e.firstNormal||null,u=e.adjustFrame||!1,m=Z._GetDefaultSideOrientation(e.sideOrientation),p=e.instance,_=e.invertUV||!1,g=e.capFunction||null;return Hk(n,r,i,null,null,(v=e.scaleVectorFunction)!=null?v:a,o,l,c,f,!0,t,!!h,m,p||null,_,e.frontUVs||null,e.backUVs||null,d,u,g||null)}function Hk(n,e,t,i,r,s,a,o,l,c,f,h,d,u,m,p,_,g,v,x,A){let S=(D,O,V,N,F,U,k,ee,q,Q,Y)=>{let K=V.getTangents(),de=V.getNormals(),Re=V.getBinormals(),Fe=V.getDistances();if(Y){for(let Ke=0;Ke0){let qe=K[Ke-1];b.Dot(qe,K[Ke])<0&&K[Ke].scaleInPlace(-1),qe=de[Ke-1],b.Dot(qe,de[Ke])<0&&de[Ke].scaleInPlace(-1),qe=Re[Ke-1],b.Dot(qe,Re[Ke])<0&&Re[Ke].scaleInPlace(-1)}}let se=0,ue=()=>F!==null?F:b.OneReadOnly,he=Q&&ee?ee:()=>U!==null?U:0,De=Q&&k?k:ue,fe=q===Z.NO_CAP||q===Z.CAP_END?0:2,be=$.Matrix[0];for(let Ke=0;Ke{let qe=Array(),Qt=b.Zero(),Dt;for(Dt=0;Dt3?0:c,R=S(e,t,I,y,E,r,s,a,c,f,x);let M=go(n,{pathArray:R,closeArray:o,closePath:l,updatable:d,sideOrientation:u,invertUV:p,frontUVs:_||void 0,backUVs:g||void 0},h);return M._creationDataStorage.pathArray=R,M._creationDataStorage.path3D=I,M._creationDataStorage.cap=c,M}var zk=C(()=>{Ve();Ii();mg();Fh();Z.ExtrudeShape=(n,e,t,i,r,s,a=null,o,l,c)=>{let f={shape:e,path:t,scale:i,rotation:r,cap:s===0?0:s||Z.NO_CAP,sideOrientation:l,instance:c,updatable:o};return fP(n,f,a)};Z.ExtrudeShapeCustom=(n,e,t,i,r,s,a,o,l,c,f,h)=>{let d={shape:e,path:t,scaleFunction:i,rotationFunction:r,ribbonCloseArray:s,ribbonClosePath:a,cap:o===0?0:o||Z.NO_CAP,sideOrientation:f,instance:h,updatable:c};return hP(n,d,l)}});function dP(n,e,t=null){let i=e.arc?e.arc<=0||e.arc>1?1:e.arc:1,r=e.closed===void 0?!0:e.closed,s=e.shape,a=e.radius||1,o=e.tessellation||64,l=e.clip||0,c=e.updatable,f=Z._GetDefaultSideOrientation(e.sideOrientation),h=e.cap||Z.NO_CAP,d=Math.PI*2,u=[],m=e.invertUV||!1,p,_,g=d/o*i,v,x;for(p=0;p<=o-l;p++){for(x=[],(h==Z.CAP_START||h==Z.CAP_ALL)&&(x.push(new b(0,s[0].y,0)),x.push(new b(Math.cos(p*g)*s[0].x*a,s[0].y,Math.sin(p*g)*s[0].x*a))),_=0;_{Ve();Ii();mg();Z.CreateLathe=(n,e,t,i,r,s,a)=>dP(n,{shape:e,radius:t,tessellation:i,sideOrientation:a,updatable:s},r)});function Yk(n){let e=[],t=[],i=[],r=[],s=n.width!==void 0?n.width:n.size!==void 0?n.size:1,a=n.height!==void 0?n.height:n.size!==void 0?n.size:1,o=n.sideOrientation===0?0:n.sideOrientation||Me.DEFAULTSIDE,l=s/2,c=a/2;t.push(-l,-c,0),i.push(0,0,-1),r.push(0,It?1:0),t.push(l,-c,0),i.push(0,0,-1),r.push(1,It?1:0),t.push(l,c,0),i.push(0,0,-1),r.push(1,It?0:1),t.push(-l,c,0),i.push(0,0,-1),r.push(0,It?0:1),e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),Me._ComputeSides(o,t,e,i,r,n.frontUVs,n.backUVs);let f=new Me;return f.indices=e,f.positions=t,f.normals=i,f.uvs=r,f}function uP(n,e={},t=null){let i=new Z(n,t);return e.sideOrientation=Z._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,Yk(e).applyToMesh(i,e.updatable),e.sourcePlane&&(i.translate(e.sourcePlane.normal,-e.sourcePlane.d),i.setDirection(e.sourcePlane.normal.scale(-1))),i}var Kk=C(()=>{Ii();hr();en();Me.CreatePlane=Yk;Z.CreatePlane=(n,e,t,i,r)=>uP(n,{size:e,width:e,height:e,sideOrientation:r,updatable:i},t)});function mP(n,e,t=null){let i=e.path,r=e.instance,s=1;e.radius!==void 0?s=e.radius:r&&(s=r._creationDataStorage.radius);let a=e.tessellation||64,o=e.radiusFunction||null,l=e.cap||Z.NO_CAP,c=e.invertUV||!1,f=e.updatable,h=Z._GetDefaultSideOrientation(e.sideOrientation);e.arc=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1;let d=(g,v,x,A,S,E,R,I)=>{let y=v.getTangents(),M=v.getNormals(),D=v.getDistances(),V=Math.PI*2/S*I,F=E||(()=>A),U,k,ee,q,Q=$.Matrix[0],Y=R===Z.NO_CAP||R===Z.CAP_END?0:2;for(let de=0;de{let Fe=Array();for(let se=0;se3?0:l,m=d(i,u,p,s,a,o,l,e.arc);let _=go(n,{pathArray:m,closePath:!0,closeArray:!1,updatable:f,sideOrientation:h,invertUV:c,frontUVs:e.frontUVs,backUVs:e.backUVs},t);return _._creationDataStorage.pathArray=m,_._creationDataStorage.path3D=u,_._creationDataStorage.tessellation=a,_._creationDataStorage.cap=l,_._creationDataStorage.arc=e.arc,_._creationDataStorage.radius=s,_}var jk=C(()=>{Ve();Ii();mg();Fh();Z.CreateTube=(n,e,t,i,r,s,a,o,l,c)=>mP(n,{path:e,radius:t,tessellation:i,radiusFunction:r,arc:1,cap:s,updatable:o,sideOrientation:l,instance:c},a)});function qk(n){let e=[];e[0]={vertex:[[0,0,1.732051],[1.632993,0,-.5773503],[-.8164966,1.414214,-.5773503],[-.8164966,-1.414214,-.5773503]],face:[[0,1,2],[0,2,3],[0,3,1],[1,3,2]]},e[1]={vertex:[[0,0,1.414214],[1.414214,0,0],[0,1.414214,0],[-1.414214,0,0],[0,-1.414214,0],[0,0,-1.414214]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,1],[1,4,5],[1,5,2],[2,5,3],[3,5,4]]},e[2]={vertex:[[0,0,1.070466],[.7136442,0,.7978784],[-.3568221,.618034,.7978784],[-.3568221,-.618034,.7978784],[.7978784,.618034,.3568221],[.7978784,-.618034,.3568221],[-.9341724,.381966,.3568221],[.1362939,1,.3568221],[.1362939,-1,.3568221],[-.9341724,-.381966,.3568221],[.9341724,.381966,-.3568221],[.9341724,-.381966,-.3568221],[-.7978784,.618034,-.3568221],[-.1362939,1,-.3568221],[-.1362939,-1,-.3568221],[-.7978784,-.618034,-.3568221],[.3568221,.618034,-.7978784],[.3568221,-.618034,-.7978784],[-.7136442,0,-.7978784],[0,0,-1.070466]],face:[[0,1,4,7,2],[0,2,6,9,3],[0,3,8,5,1],[1,5,11,10,4],[2,7,13,12,6],[3,9,15,14,8],[4,10,16,13,7],[5,8,14,17,11],[6,12,18,15,9],[10,11,17,19,16],[12,13,16,19,18],[14,15,18,19,17]]},e[3]={vertex:[[0,0,1.175571],[1.051462,0,.5257311],[.3249197,1,.5257311],[-.8506508,.618034,.5257311],[-.8506508,-.618034,.5257311],[.3249197,-1,.5257311],[.8506508,.618034,-.5257311],[.8506508,-.618034,-.5257311],[-.3249197,1,-.5257311],[-1.051462,0,-.5257311],[-.3249197,-1,-.5257311],[0,0,-1.175571]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,5],[0,5,1],[1,5,7],[1,7,6],[1,6,2],[2,6,8],[2,8,3],[3,8,9],[3,9,4],[4,9,10],[4,10,5],[5,10,7],[6,7,11],[6,11,8],[7,10,11],[8,11,9],[9,11,10]]},e[4]={vertex:[[0,0,1.070722],[.7148135,0,.7971752],[-.104682,.7071068,.7971752],[-.6841528,.2071068,.7971752],[-.104682,-.7071068,.7971752],[.6101315,.7071068,.5236279],[1.04156,.2071068,.1367736],[.6101315,-.7071068,.5236279],[-.3574067,1,.1367736],[-.7888348,-.5,.5236279],[-.9368776,.5,.1367736],[-.3574067,-1,.1367736],[.3574067,1,-.1367736],[.9368776,-.5,-.1367736],[.7888348,.5,-.5236279],[.3574067,-1,-.1367736],[-.6101315,.7071068,-.5236279],[-1.04156,-.2071068,-.1367736],[-.6101315,-.7071068,-.5236279],[.104682,.7071068,-.7971752],[.6841528,-.2071068,-.7971752],[.104682,-.7071068,-.7971752],[-.7148135,0,-.7971752],[0,0,-1.070722]],face:[[0,2,3],[1,6,5],[4,9,11],[7,15,13],[8,16,10],[12,14,19],[17,22,18],[20,21,23],[0,1,5,2],[0,3,9,4],[0,4,7,1],[1,7,13,6],[2,5,12,8],[2,8,10,3],[3,10,17,9],[4,11,15,7],[5,6,14,12],[6,13,20,14],[8,12,19,16],[9,17,18,11],[10,16,22,17],[11,18,21,15],[13,15,21,20],[14,20,23,19],[16,19,23,22],[18,22,23,21]]},e[5]={vertex:[[0,0,1.322876],[1.309307,0,.1889822],[-.9819805,.8660254,.1889822],[.1636634,-1.299038,.1889822],[.3273268,.8660254,-.9449112],[-.8183171,-.4330127,-.9449112]],face:[[0,3,1],[2,4,5],[0,1,4,2],[0,2,5,3],[1,3,5,4]]},e[6]={vertex:[[0,0,1.159953],[1.013464,0,.5642542],[-.3501431,.9510565,.5642542],[-.7715208,-.6571639,.5642542],[.6633206,.9510565,-.03144481],[.8682979,-.6571639,-.3996071],[-1.121664,.2938926,-.03144481],[-.2348831,-1.063314,-.3996071],[.5181548,.2938926,-.9953061],[-.5850262,-.112257,-.9953061]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,9,7],[5,7,9,8],[0,3,7,5,1],[2,4,8,9,6]]},e[7]={vertex:[[0,0,1.118034],[.8944272,0,.6708204],[-.2236068,.8660254,.6708204],[-.7826238,-.4330127,.6708204],[.6708204,.8660254,.2236068],[1.006231,-.4330127,-.2236068],[-1.006231,.4330127,.2236068],[-.6708204,-.8660254,-.2236068],[.7826238,.4330127,-.6708204],[.2236068,-.8660254,-.6708204],[-.8944272,0,-.6708204],[0,0,-1.118034]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,10,7],[5,9,11,8],[7,10,11,9],[0,3,7,9,5,1],[2,4,8,11,10,6]]},e[8]={vertex:[[-.729665,.670121,.319155],[-.655235,-.29213,-.754096],[-.093922,-.607123,.537818],[.702196,.595691,.485187],[.776626,-.36656,-.588064]],face:[[1,4,2],[0,1,2],[3,0,2],[4,3,2],[4,1,0,3]]},e[9]={vertex:[[-.868849,-.100041,.61257],[-.329458,.976099,.28078],[-.26629,-.013796,-.477654],[-.13392,-1.034115,.229829],[.738834,.707117,-.307018],[.859683,-.535264,-.338508]],face:[[3,0,2],[5,3,2],[4,5,2],[1,4,2],[0,1,2],[0,3,5,4,1]]},e[10]={vertex:[[-.610389,.243975,.531213],[-.187812,-.48795,-.664016],[-.187812,.9759,-.664016],[.187812,-.9759,.664016],[.798201,.243975,.132803]],face:[[1,3,0],[3,4,0],[3,1,4],[0,2,1],[0,4,2],[2,4,1]]},e[11]={vertex:[[-1.028778,.392027,-.048786],[-.640503,-.646161,.621837],[-.125162,-.395663,-.540059],[.004683,.888447,-.651988],[.125161,.395663,.540059],[.632925,-.791376,.433102],[1.031672,.157063,-.354165]],face:[[3,2,0],[2,1,0],[2,5,1],[0,4,3],[0,1,4],[4,1,5],[2,3,6],[3,4,6],[5,2,6],[4,5,6]]},e[12]={vertex:[[-.669867,.334933,-.529576],[-.669867,.334933,.529577],[-.4043,1.212901,0],[-.334933,-.669867,-.529576],[-.334933,-.669867,.529577],[.334933,.669867,-.529576],[.334933,.669867,.529577],[.4043,-1.212901,0],[.669867,-.334933,-.529576],[.669867,-.334933,.529577]],face:[[8,9,7],[6,5,2],[3,8,7],[5,0,2],[4,3,7],[0,1,2],[9,4,7],[1,6,2],[9,8,5,6],[8,3,0,5],[3,4,1,0],[4,9,6,1]]},e[13]={vertex:[[-.931836,.219976,-.264632],[-.636706,.318353,.692816],[-.613483,-.735083,-.264632],[-.326545,.979634,0],[-.318353,-.636706,.692816],[-.159176,.477529,-.856368],[.159176,-.477529,-.856368],[.318353,.636706,.692816],[.326545,-.979634,0],[.613482,.735082,-.264632],[.636706,-.318353,.692816],[.931835,-.219977,-.264632]],face:[[11,10,8],[7,9,3],[6,11,8],[9,5,3],[2,6,8],[5,0,3],[4,2,8],[0,1,3],[10,4,8],[1,7,3],[10,11,9,7],[11,6,5,9],[6,2,0,5],[2,4,1,0],[4,10,7,1]]},e[14]={vertex:[[-.93465,.300459,-.271185],[-.838689,-.260219,-.516017],[-.711319,.717591,.128359],[-.710334,-.156922,.080946],[-.599799,.556003,-.725148],[-.503838,-.004675,-.969981],[-.487004,.26021,.48049],[-.460089,-.750282,-.512622],[-.376468,.973135,-.325605],[-.331735,-.646985,.084342],[-.254001,.831847,.530001],[-.125239,-.494738,-.966586],[.029622,.027949,.730817],[.056536,-.982543,-.262295],[.08085,1.087391,.076037],[.125583,-.532729,.485984],[.262625,.599586,.780328],[.391387,-.726999,-.716259],[.513854,-.868287,.139347],[.597475,.85513,.326364],[.641224,.109523,.783723],[.737185,-.451155,.538891],[.848705,-.612742,-.314616],[.976075,.365067,.32976],[1.072036,-.19561,.084927]],face:[[15,18,21],[12,20,16],[6,10,2],[3,0,1],[9,7,13],[2,8,4,0],[0,4,5,1],[1,5,11,7],[7,11,17,13],[13,17,22,18],[18,22,24,21],[21,24,23,20],[20,23,19,16],[16,19,14,10],[10,14,8,2],[15,9,13,18],[12,15,21,20],[6,12,16,10],[3,6,2,0],[9,3,1,7],[9,15,12,6,3],[22,17,11,5,4,8,14,19,23,24]]};let t=n.type&&(n.type<0||n.type>=e.length)?0:n.type||0,i=n.size,r=n.sizeX||i||1,s=n.sizeY||i||1,a=n.sizeZ||i||1,o=n.custom||e[t],l=o.face.length,c=n.faceUV||new Array(l),f=n.faceColors,h=n.flat===void 0?!0:n.flat,d=n.sideOrientation===0?0:n.sideOrientation||Me.DEFAULTSIDE,u=[],m=[],p=[],_=[],g=[],v=0,x=0,A=[],S,E,R,I,y,M,D,O;if(h)for(E=0;E{Ve();zt();Ii();hr();en();Me.CreatePolyhedron=qk;Z.CreatePolyhedron=(n,e,t)=>yg(n,e,t)});function Zk(n){let e=n.sideOrientation||Me.DEFAULTSIDE,t=n.radius||1,i=n.flat===void 0?!0:n.flat,r=(n.subdivisions||4)|0,s=n.radiusX||t,a=n.radiusY||t,o=n.radiusZ||t,l=(1+Math.sqrt(5))/2,c=[-1,l,-0,1,l,0,-1,-l,0,1,-l,0,0,-1,-l,0,1,-l,0,-1,l,0,1,l,l,0,1,l,0,-1,-l,0,1,-l,0,-1],f=[0,11,5,0,5,1,0,1,7,0,7,10,12,22,23,1,5,20,5,11,4,23,22,13,22,18,6,7,1,8,14,21,4,14,4,2,16,13,6,15,6,19,3,8,9,4,21,5,13,17,23,6,13,22,19,6,18,9,8,1],h=[0,1,2,3,4,5,6,7,8,9,10,11,0,2,3,3,3,4,7,8,9,9,10,11],d=[5,1,3,1,6,4,0,0,5,3,4,2,2,2,4,0,2,0,1,1,6,0,6,2,0,4,3,3,4,4,3,1,4,2,4,4,0,2,1,1,2,2,3,3,1,3,2,4],u=138/1024,m=239/1024,p=60/1024,_=26/1024,g=-40/1024,v=20/1024,x=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],A=[],S=[],E=[],R=[],I=0,y=new Array(3),M=new Array(3),D;for(D=0;D<3;D++)y[D]=b.Zero(),M[D]=we.Zero();for(let V=0;V<20;V++){for(D=0;D<3;D++){let F=f[3*V+D];y[D].copyFromFloats(c[3*h[F]],c[3*h[F]+1],c[3*h[F]+2]),y[D].normalize(),M[D].copyFromFloats(d[2*F]*u+p+x[V]*g,d[2*F+1]*m+_+x[V]*v)}let N=(F,U,k,ee)=>{let q=b.Lerp(y[0],y[2],U/r),Q=b.Lerp(y[1],y[2],U/r),Y=r===U?y[2]:b.Lerp(q,Q,F/(r-U));Y.normalize();let K;if(i){let se=b.Lerp(y[0],y[2],ee/r),ue=b.Lerp(y[1],y[2],ee/r);K=b.Lerp(se,ue,k/(r-ee))}else K=new b(Y.x,Y.y,Y.z);K.x/=s,K.y/=a,K.z/=o,K.normalize();let de=we.Lerp(M[0],M[2],U/r),Re=we.Lerp(M[1],M[2],U/r),Fe=r===U?M[2]:we.Lerp(de,Re,F/(r-U));S.push(Y.x*s,Y.y*a,Y.z*o),E.push(K.x,K.y,K.z),R.push(Fe.x,It?1-Fe.y:Fe.y),A.push(I),I++};for(let F=0;F{Ve();Ii();hr();en();Me.CreateIcoSphere=Zk;Z.CreateIcoSphere=(n,e,t)=>_P(n,e,t)});function gP(n,e,t){var k,ee,q,Q,Y;let i=!!e.skeleton,r=!!((k=e.morphTargetManager)!=null&&k.numTargets),s=t.localMode||i,a=e.getIndices(),o=i||r?e.getPositionData(!0,!0):e.getVerticesData(L.PositionKind),l=i||r?e.getNormalsData(!0,!0):e.getVerticesData(L.NormalKind),c=s?i?e.getVerticesData(L.PositionKind):o:null,f=s?i?e.getVerticesData(L.NormalKind):l:null,h=e.getVerticesData(L.UVKind),d=i?e.getVerticesData(L.MatricesIndicesKind):null,u=i?e.getVerticesData(L.MatricesWeightsKind):null,m=i?e.getVerticesData(L.MatricesIndicesExtraKind):null,p=i?e.getVerticesData(L.MatricesWeightsExtraKind):null,_=t.position||b.Zero(),g=t.normal||b.Up(),v=t.size||b.One(),x=t.angle||0;if(!g){let K=new b(0,0,1),de=e.getScene().activeCamera,Re=b.TransformCoordinates(K,de.getWorldMatrix());g=de.globalPosition.subtract(Re)}let A=-Math.atan2(g.z,g.x)-Math.PI/2,S=Math.sqrt(g.x*g.x+g.z*g.z),E=Math.atan2(g.y,S),R=new Me;R.indices=[],R.positions=[],R.normals=[],R.uvs=[],R.matricesIndices=i?[]:null,R.matricesWeights=i?[]:null,R.matricesIndicesExtra=m?[]:null,R.matricesWeightsExtra=p?[]:null;let I=0,y=(K,de)=>{let Re=new YA;if(!a||!o||!l)return Re;let Fe=a[K];if(Re.vertexIdx=Fe*3,Re.vertexIdxForBones=Fe*4,Re.position=new b(o[Fe*3],o[Fe*3+1],o[Fe*3+2]),b.TransformCoordinatesToRef(Re.position,de,Re.position),Re.normal=new b(l[Fe*3],l[Fe*3+1],l[Fe*3+2]),b.TransformNormalToRef(Re.normal,de,Re.normal),t.captureUVS&&h){let se=h[Fe*2+1];Re.uv=new we(h[Fe*2],It?1-se:se)}return Re},M=[0,0,0,0],D=(K,de)=>{if(K.length===0)return K;let Re=.5*Math.abs(b.Dot(v,de)),Fe=(re,he,De,fe)=>{for(let be=0;be{var ye,Be,Je,rt,Ce,Pe,je,St,nt,et,Vt,jt,vi,G,ve,Ae;let De=b.GetClipFactor(re.position,he.position,de,Re),fe=M,be=M;if(d&&u){let He=re.matrixIndicesOverride?0:re.vertexIdxForBones,ke=(ye=re.matrixIndicesOverride)!=null?ye:d,Oe=(Be=re.matrixWeightsOverride)!=null?Be:u,Tt=he.matrixIndicesOverride?0:he.vertexIdxForBones,Wt=(Je=he.matrixIndicesOverride)!=null?Je:d,nr=(rt=he.matrixWeightsOverride)!=null?rt:u;fe=[0,0,0,0],be=[0,0,0,0];let di=0;for(let Er=0;Er<4;++Er)if(Oe[He+Er]>0){let Xn=Fe(Wt,ke[He+Er],Tt,4);fe[di]=ke[He+Er],be[di]=Ja(Oe[He+Er],Xn>=0?nr[Xn]:0,De),di++}for(let Er=0;Er<4&&di<4;++Er){let Xn=Wt[Tt+Er];Fe(ke,Xn,He,4)===-1&&(fe[di]=Xn,be[di]=Ja(0,nr[Tt+Er],De),di++)}let xn=be[0]+be[1]+be[2]+be[3];be[0]/=xn,be[1]/=xn,be[2]/=xn,be[3]/=xn}let Xe=re.localPositionOverride?re.localPositionOverride[0]:(Ce=c==null?void 0:c[re.vertexIdx])!=null?Ce:0,Et=re.localPositionOverride?re.localPositionOverride[1]:(Pe=c==null?void 0:c[re.vertexIdx+1])!=null?Pe:0,Ke=re.localPositionOverride?re.localPositionOverride[2]:(je=c==null?void 0:c[re.vertexIdx+2])!=null?je:0,qe=he.localPositionOverride?he.localPositionOverride[0]:(St=c==null?void 0:c[he.vertexIdx])!=null?St:0,Qt=he.localPositionOverride?he.localPositionOverride[1]:(nt=c==null?void 0:c[he.vertexIdx+1])!=null?nt:0,Dt=he.localPositionOverride?he.localPositionOverride[2]:(et=c==null?void 0:c[he.vertexIdx+2])!=null?et:0,Fi=re.localNormalOverride?re.localNormalOverride[0]:(Vt=f==null?void 0:f[re.vertexIdx])!=null?Vt:0,ae=re.localNormalOverride?re.localNormalOverride[1]:(jt=f==null?void 0:f[re.vertexIdx+1])!=null?jt:0,Bi=re.localNormalOverride?re.localNormalOverride[2]:(vi=f==null?void 0:f[re.vertexIdx+2])!=null?vi:0,ei=he.localNormalOverride?he.localNormalOverride[0]:(G=f==null?void 0:f[he.vertexIdx])!=null?G:0,Wi=he.localNormalOverride?he.localNormalOverride[1]:(ve=f==null?void 0:f[he.vertexIdx+1])!=null?ve:0,ot=he.localNormalOverride?he.localNormalOverride[2]:(Ae=f==null?void 0:f[he.vertexIdx+2])!=null?Ae:0,Ci=Fi+(ei-Fi)*De,X=ae+(Wi-ae)*De,B=Bi+(ot-Bi)*De,me=Math.sqrt(Ci*Ci+X*X+B*B);return new YA(b.Lerp(re.position,he.position,De),b.Lerp(re.normal,he.normal,De).normalize(),we.Lerp(re.uv,he.uv,De),-1,-1,c?[Xe+(qe-Xe)*De,Et+(Qt-Et)*De,Ke+(Dt-Ke)*De]:null,f?[Ci/me,X/me,B/me]:null,fe,be)},ue=null;K.length>3&&(ue=[]);for(let re=0;re0,Qt=Et>0,Dt=Ke>0;switch((qe?1:0)+(Qt?1:0)+(Dt?1:0)){case 0:K.length>3?(ue.push(K[re]),ue.push(K[re+1]),ue.push(K[re+2])):ue=K;break;case 1:if(ue=ue!=null?ue:new Array,qe&&(he=K[re+1],De=K[re+2],fe=se(K[re],he),be=se(K[re],De)),Qt){he=K[re],De=K[re+2],fe=se(K[re+1],he),be=se(K[re+1],De),ue.push(fe),ue.push(De.clone()),ue.push(he.clone()),ue.push(De.clone()),ue.push(fe.clone()),ue.push(be);break}Dt&&(he=K[re],De=K[re+1],fe=se(K[re+2],he),be=se(K[re+2],De)),he&&De&&fe&&be&&(ue.push(he.clone()),ue.push(De.clone()),ue.push(fe),ue.push(be),ue.push(fe.clone()),ue.push(De.clone()));break;case 2:ue=ue!=null?ue:new Array,qe||(he=K[re].clone(),De=se(he,K[re+1]),fe=se(he,K[re+2]),ue.push(he),ue.push(De),ue.push(fe)),Qt||(he=K[re+1].clone(),De=se(he,K[re+2]),fe=se(he,K[re]),ue.push(he),ue.push(De),ue.push(fe)),Dt||(he=K[re+2].clone(),De=se(he,K[re]),fe=se(he,K[re+1]),ue.push(he),ue.push(De),ue.push(fe));break;case 3:break}}return ue},O=e instanceof Z?e:null,V=O==null?void 0:O._thinInstanceDataStorage.matrixData,N=(O==null?void 0:O.thinInstanceCount)||1,F=$.Matrix[0];F.copyFrom(j.IdentityReadOnly);for(let K=0;K{Ve();Ln();Ii();Gi();hr();en();dae=new b(1,0,0),uae=new b(-1,0,0),mae=new b(0,1,0),pae=new b(0,-1,0),_ae=new b(0,0,1),gae=new b(0,0,-1),YA=class n{constructor(e=b.Zero(),t=b.Up(),i=we.Zero(),r=0,s=0,a=null,o=null,l=null,c=null){this.position=e,this.normal=t,this.uv=i,this.vertexIdx=r,this.vertexIdxForBones=s,this.localPositionOverride=a,this.localNormalOverride=o,this.matrixIndicesOverride=l,this.matrixWeightsOverride=c}clone(){var e,t,i,r;return new n(this.position.clone(),this.normal.clone(),this.uv.clone(),this.vertexIdx,this.vertexIdxForBones,(e=this.localPositionOverride)==null?void 0:e.slice(),(t=this.localNormalOverride)==null?void 0:t.slice(),(i=this.matrixIndicesOverride)==null?void 0:i.slice(),(r=this.matrixWeightsOverride)==null?void 0:r.slice())}};Z.CreateDecal=(n,e,t,i,r,s)=>gP(n,e,{position:t,normal:i,size:r,angle:s})});function Jk(n={subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){let e=Math.max(n.subdivisions?n.subdivisions:2,1)|0,t=Math.max(n.tessellation?n.tessellation:16,3)|0,i=Math.max(n.height?n.height:1,0),r=Math.max(n.radius?n.radius:.25,0),s=Math.max(n.capSubdivisions?n.capSubdivisions:6,1)|0,a=t,o=e,l=Math.max(n.radiusTop?n.radiusTop:r,0),c=Math.max(n.radiusBottom?n.radiusBottom:r,0),f=i-(l+c),h=0,d=2*Math.PI,u=Math.max(n.topCapSubdivisions?n.topCapSubdivisions:s,1),m=Math.max(n.bottomCapSubdivisions?n.bottomCapSubdivisions:s,1),p=Math.acos((c-l)/i),_=[],g=[],v=[],x=[],A=0,S=[],E=f*.5,R=Math.PI*.5,I,y,M=b.Zero(),D=b.Zero(),O=Math.cos(p),V=Math.sin(p),N=new we(l*V,E+l*O).subtract(new we(c*V,-E+c*O)).length(),F=l*p+N+c*(R-p),U=0;for(y=0;y<=u;y++){let Q=[],Y=R-p*(y/u);U+=l*p/u;let K=Math.cos(Y),de=Math.sin(Y),Re=K*l;for(I=0;I<=a;I++){let Fe=I/a,se=Fe*d+h,ue=Math.sin(se),re=Math.cos(se);D.x=Re*ue,D.y=E+de*l,D.z=Re*re,g.push(D.x,D.y,D.z),M.set(K*ue,de,K*re),v.push(M.x,M.y,M.z),x.push(Fe,It?U/F:1-U/F),Q.push(A),A++}S.push(Q)}let k=i-l-c+O*l-O*c,ee=V*(c-l)/k;for(y=1;y<=o;y++){let Q=[];U+=N/o;let Y=V*(y*(c-l)/o+l);for(I=0;I<=a;I++){let K=I/a,de=K*d+h,Re=Math.sin(de),Fe=Math.cos(de);D.x=Y*Re,D.y=E+O*l-y*k/o,D.z=Y*Fe,g.push(D.x,D.y,D.z),M.set(Re,ee,Fe).normalize(),v.push(M.x,M.y,M.z),x.push(K,It?U/F:1-U/F),Q.push(A),A++}S.push(Q)}for(y=1;y<=m;y++){let Q=[],Y=R-p-(Math.PI-p)*(y/m);U+=c*p/m;let K=Math.cos(Y),de=Math.sin(Y),Re=K*c;for(I=0;I<=a;I++){let Fe=I/a,se=Fe*d+h,ue=Math.sin(se),re=Math.cos(se);D.x=Re*ue,D.y=-E+de*c,D.z=Re*re,g.push(D.x,D.y,D.z),M.set(K*ue,de,K*re),v.push(M.x,M.y,M.z),x.push(Fe,It?U/F:1-U/F),Q.push(A),A++}S.push(Q)}for(I=0;I{hr();Ve();Ii();en();Z.CreateCapsule=(n,e,t)=>vP(n,e,t);Me.CreateCapsule=Jk});var Ki,tW=C(()=>{yt();Ve();Ki=class n{constructor(e=0,t=0){this.x=e,this.y=t,e!==Math.floor(e)&&(e=Math.floor(e),te.Warn("x is not an integer, floor(x) used")),t!==Math.floor(t)&&(t=Math.floor(t),te.Warn("y is not an integer, floor(y) used"))}clone(){return new n(this.x,this.y)}rotate60About(e){let t=this.x;return this.x=e.x+e.y-this.y,this.y=t+this.y-e.x,this}rotateNeg60About(e){let t=this.x;return this.x=t+this.y-e.y,this.y=e.x+e.y-t,this}rotate120(e,t){e!==Math.floor(e)&&(e=Math.floor(e),te.Warn("m not an integer only floor(m) used")),t!==Math.floor(t)&&(t=Math.floor(t),te.Warn("n not an integer only floor(n) used"));let i=this.x;return this.x=e-i-this.y,this.y=t+i,this}rotateNeg120(e,t){e!==Math.floor(e)&&(e=Math.floor(e),te.Warn("m is not an integer, floor(m) used")),t!==Math.floor(t)&&(t=Math.floor(t),te.Warn("n is not an integer, floor(n) used"));let i=this.x;return this.x=this.y-t,this.y=e+t-i-this.y,this}toCartesianOrigin(e,t){let i=b.Zero();return i.x=e.x+2*this.x*t+this.y*t,i.y=e.y+Math.sqrt(3)*this.y*t,i}static Zero(){return new n(0,0)}}});var Wm,Pg,Hm,EP=C(()=>{Ve();Ln();Dn();tW();Wm=class{constructor(){this.cartesian=[],this.vertices=[],this.max=[],this.min=[],this.closestTo=[],this.innerFacets=[],this.isoVecsABOB=[],this.isoVecsOBOA=[],this.isoVecsBAOA=[],this.vertexTypes=[],this.IDATA=new Pg("icosahedron","Regular",[[0,pr,-1],[-pr,1,0],[-1,0,-pr],[1,0,-pr],[pr,1,0],[0,pr,1],[-1,0,pr],[-pr,-1,0],[0,-pr,-1],[pr,-1,0],[1,0,pr],[0,-pr,1]],[[0,2,1],[0,3,2],[0,4,3],[0,5,4],[0,1,5],[7,6,1],[8,7,2],[9,8,3],[10,9,4],[6,10,5],[2,7,1],[3,8,2],[4,9,3],[5,10,4],[1,6,5],[11,6,7],[11,7,8],[11,8,9],[11,9,10],[11,10,6]])}setIndices(){let e=12,t={},i=this.m,r=this.n,s=i;r!==0&&(s=NT(i,r));let a=i/s,o=r/s,l,c,f,h,d,u=Ki.Zero(),m=new Ki(i,r),p=new Ki(-r,i+r),_=Ki.Zero(),g=Ki.Zero(),v=Ki.Zero(),x=[],A,S,E,R,I=[],y=this.vertByDist,M=(D,O,V,N)=>{A=D+"|"+V,S=O+"|"+N,A in t||S in t?A in t&&!(S in t)?t[S]=t[A]:S in t&&!(A in t)&&(t[A]=t[S]):(t[A]=e,t[S]=e,e++),y[V][0]>2?I[t[A]]=[-y[V][0],y[V][1],t[A]]:I[t[A]]=[x[y[V][0]],y[V][1],t[A]]};this.IDATA.edgematch=[[1,"B"],[2,"B"],[3,"B"],[4,"B"],[0,"B"],[10,"O",14,"A"],[11,"O",10,"A"],[12,"O",11,"A"],[13,"O",12,"A"],[14,"O",13,"A"],[0,"O"],[1,"O"],[2,"O"],[3,"O"],[4,"O"],[19,"B",5,"A"],[15,"B",6,"A"],[16,"B",7,"A"],[17,"B",8,"A"],[18,"B",9,"A"]];for(let D=0;D<20;D++){if(x=this.IDATA.face[D],f=x[2],h=x[1],d=x[0],E=u.x+"|"+u.y,A=D+"|"+E,A in t||(t[A]=f,I[f]=[x[y[E][0]],y[E][1]]),E=m.x+"|"+m.y,A=D+"|"+E,A in t||(t[A]=h,I[h]=[x[y[E][0]],y[E][1]]),E=p.x+"|"+p.y,A=D+"|"+E,A in t||(t[A]=d,I[d]=[x[y[E][0]],y[E][1]]),l=this.IDATA.edgematch[D][0],c=this.IDATA.edgematch[D][1],c==="B")for(let O=1;O2?I[t[A]]=[-y[E][0],y[E][1],t[A]]:I[t[A]]=[x[y[E][0]],y[E][1],t[A]])}this.closestTo=I,this.vecToidx=t}calcCoeffs(){let e=this.m,t=this.n,i=Math.sqrt(3)/3,r=e*e+t*t+e*t;this.coau=(e+t)/r,this.cobu=-t/r,this.coav=-i*(e-t)/r,this.cobv=i*(2*e+t)/r}createInnerFacets(){let e=this.m,t=this.n;for(let i=0;i0&&r0){let S=NT(e,t),E=e/S,R=t/S;for(let y=1;yS.x-E.x),i.sort((S,E)=>S.y-E.y);let o=new Array(e+t+1),l=new Array(e+t+1);for(let S=0;S{let R=S.clone();return E==="A"&&R.rotateNeg120(e,t),E==="B"&&R.rotate120(e,t),R.x<0?R.y:R.x+R.y},u=[],m=[],p=[],_=[],g={},v=[],x=-1,A=-1;for(let S=0;SS[2]-E[2]),v.sort((S,E)=>S[3]-E[3]),v.sort((S,E)=>S[1]-E[1]),v.sort((S,E)=>S[0]-E[0]);for(let S=0;St.vecToidx[e+r]))}mapABOBtoDATA(e,t){let i=t.IDATA.edgematch[e][0];for(let r=0;r-1?i[a][1]>0&&t[i[a][0]].push([a,i[a][1]]):t[12].push([a,i[a][0]]);let r=[];for(let a=0;a<12;a++)r[a]=a;let s=12;for(let a=0;a<12;a++){t[a].sort((o,l)=>o[1]-l[1]);for(let o=0;oa[3]-o[3]);for(let a=0;a0;)s=t[l],this.face[s].indexOf(o)>-1?(a=(this.face[s].indexOf(o)+1)%3,o=this.face[s][a],i.push(o),r.push(s),t.splice(l,1),l=0):l++;return this.adjacentFaces.push(i),r}toGoldbergPolyhedronData(){let e=new Pg("GeoDual","Goldberg",[],[]);e.name="GD dual";let t=this.vertex.length,i=new Array(t);for(let c=0;ci){let c=r;r=i,i=c,te.Warn("n > m therefore m and n swapped")}let s=new Wm;s.build(i,r);let o={custom:Hm.BuildGeodesicData(s),size:e.size,sizeX:e.sizeX,sizeY:e.sizeY,sizeZ:e.sizeZ,faceUV:e.faceUV,faceColors:e.faceColors,flat:e.flat,updatable:e.updatable,sideOrientation:e.sideOrientation,frontUVs:e.frontUVs,backUVs:e.backUVs};return yg(n,o,t)}var rW=C(()=>{pP();yt();EP()});var Dg,nW=C(()=>{Ve();Gi();Ii();zt();yt();Z._GoldbergMeshParser=(n,e)=>Dg.Parse(n,e);Dg=class n extends Z{constructor(){super(...arguments),this.goldbergData={faceColors:[],faceCenters:[],faceZaxis:[],faceXaxis:[],faceYaxis:[],nbSharedFaces:0,nbUnsharedFaces:0,nbFaces:0,nbFacesAtPole:0,adjacentFaces:[]}}relatedGoldbergFace(e,t){return t===void 0?(e>this.goldbergData.nbUnsharedFaces-1&&(te.Warn("Maximum number of unshared faces used"),e=this.goldbergData.nbUnsharedFaces-1),this.goldbergData.nbUnsharedFaces+e):(e>11&&(te.Warn("Last pole used"),e=11),t>this.goldbergData.nbFacesAtPole-1&&(te.Warn("Maximum number of faces at a pole used"),t=this.goldbergData.nbFacesAtPole-1),12+e*this.goldbergData.nbFacesAtPole+t)}_changeGoldbergFaceColors(e){for(let i=0;i1&&(h=1),c.push(h,d);for(let u=0;u<6;u++)h=a.x+o*Math.cos(l+u*Math.PI/3),d=a.y+o*Math.sin(l+u*Math.PI/3),h<0&&(h=0),h>1&&(h=1),f.push(h,d);for(let u=r;ult.FromArray(s)),i.faceCenters=i.faceCenters.map(s=>b.FromArray(s)),i.faceZaxis=i.faceZaxis.map(s=>b.FromArray(s)),i.faceXaxis=i.faceXaxis.map(s=>b.FromArray(s)),i.faceYaxis=i.faceYaxis.map(s=>b.FromArray(s));let r=new n(e.name,t);return r.goldbergData=i,r}}});function vae(n,e){let t=n.size,i=n.sizeX||t||1,r=n.sizeY||t||1,s=n.sizeZ||t||1,a=n.sideOrientation===0?0:n.sideOrientation||Me.DEFAULTSIDE,o=[],l=[],c=[],f=[],h=1/0,d=-1/0,u=1/0,m=-1/0;for(let g=0;go){let m=l;l=o,o=m,te.Warn("n > m therefore m and n swapped")}let c=new Wm;c.build(o,l);let f=Hm.BuildGeodesicData(c),h=f.toGoldbergPolyhedronData(),d=new Dg(n,t);e.sideOrientation=Z._GetDefaultSideOrientation(e.sideOrientation),d._originalBuilderSideOrientation=e.sideOrientation,vae(e,h).applyToMesh(d,e.updatable),d.goldbergData.nbSharedFaces=f.sharedNodes,d.goldbergData.nbUnsharedFaces=f.poleNodes,d.goldbergData.adjacentFaces=f.adjacentFaces,d.goldbergData.nbFaces=d.goldbergData.nbSharedFaces+d.goldbergData.nbUnsharedFaces,d.goldbergData.nbFacesAtPole=(d.goldbergData.nbUnsharedFaces-12)/12;for(let m=0;m{Ve();zt();Ii();hr();yt();EP();nW();en()});function Eae(n,e,t,i,r,s){let a=s.glyphs[n]||s.glyphs["?"];if(!a)return null;let o=new SP(r);if(a.o){let l=a.o.split(" ");for(let c=0,f=l.length;c{Fh();Ve();Ii();qh();cP();SP=class{constructor(e){this._paths=[],this._tempPaths=[],this._holes=[],this._resolution=e}moveTo(e,t){this._currentPath=new $u(e,t),this._tempPaths.push(this._currentPath)}lineTo(e,t){this._currentPath.addLineTo(e,t)}quadraticCurveTo(e,t,i,r){this._currentPath.addQuadraticCurveTo(e,t,i,r,this._resolution)}bezierCurveTo(e,t,i,r,s,a){this._currentPath.addBezierCurveTo(e,t,i,r,s,a,this._resolution)}extractHoles(){for(let e of this._tempPaths)e.area()>0?this._holes.push(e):this._paths.push(e);if(!this._paths.length&&this._holes.length){let e=this._holes;this._holes=this._paths,this._paths=e}this._tempPaths.length=0}get paths(){return this._paths}get holes(){return this._holes}}});var is,TP=C(()=>{mg();LG();zy();VG();kG();HG();XG();KG();Gk();cP();zk();Xk();Kk();Xy();Wy();jk();pP();Qk();$k();eW();rW();aW();lW();is={CreateBox:Hy,CreateTiledBox:UG,CreateSphere:Ky,CreateDisc:By,CreateIcoSphere:_P,CreateRibbon:go,CreateCylinder:jy,CreateTorus:qy,CreateTorusKnot:Zy,CreateLineSystem:sP,CreateLines:aP,CreateDashedLines:oP,ExtrudeShape:fP,ExtrudeShapeCustom:hP,CreateLathe:dP,CreateTiledPlane:FG,CreatePlane:uP,CreateGround:Vy,CreateTiledGround:Gy,CreateGroundFromHeightMap:ky,CreatePolygon:XA,ExtrudePolygon:Cg,CreateTube:mP,CreatePolyhedron:yg,CreateGeodesic:iW,CreateGoldberg:sW,CreateDecal:gP,CreateCapsule:vP,CreateText:oW}});var ys,KA=C(()=>{ys=class{constructor(){this.previousWorldMatrices={},this.previousBones={}}static AddUniforms(e){e.push("previousWorld","previousViewProjection","mPreviousBones")}static AddSamplers(e){}bindForSubMesh(e,t,i,r,s){if(t.prePassRenderer&&t.prePassRenderer.enabled&&t.prePassRenderer.currentRTisSceneRT&&(t.prePassRenderer.getIndex(2)!==-1||t.prePassRenderer.getIndex(11)!==-1)){this.previousWorldMatrices[i.uniqueId]||(this.previousWorldMatrices[i.uniqueId]=r.clone()),this.previousViewProjection||(this.previousViewProjection=t.getTransformMatrix().clone(),this.currentViewProjection=t.getTransformMatrix().clone());let a=t.getEngine();this.currentViewProjection.updateFlag!==t.getTransformMatrix().updateFlag?(this._lastUpdateFrameId=a.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection),this.currentViewProjection.copyFrom(t.getTransformMatrix())):this._lastUpdateFrameId!==a.frameId&&(this._lastUpdateFrameId=a.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection)),e.setMatrix("previousWorld",this.previousWorldMatrices[i.uniqueId]),e.setMatrix("previousViewProjection",this.previousViewProjection),this.previousWorldMatrices[i.uniqueId]=r.clone()}}}});var xr,Oa=C(()=>{xr=class{constructor(e){if(this.VERTEXOUTPUT_INVARIANT=!1,this._keys=[],this._isDirty=!0,this._areLightsDirty=!0,this._areLightsDisposed=!1,this._areAttributesDirty=!0,this._areTexturesDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!0,this._areImageProcessingDirty=!0,this._normals=!1,this._uvs=!1,this._needNormals=!1,this._needUVs=!1,this._externalProperties=e,e)for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&this._setDefaultValue(t)}get isDirty(){return this._isDirty}markAsProcessed(){this._isDirty=!1,this._areAttributesDirty=!1,this._areTexturesDirty=!1,this._areFresnelDirty=!1,this._areLightsDirty=!1,this._areLightsDisposed=!1,this._areMiscDirty=!1,this._arePrePassDirty=!1,this._areImageProcessingDirty=!1}markAsUnprocessed(){this._isDirty=!0}markAllAsDirty(){this._areTexturesDirty=!0,this._areAttributesDirty=!0,this._areLightsDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!0,this._areImageProcessingDirty=!0,this._isDirty=!0}markAsImageProcessingDirty(){this._areImageProcessingDirty=!0,this._isDirty=!0}markAsLightDirty(e=!1){this._areLightsDirty=!0,this._areLightsDisposed=this._areLightsDisposed||e,this._isDirty=!0}markAsAttributesDirty(){this._areAttributesDirty=!0,this._isDirty=!0}markAsTexturesDirty(){this._areTexturesDirty=!0,this._isDirty=!0}markAsFresnelDirty(){this._areFresnelDirty=!0,this._isDirty=!0}markAsMiscDirty(){this._areMiscDirty=!0,this._isDirty=!0}markAsPrePassDirty(){this._arePrePassDirty=!0,this._isDirty=!0}rebuild(){this._keys.length=0;for(let e of Object.keys(this))e[0]!=="_"&&this._keys.push(e);if(this._externalProperties)for(let e in this._externalProperties)this._keys.indexOf(e)===-1&&this._keys.push(e)}isEqual(e){if(this._keys.length!==e._keys.length)return!1;for(let t=0;t{zt();ki();Mi();Qy();Vn();Jy();q._LinesMeshParser=(n,e)=>Jh.Parse(n,e);Jh=class n extends q{_isShaderMaterial(e){return e?e.getClassName()==="ShaderMaterial":!1}constructor(e,t=null,i=null,r=null,s,a,o,l){super(e,t,i,r,s),this.useVertexColor=a,this.useVertexAlpha=o,this.color=new ve(1,1,1),this.alpha=1,this._shaderLanguage=0,this._ownsMaterial=!1,r&&(this.color=r.color.clone(),this.alpha=r.alpha,this.useVertexColor=r.useVertexColor,this.useVertexAlpha=r.useVertexAlpha),this.intersectionThreshold=.1;let c=[],f={attributes:[L.PositionKind],uniforms:["world","viewProjection"],needAlphaBlending:!0,defines:c,useClipPlane:null,shaderLanguage:0};if(this.useVertexAlpha?f.defines.push("#define VERTEXALPHA"):f.needAlphaBlending=!1,this.useVertexColor?(f.defines.push("#define VERTEXCOLOR"),f.attributes.push(L.ColorKind)):(f.uniforms.push("color"),this._color4=new lt),l)this.material=l;else{this.getScene().getEngine().isWebGPU&&!n.ForceGLSL&&(this._shaderLanguage=1),f.shaderLanguage=this._shaderLanguage,f.extraInitializationsAsync=async()=>{this._shaderLanguage===1?await Promise.all([Promise.resolve().then(()=>(lk(),ok)),Promise.resolve().then(()=>(pk(),mk))]):await Promise.all([Promise.resolve().then(()=>(yk(),Ck)),Promise.resolve().then(()=>(Fk(),wk))])};let d=new vo("colorShader",this.getScene(),"color",f,!1);d.doNotSerialize=!0,this._ownsMaterial=!0,this._setInternalMaterial(d)}}getClassName(){return"LinesMesh"}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){let t=this.material;if(t===e)return;let i=t&&this._ownsMaterial;this._ownsMaterial=!1,this._setInternalMaterial(e),i&&(t==null||t.dispose())}_setInternalMaterial(e){this._setMaterial(e),this.material&&(this.material.fillMode=Ee.LineListDrawMode,this.material.disableLighting=!0)}get checkCollisions(){return!1}set checkCollisions(e){}_bind(e,t){if(!this._geometry)return this;let i=this.isUnIndexed?null:this._geometry.getIndexBuffer();if(!this._userInstancedBuffersStorage||this.hasThinInstances?this._geometry._bind(t,i):this._geometry._bind(t,i,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects),!this.useVertexColor&&this._isShaderMaterial(this.material)){let{r,g:s,b:a}=this.color;this._color4.set(r,s,a,this.alpha),this.material.setColor4("color",this._color4)}return this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;let r=this.getScene().getEngine();return this._unIndexed?r.drawArraysType(Ee.LineListDrawMode,e.verticesStart,e.verticesCount,i):r.drawElementsType(Ee.LineListDrawMode,e.indexStart,e.indexCount,i),this}dispose(e,t=!1,i){var r,s;i||(this._ownsMaterial?(r=this.material)==null||r.dispose(!1,!1,!0):t&&((s=this.material)==null||s.dispose(!1,!1,!0))),super.dispose(e)}clone(e,t=null,i){if(t&&t._addToSceneRootNodes===void 0){let r=t;return r.source=this,new n(e,this.getScene(),r.parent,r.source,r.doNotCloneChildren)}return new n(e,this.getScene(),t,this,i)}createInstance(e){let t=new nP(e,this);if(this.instancedBuffers){t.instancedBuffers={};for(let i in this.instancedBuffers)t.instancedBuffers[i]=this.instancedBuffers[i]}return t}serialize(e){super.serialize(e),e.color=this.color.asArray(),e.alpha=this.alpha}static Parse(e,t){let i=new n(e.name,t);return i.color=ve.FromArray(e.color),i.alpha=e.alpha,i}};Jh.ForceGLSL=!1;nP=class extends tc{constructor(e,t){super(e,t),this.intersectionThreshold=t.intersectionThreshold}getClassName(){return"InstancedLinesMesh"}}});function Uk(n){let e=[],t=[],i=n.lines,r=n.colors,s=[],a=0;for(let l=0;l0&&(e.push(a-1),e.push(a)),a++}}let o=new Ce;return o.indices=e,o.positions=t,r&&(o.colors=s),o}function Vk(n){let e=n.dashSize||3,t=n.gapSize||1,i=n.dashNb||200,r=n.points,s=[],a=[],o=b.Zero(),l=0,c,f,h=0,d;for(d=0;d{let h=b.Zero(),d=f.length/6,u=0,m,p,_=0,g,v;for(g=0;g{Ge();Mi();dr();Bk();ki();Pt();Ce.CreateLineSystem=Uk;Ce.CreateDashedLines=Vk;q.CreateLines=(n,e,t=null,i=!1,r=null)=>aP(n,{points:e,updatable:i,instance:r},t);q.CreateDashedLines=(n,e,t,i,r,s=null,a,o)=>oP(n,{points:e,dashSize:t,gapSize:i,dashNb:r,updatable:a,instance:o},s)});var lP,Mg,XA,kk=C(()=>{Pt();Ge();ki();Mi();dr();Fh();Dn();Di();lP=class extends we{constructor(e,t){super(e.x,e.y),this.index=t}},Mg=class{constructor(){this.elements=[]}add(e){let t=[];for(let i of e){let r=new lP(i,this.elements.length);t.push(r),this.elements.push(r)}return t}computeBounds(){let e=new we(this.elements[0].x,this.elements[0].y),t=new we(this.elements[0].x,this.elements[0].y);for(let i of this.elements)i.xt.x&&(t.x=i.x),i.yt.y&&(t.y=i.y);return{min:e,max:t,width:t.x-e.x,height:t.y-e.y}}},XA=class{_addToepoint(e){for(let t of e)this._epoints.push(t.x,t.y)}constructor(e,t,i,r=earcut){this._points=new Mg,this._outlinepoints=new Mg,this._holes=new Array,this._epoints=new Array,this._eholes=new Array,this.bjsEarcut=r,this._name=e,this._scene=i||Oe.LastCreatedScene;let s;t instanceof Qu?s=t.getPoints():s=t,this._addToepoint(s),this._points.add(s),this._outlinepoints.add(s),typeof this.bjsEarcut=="undefined"&&te.Warn("Earcut was not found, the polygon will not be built.")}addHole(e){this._points.add(e);let t=new Mg;return t.add(e),this._holes.push(t),this._eholes.push(this._epoints.length/2),this._addToepoint(e),this}build(e=!1,t=0,i=2){let r=new q(this._name,this._scene),s=this.buildVertexData(t,i);return r.setVerticesData(L.PositionKind,s.positions,e),r.setVerticesData(L.NormalKind,s.normals,e),r.setVerticesData(L.UVKind,s.uvs,e),r.setIndices(s.indices),r}buildVertexData(e=0,t=2){let i=new Ce,r=[],s=[],a=[],o=this._points.computeBounds();for(let f of this._points.elements)r.push(0,1,0),s.push(f.x,0,f.y),a.push((f.x-o.min.x)/o.width,(f.y-o.min.y)/o.height);let l=[],c=this.bjsEarcut(this._epoints,this._eholes,2);for(let f=0;f0){let f=s.length/3;for(let d of this._points.elements)r.push(0,-1,0),s.push(d.x,-e,d.y),a.push(1-(d.x-o.min.x)/o.width,1-(d.y-o.min.y)/o.height);let h=l.length;for(let d=0;dc?Rc?I{Ge();zt();Mi();dr();kk();ki();Di();en();Ce.CreatePolygon=Wk;q.CreatePolygon=(n,e,t,i,r,s,a=earcut)=>YA(n,{shape:e,holes:i,updatable:r,sideOrientation:s},t,a);q.ExtrudePolygon=(n,e,t,i,r,s,a,o=earcut)=>Cg(n,{shape:e,holes:r,depth:t,updatable:s,sideOrientation:a},i,o)});function fP(n,e,t=null){let i=e.path,r=e.shape,s=e.scale||1,a=e.rotation||0,o=e.cap===0?0:e.cap||q.NO_CAP,l=e.updatable,c=q._GetDefaultSideOrientation(e.sideOrientation),f=e.instance||null,h=e.invertUV||!1,d=e.closeShape||!1,u=e.closePath||!1,m=e.capFunction||null;return Hk(n,r,i,s,a,null,null,u,d,o,!1,t,!!l,c,f,h,e.frontUVs||null,e.backUVs||null,e.firstNormal||null,!!e.adjustFrame,m)}function hP(n,e,t=null){var v;let i=e.path,r=e.shape,s=b.Zero(),a=(x,A)=>{var E,R;let S=(R=(E=e.scaleFunction)==null?void 0:E.call(e,x,A))!=null?R:1;return s.copyFromFloats(S,S,S)},o=e.rotationFunction||(()=>0),l=e.closePath||e.ribbonCloseArray||!1,c=e.closeShape||e.ribbonClosePath||!1,f=e.cap===0?0:e.cap||q.NO_CAP,h=e.updatable,d=e.firstNormal||null,u=e.adjustFrame||!1,m=q._GetDefaultSideOrientation(e.sideOrientation),p=e.instance,_=e.invertUV||!1,g=e.capFunction||null;return Hk(n,r,i,null,null,(v=e.scaleVectorFunction)!=null?v:a,o,l,c,f,!0,t,!!h,m,p||null,_,e.frontUVs||null,e.backUVs||null,d,u,g||null)}function Hk(n,e,t,i,r,s,a,o,l,c,f,h,d,u,m,p,_,g,v,x,A){let S=(D,O,V,N,F,U,G,ee,j,Z,X)=>{let Y=V.getTangents(),ue=V.getNormals(),Re=V.getBinormals(),Be=V.getDistances();if(X){for(let Ye=0;Ye0){let je=Y[Ye-1];b.Dot(je,Y[Ye])<0&&Y[Ye].scaleInPlace(-1),je=ue[Ye-1],b.Dot(je,ue[Ye])<0&&ue[Ye].scaleInPlace(-1),je=Re[Ye-1],b.Dot(je,Re[Ye])<0&&Re[Ye].scaleInPlace(-1)}}let ae=0,me=()=>F!==null?F:b.OneReadOnly,de=Z&&ee?ee:()=>U!==null?U:0,De=Z&&G?G:me,he=j===q.NO_CAP||j===q.CAP_END?0:2,Ie=$.Matrix[0];for(let Ye=0;Ye{let je=Array(),$t=b.Zero(),Lt;for(Lt=0;Lt3?0:c,R=S(e,t,I,y,E,r,s,a,c,f,x);let M=go(n,{pathArray:R,closeArray:o,closePath:l,updatable:d,sideOrientation:u,invertUV:p,frontUVs:_||void 0,backUVs:g||void 0},h);return M._creationDataStorage.pathArray=R,M._creationDataStorage.path3D=I,M._creationDataStorage.cap=c,M}var zk=C(()=>{Ge();Mi();mg();Fh();q.ExtrudeShape=(n,e,t,i,r,s,a=null,o,l,c)=>{let f={shape:e,path:t,scale:i,rotation:r,cap:s===0?0:s||q.NO_CAP,sideOrientation:l,instance:c,updatable:o};return fP(n,f,a)};q.ExtrudeShapeCustom=(n,e,t,i,r,s,a,o,l,c,f,h)=>{let d={shape:e,path:t,scaleFunction:i,rotationFunction:r,ribbonCloseArray:s,ribbonClosePath:a,cap:o===0?0:o||q.NO_CAP,sideOrientation:f,instance:h,updatable:c};return hP(n,d,l)}});function dP(n,e,t=null){let i=e.arc?e.arc<=0||e.arc>1?1:e.arc:1,r=e.closed===void 0?!0:e.closed,s=e.shape,a=e.radius||1,o=e.tessellation||64,l=e.clip||0,c=e.updatable,f=q._GetDefaultSideOrientation(e.sideOrientation),h=e.cap||q.NO_CAP,d=Math.PI*2,u=[],m=e.invertUV||!1,p,_,g=d/o*i,v,x;for(p=0;p<=o-l;p++){for(x=[],(h==q.CAP_START||h==q.CAP_ALL)&&(x.push(new b(0,s[0].y,0)),x.push(new b(Math.cos(p*g)*s[0].x*a,s[0].y,Math.sin(p*g)*s[0].x*a))),_=0;_{Ge();Mi();mg();q.CreateLathe=(n,e,t,i,r,s,a)=>dP(n,{shape:e,radius:t,tessellation:i,sideOrientation:a,updatable:s},r)});function Yk(n){let e=[],t=[],i=[],r=[],s=n.width!==void 0?n.width:n.size!==void 0?n.size:1,a=n.height!==void 0?n.height:n.size!==void 0?n.size:1,o=n.sideOrientation===0?0:n.sideOrientation||Ce.DEFAULTSIDE,l=s/2,c=a/2;t.push(-l,-c,0),i.push(0,0,-1),r.push(0,Mt?1:0),t.push(l,-c,0),i.push(0,0,-1),r.push(1,Mt?1:0),t.push(l,c,0),i.push(0,0,-1),r.push(1,Mt?0:1),t.push(-l,c,0),i.push(0,0,-1),r.push(0,Mt?0:1),e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),Ce._ComputeSides(o,t,e,i,r,n.frontUVs,n.backUVs);let f=new Ce;return f.indices=e,f.positions=t,f.normals=i,f.uvs=r,f}function uP(n,e={},t=null){let i=new q(n,t);return e.sideOrientation=q._GetDefaultSideOrientation(e.sideOrientation),i._originalBuilderSideOrientation=e.sideOrientation,Yk(e).applyToMesh(i,e.updatable),e.sourcePlane&&(i.translate(e.sourcePlane.normal,-e.sourcePlane.d),i.setDirection(e.sourcePlane.normal.scale(-1))),i}var Kk=C(()=>{Mi();dr();en();Ce.CreatePlane=Yk;q.CreatePlane=(n,e,t,i,r)=>uP(n,{size:e,width:e,height:e,sideOrientation:r,updatable:i},t)});function mP(n,e,t=null){let i=e.path,r=e.instance,s=1;e.radius!==void 0?s=e.radius:r&&(s=r._creationDataStorage.radius);let a=e.tessellation||64,o=e.radiusFunction||null,l=e.cap||q.NO_CAP,c=e.invertUV||!1,f=e.updatable,h=q._GetDefaultSideOrientation(e.sideOrientation);e.arc=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1;let d=(g,v,x,A,S,E,R,I)=>{let y=v.getTangents(),M=v.getNormals(),D=v.getDistances(),V=Math.PI*2/S*I,F=E||(()=>A),U,G,ee,j,Z=$.Matrix[0],X=R===q.NO_CAP||R===q.CAP_END?0:2;for(let ue=0;ue{let Be=Array();for(let ae=0;ae3?0:l,m=d(i,u,p,s,a,o,l,e.arc);let _=go(n,{pathArray:m,closePath:!0,closeArray:!1,updatable:f,sideOrientation:h,invertUV:c,frontUVs:e.frontUVs,backUVs:e.backUVs},t);return _._creationDataStorage.pathArray=m,_._creationDataStorage.path3D=u,_._creationDataStorage.tessellation=a,_._creationDataStorage.cap=l,_._creationDataStorage.arc=e.arc,_._creationDataStorage.radius=s,_}var jk=C(()=>{Ge();Mi();mg();Fh();q.CreateTube=(n,e,t,i,r,s,a,o,l,c)=>mP(n,{path:e,radius:t,tessellation:i,radiusFunction:r,arc:1,cap:s,updatable:o,sideOrientation:l,instance:c},a)});function qk(n){let e=[];e[0]={vertex:[[0,0,1.732051],[1.632993,0,-.5773503],[-.8164966,1.414214,-.5773503],[-.8164966,-1.414214,-.5773503]],face:[[0,1,2],[0,2,3],[0,3,1],[1,3,2]]},e[1]={vertex:[[0,0,1.414214],[1.414214,0,0],[0,1.414214,0],[-1.414214,0,0],[0,-1.414214,0],[0,0,-1.414214]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,1],[1,4,5],[1,5,2],[2,5,3],[3,5,4]]},e[2]={vertex:[[0,0,1.070466],[.7136442,0,.7978784],[-.3568221,.618034,.7978784],[-.3568221,-.618034,.7978784],[.7978784,.618034,.3568221],[.7978784,-.618034,.3568221],[-.9341724,.381966,.3568221],[.1362939,1,.3568221],[.1362939,-1,.3568221],[-.9341724,-.381966,.3568221],[.9341724,.381966,-.3568221],[.9341724,-.381966,-.3568221],[-.7978784,.618034,-.3568221],[-.1362939,1,-.3568221],[-.1362939,-1,-.3568221],[-.7978784,-.618034,-.3568221],[.3568221,.618034,-.7978784],[.3568221,-.618034,-.7978784],[-.7136442,0,-.7978784],[0,0,-1.070466]],face:[[0,1,4,7,2],[0,2,6,9,3],[0,3,8,5,1],[1,5,11,10,4],[2,7,13,12,6],[3,9,15,14,8],[4,10,16,13,7],[5,8,14,17,11],[6,12,18,15,9],[10,11,17,19,16],[12,13,16,19,18],[14,15,18,19,17]]},e[3]={vertex:[[0,0,1.175571],[1.051462,0,.5257311],[.3249197,1,.5257311],[-.8506508,.618034,.5257311],[-.8506508,-.618034,.5257311],[.3249197,-1,.5257311],[.8506508,.618034,-.5257311],[.8506508,-.618034,-.5257311],[-.3249197,1,-.5257311],[-1.051462,0,-.5257311],[-.3249197,-1,-.5257311],[0,0,-1.175571]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,5],[0,5,1],[1,5,7],[1,7,6],[1,6,2],[2,6,8],[2,8,3],[3,8,9],[3,9,4],[4,9,10],[4,10,5],[5,10,7],[6,7,11],[6,11,8],[7,10,11],[8,11,9],[9,11,10]]},e[4]={vertex:[[0,0,1.070722],[.7148135,0,.7971752],[-.104682,.7071068,.7971752],[-.6841528,.2071068,.7971752],[-.104682,-.7071068,.7971752],[.6101315,.7071068,.5236279],[1.04156,.2071068,.1367736],[.6101315,-.7071068,.5236279],[-.3574067,1,.1367736],[-.7888348,-.5,.5236279],[-.9368776,.5,.1367736],[-.3574067,-1,.1367736],[.3574067,1,-.1367736],[.9368776,-.5,-.1367736],[.7888348,.5,-.5236279],[.3574067,-1,-.1367736],[-.6101315,.7071068,-.5236279],[-1.04156,-.2071068,-.1367736],[-.6101315,-.7071068,-.5236279],[.104682,.7071068,-.7971752],[.6841528,-.2071068,-.7971752],[.104682,-.7071068,-.7971752],[-.7148135,0,-.7971752],[0,0,-1.070722]],face:[[0,2,3],[1,6,5],[4,9,11],[7,15,13],[8,16,10],[12,14,19],[17,22,18],[20,21,23],[0,1,5,2],[0,3,9,4],[0,4,7,1],[1,7,13,6],[2,5,12,8],[2,8,10,3],[3,10,17,9],[4,11,15,7],[5,6,14,12],[6,13,20,14],[8,12,19,16],[9,17,18,11],[10,16,22,17],[11,18,21,15],[13,15,21,20],[14,20,23,19],[16,19,23,22],[18,22,23,21]]},e[5]={vertex:[[0,0,1.322876],[1.309307,0,.1889822],[-.9819805,.8660254,.1889822],[.1636634,-1.299038,.1889822],[.3273268,.8660254,-.9449112],[-.8183171,-.4330127,-.9449112]],face:[[0,3,1],[2,4,5],[0,1,4,2],[0,2,5,3],[1,3,5,4]]},e[6]={vertex:[[0,0,1.159953],[1.013464,0,.5642542],[-.3501431,.9510565,.5642542],[-.7715208,-.6571639,.5642542],[.6633206,.9510565,-.03144481],[.8682979,-.6571639,-.3996071],[-1.121664,.2938926,-.03144481],[-.2348831,-1.063314,-.3996071],[.5181548,.2938926,-.9953061],[-.5850262,-.112257,-.9953061]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,9,7],[5,7,9,8],[0,3,7,5,1],[2,4,8,9,6]]},e[7]={vertex:[[0,0,1.118034],[.8944272,0,.6708204],[-.2236068,.8660254,.6708204],[-.7826238,-.4330127,.6708204],[.6708204,.8660254,.2236068],[1.006231,-.4330127,-.2236068],[-1.006231,.4330127,.2236068],[-.6708204,-.8660254,-.2236068],[.7826238,.4330127,-.6708204],[.2236068,-.8660254,-.6708204],[-.8944272,0,-.6708204],[0,0,-1.118034]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,10,7],[5,9,11,8],[7,10,11,9],[0,3,7,9,5,1],[2,4,8,11,10,6]]},e[8]={vertex:[[-.729665,.670121,.319155],[-.655235,-.29213,-.754096],[-.093922,-.607123,.537818],[.702196,.595691,.485187],[.776626,-.36656,-.588064]],face:[[1,4,2],[0,1,2],[3,0,2],[4,3,2],[4,1,0,3]]},e[9]={vertex:[[-.868849,-.100041,.61257],[-.329458,.976099,.28078],[-.26629,-.013796,-.477654],[-.13392,-1.034115,.229829],[.738834,.707117,-.307018],[.859683,-.535264,-.338508]],face:[[3,0,2],[5,3,2],[4,5,2],[1,4,2],[0,1,2],[0,3,5,4,1]]},e[10]={vertex:[[-.610389,.243975,.531213],[-.187812,-.48795,-.664016],[-.187812,.9759,-.664016],[.187812,-.9759,.664016],[.798201,.243975,.132803]],face:[[1,3,0],[3,4,0],[3,1,4],[0,2,1],[0,4,2],[2,4,1]]},e[11]={vertex:[[-1.028778,.392027,-.048786],[-.640503,-.646161,.621837],[-.125162,-.395663,-.540059],[.004683,.888447,-.651988],[.125161,.395663,.540059],[.632925,-.791376,.433102],[1.031672,.157063,-.354165]],face:[[3,2,0],[2,1,0],[2,5,1],[0,4,3],[0,1,4],[4,1,5],[2,3,6],[3,4,6],[5,2,6],[4,5,6]]},e[12]={vertex:[[-.669867,.334933,-.529576],[-.669867,.334933,.529577],[-.4043,1.212901,0],[-.334933,-.669867,-.529576],[-.334933,-.669867,.529577],[.334933,.669867,-.529576],[.334933,.669867,.529577],[.4043,-1.212901,0],[.669867,-.334933,-.529576],[.669867,-.334933,.529577]],face:[[8,9,7],[6,5,2],[3,8,7],[5,0,2],[4,3,7],[0,1,2],[9,4,7],[1,6,2],[9,8,5,6],[8,3,0,5],[3,4,1,0],[4,9,6,1]]},e[13]={vertex:[[-.931836,.219976,-.264632],[-.636706,.318353,.692816],[-.613483,-.735083,-.264632],[-.326545,.979634,0],[-.318353,-.636706,.692816],[-.159176,.477529,-.856368],[.159176,-.477529,-.856368],[.318353,.636706,.692816],[.326545,-.979634,0],[.613482,.735082,-.264632],[.636706,-.318353,.692816],[.931835,-.219977,-.264632]],face:[[11,10,8],[7,9,3],[6,11,8],[9,5,3],[2,6,8],[5,0,3],[4,2,8],[0,1,3],[10,4,8],[1,7,3],[10,11,9,7],[11,6,5,9],[6,2,0,5],[2,4,1,0],[4,10,7,1]]},e[14]={vertex:[[-.93465,.300459,-.271185],[-.838689,-.260219,-.516017],[-.711319,.717591,.128359],[-.710334,-.156922,.080946],[-.599799,.556003,-.725148],[-.503838,-.004675,-.969981],[-.487004,.26021,.48049],[-.460089,-.750282,-.512622],[-.376468,.973135,-.325605],[-.331735,-.646985,.084342],[-.254001,.831847,.530001],[-.125239,-.494738,-.966586],[.029622,.027949,.730817],[.056536,-.982543,-.262295],[.08085,1.087391,.076037],[.125583,-.532729,.485984],[.262625,.599586,.780328],[.391387,-.726999,-.716259],[.513854,-.868287,.139347],[.597475,.85513,.326364],[.641224,.109523,.783723],[.737185,-.451155,.538891],[.848705,-.612742,-.314616],[.976075,.365067,.32976],[1.072036,-.19561,.084927]],face:[[15,18,21],[12,20,16],[6,10,2],[3,0,1],[9,7,13],[2,8,4,0],[0,4,5,1],[1,5,11,7],[7,11,17,13],[13,17,22,18],[18,22,24,21],[21,24,23,20],[20,23,19,16],[16,19,14,10],[10,14,8,2],[15,9,13,18],[12,15,21,20],[6,12,16,10],[3,6,2,0],[9,3,1,7],[9,15,12,6,3],[22,17,11,5,4,8,14,19,23,24]]};let t=n.type&&(n.type<0||n.type>=e.length)?0:n.type||0,i=n.size,r=n.sizeX||i||1,s=n.sizeY||i||1,a=n.sizeZ||i||1,o=n.custom||e[t],l=o.face.length,c=n.faceUV||new Array(l),f=n.faceColors,h=n.flat===void 0?!0:n.flat,d=n.sideOrientation===0?0:n.sideOrientation||Ce.DEFAULTSIDE,u=[],m=[],p=[],_=[],g=[],v=0,x=0,A=[],S,E,R,I,y,M,D,O;if(h)for(E=0;E{Ge();zt();Mi();dr();en();Ce.CreatePolyhedron=qk;q.CreatePolyhedron=(n,e,t)=>yg(n,e,t)});function Zk(n){let e=n.sideOrientation||Ce.DEFAULTSIDE,t=n.radius||1,i=n.flat===void 0?!0:n.flat,r=(n.subdivisions||4)|0,s=n.radiusX||t,a=n.radiusY||t,o=n.radiusZ||t,l=(1+Math.sqrt(5))/2,c=[-1,l,-0,1,l,0,-1,-l,0,1,-l,0,0,-1,-l,0,1,-l,0,-1,l,0,1,l,l,0,1,l,0,-1,-l,0,1,-l,0,-1],f=[0,11,5,0,5,1,0,1,7,0,7,10,12,22,23,1,5,20,5,11,4,23,22,13,22,18,6,7,1,8,14,21,4,14,4,2,16,13,6,15,6,19,3,8,9,4,21,5,13,17,23,6,13,22,19,6,18,9,8,1],h=[0,1,2,3,4,5,6,7,8,9,10,11,0,2,3,3,3,4,7,8,9,9,10,11],d=[5,1,3,1,6,4,0,0,5,3,4,2,2,2,4,0,2,0,1,1,6,0,6,2,0,4,3,3,4,4,3,1,4,2,4,4,0,2,1,1,2,2,3,3,1,3,2,4],u=138/1024,m=239/1024,p=60/1024,_=26/1024,g=-40/1024,v=20/1024,x=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],A=[],S=[],E=[],R=[],I=0,y=new Array(3),M=new Array(3),D;for(D=0;D<3;D++)y[D]=b.Zero(),M[D]=we.Zero();for(let V=0;V<20;V++){for(D=0;D<3;D++){let F=f[3*V+D];y[D].copyFromFloats(c[3*h[F]],c[3*h[F]+1],c[3*h[F]+2]),y[D].normalize(),M[D].copyFromFloats(d[2*F]*u+p+x[V]*g,d[2*F+1]*m+_+x[V]*v)}let N=(F,U,G,ee)=>{let j=b.Lerp(y[0],y[2],U/r),Z=b.Lerp(y[1],y[2],U/r),X=r===U?y[2]:b.Lerp(j,Z,F/(r-U));X.normalize();let Y;if(i){let ae=b.Lerp(y[0],y[2],ee/r),me=b.Lerp(y[1],y[2],ee/r);Y=b.Lerp(ae,me,G/(r-ee))}else Y=new b(X.x,X.y,X.z);Y.x/=s,Y.y/=a,Y.z/=o,Y.normalize();let ue=we.Lerp(M[0],M[2],U/r),Re=we.Lerp(M[1],M[2],U/r),Be=r===U?M[2]:we.Lerp(ue,Re,F/(r-U));S.push(X.x*s,X.y*a,X.z*o),E.push(Y.x,Y.y,Y.z),R.push(Be.x,Mt?1-Be.y:Be.y),A.push(I),I++};for(let F=0;F{Ge();Mi();dr();en();Ce.CreateIcoSphere=Zk;q.CreateIcoSphere=(n,e,t)=>_P(n,e,t)});function gP(n,e,t){var G,ee,j,Z,X;let i=!!e.skeleton,r=!!((G=e.morphTargetManager)!=null&&G.numTargets),s=t.localMode||i,a=e.getIndices(),o=i||r?e.getPositionData(!0,!0):e.getVerticesData(L.PositionKind),l=i||r?e.getNormalsData(!0,!0):e.getVerticesData(L.NormalKind),c=s?i?e.getVerticesData(L.PositionKind):o:null,f=s?i?e.getVerticesData(L.NormalKind):l:null,h=e.getVerticesData(L.UVKind),d=i?e.getVerticesData(L.MatricesIndicesKind):null,u=i?e.getVerticesData(L.MatricesWeightsKind):null,m=i?e.getVerticesData(L.MatricesIndicesExtraKind):null,p=i?e.getVerticesData(L.MatricesWeightsExtraKind):null,_=t.position||b.Zero(),g=t.normal||b.Up(),v=t.size||b.One(),x=t.angle||0;if(!g){let Y=new b(0,0,1),ue=e.getScene().activeCamera,Re=b.TransformCoordinates(Y,ue.getWorldMatrix());g=ue.globalPosition.subtract(Re)}let A=-Math.atan2(g.z,g.x)-Math.PI/2,S=Math.sqrt(g.x*g.x+g.z*g.z),E=Math.atan2(g.y,S),R=new Ce;R.indices=[],R.positions=[],R.normals=[],R.uvs=[],R.matricesIndices=i?[]:null,R.matricesWeights=i?[]:null,R.matricesIndicesExtra=m?[]:null,R.matricesWeightsExtra=p?[]:null;let I=0,y=(Y,ue)=>{let Re=new KA;if(!a||!o||!l)return Re;let Be=a[Y];if(Re.vertexIdx=Be*3,Re.vertexIdxForBones=Be*4,Re.position=new b(o[Be*3],o[Be*3+1],o[Be*3+2]),b.TransformCoordinatesToRef(Re.position,ue,Re.position),Re.normal=new b(l[Be*3],l[Be*3+1],l[Be*3+2]),b.TransformNormalToRef(Re.normal,ue,Re.normal),t.captureUVS&&h){let ae=h[Be*2+1];Re.uv=new we(h[Be*2],Mt?1-ae:ae)}return Re},M=[0,0,0,0],D=(Y,ue)=>{if(Y.length===0)return Y;let Re=.5*Math.abs(b.Dot(v,ue)),Be=(re,de,De,he)=>{for(let Ie=0;Ie{var Pe,Ve,$e,rt,ye,be,ct,Tt,nt,Ze,Wt,jt,se,Q,Le,Ae;let De=b.GetClipFactor(re.position,de.position,ue,Re),he=M,Ie=M;if(d&&u){let Je=re.matrixIndicesOverride?0:re.vertexIdxForBones,Ke=(Pe=re.matrixIndicesOverride)!=null?Pe:d,Fe=(Ve=re.matrixWeightsOverride)!=null?Ve:u,At=de.matrixIndicesOverride?0:de.vertexIdxForBones,qt=($e=de.matrixIndicesOverride)!=null?$e:d,Ji=(rt=de.matrixWeightsOverride)!=null?rt:u;he=[0,0,0,0],Ie=[0,0,0,0];let vi=0;for(let ji=0;ji<4;++ji)if(Fe[Je+ji]>0){let Fa=Be(qt,Ke[Je+ji],At,4);he[vi]=Ke[Je+ji],Ie[vi]=Ja(Fe[Je+ji],Fa>=0?Ji[Fa]:0,De),vi++}for(let ji=0;ji<4&&vi<4;++ji){let Fa=qt[At+ji];Be(Ke,Fa,Je,4)===-1&&(he[vi]=Fa,Ie[vi]=Ja(0,Ji[At+ji],De),vi++)}let xn=Ie[0]+Ie[1]+Ie[2]+Ie[3];Ie[0]/=xn,Ie[1]/=xn,Ie[2]/=xn,Ie[3]/=xn}let ze=re.localPositionOverride?re.localPositionOverride[0]:(ye=c==null?void 0:c[re.vertexIdx])!=null?ye:0,St=re.localPositionOverride?re.localPositionOverride[1]:(be=c==null?void 0:c[re.vertexIdx+1])!=null?be:0,Ye=re.localPositionOverride?re.localPositionOverride[2]:(ct=c==null?void 0:c[re.vertexIdx+2])!=null?ct:0,je=de.localPositionOverride?de.localPositionOverride[0]:(Tt=c==null?void 0:c[de.vertexIdx])!=null?Tt:0,$t=de.localPositionOverride?de.localPositionOverride[1]:(nt=c==null?void 0:c[de.vertexIdx+1])!=null?nt:0,Lt=de.localPositionOverride?de.localPositionOverride[2]:(Ze=c==null?void 0:c[de.vertexIdx+2])!=null?Ze:0,xi=re.localNormalOverride?re.localNormalOverride[0]:(Wt=f==null?void 0:f[re.vertexIdx])!=null?Wt:0,oe=re.localNormalOverride?re.localNormalOverride[1]:(jt=f==null?void 0:f[re.vertexIdx+1])!=null?jt:0,Ui=re.localNormalOverride?re.localNormalOverride[2]:(se=f==null?void 0:f[re.vertexIdx+2])!=null?se:0,ti=de.localNormalOverride?de.localNormalOverride[0]:(Q=f==null?void 0:f[de.vertexIdx])!=null?Q:0,Ni=de.localNormalOverride?de.localNormalOverride[1]:(Le=f==null?void 0:f[de.vertexIdx+1])!=null?Le:0,ot=de.localNormalOverride?de.localNormalOverride[2]:(Ae=f==null?void 0:f[de.vertexIdx+2])!=null?Ae:0,yi=xi+(ti-xi)*De,z=oe+(Ni-oe)*De,B=Ui+(ot-Ui)*De,pe=Math.sqrt(yi*yi+z*z+B*B);return new KA(b.Lerp(re.position,de.position,De),b.Lerp(re.normal,de.normal,De).normalize(),we.Lerp(re.uv,de.uv,De),-1,-1,c?[ze+(je-ze)*De,St+($t-St)*De,Ye+(Lt-Ye)*De]:null,f?[yi/pe,z/pe,B/pe]:null,he,Ie)},me=null;Y.length>3&&(me=[]);for(let re=0;re0,$t=St>0,Lt=Ye>0;switch((je?1:0)+($t?1:0)+(Lt?1:0)){case 0:Y.length>3?(me.push(Y[re]),me.push(Y[re+1]),me.push(Y[re+2])):me=Y;break;case 1:if(me=me!=null?me:new Array,je&&(de=Y[re+1],De=Y[re+2],he=ae(Y[re],de),Ie=ae(Y[re],De)),$t){de=Y[re],De=Y[re+2],he=ae(Y[re+1],de),Ie=ae(Y[re+1],De),me.push(he),me.push(De.clone()),me.push(de.clone()),me.push(De.clone()),me.push(he.clone()),me.push(Ie);break}Lt&&(de=Y[re],De=Y[re+1],he=ae(Y[re+2],de),Ie=ae(Y[re+2],De)),de&&De&&he&&Ie&&(me.push(de.clone()),me.push(De.clone()),me.push(he),me.push(Ie),me.push(he.clone()),me.push(De.clone()));break;case 2:me=me!=null?me:new Array,je||(de=Y[re].clone(),De=ae(de,Y[re+1]),he=ae(de,Y[re+2]),me.push(de),me.push(De),me.push(he)),$t||(de=Y[re+1].clone(),De=ae(de,Y[re+2]),he=ae(de,Y[re]),me.push(de),me.push(De),me.push(he)),Lt||(de=Y[re+2].clone(),De=ae(de,Y[re]),he=ae(de,Y[re+1]),me.push(de),me.push(De),me.push(he));break;case 3:break}}return me},O=e instanceof q?e:null,V=O==null?void 0:O._thinInstanceDataStorage.matrixData,N=(O==null?void 0:O.thinInstanceCount)||1,F=$.Matrix[0];F.copyFrom(K.IdentityReadOnly);for(let Y=0;Y{Ge();Ln();Mi();ki();dr();en();dae=new b(1,0,0),uae=new b(-1,0,0),mae=new b(0,1,0),pae=new b(0,-1,0),_ae=new b(0,0,1),gae=new b(0,0,-1),KA=class n{constructor(e=b.Zero(),t=b.Up(),i=we.Zero(),r=0,s=0,a=null,o=null,l=null,c=null){this.position=e,this.normal=t,this.uv=i,this.vertexIdx=r,this.vertexIdxForBones=s,this.localPositionOverride=a,this.localNormalOverride=o,this.matrixIndicesOverride=l,this.matrixWeightsOverride=c}clone(){var e,t,i,r;return new n(this.position.clone(),this.normal.clone(),this.uv.clone(),this.vertexIdx,this.vertexIdxForBones,(e=this.localPositionOverride)==null?void 0:e.slice(),(t=this.localNormalOverride)==null?void 0:t.slice(),(i=this.matrixIndicesOverride)==null?void 0:i.slice(),(r=this.matrixWeightsOverride)==null?void 0:r.slice())}};q.CreateDecal=(n,e,t,i,r,s)=>gP(n,e,{position:t,normal:i,size:r,angle:s})});function Jk(n={subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){let e=Math.max(n.subdivisions?n.subdivisions:2,1)|0,t=Math.max(n.tessellation?n.tessellation:16,3)|0,i=Math.max(n.height?n.height:1,0),r=Math.max(n.radius?n.radius:.25,0),s=Math.max(n.capSubdivisions?n.capSubdivisions:6,1)|0,a=t,o=e,l=Math.max(n.radiusTop?n.radiusTop:r,0),c=Math.max(n.radiusBottom?n.radiusBottom:r,0),f=i-(l+c),h=0,d=2*Math.PI,u=Math.max(n.topCapSubdivisions?n.topCapSubdivisions:s,1),m=Math.max(n.bottomCapSubdivisions?n.bottomCapSubdivisions:s,1),p=Math.acos((c-l)/i),_=[],g=[],v=[],x=[],A=0,S=[],E=f*.5,R=Math.PI*.5,I,y,M=b.Zero(),D=b.Zero(),O=Math.cos(p),V=Math.sin(p),N=new we(l*V,E+l*O).subtract(new we(c*V,-E+c*O)).length(),F=l*p+N+c*(R-p),U=0;for(y=0;y<=u;y++){let Z=[],X=R-p*(y/u);U+=l*p/u;let Y=Math.cos(X),ue=Math.sin(X),Re=Y*l;for(I=0;I<=a;I++){let Be=I/a,ae=Be*d+h,me=Math.sin(ae),re=Math.cos(ae);D.x=Re*me,D.y=E+ue*l,D.z=Re*re,g.push(D.x,D.y,D.z),M.set(Y*me,ue,Y*re),v.push(M.x,M.y,M.z),x.push(Be,Mt?U/F:1-U/F),Z.push(A),A++}S.push(Z)}let G=i-l-c+O*l-O*c,ee=V*(c-l)/G;for(y=1;y<=o;y++){let Z=[];U+=N/o;let X=V*(y*(c-l)/o+l);for(I=0;I<=a;I++){let Y=I/a,ue=Y*d+h,Re=Math.sin(ue),Be=Math.cos(ue);D.x=X*Re,D.y=E+O*l-y*G/o,D.z=X*Be,g.push(D.x,D.y,D.z),M.set(Re,ee,Be).normalize(),v.push(M.x,M.y,M.z),x.push(Y,Mt?U/F:1-U/F),Z.push(A),A++}S.push(Z)}for(y=1;y<=m;y++){let Z=[],X=R-p-(Math.PI-p)*(y/m);U+=c*p/m;let Y=Math.cos(X),ue=Math.sin(X),Re=Y*c;for(I=0;I<=a;I++){let Be=I/a,ae=Be*d+h,me=Math.sin(ae),re=Math.cos(ae);D.x=Re*me,D.y=-E+ue*c,D.z=Re*re,g.push(D.x,D.y,D.z),M.set(Y*me,ue,Y*re),v.push(M.x,M.y,M.z),x.push(Be,Mt?U/F:1-U/F),Z.push(A),A++}S.push(Z)}for(I=0;I{dr();Ge();Mi();en();q.CreateCapsule=(n,e,t)=>vP(n,e,t);Ce.CreateCapsule=Jk});var Ki,tW=C(()=>{Pt();Ge();Ki=class n{constructor(e=0,t=0){this.x=e,this.y=t,e!==Math.floor(e)&&(e=Math.floor(e),te.Warn("x is not an integer, floor(x) used")),t!==Math.floor(t)&&(t=Math.floor(t),te.Warn("y is not an integer, floor(y) used"))}clone(){return new n(this.x,this.y)}rotate60About(e){let t=this.x;return this.x=e.x+e.y-this.y,this.y=t+this.y-e.x,this}rotateNeg60About(e){let t=this.x;return this.x=t+this.y-e.y,this.y=e.x+e.y-t,this}rotate120(e,t){e!==Math.floor(e)&&(e=Math.floor(e),te.Warn("m not an integer only floor(m) used")),t!==Math.floor(t)&&(t=Math.floor(t),te.Warn("n not an integer only floor(n) used"));let i=this.x;return this.x=e-i-this.y,this.y=t+i,this}rotateNeg120(e,t){e!==Math.floor(e)&&(e=Math.floor(e),te.Warn("m is not an integer, floor(m) used")),t!==Math.floor(t)&&(t=Math.floor(t),te.Warn("n is not an integer, floor(n) used"));let i=this.x;return this.x=this.y-t,this.y=e+t-i-this.y,this}toCartesianOrigin(e,t){let i=b.Zero();return i.x=e.x+2*this.x*t+this.y*t,i.y=e.y+Math.sqrt(3)*this.y*t,i}static Zero(){return new n(0,0)}}});var km,Pg,Wm,EP=C(()=>{Ge();Ln();Dn();tW();km=class{constructor(){this.cartesian=[],this.vertices=[],this.max=[],this.min=[],this.closestTo=[],this.innerFacets=[],this.isoVecsABOB=[],this.isoVecsOBOA=[],this.isoVecsBAOA=[],this.vertexTypes=[],this.IDATA=new Pg("icosahedron","Regular",[[0,_r,-1],[-_r,1,0],[-1,0,-_r],[1,0,-_r],[_r,1,0],[0,_r,1],[-1,0,_r],[-_r,-1,0],[0,-_r,-1],[_r,-1,0],[1,0,_r],[0,-_r,1]],[[0,2,1],[0,3,2],[0,4,3],[0,5,4],[0,1,5],[7,6,1],[8,7,2],[9,8,3],[10,9,4],[6,10,5],[2,7,1],[3,8,2],[4,9,3],[5,10,4],[1,6,5],[11,6,7],[11,7,8],[11,8,9],[11,9,10],[11,10,6]])}setIndices(){let e=12,t={},i=this.m,r=this.n,s=i;r!==0&&(s=wT(i,r));let a=i/s,o=r/s,l,c,f,h,d,u=Ki.Zero(),m=new Ki(i,r),p=new Ki(-r,i+r),_=Ki.Zero(),g=Ki.Zero(),v=Ki.Zero(),x=[],A,S,E,R,I=[],y=this.vertByDist,M=(D,O,V,N)=>{A=D+"|"+V,S=O+"|"+N,A in t||S in t?A in t&&!(S in t)?t[S]=t[A]:S in t&&!(A in t)&&(t[A]=t[S]):(t[A]=e,t[S]=e,e++),y[V][0]>2?I[t[A]]=[-y[V][0],y[V][1],t[A]]:I[t[A]]=[x[y[V][0]],y[V][1],t[A]]};this.IDATA.edgematch=[[1,"B"],[2,"B"],[3,"B"],[4,"B"],[0,"B"],[10,"O",14,"A"],[11,"O",10,"A"],[12,"O",11,"A"],[13,"O",12,"A"],[14,"O",13,"A"],[0,"O"],[1,"O"],[2,"O"],[3,"O"],[4,"O"],[19,"B",5,"A"],[15,"B",6,"A"],[16,"B",7,"A"],[17,"B",8,"A"],[18,"B",9,"A"]];for(let D=0;D<20;D++){if(x=this.IDATA.face[D],f=x[2],h=x[1],d=x[0],E=u.x+"|"+u.y,A=D+"|"+E,A in t||(t[A]=f,I[f]=[x[y[E][0]],y[E][1]]),E=m.x+"|"+m.y,A=D+"|"+E,A in t||(t[A]=h,I[h]=[x[y[E][0]],y[E][1]]),E=p.x+"|"+p.y,A=D+"|"+E,A in t||(t[A]=d,I[d]=[x[y[E][0]],y[E][1]]),l=this.IDATA.edgematch[D][0],c=this.IDATA.edgematch[D][1],c==="B")for(let O=1;O2?I[t[A]]=[-y[E][0],y[E][1],t[A]]:I[t[A]]=[x[y[E][0]],y[E][1],t[A]])}this.closestTo=I,this.vecToidx=t}calcCoeffs(){let e=this.m,t=this.n,i=Math.sqrt(3)/3,r=e*e+t*t+e*t;this.coau=(e+t)/r,this.cobu=-t/r,this.coav=-i*(e-t)/r,this.cobv=i*(2*e+t)/r}createInnerFacets(){let e=this.m,t=this.n;for(let i=0;i0&&r0){let S=wT(e,t),E=e/S,R=t/S;for(let y=1;yS.x-E.x),i.sort((S,E)=>S.y-E.y);let o=new Array(e+t+1),l=new Array(e+t+1);for(let S=0;S{let R=S.clone();return E==="A"&&R.rotateNeg120(e,t),E==="B"&&R.rotate120(e,t),R.x<0?R.y:R.x+R.y},u=[],m=[],p=[],_=[],g={},v=[],x=-1,A=-1;for(let S=0;SS[2]-E[2]),v.sort((S,E)=>S[3]-E[3]),v.sort((S,E)=>S[1]-E[1]),v.sort((S,E)=>S[0]-E[0]);for(let S=0;St.vecToidx[e+r]))}mapABOBtoDATA(e,t){let i=t.IDATA.edgematch[e][0];for(let r=0;r-1?i[a][1]>0&&t[i[a][0]].push([a,i[a][1]]):t[12].push([a,i[a][0]]);let r=[];for(let a=0;a<12;a++)r[a]=a;let s=12;for(let a=0;a<12;a++){t[a].sort((o,l)=>o[1]-l[1]);for(let o=0;oa[3]-o[3]);for(let a=0;a0;)s=t[l],this.face[s].indexOf(o)>-1?(a=(this.face[s].indexOf(o)+1)%3,o=this.face[s][a],i.push(o),r.push(s),t.splice(l,1),l=0):l++;return this.adjacentFaces.push(i),r}toGoldbergPolyhedronData(){let e=new Pg("GeoDual","Goldberg",[],[]);e.name="GD dual";let t=this.vertex.length,i=new Array(t);for(let c=0;ci){let c=r;r=i,i=c,te.Warn("n > m therefore m and n swapped")}let s=new km;s.build(i,r);let o={custom:Wm.BuildGeodesicData(s),size:e.size,sizeX:e.sizeX,sizeY:e.sizeY,sizeZ:e.sizeZ,faceUV:e.faceUV,faceColors:e.faceColors,flat:e.flat,updatable:e.updatable,sideOrientation:e.sideOrientation,frontUVs:e.frontUVs,backUVs:e.backUVs};return yg(n,o,t)}var rW=C(()=>{pP();Pt();EP()});var Dg,nW=C(()=>{Ge();ki();Mi();zt();Pt();q._GoldbergMeshParser=(n,e)=>Dg.Parse(n,e);Dg=class n extends q{constructor(){super(...arguments),this.goldbergData={faceColors:[],faceCenters:[],faceZaxis:[],faceXaxis:[],faceYaxis:[],nbSharedFaces:0,nbUnsharedFaces:0,nbFaces:0,nbFacesAtPole:0,adjacentFaces:[]}}relatedGoldbergFace(e,t){return t===void 0?(e>this.goldbergData.nbUnsharedFaces-1&&(te.Warn("Maximum number of unshared faces used"),e=this.goldbergData.nbUnsharedFaces-1),this.goldbergData.nbUnsharedFaces+e):(e>11&&(te.Warn("Last pole used"),e=11),t>this.goldbergData.nbFacesAtPole-1&&(te.Warn("Maximum number of faces at a pole used"),t=this.goldbergData.nbFacesAtPole-1),12+e*this.goldbergData.nbFacesAtPole+t)}_changeGoldbergFaceColors(e){for(let i=0;i1&&(h=1),c.push(h,d);for(let u=0;u<6;u++)h=a.x+o*Math.cos(l+u*Math.PI/3),d=a.y+o*Math.sin(l+u*Math.PI/3),h<0&&(h=0),h>1&&(h=1),f.push(h,d);for(let u=r;ult.FromArray(s)),i.faceCenters=i.faceCenters.map(s=>b.FromArray(s)),i.faceZaxis=i.faceZaxis.map(s=>b.FromArray(s)),i.faceXaxis=i.faceXaxis.map(s=>b.FromArray(s)),i.faceYaxis=i.faceYaxis.map(s=>b.FromArray(s));let r=new n(e.name,t);return r.goldbergData=i,r}}});function vae(n,e){let t=n.size,i=n.sizeX||t||1,r=n.sizeY||t||1,s=n.sizeZ||t||1,a=n.sideOrientation===0?0:n.sideOrientation||Ce.DEFAULTSIDE,o=[],l=[],c=[],f=[],h=1/0,d=-1/0,u=1/0,m=-1/0;for(let g=0;go){let m=l;l=o,o=m,te.Warn("n > m therefore m and n swapped")}let c=new km;c.build(o,l);let f=Wm.BuildGeodesicData(c),h=f.toGoldbergPolyhedronData(),d=new Dg(n,t);e.sideOrientation=q._GetDefaultSideOrientation(e.sideOrientation),d._originalBuilderSideOrientation=e.sideOrientation,vae(e,h).applyToMesh(d,e.updatable),d.goldbergData.nbSharedFaces=f.sharedNodes,d.goldbergData.nbUnsharedFaces=f.poleNodes,d.goldbergData.adjacentFaces=f.adjacentFaces,d.goldbergData.nbFaces=d.goldbergData.nbSharedFaces+d.goldbergData.nbUnsharedFaces,d.goldbergData.nbFacesAtPole=(d.goldbergData.nbUnsharedFaces-12)/12;for(let m=0;m{Ge();zt();Mi();dr();Pt();EP();nW();en()});function Eae(n,e,t,i,r,s){let a=s.glyphs[n]||s.glyphs["?"];if(!a)return null;let o=new SP(r);if(a.o){let l=a.o.split(" ");for(let c=0,f=l.length;c{Fh();Ge();Mi();qh();cP();SP=class{constructor(e){this._paths=[],this._tempPaths=[],this._holes=[],this._resolution=e}moveTo(e,t){this._currentPath=new Qu(e,t),this._tempPaths.push(this._currentPath)}lineTo(e,t){this._currentPath.addLineTo(e,t)}quadraticCurveTo(e,t,i,r){this._currentPath.addQuadraticCurveTo(e,t,i,r,this._resolution)}bezierCurveTo(e,t,i,r,s,a){this._currentPath.addBezierCurveTo(e,t,i,r,s,a,this._resolution)}extractHoles(){for(let e of this._tempPaths)e.area()>0?this._holes.push(e):this._paths.push(e);if(!this._paths.length&&this._holes.length){let e=this._holes;this._holes=this._paths,this._paths=e}this._tempPaths.length=0}get paths(){return this._paths}get holes(){return this._holes}}});var ts,TP=C(()=>{mg();LG();zy();VG();kG();HG();XG();KG();Gk();cP();zk();Xk();Kk();Xy();Wy();jk();pP();Qk();$k();eW();rW();aW();lW();ts={CreateBox:Hy,CreateTiledBox:UG,CreateSphere:Ky,CreateDisc:By,CreateIcoSphere:_P,CreateRibbon:go,CreateCylinder:jy,CreateTorus:qy,CreateTorusKnot:Zy,CreateLineSystem:sP,CreateLines:aP,CreateDashedLines:oP,ExtrudeShape:fP,ExtrudeShapeCustom:hP,CreateLathe:dP,CreateTiledPlane:FG,CreatePlane:uP,CreateGround:Vy,CreateTiledGround:Gy,CreateGroundFromHeightMap:ky,CreatePolygon:YA,ExtrudePolygon:Cg,CreateTube:mP,CreatePolyhedron:yg,CreateGeodesic:iW,CreateGoldberg:sW,CreateDecal:gP,CreateCapsule:vP,CreateText:oW}});var Cs,jA=C(()=>{Cs=class{constructor(){this.previousWorldMatrices={},this.previousBones={}}static AddUniforms(e){e.push("previousWorld","previousViewProjection","mPreviousBones")}static AddSamplers(e){}bindForSubMesh(e,t,i,r,s){if(t.prePassRenderer&&t.prePassRenderer.enabled&&t.prePassRenderer.currentRTisSceneRT&&(t.prePassRenderer.getIndex(2)!==-1||t.prePassRenderer.getIndex(11)!==-1)){this.previousWorldMatrices[i.uniqueId]||(this.previousWorldMatrices[i.uniqueId]=r.clone()),this.previousViewProjection||(this.previousViewProjection=t.getTransformMatrix().clone(),this.currentViewProjection=t.getTransformMatrix().clone());let a=t.getEngine();this.currentViewProjection.updateFlag!==t.getTransformMatrix().updateFlag?(this._lastUpdateFrameId=a.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection),this.currentViewProjection.copyFrom(t.getTransformMatrix())):this._lastUpdateFrameId!==a.frameId&&(this._lastUpdateFrameId=a.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection)),e.setMatrix("previousWorld",this.previousWorldMatrices[i.uniqueId]),e.setMatrix("previousViewProjection",this.previousViewProjection),this.previousWorldMatrices[i.uniqueId]=r.clone()}}}});var xr,La=C(()=>{xr=class{constructor(e){if(this.VERTEXOUTPUT_INVARIANT=!1,this._keys=[],this._isDirty=!0,this._areLightsDirty=!0,this._areLightsDisposed=!1,this._areAttributesDirty=!0,this._areTexturesDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!0,this._areImageProcessingDirty=!0,this._normals=!1,this._uvs=!1,this._needNormals=!1,this._needUVs=!1,this._externalProperties=e,e)for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&this._setDefaultValue(t)}get isDirty(){return this._isDirty}markAsProcessed(){this._isDirty=!1,this._areAttributesDirty=!1,this._areTexturesDirty=!1,this._areFresnelDirty=!1,this._areLightsDirty=!1,this._areLightsDisposed=!1,this._areMiscDirty=!1,this._arePrePassDirty=!1,this._areImageProcessingDirty=!1}markAsUnprocessed(){this._isDirty=!0}markAllAsDirty(){this._areTexturesDirty=!0,this._areAttributesDirty=!0,this._areLightsDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!0,this._areImageProcessingDirty=!0,this._isDirty=!0}markAsImageProcessingDirty(){this._areImageProcessingDirty=!0,this._isDirty=!0}markAsLightDirty(e=!1){this._areLightsDirty=!0,this._areLightsDisposed=this._areLightsDisposed||e,this._isDirty=!0}markAsAttributesDirty(){this._areAttributesDirty=!0,this._isDirty=!0}markAsTexturesDirty(){this._areTexturesDirty=!0,this._isDirty=!0}markAsFresnelDirty(){this._areFresnelDirty=!0,this._isDirty=!0}markAsMiscDirty(){this._areMiscDirty=!0,this._isDirty=!0}markAsPrePassDirty(){this._arePrePassDirty=!0,this._isDirty=!0}rebuild(){this._keys.length=0;for(let e of Object.keys(this))e[0]!=="_"&&this._keys.push(e);if(this._externalProperties)for(let e in this._externalProperties)this._keys.indexOf(e)===-1&&this._keys.push(e)}isEqual(e){if(this._keys.length!==e._keys.length)return!1;for(let t=0;t{Oa()});function Rae(){Aae.length=0,xae=!1,Ee.OnEventObservable.remove(cW),cW=null}var Tae,Xm,Aae,xae,cW,fW=C(()=>{Vn();Pi();ST();W();Tae=new RegExp("^([gimus]+)!"),Xm=class n{constructor(e){this._plugins=[],this._activePlugins=[],this._activePluginsForExtraEvents=[],this._material=e,this._scene=e.getScene(),this._engine=this._scene.getEngine()}_addPlugin(e){for(let r=0;rthis._handlePluginEvent(r,s),this._plugins.push(e),this._plugins.sort((r,s)=>r.priority-s.priority),this._codeInjectionPoints={};let i={};i[n._MaterialPluginClassToMainDefine[t]]={type:"boolean",default:!0};for(let r of this._plugins)r.collectDefines(i),this._collectPointNames("vertex",r.getCustomCode("vertex",this._material.shaderLanguage)),this._collectPointNames("fragment",r.getCustomCode("fragment",this._material.shaderLanguage));return this._defineNamesFromPlugins=i,!0}_activatePlugin(e){this._activePlugins.indexOf(e)===-1&&(this._activePlugins.push(e),this._activePlugins.sort((t,i)=>t.priority-i.priority),this._material._callbackPluginEventIsReadyForSubMesh=this._handlePluginEventIsReadyForSubMesh.bind(this),this._material._callbackPluginEventPrepareDefinesBeforeAttributes=this._handlePluginEventPrepareDefinesBeforeAttributes.bind(this),this._material._callbackPluginEventPrepareDefines=this._handlePluginEventPrepareDefines.bind(this),this._material._callbackPluginEventBindForSubMesh=this._handlePluginEventBindForSubMesh.bind(this),e.registerForExtraEvents&&(this._activePluginsForExtraEvents.push(e),this._activePluginsForExtraEvents.sort((t,i)=>t.priority-i.priority),this._material._callbackPluginEventHasRenderTargetTextures=this._handlePluginEventHasRenderTargetTextures.bind(this),this._material._callbackPluginEventFillRenderTargetTextures=this._handlePluginEventFillRenderTargetTextures.bind(this),this._material._callbackPluginEventHardBindForSubMesh=this._handlePluginEventHardBindForSubMesh.bind(this)))}getPlugin(e){for(let t=0;t0&&r.uniforms.push(...this._uniformList),this._samplerList.length>0&&r.samplers.push(...this._samplerList),this._uboList.length>0&&r.uniformBuffersNames.push(...this._uboList),r.customCode=this._injectCustomCode(r,r.customCode);break}case 8:{let r=t;this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[];let s=this._material.shaderLanguage===1;for(let a of this._plugins){let o=a.getUniforms(this._material.shaderLanguage);if(o){if(o.ubo)for(let l of o.ubo){if(l.size&&l.type){let c=(i=l.arraySize)!=null?i:0;if(r.ubo.addUniform(l.name,l.size,c),s){let f;switch(l.type){case"mat4":f="mat4x4f";break;case"float":f="f32";break;default:f=`${l.type}f`;break}c>0?this._uboDeclaration+=`uniform ${l.name}: array<${f}, ${c}>; +`);break}}return e}}});function Hm(n){return class extends n{constructor(){super(...arguments),this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.EXPOSURE=!1}}}var qA=C(()=>{La()});function Rae(){Aae.length=0,xae=!1,Ee.OnEventObservable.remove(cW),cW=null}var Tae,zm,Aae,xae,cW,fW=C(()=>{Vn();Di();TT();k();Tae=new RegExp("^([gimus]+)!"),zm=class n{constructor(e){this._plugins=[],this._activePlugins=[],this._activePluginsForExtraEvents=[],this._material=e,this._scene=e.getScene(),this._engine=this._scene.getEngine()}_addPlugin(e){for(let r=0;rthis._handlePluginEvent(r,s),this._plugins.push(e),this._plugins.sort((r,s)=>r.priority-s.priority),this._codeInjectionPoints={};let i={};i[n._MaterialPluginClassToMainDefine[t]]={type:"boolean",default:!0};for(let r of this._plugins)r.collectDefines(i),this._collectPointNames("vertex",r.getCustomCode("vertex",this._material.shaderLanguage)),this._collectPointNames("fragment",r.getCustomCode("fragment",this._material.shaderLanguage));return this._defineNamesFromPlugins=i,!0}_activatePlugin(e){this._activePlugins.indexOf(e)===-1&&(this._activePlugins.push(e),this._activePlugins.sort((t,i)=>t.priority-i.priority),this._material._callbackPluginEventIsReadyForSubMesh=this._handlePluginEventIsReadyForSubMesh.bind(this),this._material._callbackPluginEventPrepareDefinesBeforeAttributes=this._handlePluginEventPrepareDefinesBeforeAttributes.bind(this),this._material._callbackPluginEventPrepareDefines=this._handlePluginEventPrepareDefines.bind(this),this._material._callbackPluginEventBindForSubMesh=this._handlePluginEventBindForSubMesh.bind(this),e.registerForExtraEvents&&(this._activePluginsForExtraEvents.push(e),this._activePluginsForExtraEvents.sort((t,i)=>t.priority-i.priority),this._material._callbackPluginEventHasRenderTargetTextures=this._handlePluginEventHasRenderTargetTextures.bind(this),this._material._callbackPluginEventFillRenderTargetTextures=this._handlePluginEventFillRenderTargetTextures.bind(this),this._material._callbackPluginEventHardBindForSubMesh=this._handlePluginEventHardBindForSubMesh.bind(this)))}getPlugin(e){for(let t=0;t0&&r.uniforms.push(...this._uniformList),this._samplerList.length>0&&r.samplers.push(...this._samplerList),this._uboList.length>0&&r.uniformBuffersNames.push(...this._uboList),r.customCode=this._injectCustomCode(r,r.customCode);break}case 8:{let r=t;this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[];let s=this._material.shaderLanguage===1;for(let a of this._plugins){let o=a.getUniforms(this._material.shaderLanguage);if(o){if(o.ubo)for(let l of o.ubo){if(l.size&&l.type){let c=(i=l.arraySize)!=null?i:0;if(r.ubo.addUniform(l.name,l.size,c),s){let f;switch(l.type){case"mat4":f="mat4x4f";break;case"float":f="f32";break;default:f=`${l.type}f`;break}c>0?this._uboDeclaration+=`uniform ${l.name}: array<${f}, ${c}>; `:this._uboDeclaration+=`uniform ${l.name}: ${f}; `}else this._uboDeclaration+=`${l.type} ${l.name}${c>0?`[${c}]`:""}; `}this._uniformList.push(l.name)}o.vertex&&(this._vertexDeclaration+=o.vertex+` @@ -5140,7 +5140,7 @@ gl_FragColor=color; `),o.externalUniforms&&this._uniformList.push(...o.externalUniforms)}a.getSamplers(this._samplerList),a.getUniformBuffersNames(this._uboList)}break}}}_collectPointNames(e,t){if(t)for(let i in t)this._codeInjectionPoints[e]||(this._codeInjectionPoints[e]={}),this._codeInjectionPoints[e][i]=!0}_injectCustomCode(e,t){return(i,r)=>{var o,l;t&&(r=t(i,r)),this._uboDeclaration&&(r=r.replace("#define ADDITIONAL_UBO_DECLARATION",this._uboDeclaration)),this._vertexDeclaration&&(r=r.replace("#define ADDITIONAL_VERTEX_DECLARATION",this._vertexDeclaration)),this._fragmentDeclaration&&(r=r.replace("#define ADDITIONAL_FRAGMENT_DECLARATION",this._fragmentDeclaration));let s=(o=this._codeInjectionPoints)==null?void 0:o[i];if(!s)return r;let a=null;for(let c in s){let f="";for(let h of this._activePlugins){let d=this._material.shaderLanguage,u=(l=h.getCustomCode(i,d))==null?void 0:l[c];u&&(h.resolveIncludes&&(a===null&&(a={defines:[],indexParameters:e.indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:void 0,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:T.GetShadersRepository(d),includesShadersStore:T.GetIncludesShadersStore(d),version:void 0,platformName:this._engine.shaderPlatformName,processingContext:void 0,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:void 0}),a.isFragment=i==="fragment",D_(u,a,m=>u=m)),f+=u+` `)}if(f.length>0)if(c.charAt(0)==="!"){c=c.substring(1);let h="g";if(c.charAt(0)==="!")h="",c=c.substring(1);else{let p=Tae.exec(c);p&&p.length>=2&&(h=p[1],c=c.substring(h.length+1))}h.indexOf("g")<0&&(h+="g");let d=r,u=new RegExp(c,h),m=u.exec(d);for(;m!==null;){let p=f;for(let _=0;_{Rae()});Aae=[],xae=!1,cW=null});var Vr,Bf=C(()=>{Gt();Ut();fW();Tr();Hi();Vr=class{isCompatible(e){return e===0}_enable(e){e&&this._pluginManager._activatePlugin(this)}constructor(e,t,i,r,s=!0,a=!1,o=!1){this.priority=500,this.resolveIncludes=!1,this.registerForExtraEvents=!1,this.doNotSerialize=!1,this._material=e,this.name=t,this.priority=i,this.resolveIncludes=o,e.pluginManager||(e.pluginManager=new Xm(e),e.onDisposeObservable.add(()=>{e.pluginManager=void 0})),this._pluginDefineNames=r,this._pluginManager=e.pluginManager,s&&this._pluginManager._addPlugin(this),a&&this._enable(!0),this.markAllDefinesAsDirty=e._dirtyCallbacks[127]}getClassName(){return"MaterialPluginBase"}isReadyForSubMesh(e,t,i,r){return!0}hardBindForSubMesh(e,t,i,r){}bindForSubMesh(e,t,i,r){}dispose(e){}getCustomCode(e,t=0){return null}collectDefines(e){if(this._pluginDefineNames)for(let t of Object.keys(this._pluginDefineNames)){if(t[0]==="_")continue;let i=typeof this._pluginDefineNames[t];e[t]={type:i==="number"?"number":i==="string"?"string":i==="boolean"?"boolean":"object",default:this._pluginDefineNames[t]}}}prepareDefinesBeforeAttributes(e,t,i){}prepareDefines(e,t,i){}hasTexture(e){return!1}hasRenderTargetTextures(){return!1}fillRenderTargetTextures(e){}getActiveTextures(e){}getAnimatables(e){}addFallbacks(e,t,i){return i}getSamplers(e){}getAttributes(e,t,i){}getUniformBuffersNames(e){}getUniforms(e=0){return{}}copyTo(e){it.Clone(()=>e,this)}serialize(){return it.Serialize(this)}parse(e,t,i){it.Parse(()=>this,e,t,i)}};P([w()],Vr.prototype,"name",void 0);P([w()],Vr.prototype,"priority",void 0);P([w()],Vr.prototype,"resolveIncludes",void 0);P([w()],Vr.prototype,"registerForExtraEvents",void 0);wt("BABYLON.MaterialPluginBase",Vr)});var AP,Na,xP=C(()=>{Gt();Vn();Ut();Da();Oa();Bf();Un();AP=class extends xr{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}},Na=class extends Vr{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"DetailMap",140,new AP,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=Ee.MATERIAL_NORMALBLENDMETHOD_WHITEOUT,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){return this._isEnabled?!(e._areTexturesDirty&&t.texturesEnabled&&i.getCaps().standardDerivatives&&this._texture&&le.DetailTextureEnabled&&!this._texture.isReady()):!0}prepareDefines(e,t){if(this._isEnabled){e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod;let i=t.getEngine();e._areTexturesDirty&&(i.getCaps().standardDerivatives&&this._texture&&le.DetailTextureEnabled&&this._isEnabled?(ri(this._texture,e,"DETAIL"),e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod):e.DETAIL=!1)}else e.DETAIL=!1}bindForSubMesh(e,t){if(!this._isEnabled)return;let i=this._material.isFrozen;(!e.useUbo||!i||!e.isSync)&&this._texture&&le.DetailTextureEnabled&&(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),ni(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&le.DetailTextureEnabled&&e.setTexture("detailSampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){var t;e&&((t=this._texture)==null||t.dispose())}getClassName(){return"DetailMapConfiguration"}getSamplers(e){e.push("detailSampler")}getUniforms(){return{ubo:[{name:"vDetailInfos",size:4,type:"vec4"},{name:"detailMatrix",size:16,type:"mat4"}]}}};P([Bt("detailTexture"),oe("_markAllSubMeshesAsTexturesDirty")],Na.prototype,"texture",void 0);P([w()],Na.prototype,"diffuseBlendLevel",void 0);P([w()],Na.prototype,"roughnessBlendLevel",void 0);P([w()],Na.prototype,"bumpLevel",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],Na.prototype,"normalBlendMethod",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],Na.prototype,"isEnabled",void 0)});var hW,Hn,qA=C(()=>{Ve();(function(n){n[n.Zero=0]="Zero",n[n.One=1]="One",n[n.MaxViewZ=2]="MaxViewZ",n[n.NoClear=3]="NoClear"})(hW||(hW={}));Hn=class n{static CreateConfiguration(e){return n._Configurations[e]={defines:{},previousWorldMatrices:{},previousViewProjection:j.Zero(),currentViewProjection:j.Zero(),previousBones:{},lastUpdateFrameId:-1,excludedSkinnedMesh:[],reverseCulling:!1},n._Configurations[e]}static DeleteConfiguration(e){delete n._Configurations[e]}static GetConfiguration(e){return n._Configurations[e]}static AddUniformsAndSamplers(e,t){e.push("previousWorld","previousViewProjection","mPreviousBones")}static MarkAsDirty(e,t){for(let i of t)if(i.subMeshes)for(let r of i.subMeshes)r._removeDrawWrapper(e)}static PrepareDefines(e,t,i){if(!i._arePrePassDirty)return;let r=n._Configurations[e];if(!r)return;i.PREPASS=!0;let s=0;for(let a=0;a{});function Km(n){return class extends n{constructor(){super(...arguments),this.PREPASS=!1,this.PREPASS_COLOR=!1,this.PREPASS_COLOR_INDEX=-1,this.PREPASS_IRRADIANCE_LEGACY=!1,this.PREPASS_IRRADIANCE_LEGACY_INDEX=-1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO=!1,this.PREPASS_ALBEDO_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_SCREENSPACE_DEPTH=!1,this.PREPASS_SCREENSPACE_DEPTH_INDEX=-1,this.PREPASS_NORMALIZED_VIEW_DEPTH=!1,this.PREPASS_NORMALIZED_VIEW_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_WORLD_NORMAL=!1,this.PREPASS_WORLD_NORMAL_INDEX=-1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_LOCAL_POSITION=!1,this.PREPASS_LOCAL_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_VELOCITY_LINEAR=!1,this.PREPASS_VELOCITY_LINEAR_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0}}}var QA=C(()=>{});function jm(n){return class extends n{constructor(...e){super(...e),b2()(this,"_imageProcessingConfiguration")}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsImageProcessingDirty&&this._markAllSubMeshesAsImageProcessingDirty()}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),!e&&this.getScene?this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration:e&&(this._imageProcessingConfiguration=e),this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty&&this._markAllSubMeshesAsImageProcessingDirty()})))}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}}}var $A=C(()=>{Ut()});var dW,bae,ed=C(()=>{W();dW="sceneUboDeclaration",bae=`struct Scene {viewProjection : mat4x4, +`+h)}}return r}}};zm._MaterialPluginClassToMainDefine={};zm._MaterialPluginCounter=0;Oe.OnEnginesDisposedObservable.add(()=>{Rae()});Aae=[],xae=!1,cW=null});var Vr,Ff=C(()=>{Gt();Vt();fW();Tr();Hi();Vr=class{isCompatible(e){return e===0}_enable(e){e&&this._pluginManager._activatePlugin(this)}constructor(e,t,i,r,s=!0,a=!1,o=!1){this.priority=500,this.resolveIncludes=!1,this.registerForExtraEvents=!1,this.doNotSerialize=!1,this._material=e,this.name=t,this.priority=i,this.resolveIncludes=o,e.pluginManager||(e.pluginManager=new zm(e),e.onDisposeObservable.add(()=>{e.pluginManager=void 0})),this._pluginDefineNames=r,this._pluginManager=e.pluginManager,s&&this._pluginManager._addPlugin(this),a&&this._enable(!0),this.markAllDefinesAsDirty=e._dirtyCallbacks[127]}getClassName(){return"MaterialPluginBase"}isReadyForSubMesh(e,t,i,r){return!0}hardBindForSubMesh(e,t,i,r){}bindForSubMesh(e,t,i,r){}dispose(e){}getCustomCode(e,t=0){return null}collectDefines(e){if(this._pluginDefineNames)for(let t of Object.keys(this._pluginDefineNames)){if(t[0]==="_")continue;let i=typeof this._pluginDefineNames[t];e[t]={type:i==="number"?"number":i==="string"?"string":i==="boolean"?"boolean":"object",default:this._pluginDefineNames[t]}}}prepareDefinesBeforeAttributes(e,t,i){}prepareDefines(e,t,i){}hasTexture(e){return!1}hasRenderTargetTextures(){return!1}fillRenderTargetTextures(e){}getActiveTextures(e){}getAnimatables(e){}addFallbacks(e,t,i){return i}getSamplers(e){}getAttributes(e,t,i){}getUniformBuffersNames(e){}getUniforms(e=0){return{}}copyTo(e){it.Clone(()=>e,this)}serialize(){return it.Serialize(this)}parse(e,t,i){it.Parse(()=>this,e,t,i)}};P([w()],Vr.prototype,"name",void 0);P([w()],Vr.prototype,"priority",void 0);P([w()],Vr.prototype,"resolveIncludes",void 0);P([w()],Vr.prototype,"registerForExtraEvents",void 0);Ft("BABYLON.MaterialPluginBase",Vr)});var AP,Oa,xP=C(()=>{Gt();Vn();Vt();Pa();La();Ff();Un();AP=class extends xr{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}},Oa=class extends Vr{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"DetailMap",140,new AP,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=Ee.MATERIAL_NORMALBLENDMETHOD_WHITEOUT,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){return this._isEnabled?!(e._areTexturesDirty&&t.texturesEnabled&&i.getCaps().standardDerivatives&&this._texture&&ce.DetailTextureEnabled&&!this._texture.isReady()):!0}prepareDefines(e,t){if(this._isEnabled){e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod;let i=t.getEngine();e._areTexturesDirty&&(i.getCaps().standardDerivatives&&this._texture&&ce.DetailTextureEnabled&&this._isEnabled?(ni(this._texture,e,"DETAIL"),e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod):e.DETAIL=!1)}else e.DETAIL=!1}bindForSubMesh(e,t){if(!this._isEnabled)return;let i=this._material.isFrozen;(!e.useUbo||!i||!e.isSync)&&this._texture&&ce.DetailTextureEnabled&&(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),si(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&ce.DetailTextureEnabled&&e.setTexture("detailSampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){var t;e&&((t=this._texture)==null||t.dispose())}getClassName(){return"DetailMapConfiguration"}getSamplers(e){e.push("detailSampler")}getUniforms(){return{ubo:[{name:"vDetailInfos",size:4,type:"vec4"},{name:"detailMatrix",size:16,type:"mat4"}]}}};P([Ut("detailTexture"),le("_markAllSubMeshesAsTexturesDirty")],Oa.prototype,"texture",void 0);P([w()],Oa.prototype,"diffuseBlendLevel",void 0);P([w()],Oa.prototype,"roughnessBlendLevel",void 0);P([w()],Oa.prototype,"bumpLevel",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],Oa.prototype,"normalBlendMethod",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],Oa.prototype,"isEnabled",void 0)});var hW,Hn,ZA=C(()=>{Ge();(function(n){n[n.Zero=0]="Zero",n[n.One=1]="One",n[n.MaxViewZ=2]="MaxViewZ",n[n.NoClear=3]="NoClear"})(hW||(hW={}));Hn=class n{static CreateConfiguration(e){return n._Configurations[e]={defines:{},previousWorldMatrices:{},previousViewProjection:K.Zero(),currentViewProjection:K.Zero(),previousBones:{},lastUpdateFrameId:-1,excludedSkinnedMesh:[],reverseCulling:!1},n._Configurations[e]}static DeleteConfiguration(e){delete n._Configurations[e]}static GetConfiguration(e){return n._Configurations[e]}static AddUniformsAndSamplers(e,t){e.push("previousWorld","previousViewProjection","mPreviousBones")}static MarkAsDirty(e,t){for(let i of t)if(i.subMeshes)for(let r of i.subMeshes)r._removeDrawWrapper(e)}static PrepareDefines(e,t,i){if(!i._arePrePassDirty)return;let r=n._Configurations[e];if(!r)return;i.PREPASS=!0;let s=0;for(let a=0;a{});function Ym(n){return class extends n{constructor(){super(...arguments),this.PREPASS=!1,this.PREPASS_COLOR=!1,this.PREPASS_COLOR_INDEX=-1,this.PREPASS_IRRADIANCE_LEGACY=!1,this.PREPASS_IRRADIANCE_LEGACY_INDEX=-1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO=!1,this.PREPASS_ALBEDO_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_SCREENSPACE_DEPTH=!1,this.PREPASS_SCREENSPACE_DEPTH_INDEX=-1,this.PREPASS_NORMALIZED_VIEW_DEPTH=!1,this.PREPASS_NORMALIZED_VIEW_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_WORLD_NORMAL=!1,this.PREPASS_WORLD_NORMAL_INDEX=-1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_LOCAL_POSITION=!1,this.PREPASS_LOCAL_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_VELOCITY_LINEAR=!1,this.PREPASS_VELOCITY_LINEAR_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0}}}var $A=C(()=>{});function Km(n){return class extends n{constructor(...e){super(...e),b2()(this,"_imageProcessingConfiguration")}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsImageProcessingDirty&&this._markAllSubMeshesAsImageProcessingDirty()}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),!e&&this.getScene?this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration:e&&(this._imageProcessingConfiguration=e),this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty&&this._markAllSubMeshesAsImageProcessingDirty()})))}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}}}var JA=C(()=>{Vt()});var dW,bae,ed=C(()=>{k();dW="sceneUboDeclaration",bae=`struct Scene {viewProjection : mat4x4, #ifdef MULTIVIEW viewProjectionR : mat4x4, #endif @@ -5150,17 +5150,17 @@ vEyePosition : vec4, inverseProjection : mat4x4,}; #define SCENE_UBO var scene : Scene; -`;T.IncludesShadersStoreWGSL[dW]||(T.IncludesShadersStoreWGSL[dW]=bae)});var uW,Iae,Lg=C(()=>{W();uW="meshUboDeclaration",Iae=`struct Mesh {world : mat4x4, +`;T.IncludesShadersStoreWGSL[dW]||(T.IncludesShadersStoreWGSL[dW]=bae)});var uW,Iae,Lg=C(()=>{k();uW="meshUboDeclaration",Iae=`struct Mesh {world : mat4x4, visibility : f32,};var mesh : Mesh; #define WORLD_UBO -`;T.IncludesShadersStoreWGSL[uW]||(T.IncludesShadersStoreWGSL[uW]=Iae)});var mW,Mae,RP=C(()=>{W();ed();Lg();mW="defaultUboDeclaration",Mae=`uniform diffuseLeftColor: vec4f;uniform diffuseRightColor: vec4f;uniform opacityParts: vec4f;uniform reflectionLeftColor: vec4f;uniform reflectionRightColor: vec4f;uniform refractionLeftColor: vec4f;uniform refractionRightColor: vec4f;uniform emissiveLeftColor: vec4f;uniform emissiveRightColor: vec4f;uniform vDiffuseInfos: vec2f;uniform vAmbientInfos: vec2f;uniform vOpacityInfos: vec2f;uniform vEmissiveInfos: vec2f;uniform vLightmapInfos: vec2f;uniform vSpecularInfos: vec2f;uniform vBumpInfos: vec3f;uniform diffuseMatrix: mat4x4f;uniform ambientMatrix: mat4x4f;uniform opacityMatrix: mat4x4f;uniform emissiveMatrix: mat4x4f;uniform lightmapMatrix: mat4x4f;uniform specularMatrix: mat4x4f;uniform bumpMatrix: mat4x4f;uniform vTangentSpaceParams: vec2f;uniform pointSize: f32;uniform alphaCutOff: f32;uniform refractionMatrix: mat4x4f;uniform vRefractionInfos: vec4f;uniform vRefractionPosition: vec3f;uniform vRefractionSize: vec3f;uniform vSpecularColor: vec4f;uniform vEmissiveColor: vec3f;uniform vDiffuseColor: vec4f;uniform vAmbientColor: vec3f;uniform cameraInfo: vec4f;uniform vReflectionInfos: vec2f;uniform reflectionMatrix: mat4x4f;uniform vReflectionPosition: vec3f;uniform vReflectionSize: vec3f; +`;T.IncludesShadersStoreWGSL[uW]||(T.IncludesShadersStoreWGSL[uW]=Iae)});var mW,Mae,RP=C(()=>{k();ed();Lg();mW="defaultUboDeclaration",Mae=`uniform diffuseLeftColor: vec4f;uniform diffuseRightColor: vec4f;uniform opacityParts: vec4f;uniform reflectionLeftColor: vec4f;uniform reflectionRightColor: vec4f;uniform refractionLeftColor: vec4f;uniform refractionRightColor: vec4f;uniform emissiveLeftColor: vec4f;uniform emissiveRightColor: vec4f;uniform vDiffuseInfos: vec2f;uniform vAmbientInfos: vec2f;uniform vOpacityInfos: vec2f;uniform vEmissiveInfos: vec2f;uniform vLightmapInfos: vec2f;uniform vSpecularInfos: vec2f;uniform vBumpInfos: vec3f;uniform diffuseMatrix: mat4x4f;uniform ambientMatrix: mat4x4f;uniform opacityMatrix: mat4x4f;uniform emissiveMatrix: mat4x4f;uniform lightmapMatrix: mat4x4f;uniform specularMatrix: mat4x4f;uniform bumpMatrix: mat4x4f;uniform vTangentSpaceParams: vec2f;uniform pointSize: f32;uniform alphaCutOff: f32;uniform refractionMatrix: mat4x4f;uniform vRefractionInfos: vec4f;uniform vRefractionPosition: vec3f;uniform vRefractionSize: vec3f;uniform vSpecularColor: vec4f;uniform vEmissiveColor: vec3f;uniform vDiffuseColor: vec4f;uniform vAmbientColor: vec3f;uniform cameraInfo: vec4f;uniform vReflectionInfos: vec2f;uniform reflectionMatrix: mat4x4f;uniform vReflectionPosition: vec3f;uniform vReflectionSize: vec3f; #define ADDITIONAL_UBO_DECLARATION #include #include -`;T.IncludesShadersStoreWGSL[mW]||(T.IncludesShadersStoreWGSL[mW]=Mae)});var pW,Cae,JA=C(()=>{W();pW="uvAttributeDeclaration",Cae=`#if defined(UV{X}) && !defined(USE_VERTEX_PULLING) +`;T.IncludesShadersStoreWGSL[mW]||(T.IncludesShadersStoreWGSL[mW]=Mae)});var pW,Cae,ex=C(()=>{k();pW="uvAttributeDeclaration",Cae=`#if defined(UV{X}) && !defined(USE_VERTEX_PULLING) attribute uv{X}: vec2f; #endif -`;T.IncludesShadersStoreWGSL[pW]||(T.IncludesShadersStoreWGSL[pW]=Cae)});var _W,yae,ex=C(()=>{W();_W="prePassVertexDeclaration",yae=`#ifdef PREPASS +`;T.IncludesShadersStoreWGSL[pW]||(T.IncludesShadersStoreWGSL[pW]=Cae)});var _W,yae,tx=C(()=>{k();_W="prePassVertexDeclaration",yae=`#ifdef PREPASS #ifdef PREPASS_LOCAL_POSITION varying vPosition : vec3f; #endif @@ -5174,18 +5174,18 @@ varying vNormViewDepth: f32; uniform previousViewProjection: mat4x4f;varying vCurrentPosition: vec4f;varying vPreviousPosition: vec4f; #endif #endif -`;T.IncludesShadersStoreWGSL[_W]||(T.IncludesShadersStoreWGSL[_W]=yae)});var gW,Pae,qm=C(()=>{W();gW="mainUVVaryingDeclaration",Pae=`#ifdef MAINUV{X} +`;T.IncludesShadersStoreWGSL[_W]||(T.IncludesShadersStoreWGSL[_W]=yae)});var gW,Pae,jm=C(()=>{k();gW="mainUVVaryingDeclaration",Pae=`#ifdef MAINUV{X} varying vMainUV{X}: vec2f; #endif -`;T.IncludesShadersStoreWGSL[gW]||(T.IncludesShadersStoreWGSL[gW]=Pae)});var vW,Dae,tx=C(()=>{W();vW="samplerVertexDeclaration",Dae=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 +`;T.IncludesShadersStoreWGSL[gW]||(T.IncludesShadersStoreWGSL[gW]=Pae)});var vW,Dae,ix=C(()=>{k();vW="samplerVertexDeclaration",Dae=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 varying v_VARYINGNAME_UV: vec2f; #endif -`;T.IncludesShadersStoreWGSL[vW]||(T.IncludesShadersStoreWGSL[vW]=Dae)});var EW,Lae,bP=C(()=>{W();EW="bumpVertexDeclaration",Lae=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) +`;T.IncludesShadersStoreWGSL[vW]||(T.IncludesShadersStoreWGSL[vW]=Dae)});var EW,Lae,bP=C(()=>{k();EW="bumpVertexDeclaration",Lae=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) #if defined(TANGENT) && defined(NORMAL) varying vTBN0: vec3f;varying vTBN1: vec3f;varying vTBN2: vec3f; #endif #endif -`;T.IncludesShadersStoreWGSL[EW]||(T.IncludesShadersStoreWGSL[EW]=Lae)});var SW,Oae,TW=C(()=>{W();SW="lightVxFragmentDeclaration",Oae=`#ifdef LIGHT{X} +`;T.IncludesShadersStoreWGSL[EW]||(T.IncludesShadersStoreWGSL[EW]=Lae)});var SW,Oae,TW=C(()=>{k();SW="lightVxFragmentDeclaration",Oae=`#ifdef LIGHT{X} uniform vLightData{X}: vec4f;uniform vLightDiffuse{X}: vec4f; #ifdef SPECULARTERM uniform vLightSpecular{X}: vec4f; @@ -5212,7 +5212,7 @@ uniform vLightGround{X}: vec3f; uniform vLightWidth{X}: vec4f;uniform vLightHeight{X}: vec4f; #endif #endif -`;T.IncludesShadersStoreWGSL[SW]||(T.IncludesShadersStoreWGSL[SW]=Oae)});var AW,Nae,ix=C(()=>{W();AW="lightVxUboDeclaration",Nae=`#ifdef LIGHT{X} +`;T.IncludesShadersStoreWGSL[SW]||(T.IncludesShadersStoreWGSL[SW]=Oae)});var AW,Nae,rx=C(()=>{k();AW="lightVxUboDeclaration",Nae=`#ifdef LIGHT{X} struct Light{X} {vLightData: vec4f, vLightDiffuse: vec4f, @@ -5243,7 +5243,7 @@ varying vPositionFromLight{X}: vec4f;varying vDepthMetric{X}: f32;uniform lightM #endif #endif #endif -`;T.IncludesShadersStoreWGSL[AW]||(T.IncludesShadersStoreWGSL[AW]=Nae)});var xW,wae,Uf=C(()=>{W();xW="morphTargetsVertexGlobalDeclaration",wae=`#ifdef MORPHTARGETS +`;T.IncludesShadersStoreWGSL[AW]||(T.IncludesShadersStoreWGSL[AW]=Nae)});var xW,wae,Bf=C(()=>{k();xW="morphTargetsVertexGlobalDeclaration",wae=`#ifdef MORPHTARGETS uniform morphTargetInfluences : array; #ifdef MORPHTARGETS_TEXTURE uniform morphTargetTextureIndices : array;uniform morphTargetTextureInfo : vec3;var morphTargets : texture_2d_array;fn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec3 @@ -5255,7 +5255,7 @@ let textureWidth: i32=i32(uniforms.morphTargetTextureInfo.y); let y: i32=i32(vertexIndex)/textureWidth;let x: i32=i32(vertexIndex) % textureWidth;return textureLoad(morphTargets,vec2i(x,y),i32(uniforms.morphTargetTextureIndices[targetIndex]),0);} #endif #endif -`;T.IncludesShadersStoreWGSL[xW]||(T.IncludesShadersStoreWGSL[xW]=wae)});var RW,Fae,Vf=C(()=>{W();RW="morphTargetsVertexDeclaration",Fae=`#ifdef MORPHTARGETS +`;T.IncludesShadersStoreWGSL[xW]||(T.IncludesShadersStoreWGSL[xW]=wae)});var RW,Fae,Uf=C(()=>{k();RW="morphTargetsVertexDeclaration",Fae=`#ifdef MORPHTARGETS #ifndef MORPHTARGETS_TEXTURE #ifdef MORPHTARGETS_POSITION attribute position{X} : vec3; @@ -5279,10 +5279,10 @@ attribute color{X} : vec4; uniform morphTargetCount: f32; #endif #endif -`;T.IncludesShadersStoreWGSL[RW]||(T.IncludesShadersStoreWGSL[RW]=Fae)});var bW,Bae,td=C(()=>{W();bW="logDepthDeclaration",Bae=`#ifdef LOGARITHMICDEPTH +`;T.IncludesShadersStoreWGSL[RW]||(T.IncludesShadersStoreWGSL[RW]=Fae)});var bW,Bae,td=C(()=>{k();bW="logDepthDeclaration",Bae=`#ifdef LOGARITHMICDEPTH uniform logarithmicDepthConstant: f32;varying vFragmentDepth: f32; #endif -`;T.IncludesShadersStoreWGSL[bW]||(T.IncludesShadersStoreWGSL[bW]=Bae)});var IW,Uae,rx=C(()=>{W();IW="vertexPullingDeclaration",Uae=`#ifdef USE_VERTEX_PULLING +`;T.IncludesShadersStoreWGSL[bW]||(T.IncludesShadersStoreWGSL[bW]=Bae)});var IW,Uae,nx=C(()=>{k();IW="vertexPullingDeclaration",Uae=`#ifdef USE_VERTEX_PULLING #ifdef VERTEX_PULLING_USE_INDEX_BUFFER var indices : array; #endif @@ -5460,7 +5460,7 @@ vp_readMatrixWeightExtraValue(offset+cs*3u,dataType,normalized) #endif #endif #endif -`;T.IncludesShadersStoreWGSL[IW]||(T.IncludesShadersStoreWGSL[IW]=Uae)});var MW,Vae,nx=C(()=>{W();MW="vertexPullingVertex",Vae=`#ifdef USE_VERTEX_PULLING +`;T.IncludesShadersStoreWGSL[IW]||(T.IncludesShadersStoreWGSL[IW]=Uae)});var MW,Vae,sx=C(()=>{k();MW="vertexPullingVertex",Vae=`#ifdef USE_VERTEX_PULLING let vpVertexIndex: u32=vp_readVertexIndex(vertexInputs.vertexIndex);positionUpdated=vp_readPosition(uniforms.vp_position_info,vpVertexIndex); #ifdef NORMAL normalUpdated=vp_readNormal(uniforms.vp_normal_info,vpVertexIndex); @@ -5514,12 +5514,12 @@ var vp_matricesIndicesExtra: vec4f=vp_readBoneIndicesExtra(uniforms.vp_matricesI #endif #endif #endif -`;T.IncludesShadersStoreWGSL[MW]||(T.IncludesShadersStoreWGSL[MW]=Vae)});var CW,Gae,Gf=C(()=>{W();CW="morphTargetsVertexGlobal",Gae=`#ifdef MORPHTARGETS +`;T.IncludesShadersStoreWGSL[MW]||(T.IncludesShadersStoreWGSL[MW]=Vae)});var CW,Gae,Vf=C(()=>{k();CW="morphTargetsVertexGlobal",Gae=`#ifdef MORPHTARGETS #ifdef MORPHTARGETS_TEXTURE var vertexID : f32; #endif #endif -`;T.IncludesShadersStoreWGSL[CW]||(T.IncludesShadersStoreWGSL[CW]=Gae)});var yW,kae,kf=C(()=>{W();yW="morphTargetsVertex",kae=`#ifdef MORPHTARGETS +`;T.IncludesShadersStoreWGSL[CW]||(T.IncludesShadersStoreWGSL[CW]=Gae)});var yW,kae,Gf=C(()=>{k();yW="morphTargetsVertex",kae=`#ifdef MORPHTARGETS #ifdef MORPHTARGETS_TEXTURE #if {X}==0 for (var i=0; i=uniforms.morphTargetCount) {break;} @@ -5629,7 +5629,7 @@ colorUpdated=colorUpdated+(vertexInputs.color{X}-vertexInputs.color)*uniforms.mo #endif #endif #endif -`;T.IncludesShadersStoreWGSL[yW]||(T.IncludesShadersStoreWGSL[yW]=kae)});var PW,Wae,sx=C(()=>{W();PW="prePassVertex",Wae=`#ifdef PREPASS_DEPTH +`;T.IncludesShadersStoreWGSL[yW]||(T.IncludesShadersStoreWGSL[yW]=kae)});var PW,Wae,ax=C(()=>{k();PW="prePassVertex",Wae=`#ifdef PREPASS_DEPTH vertexOutputs.vViewPos=(scene.view*worldPos).rgb; #endif #ifdef PREPASS_NORMALIZED_VIEW_DEPTH @@ -5668,7 +5668,7 @@ vertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWor vertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld* vec4f(positionUpdated,1.0); #endif #endif -`;T.IncludesShadersStoreWGSL[PW]||(T.IncludesShadersStoreWGSL[PW]=Wae)});var DW,Hae,ax=C(()=>{W();DW="uvVariableDeclaration",Hae=`#ifdef MAINUV{X} +`;T.IncludesShadersStoreWGSL[PW]||(T.IncludesShadersStoreWGSL[PW]=Wae)});var DW,Hae,ox=C(()=>{k();DW="uvVariableDeclaration",Hae=`#ifdef MAINUV{X} #if !defined(UV{X}) var uv{X}: vec2f=vec2f(0.,0.); #elif defined(USE_VERTEX_PULLING) @@ -5678,7 +5678,7 @@ var uv{X}: vec2f=vertexInputs.uv{X}; #endif vertexOutputs.vMainUV{X}=uv{X}; #endif -`;T.IncludesShadersStoreWGSL[DW]||(T.IncludesShadersStoreWGSL[DW]=Hae)});var LW,zae,ox=C(()=>{W();LW="samplerVertexImplementation",zae=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 +`;T.IncludesShadersStoreWGSL[DW]||(T.IncludesShadersStoreWGSL[DW]=Hae)});var LW,zae,lx=C(()=>{k();LW="samplerVertexImplementation",zae=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 if (uniforms.v_INFONAME_==0.) {vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(uvUpdated,1.0,0.0)).xy;} #ifdef UV2 @@ -5702,12 +5702,12 @@ else if (uniforms.v_INFONAME_==5.) {vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(vertexInputs.uv6,1.0,0.0)).xy;} #endif #endif -`;T.IncludesShadersStoreWGSL[LW]||(T.IncludesShadersStoreWGSL[LW]=zae)});var OW,Xae,lx=C(()=>{W();OW="bumpVertex",Xae=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) +`;T.IncludesShadersStoreWGSL[LW]||(T.IncludesShadersStoreWGSL[LW]=zae)});var OW,Xae,cx=C(()=>{k();OW="bumpVertex",Xae=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) #if defined(TANGENT) && defined(NORMAL) var tbnNormal: vec3f=normalize(normalUpdated);var tbnTangent: vec3f=normalize(tangentUpdated.xyz);var tbnBitangent: vec3f=cross(tbnNormal,tbnTangent)*tangentUpdated.w;var matTemp= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz)* mat3x3f(tbnTangent,tbnBitangent,tbnNormal);vertexOutputs.vTBN0=matTemp[0];vertexOutputs.vTBN1=matTemp[1];vertexOutputs.vTBN2=matTemp[2]; #endif #endif -`;T.IncludesShadersStoreWGSL[OW]||(T.IncludesShadersStoreWGSL[OW]=Xae)});var NW,Yae,cx=C(()=>{W();NW="shadowsVertex",Yae=`#ifdef SHADOWS +`;T.IncludesShadersStoreWGSL[OW]||(T.IncludesShadersStoreWGSL[OW]=Xae)});var NW,Yae,fx=C(()=>{k();NW="shadowsVertex",Yae=`#ifdef SHADOWS #if defined(SHADOWCSM{X}) #ifdef SCENE_UBO vertexOutputs.vPositionFromCamera{X}=scene.view*worldPos; @@ -5755,10 +5755,10 @@ vertexOutputs.vDepthMetric{X}=(vertexOutputs.vPositionFromLight{X}.z+light{X}.de #endif #endif #endif -`;T.IncludesShadersStoreWGSL[NW]||(T.IncludesShadersStoreWGSL[NW]=Yae)});var wW,Kae,fx=C(()=>{W();wW="logDepthVertex",Kae=`#ifdef LOGARITHMICDEPTH +`;T.IncludesShadersStoreWGSL[NW]||(T.IncludesShadersStoreWGSL[NW]=Yae)});var wW,Kae,hx=C(()=>{k();wW="logDepthVertex",Kae=`#ifdef LOGARITHMICDEPTH vertexOutputs.vFragmentDepth=1.0+vertexOutputs.position.w;vertexOutputs.position.z=log2(max(0.000001,vertexOutputs.vFragmentDepth))*uniforms.logarithmicDepthConstant; #endif -`;T.IncludesShadersStoreWGSL[wW]||(T.IncludesShadersStoreWGSL[wW]=Kae)});var BW={};tt(BW,{defaultVertexShaderWGSL:()=>jae});var IP,FW,jae,UW=C(()=>{W();RP();JA();Ca();rc();nc();wf();ex();qm();tx();bP();sc();gg();TW();ix();Uf();Vf();td();rx();nx();Gf();kf();ac();oc();lc();sx();ax();ox();lx();cc();vg();cx();Eg();fx();IP="defaultVertexShader",FW=`#include +`;T.IncludesShadersStoreWGSL[wW]||(T.IncludesShadersStoreWGSL[wW]=Kae)});var BW={};tt(BW,{defaultVertexShaderWGSL:()=>jae});var IP,FW,jae,UW=C(()=>{k();RP();ex();Ma();ic();rc();Nf();tx();jm();ix();bP();nc();gg();TW();rx();Bf();Uf();td();nx();sx();Vf();Gf();sc();ac();oc();ax();ox();lx();cx();lc();vg();fx();Eg();hx();IP="defaultVertexShader",FW=`#include #define CUSTOM_VERTEX_BEGIN #ifndef USE_VERTEX_PULLING attribute position: vec3f; @@ -5939,7 +5939,7 @@ vertexOutputs.vMainUV2=uv2Updated; #include #define CUSTOM_VERTEX_MAIN_END } -`;T.ShadersStoreWGSL[IP]||(T.ShadersStoreWGSL[IP]=FW);jae={name:IP,shader:FW}});var VW,qae,hx=C(()=>{W();VW="prePassDeclaration",qae=`#ifdef PREPASS +`;T.ShadersStoreWGSL[IP]||(T.ShadersStoreWGSL[IP]=FW);jae={name:IP,shader:FW}});var VW,qae,dx=C(()=>{k();VW="prePassDeclaration",qae=`#ifdef PREPASS #ifdef PREPASS_LOCAL_POSITION varying vPosition : vec3f; #endif @@ -5953,11 +5953,11 @@ varying vNormViewDepth: f32; varying vCurrentPosition: vec4f;varying vPreviousPosition: vec4f; #endif #endif -`;T.IncludesShadersStoreWGSL[VW]||(T.IncludesShadersStoreWGSL[VW]=qae)});var GW,Zae,dx=C(()=>{W();GW="oitDeclaration",Zae=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY +`;T.IncludesShadersStoreWGSL[VW]||(T.IncludesShadersStoreWGSL[VW]=qae)});var GW,Zae,ux=C(()=>{k();GW="oitDeclaration",Zae=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY #define MAX_DEPTH 99999.0 var oitDepthSamplerSampler: sampler;var oitDepthSampler: texture_2d;var oitFrontColorSamplerSampler: sampler;var oitFrontColorSampler: texture_2d; #endif -`;T.IncludesShadersStoreWGSL[GW]||(T.IncludesShadersStoreWGSL[GW]=Zae)});var kW,Qae,ux=C(()=>{W();kW="lightUboDeclaration",Qae=`#ifdef LIGHT{X} +`;T.IncludesShadersStoreWGSL[GW]||(T.IncludesShadersStoreWGSL[GW]=Zae)});var kW,Qae,mx=C(()=>{k();kW="lightUboDeclaration",Qae=`#ifdef LIGHT{X} struct Light{X} {vLightData: vec4f, vLightDiffuse: vec4f, @@ -6034,7 +6034,7 @@ uniform lightMatrix{X}: mat4x4f; #endif #endif #endif -`;T.IncludesShadersStoreWGSL[kW]||(T.IncludesShadersStoreWGSL[kW]=Qae)});var WW,$ae,MP=C(()=>{W();WW="ltcHelperFunctions",$ae=`fn LTCUv(N: vec3f,V: vec3f,roughness: f32)->vec2f {var LUTSIZE: f32=64.0;var LUTSCALE: f32=( LUTSIZE-1.0 )/LUTSIZE;var LUTBIAS:f32=0.5/LUTSIZE;var dotNV:f32=saturate( dot( N,V ) );var uv:vec2f=vec2f( roughness,sqrt( 1.0-dotNV ) );uv=uv*LUTSCALE+LUTBIAS;return uv;} +`;T.IncludesShadersStoreWGSL[kW]||(T.IncludesShadersStoreWGSL[kW]=Qae)});var WW,$ae,MP=C(()=>{k();WW="ltcHelperFunctions",$ae=`fn LTCUv(N: vec3f,V: vec3f,roughness: f32)->vec2f {var LUTSIZE: f32=64.0;var LUTSCALE: f32=( LUTSIZE-1.0 )/LUTSIZE;var LUTBIAS:f32=0.5/LUTSIZE;var dotNV:f32=saturate( dot( N,V ) );var uv:vec2f=vec2f( roughness,sqrt( 1.0-dotNV ) );uv=uv*LUTSCALE+LUTBIAS;return uv;} fn LTCClippedSphereFormFactor( f:vec3f )->f32 {var l: f32=length( f );return max( ( l*l+f.z )/( l+1.0 ),0.0 );} fn LTCEdgeVectorFormFactor( v1:vec3f,v2:vec3f )->vec3f {var x:f32=dot( v1,v2 );var y:f32=abs( x );var a:f32=0.8543985+( 0.4965155+0.0145206*y )*y;var b:f32=3.4175940+( 4.1616724+y )*y;var v:f32=a/b;var thetaSintheta:f32=0.0;if( x>0.0 ) {thetaSintheta=v;} @@ -6078,7 +6078,7 @@ vec3f(1,0,0), vec3f(0,1,0), vec3f(0,0,1) );result.Diffuse=LTCEvaluateWithEmission(normal,viewDir,position,mInvEmpty,rectCoords0,rectCoords1,rectCoords2,rectCoords3,emissionTexture,emissionTextureSampler);return result;} -`;T.IncludesShadersStoreWGSL[WW]||(T.IncludesShadersStoreWGSL[WW]=$ae)});var HW,Jae,CP=C(()=>{W();HW="clusteredLightingFunctions",Jae=`struct ClusteredLight {vLightData: vec4f, +`;T.IncludesShadersStoreWGSL[WW]||(T.IncludesShadersStoreWGSL[WW]=$ae)});var HW,Jae,CP=C(()=>{k();HW="clusteredLightingFunctions",Jae=`struct ClusteredLight {vLightData: vec4f, vLightDiffuse: vec4f, vLightSpecular: vec4f, vLightDirection: vec4f, @@ -6091,7 +6091,7 @@ textureLoad(lightDataTexture,vec2u(3,index),0), textureLoad(lightDataTexture,vec2u(4,index),0) );} fn getClusteredSliceIndex(sliceData: vec2f,viewDepth: f32)->i32 {return i32(log(viewDepth)*sliceData.x+sliceData.y);} -`;T.IncludesShadersStoreWGSL[HW]||(T.IncludesShadersStoreWGSL[HW]=Jae)});var zW,eoe,XW=C(()=>{W();MP();CP();zW="lightsFragmentFunctions",eoe=`struct lightingInfo +`;T.IncludesShadersStoreWGSL[HW]||(T.IncludesShadersStoreWGSL[HW]=Jae)});var zW,eoe,XW=C(()=>{k();MP();CP();zW="lightsFragmentFunctions",eoe=`struct lightingInfo {diffuse: vec3f, #ifdef SPECULARTERM specular: vec3f, @@ -6188,7 +6188,7 @@ result.specular+=info.specular; batchOffset+=CLUSTLIGHT_BATCH;} return result;} #endif -`;T.IncludesShadersStoreWGSL[zW]||(T.IncludesShadersStoreWGSL[zW]=eoe)});var YW,toe,mx=C(()=>{W();YW="shadowsFragmentFunctions",toe=`#ifdef SHADOWS +`;T.IncludesShadersStoreWGSL[zW]||(T.IncludesShadersStoreWGSL[zW]=eoe)});var YW,toe,px=C(()=>{k();YW="shadowsFragmentFunctions",toe=`#ifdef SHADOWS #ifndef SHADOWFLOAT fn unpack(color: vec4f)->f32 {const bit_shift: vec4f= vec4f(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);} @@ -6480,7 +6480,7 @@ fn computeShadowWithCSMPCSS32(layer: i32,vPositionFromLight: vec4f,depthMetric: fn computeShadowWithCSMPCSS64(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32 {return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64,lightSizeUVCorrection,depthCorrection,penumbraDarkness);} #endif -`;T.IncludesShadersStoreWGSL[YW]||(T.IncludesShadersStoreWGSL[YW]=toe)});var KW,ioe,id=C(()=>{W();KW="samplerFragmentDeclaration",ioe=`#ifdef _DEFINENAME_ +`;T.IncludesShadersStoreWGSL[YW]||(T.IncludesShadersStoreWGSL[YW]=toe)});var KW,ioe,id=C(()=>{k();KW="samplerFragmentDeclaration",ioe=`#ifdef _DEFINENAME_ #if _DEFINENAME_DIRECTUV==1 #define v_VARYINGNAME_UV vMainUV1 #elif _DEFINENAME_DIRECTUV==2 @@ -6498,11 +6498,11 @@ varying v_VARYINGNAME_UV: vec2f; #endif var _SAMPLERNAME_SamplerSampler: sampler;var _SAMPLERNAME_Sampler: texture_2d; #endif -`;T.IncludesShadersStoreWGSL[KW]||(T.IncludesShadersStoreWGSL[KW]=ioe)});var jW,roe,qW=C(()=>{W();jW="fresnelFunction",roe=`#ifdef FRESNEL +`;T.IncludesShadersStoreWGSL[KW]||(T.IncludesShadersStoreWGSL[KW]=ioe)});var jW,roe,qW=C(()=>{k();jW="fresnelFunction",roe=`#ifdef FRESNEL fn computeFresnelTerm(viewDirection: vec3f,worldNormal: vec3f,bias: f32,power: f32)->f32 {let fresnelTerm: f32=pow(bias+abs(dot(viewDirection,worldNormal)),power);return clamp(fresnelTerm,0.,1.);} #endif -`;T.IncludesShadersStoreWGSL[jW]||(T.IncludesShadersStoreWGSL[jW]=roe)});var ZW,noe,Og=C(()=>{W();ZW="reflectionFunction",noe=`fn computeFixedEquirectangularCoords(worldPos: vec4f,worldNormal: vec3f,direction: vec3f)->vec3f +`;T.IncludesShadersStoreWGSL[jW]||(T.IncludesShadersStoreWGSL[jW]=roe)});var ZW,noe,Og=C(()=>{k();ZW="reflectionFunction",noe=`fn computeFixedEquirectangularCoords(worldPos: vec4f,worldNormal: vec3f,direction: vec3f)->vec3f {var lon: f32=atan2(direction.z,direction.x);var lat: f32=acos(direction.y);var sphereCoords: vec2f= vec2f(lon,lat)*RECIPROCAL_PI2*2.0;var s: f32=sphereCoords.x*0.5+0.5;var t: f32=sphereCoords.y;return vec3f(s,t,0); } fn computeMirroredFixedEquirectangularCoords(worldPos: vec4f,worldNormal: vec3f,direction: vec3f)->vec3f {var lon: f32=atan2(direction.z,direction.x);var lat: f32=acos(direction.y);var sphereCoords: vec2f= vec2f(lon,lat)*RECIPROCAL_PI2*2.0;var s: f32=sphereCoords.x*0.5+0.5;var t: f32=sphereCoords.y;return vec3f(1.0-s,t,0); } @@ -6566,7 +6566,7 @@ return vec3f(0,0,0); #endif } #endif -`;T.IncludesShadersStoreWGSL[ZW]||(T.IncludesShadersStoreWGSL[ZW]=noe)});var QW,soe,px=C(()=>{W();QW="imageProcessingDeclaration",soe=`#ifdef EXPOSURE +`;T.IncludesShadersStoreWGSL[ZW]||(T.IncludesShadersStoreWGSL[ZW]=noe)});var QW,soe,_x=C(()=>{k();QW="imageProcessingDeclaration",soe=`#ifdef EXPOSURE uniform exposureLinear: f32; #endif #ifdef CONTRAST @@ -6592,7 +6592,7 @@ uniform colorTransformSettings: vec4f; #ifdef DITHER uniform ditherIntensity: f32; #endif -`;T.IncludesShadersStoreWGSL[QW]||(T.IncludesShadersStoreWGSL[QW]=soe)});var $W,aoe,_x=C(()=>{W();$W="imageProcessingFunctions",aoe=`#if TONEMAPPING==3 +`;T.IncludesShadersStoreWGSL[QW]||(T.IncludesShadersStoreWGSL[QW]=soe)});var $W,aoe,gx=C(()=>{k();$W="imageProcessingFunctions",aoe=`#if TONEMAPPING==3 const PBRNeutralStartCompression: f32=0.8-0.04;const PBRNeutralDesaturation: f32=0.15;fn PBRNeutralToneMapping( color: vec3f )->vec3f {var x: f32=min(color.r,min(color.g,color.b));var offset: f32=select(0.04,x-6.25*x*x,x<0.08);var result=color;result-=offset;var peak: f32=max(result.r,max(result.g,result.b));if (peak{W();JW="bumpFragmentMainFunctions",ooe=`#if defined(BUMP) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(DETAIL) +return vec4f(rgb,result.a);}`;T.IncludesShadersStoreWGSL[$W]||(T.IncludesShadersStoreWGSL[$W]=aoe)});var JW,ooe,vx=C(()=>{k();JW="bumpFragmentMainFunctions",ooe=`#if defined(BUMP) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(DETAIL) #if defined(TANGENT) && defined(NORMAL) varying vTBN0: vec3f;varying vTBN1: vec3f;varying vTBN2: vec3f; #endif @@ -6694,7 +6694,7 @@ fn perturbNormal(cotangentFrame: mat3x3f,textureSample: vec3f,scale: f32)->vec3f fn cotangent_frame(normal: vec3f,p: vec3f,uv: vec2f,tangentSpaceParams: vec2f)->mat3x3f {var dp1: vec3f=dpdx(p);var dp2: vec3f=dpdy(p);var duv1: vec2f=dpdx(uv);var duv2: vec2f=dpdy(uv);var dp2perp: vec3f=cross(dp2,normal);var dp1perp: vec3f=cross(normal,dp1);var tangent: vec3f=dp2perp*duv1.x+dp1perp*duv2.x;var bitangent: vec3f=dp2perp*duv1.y+dp1perp*duv2.y;tangent*=tangentSpaceParams.x;bitangent*=tangentSpaceParams.y;var det: f32=max(dot(tangent,tangent),dot(bitangent,bitangent));var invmax: f32=select(inverseSqrt(det),0.0,det==0.0);return mat3x3f(tangent*invmax,bitangent*invmax,normal);} #endif -`;T.IncludesShadersStoreWGSL[JW]||(T.IncludesShadersStoreWGSL[JW]=ooe)});var eH,loe,vx=C(()=>{W();id();eH="bumpFragmentFunctions",loe=`#if defined(BUMP) +`;T.IncludesShadersStoreWGSL[JW]||(T.IncludesShadersStoreWGSL[JW]=ooe)});var eH,loe,Ex=C(()=>{k();id();eH="bumpFragmentFunctions",loe=`#if defined(BUMP) #include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump) #endif #if defined(DETAIL) @@ -6724,7 +6724,7 @@ return -texCoordOffset; #endif } #endif -`;T.IncludesShadersStoreWGSL[eH]||(T.IncludesShadersStoreWGSL[eH]=loe)});var tH,coe,Ex=C(()=>{W();tH="bumpFragment",coe=`var uvOffset: vec2f= vec2f(0.0,0.0); +`;T.IncludesShadersStoreWGSL[eH]||(T.IncludesShadersStoreWGSL[eH]=loe)});var tH,coe,Sx=C(()=>{k();tH="bumpFragment",coe=`var uvOffset: vec2f= vec2f(0.0,0.0); #if defined(BUMP) || defined(PARALLAX) || defined(DETAIL) #ifdef NORMALXYSCALE var normalScale: f32=1.0; @@ -6776,7 +6776,7 @@ normalW=perturbNormalBase(TBN,blendedNormal,uniforms.vBumpInfos.y); #elif defined(DETAIL) detailNormal=vec3f(detailNormal.xy*uniforms.vDetailInfos.z,detailNormal.z);normalW=perturbNormalBase(TBN,detailNormal,uniforms.vDetailInfos.z); #endif -`;T.IncludesShadersStoreWGSL[tH]||(T.IncludesShadersStoreWGSL[tH]=coe)});var iH,foe,yP=C(()=>{W();iH="decalFragment",foe=`#ifdef DECAL +`;T.IncludesShadersStoreWGSL[tH]||(T.IncludesShadersStoreWGSL[tH]=coe)});var iH,foe,yP=C(()=>{k();iH="decalFragment",foe=`#ifdef DECAL var decalTempColor=decalColor.rgb;var decalTempAlpha=decalColor.a; #ifdef GAMMADECAL decalTempColor=toLinearSpaceVec3(decalColor.rgb); @@ -6786,13 +6786,13 @@ decalTempAlpha=decalColor.a*decalColor.a; #endif surfaceAlbedo=mix(surfaceAlbedo.rgb,decalTempColor,decalTempAlpha); #endif -`;T.IncludesShadersStoreWGSL[iH]||(T.IncludesShadersStoreWGSL[iH]=foe)});var rH,hoe,Sx=C(()=>{W();rH="depthPrePass",hoe=`#ifdef DEPTHPREPASS +`;T.IncludesShadersStoreWGSL[iH]||(T.IncludesShadersStoreWGSL[iH]=foe)});var rH,hoe,Tx=C(()=>{k();rH="depthPrePass",hoe=`#ifdef DEPTHPREPASS #if !defined(PREPASS) && !defined(ORDER_INDEPENDENT_TRANSPARENCY) fragmentOutputs.color= vec4f(0.,0.,0.,1.0); #endif return fragmentOutputs; #endif -`;T.IncludesShadersStoreWGSL[rH]||(T.IncludesShadersStoreWGSL[rH]=hoe)});var nH,doe,PP=C(()=>{W();nH="lightFragment",doe=`#ifdef LIGHT{X} +`;T.IncludesShadersStoreWGSL[rH]||(T.IncludesShadersStoreWGSL[rH]=hoe)});var nH,doe,PP=C(()=>{k();nH="lightFragment",doe=`#ifdef LIGHT{X} #if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}) #else var diffuse{X}: vec4f=light{X}.vLightDiffuse; @@ -7179,10 +7179,10 @@ sheenBase+=info.sheen.rgb*shadow; #endif #endif #endif -`;T.IncludesShadersStoreWGSL[nH]||(T.IncludesShadersStoreWGSL[nH]=doe)});var sH,uoe,Tx=C(()=>{W();sH="logDepthFragment",uoe=`#ifdef LOGARITHMICDEPTH +`;T.IncludesShadersStoreWGSL[nH]||(T.IncludesShadersStoreWGSL[nH]=doe)});var sH,uoe,Ax=C(()=>{k();sH="logDepthFragment",uoe=`#ifdef LOGARITHMICDEPTH fragmentOutputs.fragDepth=log2(fragmentInputs.vFragmentDepth)*uniforms.logarithmicDepthConstant*0.5; #endif -`;T.IncludesShadersStoreWGSL[sH]||(T.IncludesShadersStoreWGSL[sH]=uoe)});var aH,moe,Ax=C(()=>{W();aH="oitFragment",moe=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY +`;T.IncludesShadersStoreWGSL[sH]||(T.IncludesShadersStoreWGSL[sH]=uoe)});var aH,moe,xx=C(()=>{k();aH="oitFragment",moe=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY var fragDepth: f32=fragmentInputs.position.z; #ifdef ORDER_INDEPENDENT_TRANSPARENCY_16BITS var halfFloat: u32=pack2x16float( vec2f(fragDepth));var full: vec2f=unpack2x16float(halfFloat);fragDepth=full.x; @@ -7207,7 +7207,7 @@ if (fragDepth>nearestDepth && fragDepthpoe});var DP,oH,poe,cH=C(()=>{W();RP();hx();dx();qm();Ca();ux();XW();mx();id();qW();Og();px();_x();gx();vx();fc();td();Sg();hc();Ex();yP();Sx();PP();Tx();Tg();Ax();DP="defaultPixelShader",oH=`#include +`;T.IncludesShadersStoreWGSL[aH]||(T.IncludesShadersStoreWGSL[aH]=moe)});var lH={};tt(lH,{defaultPixelShaderWGSL:()=>poe});var DP,oH,poe,cH=C(()=>{k();RP();dx();ux();jm();Ma();mx();XW();px();id();qW();Og();_x();gx();vx();Ex();cc();td();Sg();fc();Sx();yP();Tx();PP();Ax();Tg();xx();DP="defaultPixelShader",oH=`#include #include[SCENE_MRT_COUNT] #include #define CUSTOM_FRAGMENT_BEGIN @@ -7573,10 +7573,10 @@ if (fragDepth==nearestDepth) {fragmentOutputs.frontColor=vec4f(fragmentOutputs.f #endif #define CUSTOM_FRAGMENT_MAIN_END } -`;T.ShadersStoreWGSL[DP]||(T.ShadersStoreWGSL[DP]=oH);poe={name:DP,shader:oH}});var fH,_oe,xx=C(()=>{W();fH="decalVertexDeclaration",_oe=`#ifdef DECAL +`;T.ShadersStoreWGSL[DP]||(T.ShadersStoreWGSL[DP]=oH);poe={name:DP,shader:oH}});var fH,_oe,Rx=C(()=>{k();fH="decalVertexDeclaration",_oe=`#ifdef DECAL uniform vec4 vDecalInfos;uniform mat4 decalMatrix; #endif -`;T.IncludesShadersStore[fH]||(T.IncludesShadersStore[fH]=_oe)});var hH,goe,dH=C(()=>{W();xx();hH="defaultVertexDeclaration",goe=`uniform mat4 viewProjection; +`;T.IncludesShadersStore[fH]||(T.IncludesShadersStore[fH]=_oe)});var hH,goe,dH=C(()=>{k();Rx();hH="defaultVertexDeclaration",goe=`uniform mat4 viewProjection; #ifdef MULTIVIEW mat4 viewProjectionR; #endif @@ -7614,28 +7614,28 @@ uniform vec4 vDetailInfos;uniform mat4 detailMatrix; uniform vec4 cameraInfo; #include #define ADDITIONAL_VERTEX_DECLARATION -`;T.IncludesShadersStore[hH]||(T.IncludesShadersStore[hH]=goe)});var uH,voe,rd=C(()=>{W();uH="sceneUboDeclaration",voe=`layout(std140,column_major) uniform;uniform Scene {mat4 viewProjection; +`;T.IncludesShadersStore[hH]||(T.IncludesShadersStore[hH]=goe)});var uH,voe,rd=C(()=>{k();uH="sceneUboDeclaration",voe=`layout(std140,column_major) uniform;uniform Scene {mat4 viewProjection; #ifdef MULTIVIEW mat4 viewProjectionR; #endif mat4 view;mat4 projection;vec4 vEyePosition;mat4 inverseProjection;}; -`;T.IncludesShadersStore[uH]||(T.IncludesShadersStore[uH]=voe)});var mH,Eoe,Ng=C(()=>{W();mH="meshUboDeclaration",Eoe=`#ifdef WEBGL2 +`;T.IncludesShadersStore[uH]||(T.IncludesShadersStore[uH]=voe)});var mH,Eoe,Ng=C(()=>{k();mH="meshUboDeclaration",Eoe=`#ifdef WEBGL2 uniform mat4 world;uniform float visibility; #else layout(std140,column_major) uniform;uniform Mesh {mat4 world;float visibility;}; #endif #define WORLD_UBO -`;T.IncludesShadersStore[mH]||(T.IncludesShadersStore[mH]=Eoe)});var pH,Soe,LP=C(()=>{W();rd();Ng();pH="defaultUboDeclaration",Soe=`layout(std140,column_major) uniform;uniform Material +`;T.IncludesShadersStore[mH]||(T.IncludesShadersStore[mH]=Eoe)});var pH,Soe,LP=C(()=>{k();rd();Ng();pH="defaultUboDeclaration",Soe=`layout(std140,column_major) uniform;uniform Material {vec4 diffuseLeftColor;vec4 diffuseRightColor;vec4 opacityParts;vec4 reflectionLeftColor;vec4 reflectionRightColor;vec4 refractionLeftColor;vec4 refractionRightColor;vec4 emissiveLeftColor;vec4 emissiveRightColor;vec2 vDiffuseInfos;vec2 vAmbientInfos;vec2 vOpacityInfos;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec2 vSpecularInfos;vec3 vBumpInfos;mat4 diffuseMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 specularMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;float pointSize;float alphaCutOff;mat4 refractionMatrix;vec4 vRefractionInfos;vec3 vRefractionPosition;vec3 vRefractionSize;vec4 vSpecularColor;vec3 vEmissiveColor;vec4 vDiffuseColor;vec3 vAmbientColor;vec4 cameraInfo;vec2 vReflectionInfos;mat4 reflectionMatrix;vec3 vReflectionPosition;vec3 vReflectionSize; #define ADDITIONAL_UBO_DECLARATION }; #include #include -`;T.IncludesShadersStore[pH]||(T.IncludesShadersStore[pH]=Soe)});var _H,Toe,Rx=C(()=>{W();_H="uvAttributeDeclaration",Toe=`#ifdef UV{X} +`;T.IncludesShadersStore[pH]||(T.IncludesShadersStore[pH]=Soe)});var _H,Toe,bx=C(()=>{k();_H="uvAttributeDeclaration",Toe=`#ifdef UV{X} attribute vec2 uv{X}; #endif -`;T.IncludesShadersStore[_H]||(T.IncludesShadersStore[_H]=Toe)});var gH,Aoe,bx=C(()=>{W();gH="prePassVertexDeclaration",Aoe=`#ifdef PREPASS +`;T.IncludesShadersStore[_H]||(T.IncludesShadersStore[_H]=Toe)});var gH,Aoe,Ix=C(()=>{k();gH="prePassVertexDeclaration",Aoe=`#ifdef PREPASS #ifdef PREPASS_LOCAL_POSITION varying vec3 vPosition; #endif @@ -7649,18 +7649,18 @@ varying float vNormViewDepth; uniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; #endif #endif -`;T.IncludesShadersStore[gH]||(T.IncludesShadersStore[gH]=Aoe)});var vH,xoe,Zm=C(()=>{W();vH="mainUVVaryingDeclaration",xoe=`#ifdef MAINUV{X} +`;T.IncludesShadersStore[gH]||(T.IncludesShadersStore[gH]=Aoe)});var vH,xoe,qm=C(()=>{k();vH="mainUVVaryingDeclaration",xoe=`#ifdef MAINUV{X} varying vec2 vMainUV{X}; #endif -`;T.IncludesShadersStore[vH]||(T.IncludesShadersStore[vH]=xoe)});var EH,Roe,Ix=C(()=>{W();EH="samplerVertexDeclaration",Roe=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 +`;T.IncludesShadersStore[vH]||(T.IncludesShadersStore[vH]=xoe)});var EH,Roe,Mx=C(()=>{k();EH="samplerVertexDeclaration",Roe=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 varying vec2 v_VARYINGNAME_UV; #endif -`;T.IncludesShadersStore[EH]||(T.IncludesShadersStore[EH]=Roe)});var SH,boe,OP=C(()=>{W();SH="bumpVertexDeclaration",boe=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) +`;T.IncludesShadersStore[EH]||(T.IncludesShadersStore[EH]=Roe)});var SH,boe,OP=C(()=>{k();SH="bumpVertexDeclaration",boe=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) #if defined(TANGENT) && defined(NORMAL) varying mat3 vTBN; #endif #endif -`;T.IncludesShadersStore[SH]||(T.IncludesShadersStore[SH]=boe)});var TH,Ioe,Mx=C(()=>{W();TH="lightVxFragmentDeclaration",Ioe=`#ifdef LIGHT{X} +`;T.IncludesShadersStore[SH]||(T.IncludesShadersStore[SH]=boe)});var TH,Ioe,Cx=C(()=>{k();TH="lightVxFragmentDeclaration",Ioe=`#ifdef LIGHT{X} uniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X}; #ifdef SPECULARTERM uniform vec4 vLightSpecular{X}; @@ -7687,7 +7687,7 @@ uniform vec3 vLightGround{X}; uniform vec4 vLightWidth{X};uniform vec4 vLightHeight{X}; #endif #endif -`;T.IncludesShadersStore[TH]||(T.IncludesShadersStore[TH]=Ioe)});var AH,Moe,Cx=C(()=>{W();AH="lightVxUboDeclaration",Moe=`#ifdef LIGHT{X} +`;T.IncludesShadersStore[TH]||(T.IncludesShadersStore[TH]=Ioe)});var AH,Moe,yx=C(()=>{k();AH="lightVxUboDeclaration",Moe=`#ifdef LIGHT{X} uniform Light{X} {vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular; #ifdef SPOTLIGHT{X} @@ -7712,7 +7712,7 @@ varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 li #endif #endif #endif -`;T.IncludesShadersStore[AH]||(T.IncludesShadersStore[AH]=Moe)});var xH,Coe,Wf=C(()=>{W();xH="morphTargetsVertexGlobalDeclaration",Coe=`#ifdef MORPHTARGETS +`;T.IncludesShadersStore[AH]||(T.IncludesShadersStore[AH]=Moe)});var xH,Coe,kf=C(()=>{k();xH="morphTargetsVertexGlobalDeclaration",Coe=`#ifdef MORPHTARGETS uniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS]; #ifdef MORPHTARGETS_TEXTURE uniform float morphTargetTextureIndices[NUM_MORPH_INFLUENCERS];uniform vec3 morphTargetTextureInfo;uniform highp sampler2DArray morphTargets;vec3 readVector3FromRawSampler(int targetIndex,float vertexIndex) @@ -7733,7 +7733,7 @@ float y=floor(vertexIndex/morphTargetTextureInfo.y);float x=vertexIndex-y*morphT } #endif #endif -`;T.IncludesShadersStore[xH]||(T.IncludesShadersStore[xH]=Coe)});var RH,yoe,Hf=C(()=>{W();RH="morphTargetsVertexDeclaration",yoe=`#ifdef MORPHTARGETS +`;T.IncludesShadersStore[xH]||(T.IncludesShadersStore[xH]=Coe)});var RH,yoe,Wf=C(()=>{k();RH="morphTargetsVertexDeclaration",yoe=`#ifdef MORPHTARGETS #ifndef MORPHTARGETS_TEXTURE #ifdef MORPHTARGETS_POSITION attribute vec3 position{X}; @@ -7757,15 +7757,15 @@ attribute vec4 color{X}; uniform float morphTargetCount; #endif #endif -`;T.IncludesShadersStore[RH]||(T.IncludesShadersStore[RH]=yoe)});var bH,Poe,nd=C(()=>{W();bH="logDepthDeclaration",Poe=`#ifdef LOGARITHMICDEPTH +`;T.IncludesShadersStore[RH]||(T.IncludesShadersStore[RH]=yoe)});var bH,Poe,nd=C(()=>{k();bH="logDepthDeclaration",Poe=`#ifdef LOGARITHMICDEPTH uniform float logarithmicDepthConstant;varying float vFragmentDepth; #endif -`;T.IncludesShadersStore[bH]||(T.IncludesShadersStore[bH]=Poe)});var IH,Doe,zf=C(()=>{W();IH="morphTargetsVertexGlobal",Doe=`#ifdef MORPHTARGETS +`;T.IncludesShadersStore[bH]||(T.IncludesShadersStore[bH]=Poe)});var IH,Doe,Hf=C(()=>{k();IH="morphTargetsVertexGlobal",Doe=`#ifdef MORPHTARGETS #ifdef MORPHTARGETS_TEXTURE float vertexID; #endif #endif -`;T.IncludesShadersStore[IH]||(T.IncludesShadersStore[IH]=Doe)});var MH,Loe,Xf=C(()=>{W();MH="morphTargetsVertex",Loe=`#ifdef MORPHTARGETS +`;T.IncludesShadersStore[IH]||(T.IncludesShadersStore[IH]=Doe)});var MH,Loe,zf=C(()=>{k();MH="morphTargetsVertex",Loe=`#ifdef MORPHTARGETS #ifdef MORPHTARGETS_TEXTURE #if {X}==0 for (int i=0; i=morphTargetCount) break;vertexID=float(gl_VertexID)*morphTargetTextureInfo.x; @@ -7825,7 +7825,7 @@ colorUpdated+=(color{X}-color)*morphTargetInfluences[{X}]; #endif #endif #endif -`;T.IncludesShadersStore[MH]||(T.IncludesShadersStore[MH]=Loe)});var CH,Ooe,yx=C(()=>{W();CH="prePassVertex",Ooe=`#ifdef PREPASS_DEPTH +`;T.IncludesShadersStore[MH]||(T.IncludesShadersStore[MH]=Loe)});var CH,Ooe,Px=C(()=>{k();CH="prePassVertex",Ooe=`#ifdef PREPASS_DEPTH vViewPos=(view*worldPos).rgb; #endif #ifdef PREPASS_NORMALIZED_VIEW_DEPTH @@ -7864,13 +7864,13 @@ vPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*ve vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); #endif #endif -`;T.IncludesShadersStore[CH]||(T.IncludesShadersStore[CH]=Ooe)});var yH,Noe,Px=C(()=>{W();yH="uvVariableDeclaration",Noe=`#if !defined(UV{X}) && defined(MAINUV{X}) +`;T.IncludesShadersStore[CH]||(T.IncludesShadersStore[CH]=Ooe)});var yH,Noe,Dx=C(()=>{k();yH="uvVariableDeclaration",Noe=`#if !defined(UV{X}) && defined(MAINUV{X}) vec2 uv{X}=vec2(0.,0.); #endif #ifdef MAINUV{X} vMainUV{X}=uv{X}; #endif -`;T.IncludesShadersStore[yH]||(T.IncludesShadersStore[yH]=Noe)});var PH,woe,Dx=C(()=>{W();PH="samplerVertexImplementation",woe=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 +`;T.IncludesShadersStore[yH]||(T.IncludesShadersStore[yH]=Noe)});var PH,woe,Lx=C(()=>{k();PH="samplerVertexImplementation",woe=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 if (v_INFONAME_==0.) {v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uvUpdated,1.0,0.0));} #ifdef UV2 @@ -7894,12 +7894,12 @@ else if (v_INFONAME_==5.) {v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv6,1.0,0.0));} #endif #endif -`;T.IncludesShadersStore[PH]||(T.IncludesShadersStore[PH]=woe)});var DH,Foe,Lx=C(()=>{W();DH="bumpVertex",Foe=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) +`;T.IncludesShadersStore[PH]||(T.IncludesShadersStore[PH]=woe)});var DH,Foe,Ox=C(()=>{k();DH="bumpVertex",Foe=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) #if defined(TANGENT) && defined(NORMAL) vec3 tbnNormal=normalize(normalUpdated);vec3 tbnTangent=normalize(tangentUpdated.xyz);vec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;vTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal); #endif #endif -`;T.IncludesShadersStore[DH]||(T.IncludesShadersStore[DH]=Foe)});var LH,Boe,Ox=C(()=>{W();LH="shadowsVertex",Boe=`#ifdef SHADOWS +`;T.IncludesShadersStore[DH]||(T.IncludesShadersStore[DH]=Foe)});var LH,Boe,Nx=C(()=>{k();LH="shadowsVertex",Boe=`#ifdef SHADOWS #if defined(SHADOWCSM{X}) vPositionFromCamera{X}=view*worldPos;for (int i=0; i{W();OH="pointCloudVertex",Uoe=`#if defined(POINTSIZE) && !defined(WEBGPU) +`;T.IncludesShadersStore[LH]||(T.IncludesShadersStore[LH]=Boe)});var OH,Uoe,NP=C(()=>{k();OH="pointCloudVertex",Uoe=`#if defined(POINTSIZE) && !defined(WEBGPU) gl_PointSize=pointSize; #endif -`;T.IncludesShadersStore[OH]||(T.IncludesShadersStore[OH]=Uoe)});var NH,Voe,Nx=C(()=>{W();NH="logDepthVertex",Voe=`#ifdef LOGARITHMICDEPTH +`;T.IncludesShadersStore[OH]||(T.IncludesShadersStore[OH]=Uoe)});var NH,Voe,wx=C(()=>{k();NH="logDepthVertex",Voe=`#ifdef LOGARITHMICDEPTH vFragmentDepth=1.0+gl_Position.w;gl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant; #endif -`;T.IncludesShadersStore[NH]||(T.IncludesShadersStore[NH]=Voe)});var FH={};tt(FH,{defaultVertexShader:()=>Goe});var wP,wH,Goe,BH=C(()=>{W();dH();LP();Rx();ya();dc();uc();Ff();bx();Zm();Ix();OP();mc();Ag();Mx();Cx();Wf();Hf();nd();zf();Xf();pc();_c();gc();yx();Px();Dx();Lx();vc();xg();Ox();Rg();NP();Nx();wP="defaultVertexShader",wH=`#define CUSTOM_VERTEX_EXTENSION +`;T.IncludesShadersStore[NH]||(T.IncludesShadersStore[NH]=Voe)});var FH={};tt(FH,{defaultVertexShader:()=>Goe});var wP,wH,Goe,BH=C(()=>{k();dH();LP();bx();Ca();hc();dc();wf();Ix();qm();Mx();OP();uc();Ag();Cx();yx();kf();Wf();nd();Hf();zf();mc();pc();_c();Px();Dx();Lx();Ox();gc();xg();Nx();Rg();NP();wx();wP="defaultVertexShader",wH=`#define CUSTOM_VERTEX_EXTENSION #include<__decl__defaultVertex> #define CUSTOM_VERTEX_BEGIN attribute vec3 position; @@ -8077,10 +8077,10 @@ vMainUV2=uv2Updated; #include #define CUSTOM_VERTEX_MAIN_END } -`;T.ShadersStore[wP]||(T.ShadersStore[wP]=wH);Goe={name:wP,shader:wH}});var UH,koe,wx=C(()=>{W();UH="decalFragmentDeclaration",koe=`#ifdef DECAL +`;T.ShadersStore[wP]||(T.ShadersStore[wP]=wH);Goe={name:wP,shader:wH}});var UH,koe,Fx=C(()=>{k();UH="decalFragmentDeclaration",koe=`#ifdef DECAL uniform vec4 vDecalInfos; #endif -`;T.IncludesShadersStore[UH]||(T.IncludesShadersStore[UH]=koe)});var VH,Woe,GH=C(()=>{W();wx();VH="defaultFragmentDeclaration",Woe=`uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;uniform vec4 vSpecularColor;uniform vec3 vEmissiveColor;uniform vec3 vAmbientColor;uniform float visibility; +`;T.IncludesShadersStore[UH]||(T.IncludesShadersStore[UH]=koe)});var VH,Woe,GH=C(()=>{k();Fx();VH="defaultFragmentDeclaration",Woe=`uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;uniform vec4 vSpecularColor;uniform vec3 vEmissiveColor;uniform vec3 vAmbientColor;uniform float visibility; #ifdef DIFFUSE uniform vec2 vDiffuseInfos; #endif @@ -8148,7 +8148,7 @@ uniform vec4 vDetailInfos; #endif #include #define ADDITIONAL_FRAGMENT_DECLARATION -`;T.IncludesShadersStore[VH]||(T.IncludesShadersStore[VH]=Woe)});var kH,Hoe,Fx=C(()=>{W();kH="prePassDeclaration",Hoe=`#ifdef PREPASS +`;T.IncludesShadersStore[VH]||(T.IncludesShadersStore[VH]=Woe)});var kH,Hoe,Bx=C(()=>{k();kH="prePassDeclaration",Hoe=`#ifdef PREPASS #extension GL_EXT_draw_buffers : require layout(location=0) out highp vec4 glFragData[{X}];highp vec4 gl_FragColor; #ifdef PREPASS_LOCAL_POSITION @@ -8164,14 +8164,14 @@ varying highp float vNormViewDepth; varying highp vec4 vCurrentPosition;varying highp vec4 vPreviousPosition; #endif #endif -`;T.IncludesShadersStore[kH]||(T.IncludesShadersStore[kH]=Hoe)});var WH,zoe,Bx=C(()=>{W();WH="oitDeclaration",zoe=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY +`;T.IncludesShadersStore[kH]||(T.IncludesShadersStore[kH]=Hoe)});var WH,zoe,Ux=C(()=>{k();WH="oitDeclaration",zoe=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY #extension GL_EXT_draw_buffers : require layout(location=0) out vec2 depth; layout(location=1) out vec4 frontColor;layout(location=2) out vec4 backColor; #define MAX_DEPTH 99999.0 highp vec4 gl_FragColor;uniform sampler2D oitDepthSampler;uniform sampler2D oitFrontColorSampler; #endif -`;T.IncludesShadersStore[WH]||(T.IncludesShadersStore[WH]=zoe)});var HH,Xoe,Ux=C(()=>{W();HH="lightFragmentDeclaration",Xoe=`#ifdef LIGHT{X} +`;T.IncludesShadersStore[WH]||(T.IncludesShadersStore[WH]=zoe)});var HH,Xoe,Vx=C(()=>{k();HH="lightFragmentDeclaration",Xoe=`#ifdef LIGHT{X} uniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X}; #ifdef SPECULARTERM uniform vec4 vLightSpecular{X}; @@ -8245,7 +8245,7 @@ uniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightTexture uniform vec2 vSliceData{X};uniform vec2 vSliceRanges{X}[CLUSTLIGHT_SLICES];uniform sampler2D lightDataTexture{X};uniform highp sampler2D tileMaskTexture{X}; #endif #endif -`;T.IncludesShadersStore[HH]||(T.IncludesShadersStore[HH]=Xoe)});var zH,Yoe,Vx=C(()=>{W();zH="lightUboDeclaration",Yoe=`#ifdef LIGHT{X} +`;T.IncludesShadersStore[HH]||(T.IncludesShadersStore[HH]=Xoe)});var zH,Yoe,Gx=C(()=>{k();zH="lightUboDeclaration",Yoe=`#ifdef LIGHT{X} uniform Light{X} {vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular; #ifdef SPOTLIGHT{X} @@ -8317,7 +8317,7 @@ uniform mat4 lightMatrix{X}; #endif #endif #endif -`;T.IncludesShadersStore[zH]||(T.IncludesShadersStore[zH]=Yoe)});var XH,Koe,FP=C(()=>{W();XH="ltcHelperFunctions",Koe=`vec2 LTCUv( const in vec3 N,const in vec3 V,const in float roughness ) {const float LUTSIZE=64.0;const float LUTSCALE=( LUTSIZE-1.0 )/LUTSIZE;const float LUTBIAS=0.5/LUTSIZE;float dotNV=saturate( dot( N,V ) );vec2 uv=vec2( roughness,sqrt( 1.0-dotNV ) );uv=uv*LUTSCALE+LUTBIAS;return uv;} +`;T.IncludesShadersStore[zH]||(T.IncludesShadersStore[zH]=Yoe)});var XH,Koe,FP=C(()=>{k();XH="ltcHelperFunctions",Koe=`vec2 LTCUv( const in vec3 N,const in vec3 V,const in float roughness ) {const float LUTSIZE=64.0;const float LUTSCALE=( LUTSIZE-1.0 )/LUTSIZE;const float LUTBIAS=0.5/LUTSIZE;float dotNV=saturate( dot( N,V ) );vec2 uv=vec2( roughness,sqrt( 1.0-dotNV ) );uv=uv*LUTSCALE+LUTBIAS;return uv;} float LTCClippedSphereFormFactor( const in vec3 f ) {float l=length( f );return max( ( l*l+f.z )/( l+1.0 ),0.0 );} vec3 LTCEdgeVectorFormFactor( 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 thetaSintheta=0.0;if( x>0.0 ) {thetaSintheta=v;} @@ -8355,7 +8355,7 @@ vec3( 0,1, 0 ), vec3( t1.z,0,t1.w ) );result.Specular=LTCEvaluateWithEmission( normal,viewDir,position,mInv,rectCoords,texFilteredMap );result.Fresnel=t2; #endif -result.Diffuse=LTCEvaluateWithEmission( normal,viewDir,position,mat3( 1.0 ),rectCoords,texFilteredMap );return result;}`;T.IncludesShadersStore[XH]||(T.IncludesShadersStore[XH]=Koe)});var YH,joe,BP=C(()=>{W();YH="clusteredLightingFunctions",joe=`struct ClusteredLight {vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular;vec4 vLightDirection;vec4 vLightFalloff;}; +result.Diffuse=LTCEvaluateWithEmission( normal,viewDir,position,mat3( 1.0 ),rectCoords,texFilteredMap );return result;}`;T.IncludesShadersStore[XH]||(T.IncludesShadersStore[XH]=Koe)});var YH,joe,BP=C(()=>{k();YH="clusteredLightingFunctions",joe=`struct ClusteredLight {vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular;vec4 vLightDirection;vec4 vLightFalloff;}; #define inline ClusteredLight getClusteredLight(sampler2D lightDataTexture,int index) {return ClusteredLight( texelFetch(lightDataTexture,ivec2(0,index),0), @@ -8365,7 +8365,7 @@ texelFetch(lightDataTexture,ivec2(3,index),0), texelFetch(lightDataTexture,ivec2(4,index),0) );} int getClusteredSliceIndex(vec2 sliceData,float viewDepth) {return int(log(viewDepth)*sliceData.x+sliceData.y);} -`;T.IncludesShadersStore[YH]||(T.IncludesShadersStore[YH]=joe)});var KH,qoe,jH=C(()=>{W();FP();BP();KH="lightsFragmentFunctions",qoe=`struct lightingInfo +`;T.IncludesShadersStore[YH]||(T.IncludesShadersStore[YH]=joe)});var KH,qoe,jH=C(()=>{k();FP();BP();KH="lightsFragmentFunctions",qoe=`struct lightingInfo {vec3 diffuse; #ifdef SPECULARTERM vec3 specular; @@ -8469,7 +8469,7 @@ result.specular+=info.specular; batchOffset+=CLUSTLIGHT_BATCH;} return result;} #endif -`;T.IncludesShadersStore[KH]||(T.IncludesShadersStore[KH]=qoe)});var qH,Zoe,Gx=C(()=>{W();qH="shadowsFragmentFunctions",Zoe=`#ifdef SHADOWS +`;T.IncludesShadersStore[KH]||(T.IncludesShadersStore[KH]=qoe)});var qH,Zoe,kx=C(()=>{k();qH="shadowsFragmentFunctions",Zoe=`#ifdef SHADOWS #if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) #define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) #else @@ -8812,7 +8812,7 @@ float computeShadowWithCSMPCSS64(float layer,vec4 vPositionFromLight,float depth {return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64,lightSizeUVCorrection,depthCorrection,penumbraDarkness);} #endif #endif -`;T.IncludesShadersStore[qH]||(T.IncludesShadersStore[qH]=Zoe)});var ZH,Qoe,sd=C(()=>{W();ZH="samplerFragmentDeclaration",Qoe=`#ifdef _DEFINENAME_ +`;T.IncludesShadersStore[qH]||(T.IncludesShadersStore[qH]=Zoe)});var ZH,Qoe,sd=C(()=>{k();ZH="samplerFragmentDeclaration",Qoe=`#ifdef _DEFINENAME_ #if _DEFINENAME_DIRECTUV==1 #define v_VARYINGNAME_UV vMainUV1 #elif _DEFINENAME_DIRECTUV==2 @@ -8830,11 +8830,11 @@ varying vec2 v_VARYINGNAME_UV; #endif uniform sampler2D _SAMPLERNAME_Sampler; #endif -`;T.IncludesShadersStore[ZH]||(T.IncludesShadersStore[ZH]=Qoe)});var QH,$oe,$H=C(()=>{W();QH="fresnelFunction",$oe=`#ifdef FRESNEL +`;T.IncludesShadersStore[ZH]||(T.IncludesShadersStore[ZH]=Qoe)});var QH,$oe,$H=C(()=>{k();QH="fresnelFunction",$oe=`#ifdef FRESNEL float computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power) {float fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);return clamp(fresnelTerm,0.,1.);} #endif -`;T.IncludesShadersStore[QH]||(T.IncludesShadersStore[QH]=$oe)});var JH,Joe,wg=C(()=>{W();JH="reflectionFunction",Joe=`vec3 computeFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction) +`;T.IncludesShadersStore[QH]||(T.IncludesShadersStore[QH]=$oe)});var JH,Joe,wg=C(()=>{k();JH="reflectionFunction",Joe=`vec3 computeFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction) {float lon=atan(direction.z,direction.x);float lat=acos(direction.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(s,t,0); } vec3 computeMirroredFixedEquirectangularCoords(vec4 worldPos,vec3 worldNormal,vec3 direction) {float lon=atan(direction.z,direction.x);float lat=acos(direction.y);vec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;float s=sphereCoords.x*0.5+0.5;float t=sphereCoords.y;return vec3(1.0-s,t,0); } @@ -8896,7 +8896,7 @@ return vec3(0,0,0); #endif } #endif -`;T.IncludesShadersStore[JH]||(T.IncludesShadersStore[JH]=Joe)});var ez,ele,kx=C(()=>{W();ez="imageProcessingDeclaration",ele=`#ifdef EXPOSURE +`;T.IncludesShadersStore[JH]||(T.IncludesShadersStore[JH]=Joe)});var ez,ele,Wx=C(()=>{k();ez="imageProcessingDeclaration",ele=`#ifdef EXPOSURE uniform float exposureLinear; #endif #ifdef CONTRAST @@ -8922,7 +8922,7 @@ uniform vec4 colorTransformSettings; #ifdef DITHER uniform float ditherIntensity; #endif -`;T.IncludesShadersStore[ez]||(T.IncludesShadersStore[ez]=ele)});var tz,tle,Wx=C(()=>{W();tz="imageProcessingFunctions",tle=`#if defined(COLORGRADING) && !defined(COLORGRADING3D) +`;T.IncludesShadersStore[ez]||(T.IncludesShadersStore[ez]=ele)});var tz,tle,Hx=C(()=>{k();tz="imageProcessingFunctions",tle=`#if defined(COLORGRADING) && !defined(COLORGRADING3D) /** * Polyfill for SAMPLE_TEXTURE_3D,which is unsupported in WebGL. * sampler3dSetting.x=textureOffset (0.5/textureSize). @@ -9010,7 +9010,7 @@ float luma=getLuminance(result.rgb);vec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*- float rand=getRand(gl_FragCoord.xy*vInverseScreenSize);float dither=mix(-ditherIntensity,ditherIntensity,rand);result.rgb=saturate(result.rgb+vec3(dither)); #endif #define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATEND -return result;}`;T.IncludesShadersStore[tz]||(T.IncludesShadersStore[tz]=tle)});var iz,ile,Hx=C(()=>{W();iz="bumpFragmentMainFunctions",ile=`#if defined(BUMP) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(DETAIL) +return result;}`;T.IncludesShadersStore[tz]||(T.IncludesShadersStore[tz]=tle)});var iz,ile,zx=C(()=>{k();iz="bumpFragmentMainFunctions",ile=`#if defined(BUMP) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(DETAIL) #if defined(TANGENT) && defined(NORMAL) varying mat3 vTBN; #endif @@ -9071,7 +9071,7 @@ vec3 perturbNormal(mat3 cotangentFrame,vec3 textureSample,float scale) mat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv,vec2 tangentSpaceParams) {vec3 dp1=dFdx(p);vec3 dp2=dFdy(p);vec2 duv1=dFdx(uv);vec2 duv2=dFdy(uv);vec3 dp2perp=cross(dp2,normal);vec3 dp1perp=cross(normal,dp1);vec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;vec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;tangent*=tangentSpaceParams.x;bitangent*=tangentSpaceParams.y;float det=max(dot(tangent,tangent),dot(bitangent,bitangent));float invmax=det==0.0 ? 0.0 : inversesqrt(det);return mat3(tangent*invmax,bitangent*invmax,normal);} #endif -`;T.IncludesShadersStore[iz]||(T.IncludesShadersStore[iz]=ile)});var rz,rle,zx=C(()=>{W();sd();rz="bumpFragmentFunctions",rle=`#if defined(BUMP) +`;T.IncludesShadersStore[iz]||(T.IncludesShadersStore[iz]=ile)});var rz,rle,Xx=C(()=>{k();sd();rz="bumpFragmentFunctions",rle=`#if defined(BUMP) #include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump) #endif #if defined(DETAIL) @@ -9101,7 +9101,7 @@ return -texCoordOffset; #endif } #endif -`;T.IncludesShadersStore[rz]||(T.IncludesShadersStore[rz]=rle)});var nz,nle,Xx=C(()=>{W();nz="bumpFragment",nle=`vec2 uvOffset=vec2(0.0,0.0); +`;T.IncludesShadersStore[rz]||(T.IncludesShadersStore[rz]=rle)});var nz,nle,Yx=C(()=>{k();nz="bumpFragment",nle=`vec2 uvOffset=vec2(0.0,0.0); #if defined(BUMP) || defined(PARALLAX) || defined(DETAIL) #ifdef NORMALXYSCALE float normalScale=1.0; @@ -9153,7 +9153,7 @@ normalW=perturbNormalBase(TBN,blendedNormal,vBumpInfos.y); #elif defined(DETAIL) detailNormal.xy*=vDetailInfos.z;normalW=perturbNormalBase(TBN,detailNormal,vDetailInfos.z); #endif -`;T.IncludesShadersStore[nz]||(T.IncludesShadersStore[nz]=nle)});var sz,sle,UP=C(()=>{W();sz="decalFragment",sle=`#ifdef DECAL +`;T.IncludesShadersStore[nz]||(T.IncludesShadersStore[nz]=nle)});var sz,sle,UP=C(()=>{k();sz="decalFragment",sle=`#ifdef DECAL #ifdef GAMMADECAL decalColor.rgb=toLinearSpace(decalColor.rgb); #endif @@ -9162,10 +9162,10 @@ decalColor.a*=decalColor.a; #endif surfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,decalColor.rgb,decalColor.a); #endif -`;T.IncludesShadersStore[sz]||(T.IncludesShadersStore[sz]=sle)});var az,ale,Yx=C(()=>{W();az="depthPrePass",ale=`#ifdef DEPTHPREPASS +`;T.IncludesShadersStore[sz]||(T.IncludesShadersStore[sz]=sle)});var az,ale,Kx=C(()=>{k();az="depthPrePass",ale=`#ifdef DEPTHPREPASS gl_FragColor=vec4(0.,0.,0.,1.0);return; #endif -`;T.IncludesShadersStore[az]||(T.IncludesShadersStore[az]=ale)});var oz,ole,VP=C(()=>{W();oz="lightFragment",ole=`#ifdef LIGHT{X} +`;T.IncludesShadersStore[az]||(T.IncludesShadersStore[az]=ale)});var oz,ole,VP=C(()=>{k();oz="lightFragment",ole=`#ifdef LIGHT{X} #if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}) #else vec4 diffuse{X}=light{X}.vLightDiffuse; @@ -9543,10 +9543,10 @@ sheenBase+=info.sheen.rgb*shadow; #endif #endif #endif -`;T.IncludesShadersStore[oz]||(T.IncludesShadersStore[oz]=ole)});var lz,lle,Kx=C(()=>{W();lz="logDepthFragment",lle=`#ifdef LOGARITHMICDEPTH +`;T.IncludesShadersStore[oz]||(T.IncludesShadersStore[oz]=ole)});var lz,lle,jx=C(()=>{k();lz="logDepthFragment",lle=`#ifdef LOGARITHMICDEPTH gl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5; #endif -`;T.IncludesShadersStore[lz]||(T.IncludesShadersStore[lz]=lle)});var cz,cle,jx=C(()=>{W();cz="oitFragment",cle=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY +`;T.IncludesShadersStore[lz]||(T.IncludesShadersStore[lz]=lle)});var cz,cle,qx=C(()=>{k();cz="oitFragment",cle=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY float fragDepth=gl_FragCoord.z; #ifdef ORDER_INDEPENDENT_TRANSPARENCY_16BITS uint halfFloat=packHalf2x16(vec2(fragDepth));vec2 full=unpackHalf2x16(halfFloat);fragDepth=full.x; @@ -9571,7 +9571,7 @@ if (fragDepth>nearestDepth && fragDepthfle});var GP,fz,fle,dz=C(()=>{W();GH();LP();Fx();Bx();Zm();ya();Ux();Vx();jH();Gx();sd();$H();wg();kx();Wx();Hx();zx();Ec();nd();bg();Sc();Xx();UP();Yx();VP();Kx();Ig();jx();GP="defaultPixelShader",fz=`#define CUSTOM_FRAGMENT_EXTENSION +`;T.IncludesShadersStore[cz]||(T.IncludesShadersStore[cz]=cle)});var hz={};tt(hz,{defaultPixelShader:()=>fle});var GP,fz,fle,dz=C(()=>{k();GH();LP();Bx();Ux();qm();Ca();Vx();Gx();jH();kx();sd();$H();wg();Wx();Hx();zx();Xx();vc();nd();bg();Ec();Yx();UP();Kx();VP();jx();Ig();qx();GP="defaultPixelShader",fz=`#define CUSTOM_FRAGMENT_EXTENSION #include<__decl__defaultFragment> #if defined(BUMP) || !defined(NORMAL) #extension GL_OES_standard_derivatives : enable @@ -9920,10 +9920,10 @@ if (fragDepth==nearestDepth) {frontColor.rgb+=color.rgb*color.a*alphaMultiplier; #endif #define CUSTOM_FRAGMENT_MAIN_END } -`;T.ShadersStore[GP]||(T.ShadersStore[GP]=fz);fle={name:GP,shader:fz}});var kP,WP,HP,zP,Ge,Tc=C(()=>{Gt();Ut();so();xs();zt();Gi();KA();jA();q_();Vn();Oa();pg();Hi();Da();Lf();xP();ol();_g();Un();Tr();qA();ZA();QA();$A();kP={effect:null,subMesh:null},WP=class extends Km(Ym(xr)){},HP=class extends zm(WP){constructor(e){super(e),this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.OPACITY=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.REFLECTION=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.SPECULAR=!1,this.SPECULARDIRECTUV=0,this.BUMP=!1,this.BUMPDIRECTUV=0,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.SPECULAROVERALPHA=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHAFROMDIFFUSE=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.DIFFUSEFRESNEL=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONFRESNEL=!1,this.REFRACTIONFRESNEL=!1,this.EMISSIVEFRESNEL=!1,this.FRESNEL=!1,this.NORMAL=!1,this.TANGENT=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.GLOSSINESS=!1,this.ROUGHNESS=!1,this.EMISSIVEASILLUMINATION=!1,this.LINKEMISSIVEWITHDIFFUSE=!1,this.REFLECTIONFRESNELFROMSPECULAR=!1,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.USELIGHTMAPASSHADOWMAP=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.INVERTCUBICMAP=!1,this.LOGARITHMICDEPTH=!1,this.REFRACTION=!1,this.REFRACTIONMAP_3D=!1,this.REFLECTIONOVERALPHA=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_POSITION=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.MORPHTARGETS_UV2=!1,this.MORPHTARGETS_COLOR=!1,this.MORPHTARGETTEXTURE_HASPOSITIONS=!1,this.MORPHTARGETTEXTURE_HASNORMALS=!1,this.MORPHTARGETTEXTURE_HASTANGENTS=!1,this.MORPHTARGETTEXTURE_HASUVS=!1,this.MORPHTARGETTEXTURE_HASUV2S=!1,this.MORPHTARGETTEXTURE_HASCOLORS=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.NONUNIFORMSCALING=!1,this.PREMULTIPLYALPHA=!1,this.ALPHATEST_AFTERALLALPHACOMPUTATIONS=!1,this.ALPHABLEND=!0,this.RGBDLIGHTMAP=!1,this.RGBDREFLECTION=!1,this.RGBDREFRACTION=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.AREALIGHTSUPPORTED=!0,this.USE_VERTEX_PULLING=!1,this.VERTEX_PULLING_USE_INDEX_BUFFER=!1,this.VERTEX_PULLING_INDEX_BUFFER_32BITS=!1,this.RIGHT_HANDED=!1,this.CLUSTLIGHT_SLICES=0,this.CLUSTLIGHT_BATCH=0,this.IS_REFLECTION_LINEAR=!1,this.IS_REFRACTION_LINEAR=!1,this.DECAL_AFTER_DETAIL=!1,this.rebuild()}},zP=class extends jm(hl){},Ge=class n extends zP{get isPrePassCapable(){return!this.disableDepthWrite}get canRenderToMRT(){return!0}constructor(e,t,i=!1){super(e,t,void 0,i||n.ForceGLSL),this._diffuseTexture=null,this._ambientTexture=null,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._specularTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._refractionTexture=null,this.ambientColor=new ge(0,0,0),this.diffuseColor=new ge(1,1,1),this.specularColor=new ge(1,1,1),this.emissiveColor=new ge(0,0,0),this.specularPower=64,this._useAlphaFromDiffuseTexture=!1,this._useEmissiveAsIllumination=!1,this._linkEmissiveWithDiffuse=!1,this._useSpecularOverAlpha=!1,this._useReflectionOverAlpha=!1,this._disableLighting=!1,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this._roughness=0,this.indexOfRefraction=.98,this.invertRefractionY=!0,this.alphaCutOff=.4,this._useLightmapAsShadowmap=!1,this._useReflectionFresnelFromSpecular=!1,this._useGlossinessFromSpecularMapAlpha=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._applyDecalMapAfterDetailMap=!1,this._shadersLoaded=!1,this._vertexPullingMetadata=null,this._renderTargets=new wi(16),this._globalAmbientColor=new ge(0,0,0),this._cacheHasRenderTargetTextures=!1,this.detailMap=new Na(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new ys,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),n.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),n.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&this._renderTargets.push(this._refractionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets)}get hasRenderTargetTextures(){return n.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget||n.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget?!0:this._cacheHasRenderTargetTextures}getClassName(){return"StandardMaterial"}needAlphaBlending(){return this._hasTransparencyMode?this._transparencyModeIsBlend:this._disableAlphaBlending?!1:this.alpha<1||this._opacityTexture!=null||this._shouldUseAlphaFromDiffuseTexture()||this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled}needAlphaTesting(){return this._hasTransparencyMode?this._transparencyModeIsTest:this._hasAlphaChannel()&&(this._transparencyMode==null||this._transparencyMode===Ee.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return this._diffuseTexture!=null&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==Ee.MATERIAL_OPAQUE}_hasAlphaChannel(){return this._diffuseTexture!=null&&this._diffuseTexture.hasAlpha||this._opacityTexture!=null}getAlphaTestTexture(){return this._diffuseTexture}isReadyForSubMesh(e,t,i=!1){this._uniformBufferLayoutBuilt||this.buildUniformLayout();let r=t._drawWrapper;if(r.effect&&this.isFrozen&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(4,this._eventInfo),t.materialDefines=new HP(this._eventInfo.defineNames));let s=this.getScene(),a=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let o=s.getEngine();if(a._needNormals=Mm(s,e,a,!0,this._maxSimultaneousLights,this._disableLighting),!Im(s,e,this._maxSimultaneousLights,this._disableLighting))return!1;Pm(s,a);let l=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(Lm(s,a,this.canRenderToMRT&&!l),Dm(s,a,l),Hn.PrepareDefines(o.currentRenderPassId,e,a),a._areTexturesDirty){this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,a._needUVs=!1;for(let f=1;f<=6;++f)a["MAINUV"+f]=!1;if(s.texturesEnabled){if(a.DIFFUSEDIRECTUV=0,a.BUMPDIRECTUV=0,a.AMBIENTDIRECTUV=0,a.OPACITYDIRECTUV=0,a.EMISSIVEDIRECTUV=0,a.SPECULARDIRECTUV=0,a.LIGHTMAPDIRECTUV=0,this._diffuseTexture&&n.DiffuseTextureEnabled)if(this._diffuseTexture.isReadyOrNotBlocking())ri(this._diffuseTexture,a,"DIFFUSE");else return!1;else a.DIFFUSE=!1;if(this._ambientTexture&&n.AmbientTextureEnabled)if(this._ambientTexture.isReadyOrNotBlocking())ri(this._ambientTexture,a,"AMBIENT");else return!1;else a.AMBIENT=!1;if(this._opacityTexture&&n.OpacityTextureEnabled)if(this._opacityTexture.isReadyOrNotBlocking())ri(this._opacityTexture,a,"OPACITY"),a.OPACITYRGB=this._opacityTexture.getAlphaFromRGB;else return!1;else a.OPACITY=!1;if(this._reflectionTexture&&n.ReflectionTextureEnabled?(a.ROUGHNESS=this._roughness>0,a.REFLECTIONOVERALPHA=this._useReflectionOverAlpha):(a.ROUGHNESS=!1,a.REFLECTIONOVERALPHA=!1),!Rf(s,this._reflectionTexture,a))return!1;if(this._emissiveTexture&&n.EmissiveTextureEnabled)if(this._emissiveTexture.isReadyOrNotBlocking())ri(this._emissiveTexture,a,"EMISSIVE");else return!1;else a.EMISSIVE=!1;if(this._lightmapTexture&&n.LightmapTextureEnabled)if(this._lightmapTexture.isReadyOrNotBlocking())ri(this._lightmapTexture,a,"LIGHTMAP"),a.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,a.RGBDLIGHTMAP=this._lightmapTexture.isRGBD;else return!1;else a.LIGHTMAP=!1;if(this._specularTexture&&n.SpecularTextureEnabled)if(this._specularTexture.isReadyOrNotBlocking())ri(this._specularTexture,a,"SPECULAR"),a.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha;else return!1;else a.SPECULAR=!1;if(s.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&n.BumpTextureEnabled){if(this._bumpTexture.isReady())ri(this._bumpTexture,a,"BUMP"),a.PARALLAX=this._useParallax,a.PARALLAX_RHS=s.useRightHandedSystem,a.PARALLAXOCCLUSION=this._useParallaxOcclusion;else return!1;a.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else a.BUMP=!1,a.PARALLAX=!1,a.PARALLAX_RHS=!1,a.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&n.RefractionTextureEnabled)if(this._refractionTexture.isReadyOrNotBlocking())a._needUVs=!0,a.REFRACTION=!0,a.REFRACTIONMAP_3D=this._refractionTexture.isCube,a.RGBDREFRACTION=this._refractionTexture.isRGBD,a.USE_LOCAL_REFRACTIONMAP_CUBIC=!!this._refractionTexture.boundingBoxSize;else return!1;else a.REFRACTION=!1;a.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else a.DIFFUSE=!1,a.AMBIENT=!1,a.OPACITY=!1,a.REFLECTION=!1,a.EMISSIVE=!1,a.LIGHTMAP=!1,a.BUMP=!1,a.REFRACTION=!1;a.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),a.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,a.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,a.SPECULAROVERALPHA=this._useSpecularOverAlpha,a.PREMULTIPLYALPHA=this.alphaMode===7||this.alphaMode===8,a.ALPHATEST_AFTERALLALPHACOMPUTATIONS=this.transparencyMode!==null,a.ALPHABLEND=this.transparencyMode===null||this.needAlphaBlendingForMesh(e)}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=a,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(a._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(a),a.IS_REFLECTION_LINEAR=this.reflectionTexture!=null&&!this.reflectionTexture.gammaSpace,a.IS_REFRACTION_LINEAR=this.refractionTexture!=null&&!this.refractionTexture.gammaSpace}if(a._areFresnelDirty&&(n.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(a.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,a.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,a.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,a.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,a.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,a.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,a._needNormals=!0,a.FRESNEL=!0):a.FRESNEL=!1),a.AREALIGHTUSED||a.CLUSTLIGHT_BATCH){for(let f=0;f{m.push(`vp_${y}_info`)}))}else this._vertexPullingMetadata=null;let v={};this.customShaderNameResolve&&(u=this.customShaderNameResolve(u,m,_,p,a,d,v));let x=a.toString(),A=t.effect,S=s.getEngine().createEffect(u,{attributes:d,uniformsNames:m,uniformBuffersNames:_,samplers:p,defines:x,fallbacks:h,onCompiled:this.onCompiled,onError:this.onError,indexParameters:g,processFinalCode:v.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:a.PREPASS,shaderLanguage:this._shaderLanguage,extraInitializationsAsync:this._shadersLoaded?void 0:async()=>{this._shaderLanguage===1?await Promise.all([Promise.resolve().then(()=>(UW(),BW)),Promise.resolve().then(()=>(cH(),lH))]):await Promise.all([Promise.resolve().then(()=>(BH(),FH)),Promise.resolve().then(()=>(dz(),hz))]),this._shadersLoaded=!0}},o);if(this._eventInfo.customCode=void 0,S)if(this._onEffectCreatedObservable&&(kP.effect=S,kP.subMesh=t,this._onEffectCreatedObservable.notifyObservers(kP)),this.allowShaderHotSwapping&&A&&!S.isReady()){if(a.markAsUnprocessed(),c=this.isFrozen,f)return a._areLightsDisposed=!0,!1}else s.resetCachedMaterial(),t.setEffect(S,a,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(a._renderId=s.getRenderId(),r._wasPreviouslyReady=!c,r._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}buildUniformLayout(){let e=this._uniformBuffer;e.addUniform("diffuseLeftColor",4),e.addUniform("diffuseRightColor",4),e.addUniform("opacityParts",4),e.addUniform("reflectionLeftColor",4),e.addUniform("reflectionRightColor",4),e.addUniform("refractionLeftColor",4),e.addUniform("refractionRightColor",4),e.addUniform("emissiveLeftColor",4),e.addUniform("emissiveRightColor",4),e.addUniform("vDiffuseInfos",2),e.addUniform("vAmbientInfos",2),e.addUniform("vOpacityInfos",2),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vSpecularInfos",2),e.addUniform("vBumpInfos",3),e.addUniform("diffuseMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("specularMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("pointSize",1),e.addUniform("alphaCutOff",1),e.addUniform("refractionMatrix",16),e.addUniform("vRefractionInfos",4),e.addUniform("vRefractionPosition",3),e.addUniform("vRefractionSize",3),e.addUniform("vSpecularColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vDiffuseColor",4),e.addUniform("vAmbientColor",3),e.addUniform("cameraInfo",4),Nm(e,!1,!0),super.buildUniformLayout()}bindForSubMesh(e,t,i){var f;let r=this.getScene(),s=i.materialDefines;if(!s)return;let a=i.effect;if(!a)return;this._activeEffect=a,t.getMeshUniformBuffer().bindToEffect(a,"Mesh"),t.transferToEffect(e),this._uniformBuffer.bindToEffect(a,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,r,t,e,this.isFrozen),Hn.Bind(r.getEngine().currentRenderPassId,this._activeEffect,t,e,this);let o=r.activeCamera;o?this._uniformBuffer.updateFloat4("cameraInfo",o.minZ,o.maxZ,0,0):this._uniformBuffer.updateFloat4("cameraInfo",0,0,0,0),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),s.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));let l=this._mustRebind(r,a,i,t.visibility);bs(t,a),this._vertexPullingMetadata&&Nf(a,this._vertexPullingMetadata);let c=this._uniformBuffer;if(l){if(this.bindViewProjection(a),!c.useUbo||!this.isFrozen||!c.isSync||i._drawWrapper._forceRebindOnNextCall){if(n.FresnelEnabled&&s.FRESNEL){if(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(c.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),c.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled){let h=En.Color3[0];h.set(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),c.updateColor4("opacityParts",h,this.opacityFresnelParameters.power)}this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(c.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),c.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(c.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),c.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(c.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),c.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))}if(r.texturesEnabled&&(this._diffuseTexture&&n.DiffuseTextureEnabled&&(c.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),ni(this._diffuseTexture,c,"diffuse")),this._ambientTexture&&n.AmbientTextureEnabled&&(c.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),ni(this._ambientTexture,c,"ambient")),this._opacityTexture&&n.OpacityTextureEnabled&&(c.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),ni(this._opacityTexture,c,"opacity")),this._hasAlphaChannel()&&c.updateFloat("alphaCutOff",this.alphaCutOff),Em(r,s,c,ge.White(),this._reflectionTexture,!1,!1,!0,!1,!1,!1,this.roughness),(!this._reflectionTexture||!n.ReflectionTextureEnabled)&&c.updateFloat2("vReflectionInfos",0,this.roughness),this._emissiveTexture&&n.EmissiveTextureEnabled&&(c.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),ni(this._emissiveTexture,c,"emissive")),this._lightmapTexture&&n.LightmapTextureEnabled&&(c.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),ni(this._lightmapTexture,c,"lightmap")),this._specularTexture&&n.SpecularTextureEnabled&&(c.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),ni(this._specularTexture,c,"specular")),this._bumpTexture&&r.getEngine().getCaps().standardDerivatives&&n.BumpTextureEnabled&&(c.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),ni(this._bumpTexture,c,"bump"),r._mirroredCameraPosition?c.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):c.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&n.RefractionTextureEnabled)){let h=1;if(this._refractionTexture.isCube||(c.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(h=this._refractionTexture.depth)),c.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,h,this.invertRefractionY?-1:1),this._refractionTexture.boundingBoxSize){let d=this._refractionTexture;c.updateVector3("vRefractionPosition",d.boundingBoxPosition),c.updateVector3("vRefractionSize",d.boundingBoxSize)}}this.pointsCloud&&c.updateFloat("pointSize",this.pointSize),c.updateColor4("vSpecularColor",this.specularColor,this.specularPower),c.updateColor3("vEmissiveColor",n.EmissiveTextureEnabled?this.emissiveColor:ge.BlackReadOnly),c.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),r.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),c.updateColor3("vAmbientColor",this._globalAmbientColor)}r.texturesEnabled&&(this._diffuseTexture&&n.DiffuseTextureEnabled&&a.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&n.AmbientTextureEnabled&&a.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&n.OpacityTextureEnabled&&a.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&n.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?a.setTexture("reflectionCubeSampler",this._reflectionTexture):a.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&n.EmissiveTextureEnabled&&a.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&n.LightmapTextureEnabled&&a.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&n.SpecularTextureEnabled&&a.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&r.getEngine().getCaps().standardDerivatives&&n.BumpTextureEnabled&&a.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&n.RefractionTextureEnabled&&(this._refractionTexture.isCube?a.setTexture("refractionCubeSampler",this._refractionTexture):a.setTexture("refraction2DSampler",this._refractionTexture))),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(a),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),Fn(a,this,r),this.bindEyePosition(a)}else r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(l||!this.isFrozen)&&(r.lightsEnabled&&!this._disableLighting&&Tm(r,t,a,s,this._maxSimultaneousLights),(r.fogEnabled&&t.applyFog&&r.fogMode!==$t.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||t.receiveShadows||s.PREPASS||s.CLUSTLIGHT_BATCH)&&this.bindView(a),Af(r,t,a),s.NUM_MORPH_INFLUENCERS&&Bn(t,a),s.BAKED_VERTEX_ANIMATION_TEXTURE&&((f=t.bakedVertexAnimationManager)==null||f.bind(a,s.INSTANCES)),this.useLogarithmicDepth&&Tf(s,a,r),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect,i),c.update()}getAnimatables(){let e=super.getAnimatables();return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._specularTexture&&this._specularTexture.animations&&this._specularTexture.animations.length>0&&e.push(this._specularTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),e}getActiveTextures(){let e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._specularTexture&&e.push(this._specularTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this._refractionTexture&&e.push(this._refractionTexture),e}hasTexture(e){return!!(super.hasTexture(e)||this._diffuseTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._specularTexture===e||this._bumpTexture===e||this._lightmapTexture===e||this._refractionTexture===e)}dispose(e,t){var i,r,s,a,o,l,c,f,h;t&&((i=this._diffuseTexture)==null||i.dispose(),(r=this._ambientTexture)==null||r.dispose(),(s=this._opacityTexture)==null||s.dispose(),(a=this._reflectionTexture)==null||a.dispose(),(o=this._emissiveTexture)==null||o.dispose(),(l=this._specularTexture)==null||l.dispose(),(c=this._bumpTexture)==null||c.dispose(),(f=this._lightmapTexture)==null||f.dispose(),(h=this._refractionTexture)==null||h.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}clone(e,t=!0,i=""){let r=it.Clone(()=>new n(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return r.name=e,r.id=e,this.stencil.copyTo(r.stencil),this._clonePlugins(r,i),r}static Parse(e,t,i){let r=it.Parse(()=>new n(e.name,t),e,t,i);return e.stencil&&r.stencil.parse(e.stencil,t,i),Ee._ParsePlugins(e,r,t,i),r}static get DiffuseTextureEnabled(){return le.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){le.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return le.DetailTextureEnabled}static set DetailTextureEnabled(e){le.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return le.AmbientTextureEnabled}static set AmbientTextureEnabled(e){le.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return le.OpacityTextureEnabled}static set OpacityTextureEnabled(e){le.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return le.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){le.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return le.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){le.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return le.SpecularTextureEnabled}static set SpecularTextureEnabled(e){le.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return le.BumpTextureEnabled}static set BumpTextureEnabled(e){le.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return le.LightmapTextureEnabled}static set LightmapTextureEnabled(e){le.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return le.RefractionTextureEnabled}static set RefractionTextureEnabled(e){le.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return le.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){le.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return le.FresnelEnabled}static set FresnelEnabled(e){le.FresnelEnabled=e}};Ge.ForceGLSL=!1;P([Bt("diffuseTexture")],Ge.prototype,"_diffuseTexture",void 0);P([oe("_markAllSubMeshesAsTexturesAndMiscDirty")],Ge.prototype,"diffuseTexture",void 0);P([Bt("ambientTexture")],Ge.prototype,"_ambientTexture",void 0);P([oe("_markAllSubMeshesAsTexturesDirty")],Ge.prototype,"ambientTexture",void 0);P([Bt("opacityTexture")],Ge.prototype,"_opacityTexture",void 0);P([oe("_markAllSubMeshesAsTexturesAndMiscDirty")],Ge.prototype,"opacityTexture",void 0);P([Bt("reflectionTexture")],Ge.prototype,"_reflectionTexture",void 0);P([oe("_markAllSubMeshesAsTexturesDirty")],Ge.prototype,"reflectionTexture",void 0);P([Bt("emissiveTexture")],Ge.prototype,"_emissiveTexture",void 0);P([oe("_markAllSubMeshesAsTexturesDirty")],Ge.prototype,"emissiveTexture",void 0);P([Bt("specularTexture")],Ge.prototype,"_specularTexture",void 0);P([oe("_markAllSubMeshesAsTexturesDirty")],Ge.prototype,"specularTexture",void 0);P([Bt("bumpTexture")],Ge.prototype,"_bumpTexture",void 0);P([oe("_markAllSubMeshesAsTexturesDirty")],Ge.prototype,"bumpTexture",void 0);P([Bt("lightmapTexture")],Ge.prototype,"_lightmapTexture",void 0);P([oe("_markAllSubMeshesAsTexturesDirty")],Ge.prototype,"lightmapTexture",void 0);P([Bt("refractionTexture")],Ge.prototype,"_refractionTexture",void 0);P([oe("_markAllSubMeshesAsTexturesDirty")],Ge.prototype,"refractionTexture",void 0);P([_r("ambient")],Ge.prototype,"ambientColor",void 0);P([_r("diffuse")],Ge.prototype,"diffuseColor",void 0);P([_r("specular")],Ge.prototype,"specularColor",void 0);P([_r("emissive")],Ge.prototype,"emissiveColor",void 0);P([w()],Ge.prototype,"specularPower",void 0);P([w("useAlphaFromDiffuseTexture")],Ge.prototype,"_useAlphaFromDiffuseTexture",void 0);P([oe("_markAllSubMeshesAsTexturesAndMiscDirty")],Ge.prototype,"useAlphaFromDiffuseTexture",void 0);P([w("useEmissiveAsIllumination")],Ge.prototype,"_useEmissiveAsIllumination",void 0);P([oe("_markAllSubMeshesAsTexturesDirty")],Ge.prototype,"useEmissiveAsIllumination",void 0);P([w("linkEmissiveWithDiffuse")],Ge.prototype,"_linkEmissiveWithDiffuse",void 0);P([oe("_markAllSubMeshesAsTexturesDirty")],Ge.prototype,"linkEmissiveWithDiffuse",void 0);P([w("useSpecularOverAlpha")],Ge.prototype,"_useSpecularOverAlpha",void 0);P([oe("_markAllSubMeshesAsTexturesDirty")],Ge.prototype,"useSpecularOverAlpha",void 0);P([w("useReflectionOverAlpha")],Ge.prototype,"_useReflectionOverAlpha",void 0);P([oe("_markAllSubMeshesAsTexturesDirty")],Ge.prototype,"useReflectionOverAlpha",void 0);P([w("disableLighting")],Ge.prototype,"_disableLighting",void 0);P([oe("_markAllSubMeshesAsLightsDirty")],Ge.prototype,"disableLighting",void 0);P([w("useObjectSpaceNormalMap")],Ge.prototype,"_useObjectSpaceNormalMap",void 0);P([oe("_markAllSubMeshesAsTexturesDirty")],Ge.prototype,"useObjectSpaceNormalMap",void 0);P([w("useParallax")],Ge.prototype,"_useParallax",void 0);P([oe("_markAllSubMeshesAsTexturesDirty")],Ge.prototype,"useParallax",void 0);P([w("useParallaxOcclusion")],Ge.prototype,"_useParallaxOcclusion",void 0);P([oe("_markAllSubMeshesAsTexturesDirty")],Ge.prototype,"useParallaxOcclusion",void 0);P([w()],Ge.prototype,"parallaxScaleBias",void 0);P([w("roughness")],Ge.prototype,"_roughness",void 0);P([oe("_markAllSubMeshesAsTexturesDirty")],Ge.prototype,"roughness",void 0);P([w()],Ge.prototype,"indexOfRefraction",void 0);P([w()],Ge.prototype,"invertRefractionY",void 0);P([w()],Ge.prototype,"alphaCutOff",void 0);P([w("useLightmapAsShadowmap")],Ge.prototype,"_useLightmapAsShadowmap",void 0);P([oe("_markAllSubMeshesAsTexturesDirty")],Ge.prototype,"useLightmapAsShadowmap",void 0);P([em("diffuseFresnelParameters")],Ge.prototype,"_diffuseFresnelParameters",void 0);P([oe("_markAllSubMeshesAsFresnelDirty")],Ge.prototype,"diffuseFresnelParameters",void 0);P([em("opacityFresnelParameters")],Ge.prototype,"_opacityFresnelParameters",void 0);P([oe("_markAllSubMeshesAsFresnelAndMiscDirty")],Ge.prototype,"opacityFresnelParameters",void 0);P([em("reflectionFresnelParameters")],Ge.prototype,"_reflectionFresnelParameters",void 0);P([oe("_markAllSubMeshesAsFresnelDirty")],Ge.prototype,"reflectionFresnelParameters",void 0);P([em("refractionFresnelParameters")],Ge.prototype,"_refractionFresnelParameters",void 0);P([oe("_markAllSubMeshesAsFresnelDirty")],Ge.prototype,"refractionFresnelParameters",void 0);P([em("emissiveFresnelParameters")],Ge.prototype,"_emissiveFresnelParameters",void 0);P([oe("_markAllSubMeshesAsFresnelDirty")],Ge.prototype,"emissiveFresnelParameters",void 0);P([w("useReflectionFresnelFromSpecular")],Ge.prototype,"_useReflectionFresnelFromSpecular",void 0);P([oe("_markAllSubMeshesAsFresnelDirty")],Ge.prototype,"useReflectionFresnelFromSpecular",void 0);P([w("useGlossinessFromSpecularMapAlpha")],Ge.prototype,"_useGlossinessFromSpecularMapAlpha",void 0);P([oe("_markAllSubMeshesAsTexturesDirty")],Ge.prototype,"useGlossinessFromSpecularMapAlpha",void 0);P([w("maxSimultaneousLights")],Ge.prototype,"_maxSimultaneousLights",void 0);P([oe("_markAllSubMeshesAsLightsDirty")],Ge.prototype,"maxSimultaneousLights",void 0);P([w("invertNormalMapX")],Ge.prototype,"_invertNormalMapX",void 0);P([oe("_markAllSubMeshesAsTexturesDirty")],Ge.prototype,"invertNormalMapX",void 0);P([w("invertNormalMapY")],Ge.prototype,"_invertNormalMapY",void 0);P([oe("_markAllSubMeshesAsTexturesDirty")],Ge.prototype,"invertNormalMapY",void 0);P([w("twoSidedLighting")],Ge.prototype,"_twoSidedLighting",void 0);P([oe("_markAllSubMeshesAsTexturesDirty")],Ge.prototype,"twoSidedLighting",void 0);P([w("applyDecalMapAfterDetailMap")],Ge.prototype,"_applyDecalMapAfterDetailMap",void 0);P([oe("_markAllSubMeshesAsMiscDirty")],Ge.prototype,"applyDecalMapAfterDetailMap",void 0);wt("BABYLON.StandardMaterial",Ge);$t.DefaultMaterialFactory=n=>new Ge("default material",n)});var uz=C(()=>{$a();Qn();Es();Rt.prototype.createDynamicTexture=function(n,e,t,i){let r=new yi(this,4);return r.baseWidth=n,r.baseHeight=e,t&&(n=this.needPOTTextures?gn(n,this._caps.maxTextureSize):n,e=this.needPOTTextures?gn(e,this._caps.maxTextureSize):e),r.width=n,r.height=e,r.isReady=!1,r.generateMipMaps=t,r.samplingMode=i,this.updateTextureSamplingMode(i,r),this._internalTexturesCache.push(r),r};Rt.prototype.updateDynamicTexture=function(n,e,t,i=!1,r,s=!1,a=!1){if(!n)return;let o=this._gl,l=o.TEXTURE_2D,c=this._bindTextureDirectly(l,n,!0,s);this._unpackFlipY(t===void 0?n.invertY:t),i&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);let f=this._getWebGLTextureType(n.type),h=this._getInternalFormat(r||n.format),d=this._getRGBABufferInternalSizedFormat(n.type,h);o.texImage2D(l,0,d,h,f,e),n.generateMipMaps&&o.generateMipmap(l),c||this._bindTextureDirectly(l,null),i&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),r&&(n.format=r),n._dynamicTextureSource=e,n._premulAlpha=i,n.invertY=t||!1,n.isReady=!0}});var qx,mz=C(()=>{yt();Fr();uz();qx=class n extends _e{constructor(e,t,i,r=!1,s=3,a=5,o){let l=!i||i._isScene,c=l?i:i==null?void 0:i.scene,f=l?!r:i;super(null,c,f,o,s,void 0,void 0,void 0,void 0,a),this.name=e,this.wrapU=_e.CLAMP_ADDRESSMODE,this.wrapV=_e.CLAMP_ADDRESSMODE,this._generateMipMaps=r;let h=this._getEngine();if(!h)return;if(t.getContext)this._canvas=t,this._ownCanvas=!1,this._texture=h.createDynamicTexture(this._canvas.width,this._canvas.height,r,s);else{this._canvas=h.createCanvas(1,1),this._ownCanvas=!0;let u=t;u.width||u.width===0?this._texture=h.createDynamicTexture(u.width,u.height,r,s):this._texture=h.createDynamicTexture(t,t,r,s)}let d=this.getSize();this._canvas.width!==d.width&&(this._canvas.width=d.width),this._canvas.height!==d.height&&(this._canvas.height=d.height),this._context=this._canvas.getContext("2d")}getClassName(){return"DynamicTexture"}get canRescale(){return!0}_recreate(e){this._canvas.width=e.width,this._canvas.height=e.height,this.releaseInternalTexture(),this._texture=this._getEngine().createDynamicTexture(e.width,e.height,this._generateMipMaps,this.samplingMode)}scale(e){let t=this.getSize();t.width*=e,t.height*=e,this._recreate(t)}scaleTo(e,t){let i=this.getSize();i.width=e,i.height=t,this._recreate(i)}getContext(){return this._context}clear(e){let t=this.getSize();e&&(this._context.fillStyle=e),this._context.clearRect(0,0,t.width,t.height)}update(e,t=!1,i=!1){this._texture&&this._getEngine().updateDynamicTexture(this._texture,this._canvas,e===void 0?!0:e,t,this._format||void 0,void 0,i)}drawText(e,t,i,r,s,a,o,l=!0){let c=this.getSize();if(a&&(this._context.fillStyle=a,this._context.fillRect(0,0,c.width,c.height)),this._context.font=r,t==null){let f=this._context.measureText(e);t=(c.width-f.width)/2}if(i==null){let f=parseInt(r.replace(/\D/g,""));i=c.height/2+f/3.65}this._context.fillStyle=s||"",this._context.fillText(e,t,i),l&&this.update(o)}dispose(){var e,t;super.dispose(),this._ownCanvas&&((t=(e=this._canvas)==null?void 0:e.remove)==null||t.call(e)),this._canvas=null,this._context=null}clone(){let e=this.getScene();if(!e)return this;let t=this.getSize(),i=new n(this.name,t,e,this._generateMipMaps);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.wrapU=this.wrapU,i.wrapV=this.wrapV,i}serialize(){let e=this.getScene();e&&!e.isReady()&&te.Warn("The scene must be ready before serializing the dynamic texture");let t=super.serialize();return n._IsCanvasElement(this._canvas)&&(t.base64String=this._canvas.toDataURL()),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t}static _IsCanvasElement(e){return e.toDataURL!==void 0}_rebuild(){this.update()}}});function Qx(n,e,t,i,r,s=!1){let a=Yr.Zero();return Fg(n,e,t,i,a,r,s),a}function Fg(n,e,t,i,r,s,a=!1,o=!1){let l=n.getEngine();if(!s&&!(s=n.activeCamera)&&!(s=n.cameraToUseForPointers))return n;let c=s.viewport,f=l.getRenderHeight(),{x:h,y:d,width:u,height:m}=c.toGlobal(l.getRenderWidth(),f),p=1/l.getHardwareScalingLevel();return e=e*p-h,t=t*p-(f-d-m),r.update(e,t,u,m,i||j.IdentityReadOnly,a?j.IdentityReadOnly:s.getViewMatrix(),s.getProjectionMatrix(),o),n}function gz(n,e,t,i){let r=Yr.Zero();return XP(n,e,t,r,i),r}function XP(n,e,t,i,r){if(!es)return n;let s=n.getEngine();if(!r&&!(r=n.activeCamera)&&!(r=n.cameraToUseForPointers))throw new Error("Active camera not set");let a=r.viewport,o=s.getRenderHeight(),{x:l,y:c,width:f,height:h}=a.toGlobal(s.getRenderWidth(),o),d=j.Identity(),u=1/s.getHardwareScalingLevel();return e=e*u-l,t=t*u-(o-c-h),i.update(e,t,f,h,d,d,r.getProjectionMatrix()),n}function Zx(n,e,t,i,r,s,a,o){let l=e(i,t.enableDistantPicking);return YP(n,t,i,l,r,s,a,o)}function YP(n,e,t,i,r,s,a,o){let l=e.intersects(i,r,a,s,t,o);return!l||!l.hit||!r&&n!=null&&l.distance>=n.distance?null:l}function hle(n,e){return n==="InstancedLinesMesh"||n==="LinesMesh"?e.intersectionThreshold:0}function vz(n){let e=n.getClassName();if(e==="GreasedLineMesh")return{rawBoundingInfo:null,intersectionThreshold:0};let t=n.rawBoundingInfo;return{rawBoundingInfo:t,intersectionThreshold:t?hle(e,n):0}}function Ez(n,e,t,i,r){let s=n(t,e.enableDistantPicking);return!s.intersectsSphere(i.boundingSphere,r)||!s.intersectsBox(i.boundingBox,r)?null:s}function KP(n,e,t,i,r,s){let a=null,o=!!(n.activeCameras&&n.activeCameras.length>1&&n.cameraToUseForPointers!==n.activeCamera),l=n.cameraToUseForPointers||n.activeCamera,c=_z.internalPickerForMesh||Zx,f=c===Zx;for(let h=0;h>4);for(let E=0;E1&&n.cameraToUseForPointers!==n.activeCamera),a=n.cameraToUseForPointers||n.activeCamera,o=_z.internalPickerForMesh||Zx,l=o===Zx;for(let c=0;c>4);for(let A=0;A(n._tempPickingRay||(n._tempPickingRay=Yr.Zero()),Fg(n,e,t,o,n._tempPickingRay,s||null),n._tempPickingRay),i,r,!0);return a&&(a.ray=Qx(n,e,t,j.Identity(),s||null)),a}function Az(n,e,t,i,r,s,a,o=!1){let l=KP(n,(c,f)=>(n._tempPickingRay||(n._tempPickingRay=Yr.Zero()),Fg(n,e,t,c,n._tempPickingRay,s||null,!1,f),n._tempPickingRay),i,r,!1,a);return l&&(l.ray=Qx(n,e,t,j.Identity(),s||null)),l}function xz(n,e,t,i,r){let s=KP(n,a=>(n._pickWithRayInverseMatrix||(n._pickWithRayInverseMatrix=j.Identity()),a.invertToRef(n._pickWithRayInverseMatrix),n._cachedRayForTransform||(n._cachedRayForTransform=Yr.Zero()),Yr.TransformToRef(e,n._pickWithRayInverseMatrix,n._cachedRayForTransform),n._cachedRayForTransform),t,i,!1,r);return s&&(s.ray=e),s}function Rz(n,e,t,i,r,s){return Sz(n,a=>Qx(n,e,t,a,r||null),i,s)}function bz(n,e,t,i){return Sz(n,r=>(n._pickWithRayInverseMatrix||(n._pickWithRayInverseMatrix=j.Identity()),r.invertToRef(n._pickWithRayInverseMatrix),n._cachedRayForTransform||(n._cachedRayForTransform=Yr.Zero()),Yr.TransformToRef(e,n._pickWithRayInverseMatrix,n._cachedRayForTransform),n._cachedRayForTransform),t,i)}function pz(n,e,t=100,i,r){i||(i=n.getWorldMatrix()),e.length=t,r?e.origin.copyFrom(r):e.origin.copyFrom(n.position);let s=$.Vector3[2];s.set(0,0,n._scene.useRightHandedSystem?-1:1);let a=$.Vector3[3];return b.TransformNormalToRef(s,i,a),b.NormalizeToRef(a,e.direction),e}function Iz(n,e){e&&(e.prototype.getForwardRay=function(t=100,i,r){return pz(this,new Yr(b.Zero(),b.Zero(),t),t,i,r)},e.prototype.getForwardRayToRef=function(t,i=100,r,s){return pz(this,t,i,r,s)}),n&&(Yh._IsPickingAvailable=!0,n.prototype.createPickingRay=function(t,i,r,s,a=!1){return Qx(this,t,i,r,s,a)})}var _z,Yr,jP=C(()=>{Dn();Ve();Zo();_y();Z_();Pi();xC();_z={internalPickerForMesh:void 0},Yr=class n{constructor(e,t,i=Number.MAX_VALUE,r=Ot){this.origin=e,this.direction=t,this.length=i,this.epsilon=r}clone(){return new n(this.origin.clone(),this.direction.clone(),this.length)}intersectsBoxMinMax(e,t,i=0){let r=n._TmpVector3[0].copyFromFloats(e.x-i,e.y-i,e.z-i),s=n._TmpVector3[1].copyFromFloats(t.x+i,t.y+i,t.z+i),a=0,o=Number.MAX_VALUE,l,c,f,h;if(Math.abs(this.direction.x)<1e-7){if(this.origin.xs.x)return!1}else if(l=1/this.direction.x,c=(r.x-this.origin.x)*l,f=(s.x-this.origin.x)*l,f===-1/0&&(f=1/0),c>f&&(h=c,c=f,f=h),a=Math.max(c,a),o=Math.min(f,o),a>o)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.ys.y)return!1}else if(l=1/this.direction.y,c=(r.y-this.origin.y)*l,f=(s.y-this.origin.y)*l,f===-1/0&&(f=1/0),c>f&&(h=c,c=f,f=h),a=Math.max(c,a),o=Math.min(f,o),a>o)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.zs.z)return!1}else if(l=1/this.direction.z,c=(r.z-this.origin.z)*l,f=(s.z-this.origin.z)*l,f===-1/0&&(f=1/0),c>f&&(h=c,c=f,f=h),a=Math.max(c,a),o=Math.min(f,o),a>o)return!1;return!0}intersectsBox(e,t=0){return this.intersectsBoxMinMax(e.minimum,e.maximum,t)}intersectsSphere(e,t=0){let i=e.center.x-this.origin.x,r=e.center.y-this.origin.y,s=e.center.z-this.origin.z,a=i*i+r*r+s*s,o=e.radius+t,l=o*o;if(a<=l)return!0;let c=i*this.direction.x+r*this.direction.y+s*this.direction.z;return c<0?!1:a-c*c<=l}intersectsTriangle(e,t,i){let r=n._TmpVector3[0],s=n._TmpVector3[1],a=n._TmpVector3[2],o=n._TmpVector3[3],l=n._TmpVector3[4];t.subtractToRef(e,r),i.subtractToRef(e,s),b.CrossToRef(this.direction,s,a);let c=b.Dot(r,a);if(c===0)return null;let f=1/c;this.origin.subtractToRef(e,o);let h=b.Dot(o,a)*f;if(h<-this.epsilon||h>1+this.epsilon)return null;b.CrossToRef(o,r,l);let d=b.Dot(this.direction,l)*f;if(d<-this.epsilon||h+d>1+this.epsilon)return null;let u=b.Dot(s,l)*f;return u>this.length||u<0?null:new jh(1-h-d,h,u)}intersectsPlane(e){let t,i=b.Dot(e.normal,this.direction);if(Math.abs(i)<999999997475243e-21)return null;{let r=b.Dot(e.normal,this.origin);return t=(-e.d-r)/i,t<0?t<-999999997475243e-21?null:0:t}}intersectsAxis(e,t=0){switch(e){case"y":{let i=(this.origin.y-t)/this.direction.y;return i>0?null:new b(this.origin.x+this.direction.x*-i,t,this.origin.z+this.direction.z*-i)}case"x":{let i=(this.origin.x-t)/this.direction.x;return i>0?null:new b(t,this.origin.y+this.direction.y*-i,this.origin.z+this.direction.z*-i)}case"z":{let i=(this.origin.z-t)/this.direction.z;return i>0?null:new b(this.origin.x+this.direction.x*-i,this.origin.y+this.direction.y*-i,t)}default:return null}}intersectsMesh(e,t,i,r=!1,s,a=!1){let o=$.Matrix[0];return e.getWorldMatrix().invertToRef(o),this._tmpRay?n.TransformToRef(this,o,this._tmpRay):this._tmpRay=n.Transform(this,o),e.intersects(this._tmpRay,t,i,r,s,a)}intersectsMeshes(e,t,i){i?i.length=0:i=[];for(let r=0;rt.distance?1:0}intersectionSegment(e,t,i){let r=this.origin,s=$.Vector3[0],a=$.Vector3[1],o=$.Vector3[2],l=$.Vector3[3];t.subtractToRef(e,s),this.direction.scaleToRef(n._Rayl,o),r.addToRef(o,a),e.subtractToRef(r,l);let c=b.Dot(s,s),f=b.Dot(s,o),h=b.Dot(o,o),d=b.Dot(s,l),u=b.Dot(o,l),m=c*h-f*f,p,_=m,g,v=m;m_&&(p=_,g=u+f,v=h)),g<0?(g=0,-d<0?p=0:-d>c?p=_:(p=-d,_=c)):g>v&&(g=v,-d+f<0?p=0:-d+f>c?p=_:(p=-d+f,_=c));let x=Math.abs(p)0&&A<=this.length&&R.lengthSquared(){xs();sl();jP();jP();Iz($t,ut);$t.prototype.createPickingRayToRef=function(n,e,t,i,r,s=!1,a=!1){return Fg(this,n,e,t,i,r,s,a)};$t.prototype.createPickingRayInCameraSpace=function(n,e,t){return gz(this,n,e,t)};$t.prototype.createPickingRayInCameraSpaceToRef=function(n,e,t,i){return XP(this,n,e,t,i)};$t.prototype.pickWithBoundingInfo=function(n,e,t,i,r){return Tz(this,n,e,t,i,r)};$t.prototype.pick=function(n,e,t,i,r,s,a=!1){return Az(this,n,e,t,i,r,s,a)};$t.prototype.pickWithRay=function(n,e,t,i){return xz(this,n,e,t,i)};$t.prototype.multiPick=function(n,e,t,i,r){return Rz(this,n,e,t,i,r)};$t.prototype.multiPickWithRay=function(n,e,t){return bz(this,n,e,t)}});var Mz,dle,ZP=C(()=>{W();Mz="kernelBlurVaryingDeclaration",dle="varying sampleCoord{X}: vec2f;";T.IncludesShadersStoreWGSL[Mz]||(T.IncludesShadersStoreWGSL[Mz]=dle)});var Cz,ule,$x=C(()=>{W();Cz="packingFunctions",ule=`fn pack(depth: f32)->vec4f +`;T.ShadersStore[GP]||(T.ShadersStore[GP]=fz);fle={name:GP,shader:fz}});var kP,WP,HP,zP,ke,Sc=C(()=>{Gt();Vt();so();As();zt();ki();jA();qA();q_();Vn();La();pg();Hi();Pa();Df();xP();ol();_g();Un();Tr();ZA();QA();$A();JA();kP={effect:null,subMesh:null},WP=class extends Ym(Xm(xr)){},HP=class extends Hm(WP){constructor(e){super(e),this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.OPACITY=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.REFLECTION=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.SPECULAR=!1,this.SPECULARDIRECTUV=0,this.BUMP=!1,this.BUMPDIRECTUV=0,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.SPECULAROVERALPHA=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHAFROMDIFFUSE=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.DIFFUSEFRESNEL=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONFRESNEL=!1,this.REFRACTIONFRESNEL=!1,this.EMISSIVEFRESNEL=!1,this.FRESNEL=!1,this.NORMAL=!1,this.TANGENT=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.GLOSSINESS=!1,this.ROUGHNESS=!1,this.EMISSIVEASILLUMINATION=!1,this.LINKEMISSIVEWITHDIFFUSE=!1,this.REFLECTIONFRESNELFROMSPECULAR=!1,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.USELIGHTMAPASSHADOWMAP=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.INVERTCUBICMAP=!1,this.LOGARITHMICDEPTH=!1,this.REFRACTION=!1,this.REFRACTIONMAP_3D=!1,this.REFLECTIONOVERALPHA=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_POSITION=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.MORPHTARGETS_UV2=!1,this.MORPHTARGETS_COLOR=!1,this.MORPHTARGETTEXTURE_HASPOSITIONS=!1,this.MORPHTARGETTEXTURE_HASNORMALS=!1,this.MORPHTARGETTEXTURE_HASTANGENTS=!1,this.MORPHTARGETTEXTURE_HASUVS=!1,this.MORPHTARGETTEXTURE_HASUV2S=!1,this.MORPHTARGETTEXTURE_HASCOLORS=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.NONUNIFORMSCALING=!1,this.PREMULTIPLYALPHA=!1,this.ALPHATEST_AFTERALLALPHACOMPUTATIONS=!1,this.ALPHABLEND=!0,this.RGBDLIGHTMAP=!1,this.RGBDREFLECTION=!1,this.RGBDREFRACTION=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.AREALIGHTSUPPORTED=!0,this.USE_VERTEX_PULLING=!1,this.VERTEX_PULLING_USE_INDEX_BUFFER=!1,this.VERTEX_PULLING_INDEX_BUFFER_32BITS=!1,this.RIGHT_HANDED=!1,this.CLUSTLIGHT_SLICES=0,this.CLUSTLIGHT_BATCH=0,this.IS_REFLECTION_LINEAR=!1,this.IS_REFRACTION_LINEAR=!1,this.DECAL_AFTER_DETAIL=!1,this.rebuild()}},zP=class extends Km(hl){},ke=class n extends zP{get isPrePassCapable(){return!this.disableDepthWrite}get canRenderToMRT(){return!0}constructor(e,t,i=!1){super(e,t,void 0,i||n.ForceGLSL),this._diffuseTexture=null,this._ambientTexture=null,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._specularTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._refractionTexture=null,this.ambientColor=new ve(0,0,0),this.diffuseColor=new ve(1,1,1),this.specularColor=new ve(1,1,1),this.emissiveColor=new ve(0,0,0),this.specularPower=64,this._useAlphaFromDiffuseTexture=!1,this._useEmissiveAsIllumination=!1,this._linkEmissiveWithDiffuse=!1,this._useSpecularOverAlpha=!1,this._useReflectionOverAlpha=!1,this._disableLighting=!1,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this._roughness=0,this.indexOfRefraction=.98,this.invertRefractionY=!0,this.alphaCutOff=.4,this._useLightmapAsShadowmap=!1,this._useReflectionFresnelFromSpecular=!1,this._useGlossinessFromSpecularMapAlpha=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._applyDecalMapAfterDetailMap=!1,this._shadersLoaded=!1,this._vertexPullingMetadata=null,this._renderTargets=new Bi(16),this._globalAmbientColor=new ve(0,0,0),this._cacheHasRenderTargetTextures=!1,this.detailMap=new Oa(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new Cs,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),n.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),n.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&this._renderTargets.push(this._refractionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets)}get hasRenderTargetTextures(){return n.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget||n.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget?!0:this._cacheHasRenderTargetTextures}getClassName(){return"StandardMaterial"}needAlphaBlending(){return this._hasTransparencyMode?this._transparencyModeIsBlend:this._disableAlphaBlending?!1:this.alpha<1||this._opacityTexture!=null||this._shouldUseAlphaFromDiffuseTexture()||this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled}needAlphaTesting(){return this._hasTransparencyMode?this._transparencyModeIsTest:this._hasAlphaChannel()&&(this._transparencyMode==null||this._transparencyMode===Ee.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return this._diffuseTexture!=null&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==Ee.MATERIAL_OPAQUE}_hasAlphaChannel(){return this._diffuseTexture!=null&&this._diffuseTexture.hasAlpha||this._opacityTexture!=null}getAlphaTestTexture(){return this._diffuseTexture}isReadyForSubMesh(e,t,i=!1){this._uniformBufferLayoutBuilt||this.buildUniformLayout();let r=t._drawWrapper;if(r.effect&&this.isFrozen&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(4,this._eventInfo),t.materialDefines=new HP(this._eventInfo.defineNames));let s=this.getScene(),a=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let o=s.getEngine();if(a._needNormals=Im(s,e,a,!0,this._maxSimultaneousLights,this._disableLighting),!bm(s,e,this._maxSimultaneousLights,this._disableLighting))return!1;ym(s,a);let l=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(Dm(s,a,this.canRenderToMRT&&!l),Pm(s,a,l),Hn.PrepareDefines(o.currentRenderPassId,e,a),a._areTexturesDirty){this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,a._needUVs=!1;for(let f=1;f<=6;++f)a["MAINUV"+f]=!1;if(s.texturesEnabled){if(a.DIFFUSEDIRECTUV=0,a.BUMPDIRECTUV=0,a.AMBIENTDIRECTUV=0,a.OPACITYDIRECTUV=0,a.EMISSIVEDIRECTUV=0,a.SPECULARDIRECTUV=0,a.LIGHTMAPDIRECTUV=0,this._diffuseTexture&&n.DiffuseTextureEnabled)if(this._diffuseTexture.isReadyOrNotBlocking())ni(this._diffuseTexture,a,"DIFFUSE");else return!1;else a.DIFFUSE=!1;if(this._ambientTexture&&n.AmbientTextureEnabled)if(this._ambientTexture.isReadyOrNotBlocking())ni(this._ambientTexture,a,"AMBIENT");else return!1;else a.AMBIENT=!1;if(this._opacityTexture&&n.OpacityTextureEnabled)if(this._opacityTexture.isReadyOrNotBlocking())ni(this._opacityTexture,a,"OPACITY"),a.OPACITYRGB=this._opacityTexture.getAlphaFromRGB;else return!1;else a.OPACITY=!1;if(this._reflectionTexture&&n.ReflectionTextureEnabled?(a.ROUGHNESS=this._roughness>0,a.REFLECTIONOVERALPHA=this._useReflectionOverAlpha):(a.ROUGHNESS=!1,a.REFLECTIONOVERALPHA=!1),!xf(s,this._reflectionTexture,a))return!1;if(this._emissiveTexture&&n.EmissiveTextureEnabled)if(this._emissiveTexture.isReadyOrNotBlocking())ni(this._emissiveTexture,a,"EMISSIVE");else return!1;else a.EMISSIVE=!1;if(this._lightmapTexture&&n.LightmapTextureEnabled)if(this._lightmapTexture.isReadyOrNotBlocking())ni(this._lightmapTexture,a,"LIGHTMAP"),a.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,a.RGBDLIGHTMAP=this._lightmapTexture.isRGBD;else return!1;else a.LIGHTMAP=!1;if(this._specularTexture&&n.SpecularTextureEnabled)if(this._specularTexture.isReadyOrNotBlocking())ni(this._specularTexture,a,"SPECULAR"),a.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha;else return!1;else a.SPECULAR=!1;if(s.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&n.BumpTextureEnabled){if(this._bumpTexture.isReady())ni(this._bumpTexture,a,"BUMP"),a.PARALLAX=this._useParallax,a.PARALLAX_RHS=s.useRightHandedSystem,a.PARALLAXOCCLUSION=this._useParallaxOcclusion;else return!1;a.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else a.BUMP=!1,a.PARALLAX=!1,a.PARALLAX_RHS=!1,a.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&n.RefractionTextureEnabled)if(this._refractionTexture.isReadyOrNotBlocking())a._needUVs=!0,a.REFRACTION=!0,a.REFRACTIONMAP_3D=this._refractionTexture.isCube,a.RGBDREFRACTION=this._refractionTexture.isRGBD,a.USE_LOCAL_REFRACTIONMAP_CUBIC=!!this._refractionTexture.boundingBoxSize;else return!1;else a.REFRACTION=!1;a.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else a.DIFFUSE=!1,a.AMBIENT=!1,a.OPACITY=!1,a.REFLECTION=!1,a.EMISSIVE=!1,a.LIGHTMAP=!1,a.BUMP=!1,a.REFRACTION=!1;a.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),a.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,a.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,a.SPECULAROVERALPHA=this._useSpecularOverAlpha,a.PREMULTIPLYALPHA=this.alphaMode===7||this.alphaMode===8,a.ALPHATEST_AFTERALLALPHACOMPUTATIONS=this.transparencyMode!==null,a.ALPHABLEND=this.transparencyMode===null||this.needAlphaBlendingForMesh(e)}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=a,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(a._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(a),a.IS_REFLECTION_LINEAR=this.reflectionTexture!=null&&!this.reflectionTexture.gammaSpace,a.IS_REFRACTION_LINEAR=this.refractionTexture!=null&&!this.refractionTexture.gammaSpace}if(a._areFresnelDirty&&(n.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(a.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,a.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,a.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,a.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,a.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,a.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,a._needNormals=!0,a.FRESNEL=!0):a.FRESNEL=!1),a.AREALIGHTUSED||a.CLUSTLIGHT_BATCH){for(let f=0;f{m.push(`vp_${y}_info`)}))}else this._vertexPullingMetadata=null;let v={};this.customShaderNameResolve&&(u=this.customShaderNameResolve(u,m,_,p,a,d,v));let x=a.toString(),A=t.effect,S=s.getEngine().createEffect(u,{attributes:d,uniformsNames:m,uniformBuffersNames:_,samplers:p,defines:x,fallbacks:h,onCompiled:this.onCompiled,onError:this.onError,indexParameters:g,processFinalCode:v.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:a.PREPASS,shaderLanguage:this._shaderLanguage,extraInitializationsAsync:this._shadersLoaded?void 0:async()=>{this._shaderLanguage===1?await Promise.all([Promise.resolve().then(()=>(UW(),BW)),Promise.resolve().then(()=>(cH(),lH))]):await Promise.all([Promise.resolve().then(()=>(BH(),FH)),Promise.resolve().then(()=>(dz(),hz))]),this._shadersLoaded=!0}},o);if(this._eventInfo.customCode=void 0,S)if(this._onEffectCreatedObservable&&(kP.effect=S,kP.subMesh=t,this._onEffectCreatedObservable.notifyObservers(kP)),this.allowShaderHotSwapping&&A&&!S.isReady()){if(a.markAsUnprocessed(),c=this.isFrozen,f)return a._areLightsDisposed=!0,!1}else s.resetCachedMaterial(),t.setEffect(S,a,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(a._renderId=s.getRenderId(),r._wasPreviouslyReady=!c,r._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}buildUniformLayout(){let e=this._uniformBuffer;e.addUniform("diffuseLeftColor",4),e.addUniform("diffuseRightColor",4),e.addUniform("opacityParts",4),e.addUniform("reflectionLeftColor",4),e.addUniform("reflectionRightColor",4),e.addUniform("refractionLeftColor",4),e.addUniform("refractionRightColor",4),e.addUniform("emissiveLeftColor",4),e.addUniform("emissiveRightColor",4),e.addUniform("vDiffuseInfos",2),e.addUniform("vAmbientInfos",2),e.addUniform("vOpacityInfos",2),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vSpecularInfos",2),e.addUniform("vBumpInfos",3),e.addUniform("diffuseMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("specularMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("pointSize",1),e.addUniform("alphaCutOff",1),e.addUniform("refractionMatrix",16),e.addUniform("vRefractionInfos",4),e.addUniform("vRefractionPosition",3),e.addUniform("vRefractionSize",3),e.addUniform("vSpecularColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vDiffuseColor",4),e.addUniform("vAmbientColor",3),e.addUniform("cameraInfo",4),Om(e,!1,!0),super.buildUniformLayout()}bindForSubMesh(e,t,i){var f;let r=this.getScene(),s=i.materialDefines;if(!s)return;let a=i.effect;if(!a)return;this._activeEffect=a,t.getMeshUniformBuffer().bindToEffect(a,"Mesh"),t.transferToEffect(e),this._uniformBuffer.bindToEffect(a,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,r,t,e,this.isFrozen),Hn.Bind(r.getEngine().currentRenderPassId,this._activeEffect,t,e,this);let o=r.activeCamera;o?this._uniformBuffer.updateFloat4("cameraInfo",o.minZ,o.maxZ,0,0):this._uniformBuffer.updateFloat4("cameraInfo",0,0,0,0),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),s.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));let l=this._mustRebind(r,a,i,t.visibility);Rs(t,a),this._vertexPullingMetadata&&Of(a,this._vertexPullingMetadata);let c=this._uniformBuffer;if(l){if(this.bindViewProjection(a),!c.useUbo||!this.isFrozen||!c.isSync||i._drawWrapper._forceRebindOnNextCall){if(n.FresnelEnabled&&s.FRESNEL){if(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(c.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),c.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled){let h=En.Color3[0];h.set(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),c.updateColor4("opacityParts",h,this.opacityFresnelParameters.power)}this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(c.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),c.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(c.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),c.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(c.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),c.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))}if(r.texturesEnabled&&(this._diffuseTexture&&n.DiffuseTextureEnabled&&(c.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),si(this._diffuseTexture,c,"diffuse")),this._ambientTexture&&n.AmbientTextureEnabled&&(c.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),si(this._ambientTexture,c,"ambient")),this._opacityTexture&&n.OpacityTextureEnabled&&(c.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),si(this._opacityTexture,c,"opacity")),this._hasAlphaChannel()&&c.updateFloat("alphaCutOff",this.alphaCutOff),vm(r,s,c,ve.White(),this._reflectionTexture,!1,!1,!0,!1,!1,!1,this.roughness),(!this._reflectionTexture||!n.ReflectionTextureEnabled)&&c.updateFloat2("vReflectionInfos",0,this.roughness),this._emissiveTexture&&n.EmissiveTextureEnabled&&(c.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),si(this._emissiveTexture,c,"emissive")),this._lightmapTexture&&n.LightmapTextureEnabled&&(c.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),si(this._lightmapTexture,c,"lightmap")),this._specularTexture&&n.SpecularTextureEnabled&&(c.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),si(this._specularTexture,c,"specular")),this._bumpTexture&&r.getEngine().getCaps().standardDerivatives&&n.BumpTextureEnabled&&(c.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),si(this._bumpTexture,c,"bump"),r._mirroredCameraPosition?c.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):c.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&n.RefractionTextureEnabled)){let h=1;if(this._refractionTexture.isCube||(c.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(h=this._refractionTexture.depth)),c.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,h,this.invertRefractionY?-1:1),this._refractionTexture.boundingBoxSize){let d=this._refractionTexture;c.updateVector3("vRefractionPosition",d.boundingBoxPosition),c.updateVector3("vRefractionSize",d.boundingBoxSize)}}this.pointsCloud&&c.updateFloat("pointSize",this.pointSize),c.updateColor4("vSpecularColor",this.specularColor,this.specularPower),c.updateColor3("vEmissiveColor",n.EmissiveTextureEnabled?this.emissiveColor:ve.BlackReadOnly),c.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),r.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),c.updateColor3("vAmbientColor",this._globalAmbientColor)}r.texturesEnabled&&(this._diffuseTexture&&n.DiffuseTextureEnabled&&a.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&n.AmbientTextureEnabled&&a.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&n.OpacityTextureEnabled&&a.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&n.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?a.setTexture("reflectionCubeSampler",this._reflectionTexture):a.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&n.EmissiveTextureEnabled&&a.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&n.LightmapTextureEnabled&&a.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&n.SpecularTextureEnabled&&a.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&r.getEngine().getCaps().standardDerivatives&&n.BumpTextureEnabled&&a.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&n.RefractionTextureEnabled&&(this._refractionTexture.isCube?a.setTexture("refractionCubeSampler",this._refractionTexture):a.setTexture("refraction2DSampler",this._refractionTexture))),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(a),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),Fn(a,this,r),this.bindEyePosition(a)}else r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(l||!this.isFrozen)&&(r.lightsEnabled&&!this._disableLighting&&Sm(r,t,a,s,this._maxSimultaneousLights),(r.fogEnabled&&t.applyFog&&r.fogMode!==Jt.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||t.receiveShadows||s.PREPASS||s.CLUSTLIGHT_BATCH)&&this.bindView(a),Tf(r,t,a),s.NUM_MORPH_INFLUENCERS&&Bn(t,a),s.BAKED_VERTEX_ANIMATION_TEXTURE&&((f=t.bakedVertexAnimationManager)==null||f.bind(a,s.INSTANCES)),this.useLogarithmicDepth&&Sf(s,a,r),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect,i),c.update()}getAnimatables(){let e=super.getAnimatables();return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._specularTexture&&this._specularTexture.animations&&this._specularTexture.animations.length>0&&e.push(this._specularTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),e}getActiveTextures(){let e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._specularTexture&&e.push(this._specularTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this._refractionTexture&&e.push(this._refractionTexture),e}hasTexture(e){return!!(super.hasTexture(e)||this._diffuseTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._specularTexture===e||this._bumpTexture===e||this._lightmapTexture===e||this._refractionTexture===e)}dispose(e,t){var i,r,s,a,o,l,c,f,h;t&&((i=this._diffuseTexture)==null||i.dispose(),(r=this._ambientTexture)==null||r.dispose(),(s=this._opacityTexture)==null||s.dispose(),(a=this._reflectionTexture)==null||a.dispose(),(o=this._emissiveTexture)==null||o.dispose(),(l=this._specularTexture)==null||l.dispose(),(c=this._bumpTexture)==null||c.dispose(),(f=this._lightmapTexture)==null||f.dispose(),(h=this._refractionTexture)==null||h.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}clone(e,t=!0,i=""){let r=it.Clone(()=>new n(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return r.name=e,r.id=e,this.stencil.copyTo(r.stencil),this._clonePlugins(r,i),r}static Parse(e,t,i){let r=it.Parse(()=>new n(e.name,t),e,t,i);return e.stencil&&r.stencil.parse(e.stencil,t,i),Ee._ParsePlugins(e,r,t,i),r}static get DiffuseTextureEnabled(){return ce.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){ce.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return ce.DetailTextureEnabled}static set DetailTextureEnabled(e){ce.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return ce.AmbientTextureEnabled}static set AmbientTextureEnabled(e){ce.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return ce.OpacityTextureEnabled}static set OpacityTextureEnabled(e){ce.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return ce.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){ce.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return ce.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){ce.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return ce.SpecularTextureEnabled}static set SpecularTextureEnabled(e){ce.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return ce.BumpTextureEnabled}static set BumpTextureEnabled(e){ce.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return ce.LightmapTextureEnabled}static set LightmapTextureEnabled(e){ce.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return ce.RefractionTextureEnabled}static set RefractionTextureEnabled(e){ce.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return ce.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){ce.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return ce.FresnelEnabled}static set FresnelEnabled(e){ce.FresnelEnabled=e}};ke.ForceGLSL=!1;P([Ut("diffuseTexture")],ke.prototype,"_diffuseTexture",void 0);P([le("_markAllSubMeshesAsTexturesAndMiscDirty")],ke.prototype,"diffuseTexture",void 0);P([Ut("ambientTexture")],ke.prototype,"_ambientTexture",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],ke.prototype,"ambientTexture",void 0);P([Ut("opacityTexture")],ke.prototype,"_opacityTexture",void 0);P([le("_markAllSubMeshesAsTexturesAndMiscDirty")],ke.prototype,"opacityTexture",void 0);P([Ut("reflectionTexture")],ke.prototype,"_reflectionTexture",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],ke.prototype,"reflectionTexture",void 0);P([Ut("emissiveTexture")],ke.prototype,"_emissiveTexture",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],ke.prototype,"emissiveTexture",void 0);P([Ut("specularTexture")],ke.prototype,"_specularTexture",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],ke.prototype,"specularTexture",void 0);P([Ut("bumpTexture")],ke.prototype,"_bumpTexture",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],ke.prototype,"bumpTexture",void 0);P([Ut("lightmapTexture")],ke.prototype,"_lightmapTexture",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],ke.prototype,"lightmapTexture",void 0);P([Ut("refractionTexture")],ke.prototype,"_refractionTexture",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],ke.prototype,"refractionTexture",void 0);P([gr("ambient")],ke.prototype,"ambientColor",void 0);P([gr("diffuse")],ke.prototype,"diffuseColor",void 0);P([gr("specular")],ke.prototype,"specularColor",void 0);P([gr("emissive")],ke.prototype,"emissiveColor",void 0);P([w()],ke.prototype,"specularPower",void 0);P([w("useAlphaFromDiffuseTexture")],ke.prototype,"_useAlphaFromDiffuseTexture",void 0);P([le("_markAllSubMeshesAsTexturesAndMiscDirty")],ke.prototype,"useAlphaFromDiffuseTexture",void 0);P([w("useEmissiveAsIllumination")],ke.prototype,"_useEmissiveAsIllumination",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],ke.prototype,"useEmissiveAsIllumination",void 0);P([w("linkEmissiveWithDiffuse")],ke.prototype,"_linkEmissiveWithDiffuse",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],ke.prototype,"linkEmissiveWithDiffuse",void 0);P([w("useSpecularOverAlpha")],ke.prototype,"_useSpecularOverAlpha",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],ke.prototype,"useSpecularOverAlpha",void 0);P([w("useReflectionOverAlpha")],ke.prototype,"_useReflectionOverAlpha",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],ke.prototype,"useReflectionOverAlpha",void 0);P([w("disableLighting")],ke.prototype,"_disableLighting",void 0);P([le("_markAllSubMeshesAsLightsDirty")],ke.prototype,"disableLighting",void 0);P([w("useObjectSpaceNormalMap")],ke.prototype,"_useObjectSpaceNormalMap",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],ke.prototype,"useObjectSpaceNormalMap",void 0);P([w("useParallax")],ke.prototype,"_useParallax",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],ke.prototype,"useParallax",void 0);P([w("useParallaxOcclusion")],ke.prototype,"_useParallaxOcclusion",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],ke.prototype,"useParallaxOcclusion",void 0);P([w()],ke.prototype,"parallaxScaleBias",void 0);P([w("roughness")],ke.prototype,"_roughness",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],ke.prototype,"roughness",void 0);P([w()],ke.prototype,"indexOfRefraction",void 0);P([w()],ke.prototype,"invertRefractionY",void 0);P([w()],ke.prototype,"alphaCutOff",void 0);P([w("useLightmapAsShadowmap")],ke.prototype,"_useLightmapAsShadowmap",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],ke.prototype,"useLightmapAsShadowmap",void 0);P([Ju("diffuseFresnelParameters")],ke.prototype,"_diffuseFresnelParameters",void 0);P([le("_markAllSubMeshesAsFresnelDirty")],ke.prototype,"diffuseFresnelParameters",void 0);P([Ju("opacityFresnelParameters")],ke.prototype,"_opacityFresnelParameters",void 0);P([le("_markAllSubMeshesAsFresnelAndMiscDirty")],ke.prototype,"opacityFresnelParameters",void 0);P([Ju("reflectionFresnelParameters")],ke.prototype,"_reflectionFresnelParameters",void 0);P([le("_markAllSubMeshesAsFresnelDirty")],ke.prototype,"reflectionFresnelParameters",void 0);P([Ju("refractionFresnelParameters")],ke.prototype,"_refractionFresnelParameters",void 0);P([le("_markAllSubMeshesAsFresnelDirty")],ke.prototype,"refractionFresnelParameters",void 0);P([Ju("emissiveFresnelParameters")],ke.prototype,"_emissiveFresnelParameters",void 0);P([le("_markAllSubMeshesAsFresnelDirty")],ke.prototype,"emissiveFresnelParameters",void 0);P([w("useReflectionFresnelFromSpecular")],ke.prototype,"_useReflectionFresnelFromSpecular",void 0);P([le("_markAllSubMeshesAsFresnelDirty")],ke.prototype,"useReflectionFresnelFromSpecular",void 0);P([w("useGlossinessFromSpecularMapAlpha")],ke.prototype,"_useGlossinessFromSpecularMapAlpha",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],ke.prototype,"useGlossinessFromSpecularMapAlpha",void 0);P([w("maxSimultaneousLights")],ke.prototype,"_maxSimultaneousLights",void 0);P([le("_markAllSubMeshesAsLightsDirty")],ke.prototype,"maxSimultaneousLights",void 0);P([w("invertNormalMapX")],ke.prototype,"_invertNormalMapX",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],ke.prototype,"invertNormalMapX",void 0);P([w("invertNormalMapY")],ke.prototype,"_invertNormalMapY",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],ke.prototype,"invertNormalMapY",void 0);P([w("twoSidedLighting")],ke.prototype,"_twoSidedLighting",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],ke.prototype,"twoSidedLighting",void 0);P([w("applyDecalMapAfterDetailMap")],ke.prototype,"_applyDecalMapAfterDetailMap",void 0);P([le("_markAllSubMeshesAsMiscDirty")],ke.prototype,"applyDecalMapAfterDetailMap",void 0);Ft("BABYLON.StandardMaterial",ke);Jt.DefaultMaterialFactory=n=>new ke("default material",n)});var uz=C(()=>{$a();Zn();vs();bt.prototype.createDynamicTexture=function(n,e,t,i){let r=new Pi(this,4);return r.baseWidth=n,r.baseHeight=e,t&&(n=this.needPOTTextures?gn(n,this._caps.maxTextureSize):n,e=this.needPOTTextures?gn(e,this._caps.maxTextureSize):e),r.width=n,r.height=e,r.isReady=!1,r.generateMipMaps=t,r.samplingMode=i,this.updateTextureSamplingMode(i,r),this._internalTexturesCache.push(r),r};bt.prototype.updateDynamicTexture=function(n,e,t,i=!1,r,s=!1,a=!1){if(!n)return;let o=this._gl,l=o.TEXTURE_2D,c=this._bindTextureDirectly(l,n,!0,s);this._unpackFlipY(t===void 0?n.invertY:t),i&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);let f=this._getWebGLTextureType(n.type),h=this._getInternalFormat(r||n.format),d=this._getRGBABufferInternalSizedFormat(n.type,h);o.texImage2D(l,0,d,h,f,e),n.generateMipMaps&&o.generateMipmap(l),c||this._bindTextureDirectly(l,null),i&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),r&&(n.format=r),n._dynamicTextureSource=e,n._premulAlpha=i,n.invertY=t||!1,n.isReady=!0}});var Zx,mz=C(()=>{Pt();Fr();uz();Zx=class n extends ge{constructor(e,t,i,r=!1,s=3,a=5,o){let l=!i||i._isScene,c=l?i:i==null?void 0:i.scene,f=l?!r:i;super(null,c,f,o,s,void 0,void 0,void 0,void 0,a),this.name=e,this.wrapU=ge.CLAMP_ADDRESSMODE,this.wrapV=ge.CLAMP_ADDRESSMODE,this._generateMipMaps=r;let h=this._getEngine();if(!h)return;if(t.getContext)this._canvas=t,this._ownCanvas=!1,this._texture=h.createDynamicTexture(this._canvas.width,this._canvas.height,r,s);else{this._canvas=h.createCanvas(1,1),this._ownCanvas=!0;let u=t;u.width||u.width===0?this._texture=h.createDynamicTexture(u.width,u.height,r,s):this._texture=h.createDynamicTexture(t,t,r,s)}let d=this.getSize();this._canvas.width!==d.width&&(this._canvas.width=d.width),this._canvas.height!==d.height&&(this._canvas.height=d.height),this._context=this._canvas.getContext("2d")}getClassName(){return"DynamicTexture"}get canRescale(){return!0}_recreate(e){this._canvas.width=e.width,this._canvas.height=e.height,this.releaseInternalTexture(),this._texture=this._getEngine().createDynamicTexture(e.width,e.height,this._generateMipMaps,this.samplingMode)}scale(e){let t=this.getSize();t.width*=e,t.height*=e,this._recreate(t)}scaleTo(e,t){let i=this.getSize();i.width=e,i.height=t,this._recreate(i)}getContext(){return this._context}clear(e){let t=this.getSize();e&&(this._context.fillStyle=e),this._context.clearRect(0,0,t.width,t.height)}update(e,t=!1,i=!1){this._texture&&this._getEngine().updateDynamicTexture(this._texture,this._canvas,e===void 0?!0:e,t,this._format||void 0,void 0,i)}drawText(e,t,i,r,s,a,o,l=!0){let c=this.getSize();if(a&&(this._context.fillStyle=a,this._context.fillRect(0,0,c.width,c.height)),this._context.font=r,t==null){let f=this._context.measureText(e);t=(c.width-f.width)/2}if(i==null){let f=parseInt(r.replace(/\D/g,""));i=c.height/2+f/3.65}this._context.fillStyle=s||"",this._context.fillText(e,t,i),l&&this.update(o)}dispose(){var e,t;super.dispose(),this._ownCanvas&&((t=(e=this._canvas)==null?void 0:e.remove)==null||t.call(e)),this._canvas=null,this._context=null}clone(){let e=this.getScene();if(!e)return this;let t=this.getSize(),i=new n(this.name,t,e,this._generateMipMaps);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.wrapU=this.wrapU,i.wrapV=this.wrapV,i}serialize(){let e=this.getScene();e&&!e.isReady()&&te.Warn("The scene must be ready before serializing the dynamic texture");let t=super.serialize();return n._IsCanvasElement(this._canvas)&&(t.base64String=this._canvas.toDataURL()),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t}static _IsCanvasElement(e){return e.toDataURL!==void 0}_rebuild(){this.update()}}});function $x(n,e,t,i,r,s=!1){let a=Yr.Zero();return Fg(n,e,t,i,a,r,s),a}function Fg(n,e,t,i,r,s,a=!1,o=!1){let l=n.getEngine();if(!s&&!(s=n.activeCamera)&&!(s=n.cameraToUseForPointers))return n;let c=s.viewport,f=l.getRenderHeight(),{x:h,y:d,width:u,height:m}=c.toGlobal(l.getRenderWidth(),f),p=1/l.getHardwareScalingLevel();return e=e*p-h,t=t*p-(f-d-m),r.update(e,t,u,m,i||K.IdentityReadOnly,a?K.IdentityReadOnly:s.getViewMatrix(),s.getProjectionMatrix(),o),n}function gz(n,e,t,i){let r=Yr.Zero();return XP(n,e,t,r,i),r}function XP(n,e,t,i,r){if(!Jn)return n;let s=n.getEngine();if(!r&&!(r=n.activeCamera)&&!(r=n.cameraToUseForPointers))throw new Error("Active camera not set");let a=r.viewport,o=s.getRenderHeight(),{x:l,y:c,width:f,height:h}=a.toGlobal(s.getRenderWidth(),o),d=K.Identity(),u=1/s.getHardwareScalingLevel();return e=e*u-l,t=t*u-(o-c-h),i.update(e,t,f,h,d,d,r.getProjectionMatrix()),n}function Qx(n,e,t,i,r,s,a,o){let l=e(i,t.enableDistantPicking);return YP(n,t,i,l,r,s,a,o)}function YP(n,e,t,i,r,s,a,o){let l=e.intersects(i,r,a,s,t,o);return!l||!l.hit||!r&&n!=null&&l.distance>=n.distance?null:l}function hle(n,e){return n==="InstancedLinesMesh"||n==="LinesMesh"?e.intersectionThreshold:0}function vz(n){let e=n.getClassName();if(e==="GreasedLineMesh")return{rawBoundingInfo:null,intersectionThreshold:0};let t=n.rawBoundingInfo;return{rawBoundingInfo:t,intersectionThreshold:t?hle(e,n):0}}function Ez(n,e,t,i,r){let s=n(t,e.enableDistantPicking);return!s.intersectsSphere(i.boundingSphere,r)||!s.intersectsBox(i.boundingBox,r)?null:s}function KP(n,e,t,i,r,s){let a=null,o=!!(n.activeCameras&&n.activeCameras.length>1&&n.cameraToUseForPointers!==n.activeCamera),l=n.cameraToUseForPointers||n.activeCamera,c=_z.internalPickerForMesh||Qx,f=c===Qx;for(let h=0;h>4);for(let E=0;E1&&n.cameraToUseForPointers!==n.activeCamera),a=n.cameraToUseForPointers||n.activeCamera,o=_z.internalPickerForMesh||Qx,l=o===Qx;for(let c=0;c>4);for(let A=0;A(n._tempPickingRay||(n._tempPickingRay=Yr.Zero()),Fg(n,e,t,o,n._tempPickingRay,s||null),n._tempPickingRay),i,r,!0);return a&&(a.ray=$x(n,e,t,K.Identity(),s||null)),a}function Az(n,e,t,i,r,s,a,o=!1){let l=KP(n,(c,f)=>(n._tempPickingRay||(n._tempPickingRay=Yr.Zero()),Fg(n,e,t,c,n._tempPickingRay,s||null,!1,f),n._tempPickingRay),i,r,!1,a);return l&&(l.ray=$x(n,e,t,K.Identity(),s||null)),l}function xz(n,e,t,i,r){let s=KP(n,a=>(n._pickWithRayInverseMatrix||(n._pickWithRayInverseMatrix=K.Identity()),a.invertToRef(n._pickWithRayInverseMatrix),n._cachedRayForTransform||(n._cachedRayForTransform=Yr.Zero()),Yr.TransformToRef(e,n._pickWithRayInverseMatrix,n._cachedRayForTransform),n._cachedRayForTransform),t,i,!1,r);return s&&(s.ray=e),s}function Rz(n,e,t,i,r,s){return Sz(n,a=>$x(n,e,t,a,r||null),i,s)}function bz(n,e,t,i){return Sz(n,r=>(n._pickWithRayInverseMatrix||(n._pickWithRayInverseMatrix=K.Identity()),r.invertToRef(n._pickWithRayInverseMatrix),n._cachedRayForTransform||(n._cachedRayForTransform=Yr.Zero()),Yr.TransformToRef(e,n._pickWithRayInverseMatrix,n._cachedRayForTransform),n._cachedRayForTransform),t,i)}function pz(n,e,t=100,i,r){i||(i=n.getWorldMatrix()),e.length=t,r?e.origin.copyFrom(r):e.origin.copyFrom(n.position);let s=$.Vector3[2];s.set(0,0,n._scene.useRightHandedSystem?-1:1);let a=$.Vector3[3];return b.TransformNormalToRef(s,i,a),b.NormalizeToRef(a,e.direction),e}function Iz(n,e){e&&(e.prototype.getForwardRay=function(t=100,i,r){return pz(this,new Yr(b.Zero(),b.Zero(),t),t,i,r)},e.prototype.getForwardRayToRef=function(t,i=100,r,s){return pz(this,t,i,r,s)}),n&&(Yh._IsPickingAvailable=!0,n.prototype.createPickingRay=function(t,i,r,s,a=!1){return $x(this,t,i,r,s,a)})}var _z,Yr,jP=C(()=>{Dn();Ge();Zo();_y();Z_();Di();xC();_z={internalPickerForMesh:void 0},Yr=class n{constructor(e,t,i=Number.MAX_VALUE,r=Nt){this.origin=e,this.direction=t,this.length=i,this.epsilon=r}clone(){return new n(this.origin.clone(),this.direction.clone(),this.length)}intersectsBoxMinMax(e,t,i=0){let r=n._TmpVector3[0].copyFromFloats(e.x-i,e.y-i,e.z-i),s=n._TmpVector3[1].copyFromFloats(t.x+i,t.y+i,t.z+i),a=0,o=Number.MAX_VALUE,l,c,f,h;if(Math.abs(this.direction.x)<1e-7){if(this.origin.xs.x)return!1}else if(l=1/this.direction.x,c=(r.x-this.origin.x)*l,f=(s.x-this.origin.x)*l,f===-1/0&&(f=1/0),c>f&&(h=c,c=f,f=h),a=Math.max(c,a),o=Math.min(f,o),a>o)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.ys.y)return!1}else if(l=1/this.direction.y,c=(r.y-this.origin.y)*l,f=(s.y-this.origin.y)*l,f===-1/0&&(f=1/0),c>f&&(h=c,c=f,f=h),a=Math.max(c,a),o=Math.min(f,o),a>o)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.zs.z)return!1}else if(l=1/this.direction.z,c=(r.z-this.origin.z)*l,f=(s.z-this.origin.z)*l,f===-1/0&&(f=1/0),c>f&&(h=c,c=f,f=h),a=Math.max(c,a),o=Math.min(f,o),a>o)return!1;return!0}intersectsBox(e,t=0){return this.intersectsBoxMinMax(e.minimum,e.maximum,t)}intersectsSphere(e,t=0){let i=e.center.x-this.origin.x,r=e.center.y-this.origin.y,s=e.center.z-this.origin.z,a=i*i+r*r+s*s,o=e.radius+t,l=o*o;if(a<=l)return!0;let c=i*this.direction.x+r*this.direction.y+s*this.direction.z;return c<0?!1:a-c*c<=l}intersectsTriangle(e,t,i){let r=n._TmpVector3[0],s=n._TmpVector3[1],a=n._TmpVector3[2],o=n._TmpVector3[3],l=n._TmpVector3[4];t.subtractToRef(e,r),i.subtractToRef(e,s),b.CrossToRef(this.direction,s,a);let c=b.Dot(r,a);if(c===0)return null;let f=1/c;this.origin.subtractToRef(e,o);let h=b.Dot(o,a)*f;if(h<-this.epsilon||h>1+this.epsilon)return null;b.CrossToRef(o,r,l);let d=b.Dot(this.direction,l)*f;if(d<-this.epsilon||h+d>1+this.epsilon)return null;let u=b.Dot(s,l)*f;return u>this.length||u<0?null:new jh(1-h-d,h,u)}intersectsPlane(e){let t,i=b.Dot(e.normal,this.direction);if(Math.abs(i)<999999997475243e-21)return null;{let r=b.Dot(e.normal,this.origin);return t=(-e.d-r)/i,t<0?t<-999999997475243e-21?null:0:t}}intersectsAxis(e,t=0){switch(e){case"y":{let i=(this.origin.y-t)/this.direction.y;return i>0?null:new b(this.origin.x+this.direction.x*-i,t,this.origin.z+this.direction.z*-i)}case"x":{let i=(this.origin.x-t)/this.direction.x;return i>0?null:new b(t,this.origin.y+this.direction.y*-i,this.origin.z+this.direction.z*-i)}case"z":{let i=(this.origin.z-t)/this.direction.z;return i>0?null:new b(this.origin.x+this.direction.x*-i,this.origin.y+this.direction.y*-i,t)}default:return null}}intersectsMesh(e,t,i,r=!1,s,a=!1){let o=$.Matrix[0];return e.getWorldMatrix().invertToRef(o),this._tmpRay?n.TransformToRef(this,o,this._tmpRay):this._tmpRay=n.Transform(this,o),e.intersects(this._tmpRay,t,i,r,s,a)}intersectsMeshes(e,t,i){i?i.length=0:i=[];for(let r=0;rt.distance?1:0}intersectionSegment(e,t,i){let r=this.origin,s=$.Vector3[0],a=$.Vector3[1],o=$.Vector3[2],l=$.Vector3[3];t.subtractToRef(e,s),this.direction.scaleToRef(n._Rayl,o),r.addToRef(o,a),e.subtractToRef(r,l);let c=b.Dot(s,s),f=b.Dot(s,o),h=b.Dot(o,o),d=b.Dot(s,l),u=b.Dot(o,l),m=c*h-f*f,p,_=m,g,v=m;m_&&(p=_,g=u+f,v=h)),g<0?(g=0,-d<0?p=0:-d>c?p=_:(p=-d,_=c)):g>v&&(g=v,-d+f<0?p=0:-d+f>c?p=_:(p=-d+f,_=c));let x=Math.abs(p)0&&A<=this.length&&R.lengthSquared(){As();sl();jP();jP();Iz(Jt,mt);Jt.prototype.createPickingRayToRef=function(n,e,t,i,r,s=!1,a=!1){return Fg(this,n,e,t,i,r,s,a)};Jt.prototype.createPickingRayInCameraSpace=function(n,e,t){return gz(this,n,e,t)};Jt.prototype.createPickingRayInCameraSpaceToRef=function(n,e,t,i){return XP(this,n,e,t,i)};Jt.prototype.pickWithBoundingInfo=function(n,e,t,i,r){return Tz(this,n,e,t,i,r)};Jt.prototype.pick=function(n,e,t,i,r,s,a=!1){return Az(this,n,e,t,i,r,s,a)};Jt.prototype.pickWithRay=function(n,e,t,i){return xz(this,n,e,t,i)};Jt.prototype.multiPick=function(n,e,t,i,r){return Rz(this,n,e,t,i,r)};Jt.prototype.multiPickWithRay=function(n,e,t){return bz(this,n,e,t)}});var Mz,dle,ZP=C(()=>{k();Mz="kernelBlurVaryingDeclaration",dle="varying sampleCoord{X}: vec2f;";T.IncludesShadersStoreWGSL[Mz]||(T.IncludesShadersStoreWGSL[Mz]=dle)});var Cz,ule,Jx=C(()=>{k();Cz="packingFunctions",ule=`fn pack(depth: f32)->vec4f {const bit_shift: vec4f= vec4f(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const bit_mask: vec4f= vec4f(0.0,1.0/255.0,1.0/255.0,1.0/255.0);var res: vec4f=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;} fn unpack(color: vec4f)->f32 -{const bit_shift: vec4f= vec4f(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}`;T.IncludesShadersStoreWGSL[Cz]||(T.IncludesShadersStoreWGSL[Cz]=ule)});var yz,mle,Pz=C(()=>{W();yz="kernelBlurFragment",mle=`#ifdef DOF +{const bit_shift: vec4f= vec4f(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}`;T.IncludesShadersStoreWGSL[Cz]||(T.IncludesShadersStoreWGSL[Cz]=ule)});var yz,mle,Pz=C(()=>{k();yz="kernelBlurFragment",mle=`#ifdef DOF factor=sampleCoC(fragmentInputs.sampleCoord{X}); computedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight; #else @@ -9934,7 +9934,7 @@ blend+=unpack(textureSample(textureSampler,textureSamplerSampler,fragmentInputs. #else blend+=textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCoord{X})*computedWeight; #endif -`;T.IncludesShadersStoreWGSL[yz]||(T.IncludesShadersStoreWGSL[yz]=mle)});var Dz,ple,Lz=C(()=>{W();Dz="kernelBlurFragment2",ple=`#ifdef DOF +`;T.IncludesShadersStoreWGSL[yz]||(T.IncludesShadersStoreWGSL[yz]=mle)});var Dz,ple,Lz=C(()=>{k();Dz="kernelBlurFragment2",ple=`#ifdef DOF factor=sampleCoC(fragmentInputs.sampleCenter+uniforms.delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight; #else computedWeight=KERNEL_DEP_WEIGHT{X}; @@ -9944,7 +9944,7 @@ blend+=unpack(textureSample(textureSampler,textureSamplerSampler,fragmentInputs. #else blend+=textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCenter+uniforms.delta*KERNEL_DEP_OFFSET{X})*computedWeight; #endif -`;T.IncludesShadersStoreWGSL[Dz]||(T.IncludesShadersStoreWGSL[Dz]=ple)});var Nz={};tt(Nz,{kernelBlurPixelShaderWGSL:()=>_le});var QP,Oz,_le,wz=C(()=>{W();ZP();$x();Pz();Lz();QP="kernelBlurPixelShader",Oz=`var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform delta: vec2f;varying sampleCenter: vec2f; +`;T.IncludesShadersStoreWGSL[Dz]||(T.IncludesShadersStoreWGSL[Dz]=ple)});var Nz={};tt(Nz,{kernelBlurPixelShaderWGSL:()=>_le});var QP,Oz,_le,wz=C(()=>{k();ZP();Jx();Pz();Lz();QP="kernelBlurPixelShader",Oz=`var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform delta: vec2f;varying sampleCenter: vec2f; #ifdef DOF var circleOfConfusionSamplerSampler: sampler;var circleOfConfusionSampler: texture_2d;fn sampleCoC(offset: vec2f)->f32 {var coc: f32=textureSample(circleOfConfusionSampler,circleOfConfusionSamplerSampler,offset).r;return coc; } #endif @@ -9979,7 +9979,7 @@ fragmentOutputs.color=blend; #ifdef DOF fragmentOutputs.color/=sumOfWeights; #endif -}`;T.ShadersStoreWGSL[QP]||(T.ShadersStoreWGSL[QP]=Oz);_le={name:QP,shader:Oz}});var Fz,gle,Bz=C(()=>{W();Fz="kernelBlurVertex",gle="vertexOutputs.sampleCoord{X}=vertexOutputs.sampleCenter+uniforms.delta*KERNEL_OFFSET{X};";T.IncludesShadersStoreWGSL[Fz]||(T.IncludesShadersStoreWGSL[Fz]=gle)});var Vz={};tt(Vz,{kernelBlurVertexShaderWGSL:()=>vle});var $P,Uz,vle,Gz=C(()=>{W();ZP();Bz();$P="kernelBlurVertexShader",Uz=`attribute position: vec2f;uniform delta: vec2f;varying sampleCenter: vec2f; +}`;T.ShadersStoreWGSL[QP]||(T.ShadersStoreWGSL[QP]=Oz);_le={name:QP,shader:Oz}});var Fz,gle,Bz=C(()=>{k();Fz="kernelBlurVertex",gle="vertexOutputs.sampleCoord{X}=vertexOutputs.sampleCenter+uniforms.delta*KERNEL_OFFSET{X};";T.IncludesShadersStoreWGSL[Fz]||(T.IncludesShadersStoreWGSL[Fz]=gle)});var Vz={};tt(Vz,{kernelBlurVertexShaderWGSL:()=>vle});var $P,Uz,vle,Gz=C(()=>{k();ZP();Bz();$P="kernelBlurVertexShader",Uz=`attribute position: vec2f;uniform delta: vec2f;varying sampleCenter: vec2f; #include[0..varyingCount] #define CUSTOM_VERTEX_DEFINITIONS @vertex @@ -9989,10 +9989,10 @@ vertexOutputs.sampleCenter=(vertexInputs.position*madd+madd); #include[0..varyingCount] vertexOutputs.position= vec4f(vertexInputs.position,0.0,1.0); #define CUSTOM_VERTEX_MAIN_END -}`;T.ShadersStoreWGSL[$P]||(T.ShadersStoreWGSL[$P]=Uz);vle={name:$P,shader:Uz}});var kz,Ele,JP=C(()=>{W();kz="kernelBlurVaryingDeclaration",Ele="varying vec2 sampleCoord{X};";T.IncludesShadersStore[kz]||(T.IncludesShadersStore[kz]=Ele)});var Wz,Sle,Jx=C(()=>{W();Wz="packingFunctions",Sle=`vec4 pack(float depth) +}`;T.ShadersStoreWGSL[$P]||(T.ShadersStoreWGSL[$P]=Uz);vle={name:$P,shader:Uz}});var kz,Ele,JP=C(()=>{k();kz="kernelBlurVaryingDeclaration",Ele="varying vec2 sampleCoord{X};";T.IncludesShadersStore[kz]||(T.IncludesShadersStore[kz]=Ele)});var Wz,Sle,eR=C(()=>{k();Wz="packingFunctions",Sle=`vec4 pack(float depth) {const vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);vec4 res=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;} float unpack(vec4 color) -{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}`;T.IncludesShadersStore[Wz]||(T.IncludesShadersStore[Wz]=Sle)});var Hz,Tle,zz=C(()=>{W();Hz="kernelBlurFragment",Tle=`#ifdef DOF +{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}`;T.IncludesShadersStore[Wz]||(T.IncludesShadersStore[Wz]=Sle)});var Hz,Tle,zz=C(()=>{k();Hz="kernelBlurFragment",Tle=`#ifdef DOF factor=sampleCoC(sampleCoord{X}); computedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight; #else @@ -10003,7 +10003,7 @@ blend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight; #else blend+=texture2D(textureSampler,sampleCoord{X})*computedWeight; #endif -`;T.IncludesShadersStore[Hz]||(T.IncludesShadersStore[Hz]=Tle)});var Xz,Ale,Yz=C(()=>{W();Xz="kernelBlurFragment2",Ale=`#ifdef DOF +`;T.IncludesShadersStore[Hz]||(T.IncludesShadersStore[Hz]=Tle)});var Xz,Ale,Yz=C(()=>{k();Xz="kernelBlurFragment2",Ale=`#ifdef DOF factor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight; #else computedWeight=KERNEL_DEP_WEIGHT{X}; @@ -10013,7 +10013,7 @@ blend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})) #else blend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight; #endif -`;T.IncludesShadersStore[Xz]||(T.IncludesShadersStore[Xz]=Ale)});var jz={};tt(jz,{kernelBlurPixelShader:()=>xle});var eD,Kz,xle,qz=C(()=>{W();JP();Jx();zz();Yz();eD="kernelBlurPixelShader",Kz=`uniform sampler2D textureSampler;uniform vec2 delta;varying vec2 sampleCenter; +`;T.IncludesShadersStore[Xz]||(T.IncludesShadersStore[Xz]=Ale)});var jz={};tt(jz,{kernelBlurPixelShader:()=>xle});var eD,Kz,xle,qz=C(()=>{k();JP();eR();zz();Yz();eD="kernelBlurPixelShader",Kz=`uniform sampler2D textureSampler;uniform vec2 delta;varying vec2 sampleCenter; #ifdef DOF uniform sampler2D circleOfConfusionSampler;float sampleCoC(in vec2 offset) {float coc=texture2D(circleOfConfusionSampler,offset).r;return coc; } #endif @@ -10048,7 +10048,7 @@ gl_FragColor=blend; #ifdef DOF gl_FragColor/=sumOfWeights; #endif -}`;T.ShadersStore[eD]||(T.ShadersStore[eD]=Kz);xle={name:eD,shader:Kz}});var Zz,Rle,Qz=C(()=>{W();Zz="kernelBlurVertex",Rle="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";T.IncludesShadersStore[Zz]||(T.IncludesShadersStore[Zz]=Rle)});var Jz={};tt(Jz,{kernelBlurVertexShader:()=>ble});var tD,$z,ble,e4=C(()=>{W();JP();Qz();tD="kernelBlurVertexShader",$z=`attribute vec2 position;uniform vec2 delta;varying vec2 sampleCenter; +}`;T.ShadersStore[eD]||(T.ShadersStore[eD]=Kz);xle={name:eD,shader:Kz}});var Zz,Rle,Qz=C(()=>{k();Zz="kernelBlurVertex",Rle="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";T.IncludesShadersStore[Zz]||(T.IncludesShadersStore[Zz]=Rle)});var Jz={};tt(Jz,{kernelBlurVertexShader:()=>ble});var tD,$z,ble,e4=C(()=>{k();JP();Qz();tD="kernelBlurVertexShader",$z=`attribute vec2 position;uniform vec2 delta;varying vec2 sampleCenter; #include[0..varyingCount] const vec2 madd=vec2(0.5,0.5); #define CUSTOM_VERTEX_DEFINITIONS @@ -10058,13 +10058,13 @@ sampleCenter=(position*madd+madd); #include[0..varyingCount] gl_Position=vec4(position,0.0,1.0); #define CUSTOM_VERTEX_MAIN_END -}`;T.ShadersStore[tD]||(T.ShadersStore[tD]=$z);ble={name:tD,shader:$z}});var rs,iD=C(()=>{kh();Pi();rs=class n extends zr{_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Promise.resolve().then(()=>(wz(),Nz)),Promise.resolve().then(()=>(Gz(),Vz))]))):t.push(Promise.all([Promise.resolve().then(()=>(qz(),jz)),Promise.resolve().then(()=>(e4(),Jz))]))}constructor(e,t=null,i,r,s){let a=!!(s!=null&&s.blockCompilation);super({...s,name:e,engine:t||Le.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:n.FragmentUrl,uniforms:n.Uniforms,samplers:n.Samplers,vertexUrl:n.VertexUrl,blockCompilation:!0}),this._packedFloat=!1,this._staticDefines="",this.textureWidth=0,this.textureHeight=0,this._staticDefines=s?Array.isArray(s.defines)?s.defines.join(` +}`;T.ShadersStore[tD]||(T.ShadersStore[tD]=$z);ble={name:tD,shader:$z}});var is,iD=C(()=>{kh();Di();is=class n extends zr{_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([Promise.resolve().then(()=>(wz(),Nz)),Promise.resolve().then(()=>(Gz(),Vz))]))):t.push(Promise.all([Promise.resolve().then(()=>(qz(),jz)),Promise.resolve().then(()=>(e4(),Jz))]))}constructor(e,t=null,i,r,s){let a=!!(s!=null&&s.blockCompilation);super({...s,name:e,engine:t||Oe.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:n.FragmentUrl,uniforms:n.Uniforms,samplers:n.Samplers,vertexUrl:n.VertexUrl,blockCompilation:!0}),this._packedFloat=!1,this._staticDefines="",this.textureWidth=0,this.textureHeight=0,this._staticDefines=s?Array.isArray(s.defines)?s.defines.join(` `):s.defines||"":"",this.options.blockCompilation=a,i!==void 0&&(this.direction=i),r!==void 0&&(this.kernel=r)}set kernel(e){this._idealKernel!==e&&(e=Math.max(e,1),this._idealKernel=e,this._kernel=this._nearestBestKernel(e),this.options.blockCompilation||this._updateParameters())}get kernel(){return this._idealKernel}set packedFloat(e){this._packedFloat!==e&&(this._packedFloat=e,this.options.blockCompilation||this._updateParameters())}get packedFloat(){return this._packedFloat}bind(e=!1){super.bind(e),this._drawWrapper.effect.setFloat2("delta",1/this.textureWidth*this.direction.x,1/this.textureHeight*this.direction.y)}_updateParameters(e,t){let i=this._kernel,r=(i-1)/2,s=[],a=[],o=0;for(let _=0;_0)return Math.max(i,3);return Math.max(t,3)}_gaussianWeight(e){let t=.3333333333333333,i=Math.sqrt(2*Math.PI)*t,r=-(e*e/(2*t*t));return 1/i*Math.exp(r)}_glslFloat(e,t=8){return e.toFixed(t).replace(/0+$/,"")}};rs.VertexUrl="kernelBlur";rs.FragmentUrl="kernelBlur";rs.Uniforms=["delta","direction"];rs.Samplers=["circleOfConfusionSampler"]});var wa,rD=C(()=>{Gt();Kl();Fr();Hi();Ut();Tr();iD();wa=class n extends xi{get direction(){return this._effectWrapper.direction}set direction(e){this._effectWrapper.direction=e}set kernel(e){this._effectWrapper.kernel=e}get kernel(){return this._effectWrapper.kernel}set packedFloat(e){this._effectWrapper.packedFloat=e}get packedFloat(){return this._effectWrapper.packedFloat}getClassName(){return"BlurPostProcess"}constructor(e,t,i,r,s=null,a=_e.BILINEAR_SAMPLINGMODE,o,l,c=0,f="",h=!1,d=5){let u=typeof r=="number"?h:!!r.blockCompilation,m={uniforms:rs.Uniforms,samplers:rs.Samplers,size:typeof r=="number"?r:void 0,camera:s,samplingMode:a,engine:o,reusable:l,textureType:c,vertexUrl:rs.VertexUrl,indexParameters:{varyingCount:0,depCount:0},textureFormat:d,defines:f,...r,blockCompilation:!0};super(e,rs.FragmentUrl,{effectWrapper:typeof r=="number"||!r.effectWrapper?new rs(e,o,void 0,void 0,m):void 0,...m}),this._effectWrapper.options.blockCompilation=u,this.direction=t,this.onApplyObservable.add(()=>{this._effectWrapper.textureWidth=this._outputTexture?this._outputTexture.width:this.width,this._effectWrapper.textureHeight=this._outputTexture?this._outputTexture.height:this.height}),this.kernel=i}updateEffect(e=null,t=null,i=null,r,s,a){this._effectWrapper._updateParameters(s,a)}static _Parse(e,t,i,r){return it.Parse(()=>new n(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1),e,i,r)}};P([tm()],wa.prototype,"direction",null);P([w()],wa.prototype,"kernel",null);P([w()],wa.prototype,"packedFloat",null);wt("BABYLON.BlurPostProcess",wa)});var t4,Ile,i4=C(()=>{W();t4="bayerDitherFunctions",Ile=`fn bayerDither2(_P: vec2f)->f32 {return ((2.0*_P.y+_P.x+1.0)%(4.0));} +`,p++;this.packedFloat&&(m+="#define PACKEDFLOAT 1"),this.options.blockCompilation=!1,this.updateEffect(m,null,null,{varyingCount:u,depCount:p},e,t)}_nearestBestKernel(e){let t=Math.round(e);for(let i of[t,t-1,t+1,t-2,t+2])if(i%2!==0&&Math.floor(i/2)%2===0&&i>0)return Math.max(i,3);return Math.max(t,3)}_gaussianWeight(e){let t=.3333333333333333,i=Math.sqrt(2*Math.PI)*t,r=-(e*e/(2*t*t));return 1/i*Math.exp(r)}_glslFloat(e,t=8){return e.toFixed(t).replace(/0+$/,"")}};is.VertexUrl="kernelBlur";is.FragmentUrl="kernelBlur";is.Uniforms=["delta","direction"];is.Samplers=["circleOfConfusionSampler"]});var Na,rD=C(()=>{Gt();Yl();Fr();Hi();Vt();Tr();iD();Na=class n extends Ri{get direction(){return this._effectWrapper.direction}set direction(e){this._effectWrapper.direction=e}set kernel(e){this._effectWrapper.kernel=e}get kernel(){return this._effectWrapper.kernel}set packedFloat(e){this._effectWrapper.packedFloat=e}get packedFloat(){return this._effectWrapper.packedFloat}getClassName(){return"BlurPostProcess"}constructor(e,t,i,r,s=null,a=ge.BILINEAR_SAMPLINGMODE,o,l,c=0,f="",h=!1,d=5){let u=typeof r=="number"?h:!!r.blockCompilation,m={uniforms:is.Uniforms,samplers:is.Samplers,size:typeof r=="number"?r:void 0,camera:s,samplingMode:a,engine:o,reusable:l,textureType:c,vertexUrl:is.VertexUrl,indexParameters:{varyingCount:0,depCount:0},textureFormat:d,defines:f,...r,blockCompilation:!0};super(e,is.FragmentUrl,{effectWrapper:typeof r=="number"||!r.effectWrapper?new is(e,o,void 0,void 0,m):void 0,...m}),this._effectWrapper.options.blockCompilation=u,this.direction=t,this.onApplyObservable.add(()=>{this._effectWrapper.textureWidth=this._outputTexture?this._outputTexture.width:this.width,this._effectWrapper.textureHeight=this._outputTexture?this._outputTexture.height:this.height}),this.kernel=i}updateEffect(e=null,t=null,i=null,r,s,a){this._effectWrapper._updateParameters(s,a)}static _Parse(e,t,i,r){return it.Parse(()=>new n(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1),e,i,r)}};P([em()],Na.prototype,"direction",null);P([w()],Na.prototype,"kernel",null);P([w()],Na.prototype,"packedFloat",null);Ft("BABYLON.BlurPostProcess",Na)});var t4,Ile,i4=C(()=>{k();t4="bayerDitherFunctions",Ile=`fn bayerDither2(_P: vec2f)->f32 {return ((2.0*_P.y+_P.x+1.0)%(4.0));} fn bayerDither4(_P: vec2f)->f32 {var P1: vec2f=((_P)%(2.0)); var P2: vec2f=floor(0.5*((_P)%(4.0))); return 4.0*bayerDither2(P1)+bayerDither2(P2);} @@ -10072,7 +10072,7 @@ fn bayerDither8(_P: vec2f)->f32 {var P1: vec2f=((_P)%(2.0)); var P2: vec2f=floor(0.5 *((_P)%(4.0))); var P4: vec2f=floor(0.25*((_P)%(8.0))); return 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);} -`;T.IncludesShadersStoreWGSL[t4]||(T.IncludesShadersStoreWGSL[t4]=Ile)});var r4,Mle,n4=C(()=>{W();$x();i4();r4="shadowMapFragmentExtraDeclaration",Mle=`#if SM_FLOAT==0 +`;T.IncludesShadersStoreWGSL[t4]||(T.IncludesShadersStoreWGSL[t4]=Ile)});var r4,Mle,n4=C(()=>{k();Jx();i4();r4="shadowMapFragmentExtraDeclaration",Mle=`#if SM_FLOAT==0 #include #endif #if SM_SOFTTRANSPARENTSHADOW==1 @@ -10087,7 +10087,7 @@ uniform biasAndScaleSM: vec3f;uniform depthValuesSM: vec2f; #if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 varying zSM: f32; #endif -`;T.IncludesShadersStoreWGSL[r4]||(T.IncludesShadersStoreWGSL[r4]=Mle)});var s4,Cle,a4=C(()=>{W();s4="shadowMapFragment",Cle=`var depthSM: f32=fragmentInputs.vDepthMetricSM; +`;T.IncludesShadersStoreWGSL[r4]||(T.IncludesShadersStoreWGSL[r4]=Mle)});var s4,Cle,a4=C(()=>{k();s4="shadowMapFragment",Cle=`var depthSM: f32=fragmentInputs.vDepthMetricSM; #if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 #if SM_USEDISTANCE==1 depthSM=(length(fragmentInputs.vPositionWSM-uniforms.lightDataSM)+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x; @@ -10115,7 +10115,7 @@ fragmentOutputs.color= vec4f(depthSM,1.0,1.0,1.0); #else fragmentOutputs.color=pack(depthSM); #endif -`;T.IncludesShadersStoreWGSL[s4]||(T.IncludesShadersStoreWGSL[s4]=Cle)});var l4={};tt(l4,{shadowMapPixelShaderWGSL:()=>yle});var nD,o4,yle,c4=C(()=>{W();n4();fc();hc();a4();nD="shadowMapPixelShader",o4=`#include +`;T.IncludesShadersStoreWGSL[s4]||(T.IncludesShadersStoreWGSL[s4]=Cle)});var l4={};tt(l4,{shadowMapPixelShaderWGSL:()=>yle});var nD,o4,yle,c4=C(()=>{k();n4();cc();fc();a4();nD="shadowMapPixelShader",o4=`#include #ifdef ALPHATEXTURE varying vUV: vec2f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d; #endif @@ -10141,7 +10141,7 @@ if ((bayerDither8(floor(((fragmentInputs.position.xy)%(8.0)))))/64.0>=uniforms.s #endif #endif #include -}`;T.ShadersStoreWGSL[nD]||(T.ShadersStoreWGSL[nD]=o4);yle={name:nD,shader:o4}});var f4,Ple,h4=C(()=>{W();f4="shadowMapVertexExtraDeclaration",Ple=`#if SM_NORMALBIAS==1 +}`;T.ShadersStoreWGSL[nD]||(T.ShadersStoreWGSL[nD]=o4);yle={name:nD,shader:o4}});var f4,Ple,h4=C(()=>{k();f4="shadowMapVertexExtraDeclaration",Ple=`#if SM_NORMALBIAS==1 uniform lightDataSM: vec3f; #endif uniform biasAndScaleSM: vec3f;uniform depthValuesSM: vec2f;varying vDepthMetricSM: f32; @@ -10151,7 +10151,7 @@ varying vPositionWSM: vec3f; #if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 varying zSM: f32; #endif -`;T.IncludesShadersStoreWGSL[f4]||(T.IncludesShadersStoreWGSL[f4]=Ple)});var d4,Dle,u4=C(()=>{W();d4="shadowMapVertexNormalBias",Dle=`#if SM_NORMALBIAS==1 +`;T.IncludesShadersStoreWGSL[f4]||(T.IncludesShadersStoreWGSL[f4]=Ple)});var d4,Dle,u4=C(()=>{k();d4="shadowMapVertexNormalBias",Dle=`#if SM_NORMALBIAS==1 #if SM_DIRECTIONINLIGHTDATA==1 var worldLightDirSM: vec3f=normalize(-uniforms.lightDataSM.xyz); #else @@ -10159,7 +10159,7 @@ var directionToLightSM: vec3f=uniforms.lightDataSM.xyz-worldPos.xyz;var worldLig #endif var ndlSM: f32=dot(vNormalW,worldLightDirSM);var sinNLSM: f32=sqrt(1.0-ndlSM*ndlSM);var normalBiasSM: f32=uniforms.biasAndScaleSM.y*sinNLSM;worldPos=vec4f(worldPos.xyz-vNormalW*normalBiasSM,worldPos.w); #endif -`;T.IncludesShadersStoreWGSL[d4]||(T.IncludesShadersStoreWGSL[d4]=Dle)});var m4,Lle,p4=C(()=>{W();m4="shadowMapVertexMetric",Lle=`#if SM_USEDISTANCE==1 +`;T.IncludesShadersStoreWGSL[d4]||(T.IncludesShadersStoreWGSL[d4]=Dle)});var m4,Lle,p4=C(()=>{k();m4="shadowMapVertexMetric",Lle=`#if SM_USEDISTANCE==1 vertexOutputs.vPositionWSM=worldPos.xyz; #endif #if SM_DEPTHTEXTURE==1 @@ -10183,7 +10183,7 @@ vertexOutputs.vDepthMetricSM=(-vertexOutputs.position.z+uniforms.depthValuesSM.x vertexOutputs.vDepthMetricSM=(vertexOutputs.position.z+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x; #endif #endif -`;T.IncludesShadersStoreWGSL[m4]||(T.IncludesShadersStoreWGSL[m4]=Lle)});var g4={};tt(g4,{shadowMapVertexShaderWGSL:()=>Ole});var sD,_4,Ole,v4=C(()=>{W();rc();nc();Uf();Vf();Ca();ed();Lg();h4();sc();Gf();kf();ac();oc();lc();u4();p4();cc();sD="shadowMapVertexShader",_4=`attribute position: vec3f; +`;T.IncludesShadersStoreWGSL[m4]||(T.IncludesShadersStoreWGSL[m4]=Lle)});var g4={};tt(g4,{shadowMapVertexShaderWGSL:()=>Ole});var sD,_4,Ole,v4=C(()=>{k();ic();rc();Bf();Uf();Ma();ed();Lg();h4();nc();Vf();Gf();sc();ac();oc();u4();p4();lc();sD="shadowMapVertexShader",_4=`attribute position: vec3f; #ifdef NORMAL attribute normal: vec3f; #endif @@ -10249,14 +10249,14 @@ vertexOutputs.vUV= (uniforms.diffuseMatrix* vec4f(uv2Updated,1.0,0.0)).xy; #endif #endif #include -}`;T.ShadersStoreWGSL[sD]||(T.ShadersStoreWGSL[sD]=_4);Ole={name:sD,shader:_4}});var S4={};tt(S4,{depthBoxBlurPixelShaderWGSL:()=>Nle});var aD,E4,Nle,T4=C(()=>{W();aD="depthBoxBlurPixelShader",E4=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform screenSize: vec2f; +}`;T.ShadersStoreWGSL[sD]||(T.ShadersStoreWGSL[sD]=_4);Ole={name:sD,shader:_4}});var S4={};tt(S4,{depthBoxBlurPixelShaderWGSL:()=>Nle});var aD,E4,Nle,T4=C(()=>{k();aD="depthBoxBlurPixelShader",E4=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform screenSize: vec2f; #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {var colorDepth: vec4f=vec4f(0.0);for (var x: i32=-OFFSET; x<=OFFSET; x++) {for (var y: i32=-OFFSET; y<=OFFSET; y++) {colorDepth+=textureSample(textureSampler,textureSamplerSampler,input.vUV+ vec2f(f32(x),f32(y))/uniforms.screenSize);}} -fragmentOutputs.color=(colorDepth/ f32((OFFSET*2+1)*(OFFSET*2+1)));}`;T.ShadersStoreWGSL[aD]||(T.ShadersStoreWGSL[aD]=E4);Nle={name:aD,shader:E4}});var x4={};tt(x4,{shadowMapFragmentSoftTransparentShadowWGSL:()=>wle});var oD,A4,wle,R4=C(()=>{W();oD="shadowMapFragmentSoftTransparentShadow",A4=`#if SM_SOFTTRANSPARENTSHADOW==1 +fragmentOutputs.color=(colorDepth/ f32((OFFSET*2+1)*(OFFSET*2+1)));}`;T.ShadersStoreWGSL[aD]||(T.ShadersStoreWGSL[aD]=E4);Nle={name:aD,shader:E4}});var x4={};tt(x4,{shadowMapFragmentSoftTransparentShadowWGSL:()=>wle});var oD,A4,wle,R4=C(()=>{k();oD="shadowMapFragmentSoftTransparentShadow",A4=`#if SM_SOFTTRANSPARENTSHADOW==1 if ((bayerDither8(floor(((fragmentInputs.position.xy)%(8.0)))))/64.0>=uniforms.softTransparentShadowSM.x*alpha) {discard;} #endif -`;T.IncludesShadersStoreWGSL[oD]||(T.IncludesShadersStoreWGSL[oD]=A4);wle={name:oD,shader:A4}});var b4,Fle,I4=C(()=>{W();b4="bayerDitherFunctions",Fle=`float bayerDither2(vec2 _P) {return mod(2.0*_P.y+_P.x+1.0,4.0);} +`;T.IncludesShadersStoreWGSL[oD]||(T.IncludesShadersStoreWGSL[oD]=A4);wle={name:oD,shader:A4}});var b4,Fle,I4=C(()=>{k();b4="bayerDitherFunctions",Fle=`float bayerDither2(vec2 _P) {return mod(2.0*_P.y+_P.x+1.0,4.0);} float bayerDither4(vec2 _P) {vec2 P1=mod(_P,2.0); vec2 P2=floor(0.5*mod(_P,4.0)); return 4.0*bayerDither2(P1)+bayerDither2(P2);} @@ -10264,7 +10264,7 @@ float bayerDither8(vec2 _P) {vec2 P1=mod(_P,2.0); vec2 P2=floor(0.5 *mod(_P,4.0)); vec2 P4=floor(0.25*mod(_P,8.0)); return 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);} -`;T.IncludesShadersStore[b4]||(T.IncludesShadersStore[b4]=Fle)});var M4,Ble,C4=C(()=>{W();Jx();I4();M4="shadowMapFragmentExtraDeclaration",Ble=`#if SM_FLOAT==0 +`;T.IncludesShadersStore[b4]||(T.IncludesShadersStore[b4]=Fle)});var M4,Ble,C4=C(()=>{k();eR();I4();M4="shadowMapFragmentExtraDeclaration",Ble=`#if SM_FLOAT==0 #include #endif #if SM_SOFTTRANSPARENTSHADOW==1 @@ -10279,7 +10279,7 @@ uniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM; #if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 varying float zSM; #endif -`;T.IncludesShadersStore[M4]||(T.IncludesShadersStore[M4]=Ble)});var y4,Ule,P4=C(()=>{W();y4="shadowMapFragment",Ule=`float depthSM=vDepthMetricSM; +`;T.IncludesShadersStore[M4]||(T.IncludesShadersStore[M4]=Ble)});var y4,Ule,P4=C(()=>{k();y4="shadowMapFragment",Ule=`float depthSM=vDepthMetricSM; #if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 #if SM_USEDISTANCE==1 depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; @@ -10307,7 +10307,7 @@ gl_FragColor=vec4(depthSM,1.0,1.0,1.0); #else gl_FragColor=pack(depthSM); #endif -return;`;T.IncludesShadersStore[y4]||(T.IncludesShadersStore[y4]=Ule)});var L4={};tt(L4,{shadowMapPixelShader:()=>Vle});var lD,D4,Vle,O4=C(()=>{W();C4();Ec();Sc();P4();lD="shadowMapPixelShader",D4=`#include +return;`;T.IncludesShadersStore[y4]||(T.IncludesShadersStore[y4]=Ule)});var L4={};tt(L4,{shadowMapPixelShader:()=>Vle});var lD,D4,Vle,O4=C(()=>{k();C4();vc();Ec();P4();lD="shadowMapPixelShader",D4=`#include #ifdef ALPHATEXTURE varying vec2 vUV;uniform sampler2D diffuseSampler; #endif @@ -10334,18 +10334,18 @@ if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowS #endif #endif #include -}`;T.ShadersStore[lD]||(T.ShadersStore[lD]=D4);Vle={name:lD,shader:D4}});var N4,Gle,cD=C(()=>{W();N4="sceneVertexDeclaration",Gle=`uniform mat4 viewProjection; +}`;T.ShadersStore[lD]||(T.ShadersStore[lD]=D4);Vle={name:lD,shader:D4}});var N4,Gle,cD=C(()=>{k();N4="sceneVertexDeclaration",Gle=`uniform mat4 viewProjection; #ifdef MULTIVIEW uniform mat4 viewProjectionR; #endif uniform mat4 view;uniform mat4 projection;uniform vec4 vEyePosition; -`;T.IncludesShadersStore[N4]||(T.IncludesShadersStore[N4]=Gle)});var w4,kle,F4=C(()=>{W();w4="meshVertexDeclaration",kle=`uniform mat4 world;uniform float visibility; -`;T.IncludesShadersStore[w4]||(T.IncludesShadersStore[w4]=kle)});var B4,Wle,U4=C(()=>{W();cD();F4();B4="shadowMapVertexDeclaration",Wle=`#include +`;T.IncludesShadersStore[N4]||(T.IncludesShadersStore[N4]=Gle)});var w4,kle,F4=C(()=>{k();w4="meshVertexDeclaration",kle=`uniform mat4 world;uniform float visibility; +`;T.IncludesShadersStore[w4]||(T.IncludesShadersStore[w4]=kle)});var B4,Wle,U4=C(()=>{k();cD();F4();B4="shadowMapVertexDeclaration",Wle=`#include #include -`;T.IncludesShadersStore[B4]||(T.IncludesShadersStore[B4]=Wle)});var V4,Hle,G4=C(()=>{W();rd();Ng();V4="shadowMapUboDeclaration",Hle=`layout(std140,column_major) uniform; +`;T.IncludesShadersStore[B4]||(T.IncludesShadersStore[B4]=Wle)});var V4,Hle,G4=C(()=>{k();rd();Ng();V4="shadowMapUboDeclaration",Hle=`layout(std140,column_major) uniform; #include #include -`;T.IncludesShadersStore[V4]||(T.IncludesShadersStore[V4]=Hle)});var k4,zle,W4=C(()=>{W();k4="shadowMapVertexExtraDeclaration",zle=`#if SM_NORMALBIAS==1 +`;T.IncludesShadersStore[V4]||(T.IncludesShadersStore[V4]=Hle)});var k4,zle,W4=C(()=>{k();k4="shadowMapVertexExtraDeclaration",zle=`#if SM_NORMALBIAS==1 uniform vec3 lightDataSM; #endif uniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;varying float vDepthMetricSM; @@ -10355,7 +10355,7 @@ varying vec3 vPositionWSM; #if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 varying float zSM; #endif -`;T.IncludesShadersStore[k4]||(T.IncludesShadersStore[k4]=zle)});var H4,Xle,z4=C(()=>{W();H4="shadowMapVertexNormalBias",Xle=`#if SM_NORMALBIAS==1 +`;T.IncludesShadersStore[k4]||(T.IncludesShadersStore[k4]=zle)});var H4,Xle,z4=C(()=>{k();H4="shadowMapVertexNormalBias",Xle=`#if SM_NORMALBIAS==1 #if SM_DIRECTIONINLIGHTDATA==1 vec3 worldLightDirSM=normalize(-lightDataSM.xyz); #else @@ -10363,7 +10363,7 @@ vec3 directionToLightSM=lightDataSM.xyz-worldPos.xyz;vec3 worldLightDirSM=normal #endif float ndlSM=dot(vNormalW,worldLightDirSM);float sinNLSM=sqrt(1.0-ndlSM*ndlSM);float normalBiasSM=biasAndScaleSM.y*sinNLSM;worldPos.xyz-=vNormalW*normalBiasSM; #endif -`;T.IncludesShadersStore[H4]||(T.IncludesShadersStore[H4]=Xle)});var X4,Yle,Y4=C(()=>{W();X4="shadowMapVertexMetric",Yle=`#if SM_USEDISTANCE==1 +`;T.IncludesShadersStore[H4]||(T.IncludesShadersStore[H4]=Xle)});var X4,Yle,Y4=C(()=>{k();X4="shadowMapVertexMetric",Yle=`#if SM_USEDISTANCE==1 vPositionWSM=worldPos.xyz; #endif #if SM_DEPTHTEXTURE==1 @@ -10387,7 +10387,7 @@ vDepthMetricSM=(-gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x vDepthMetricSM=(gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; #endif #endif -`;T.IncludesShadersStore[X4]||(T.IncludesShadersStore[X4]=Yle)});var j4={};tt(j4,{shadowMapVertexShader:()=>Kle});var fD,K4,Kle,q4=C(()=>{W();dc();uc();Wf();Hf();ya();U4();G4();W4();mc();zf();Xf();pc();_c();gc();z4();Y4();vc();fD="shadowMapVertexShader",K4=`attribute vec3 position; +`;T.IncludesShadersStore[X4]||(T.IncludesShadersStore[X4]=Yle)});var j4={};tt(j4,{shadowMapVertexShader:()=>Kle});var fD,K4,Kle,q4=C(()=>{k();hc();dc();kf();Wf();Ca();U4();G4();W4();uc();Hf();zf();mc();pc();_c();z4();Y4();gc();fD="shadowMapVertexShader",K4=`attribute vec3 position; #ifdef NORMAL attribute vec3 normal; #endif @@ -10452,16 +10452,16 @@ vUV=vec2(diffuseMatrix*vec4(uv2Updated,1.0,0.0)); #endif #endif #include -}`;T.ShadersStore[fD]||(T.ShadersStore[fD]=K4);Kle={name:fD,shader:K4}});var Q4={};tt(Q4,{depthBoxBlurPixelShader:()=>jle});var hD,Z4,jle,$4=C(()=>{W();hD="depthBoxBlurPixelShader",Z4=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize; +}`;T.ShadersStore[fD]||(T.ShadersStore[fD]=K4);Kle={name:fD,shader:K4}});var Q4={};tt(Q4,{depthBoxBlurPixelShader:()=>jle});var hD,Z4,jle,$4=C(()=>{k();hD="depthBoxBlurPixelShader",Z4=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec4 colorDepth=vec4(0.0);for (int x=-OFFSET; x<=OFFSET; x++) for (int y=-OFFSET; y<=OFFSET; y++) -colorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);gl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));}`;T.ShadersStore[hD]||(T.ShadersStore[hD]=Z4);jle={name:hD,shader:Z4}});var eX={};tt(eX,{shadowMapFragmentSoftTransparentShadow:()=>qle});var dD,J4,qle,tX=C(()=>{W();dD="shadowMapFragmentSoftTransparentShadow",J4=`#if SM_SOFTTRANSPARENTSHADOW==1 +colorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);gl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));}`;T.ShadersStore[hD]||(T.ShadersStore[hD]=Z4);jle={name:hD,shader:Z4}});var eX={};tt(eX,{shadowMapFragmentSoftTransparentShadow:()=>qle});var dD,J4,qle,tX=C(()=>{k();dD="shadowMapFragmentSoftTransparentShadow",J4=`#if SM_SOFTTRANSPARENTSHADOW==1 if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM.x*alpha) discard; #endif -`;T.IncludesShadersStore[dD]||(T.IncludesShadersStore[dD]=J4);qle={name:dD,shader:J4}});var Mi,eR=C(()=>{Ve();zt();Gi();Pf();Fr();gf();Kl();rD();hi();hn();Lf();ZT();Gh();ol();Un();J_();Mi=class n{get bias(){return this._bias}set bias(e){this._bias=e}get normalBias(){return this._normalBias}set normalBias(e){this._normalBias=e}get blurBoxOffset(){return this._blurBoxOffset}set blurBoxOffset(e){this._blurBoxOffset!==e&&(this._blurBoxOffset=e,this._disposeBlurPostProcesses())}get blurScale(){return this._blurScale}set blurScale(e){this._blurScale!==e&&(this._blurScale=e,this._disposeBlurPostProcesses())}get blurKernel(){return this._blurKernel}set blurKernel(e){this._blurKernel!==e&&(this._blurKernel=e,this._disposeBlurPostProcesses())}get useKernelBlur(){return this._useKernelBlur}set useKernelBlur(e){this._useKernelBlur!==e&&(this._useKernelBlur=e,this._disposeBlurPostProcesses())}get depthScale(){return this._depthScale!==void 0?this._depthScale:this._light.getDepthScale()}set depthScale(e){this._depthScale=e}_validateFilter(e){return e}get filter(){return this._filter}set filter(e){if(e=this._validateFilter(e),this._light.needCube()){if(e===n.FILTER_BLUREXPONENTIALSHADOWMAP){this.useExponentialShadowMap=!0;return}else if(e===n.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP){this.useCloseExponentialShadowMap=!0;return}else if(e===n.FILTER_PCF||e===n.FILTER_PCSS){this.usePoissonSampling=!0;return}}if((e===n.FILTER_PCF||e===n.FILTER_PCSS)&&!this._scene.getEngine()._features.supportShadowSamplers){this.usePoissonSampling=!0;return}this._filter!==e&&(this._filter=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())}get usePoissonSampling(){return this.filter===n.FILTER_POISSONSAMPLING}set usePoissonSampling(e){let t=this._validateFilter(n.FILTER_POISSONSAMPLING);!e&&this.filter!==n.FILTER_POISSONSAMPLING||(this.filter=e?t:n.FILTER_NONE)}get useExponentialShadowMap(){return this.filter===n.FILTER_EXPONENTIALSHADOWMAP}set useExponentialShadowMap(e){let t=this._validateFilter(n.FILTER_EXPONENTIALSHADOWMAP);!e&&this.filter!==n.FILTER_EXPONENTIALSHADOWMAP||(this.filter=e?t:n.FILTER_NONE)}get useBlurExponentialShadowMap(){return this.filter===n.FILTER_BLUREXPONENTIALSHADOWMAP}set useBlurExponentialShadowMap(e){let t=this._validateFilter(n.FILTER_BLUREXPONENTIALSHADOWMAP);!e&&this.filter!==n.FILTER_BLUREXPONENTIALSHADOWMAP||(this.filter=e?t:n.FILTER_NONE)}get useCloseExponentialShadowMap(){return this.filter===n.FILTER_CLOSEEXPONENTIALSHADOWMAP}set useCloseExponentialShadowMap(e){let t=this._validateFilter(n.FILTER_CLOSEEXPONENTIALSHADOWMAP);!e&&this.filter!==n.FILTER_CLOSEEXPONENTIALSHADOWMAP||(this.filter=e?t:n.FILTER_NONE)}get useBlurCloseExponentialShadowMap(){return this.filter===n.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP}set useBlurCloseExponentialShadowMap(e){let t=this._validateFilter(n.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);!e&&this.filter!==n.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP||(this.filter=e?t:n.FILTER_NONE)}get usePercentageCloserFiltering(){return this.filter===n.FILTER_PCF}set usePercentageCloserFiltering(e){let t=this._validateFilter(n.FILTER_PCF);!e&&this.filter!==n.FILTER_PCF||(this.filter=e?t:n.FILTER_NONE)}get filteringQuality(){return this._filteringQuality}set filteringQuality(e){this._filteringQuality!==e&&(this._filteringQuality=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())}get useContactHardeningShadow(){return this.filter===n.FILTER_PCSS}set useContactHardeningShadow(e){let t=this._validateFilter(n.FILTER_PCSS);!e&&this.filter!==n.FILTER_PCSS||(this.filter=e?t:n.FILTER_NONE)}get contactHardeningLightSizeUVRatio(){return this._contactHardeningLightSizeUVRatio}set contactHardeningLightSizeUVRatio(e){this._contactHardeningLightSizeUVRatio=e}get darkness(){return this._darkness}set darkness(e){this.setDarkness(e)}getDarkness(){return this._darkness}setDarkness(e){return e>=1?this._darkness=1:e<=0?this._darkness=0:this._darkness=e,this}get transparencyShadow(){return this._transparencyShadow}set transparencyShadow(e){this.setTransparencyShadow(e)}setTransparencyShadow(e){return this._transparencyShadow=e,this}getShadowMap(){return this._shadowMap}getShadowMapForRendering(){return this._shadowMap2?this._shadowMap2:this._shadowMap}getClassName(){return n.CLASSNAME}addShadowCaster(e,t=!0){if(!this._shadowMap)return this;if(this._shadowMap.renderList||(this._shadowMap.renderList=[]),this._shadowMap.renderList.indexOf(e)===-1&&this._shadowMap.renderList.push(e),t)for(let i of e.getChildMeshes())this._shadowMap.renderList.indexOf(i)===-1&&this._shadowMap.renderList.push(i);return this}removeShadowCaster(e,t=!0){if(!this._shadowMap||!this._shadowMap.renderList)return this;let i=this._shadowMap.renderList.indexOf(e);if(i!==-1&&this._shadowMap.renderList.splice(i,1),t)for(let r of e.getChildren())this.removeShadowCaster(r);return this}getLight(){return this._light}get shaderLanguage(){return this._shaderLanguage}_getCamera(){var e;return(e=this._camera)!=null?e:this._scene.activeCamera}get mapSize(){return this._mapSize}set mapSize(e){this._mapSize=e,this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}get light(){return this._light}set light(e){this._light!==e&&(this.dispose(!1),this._light=e,this._createInstance())}get useFloat32TextureType(){return this._usefullFloatFirst}set useFloat32TextureType(e){this._usefullFloatFirst!==e&&(this.dispose(!1),this._usefullFloatFirst=e,this._createInstance())}get camera(){return this._camera}set camera(e){this._camera!==e&&(this.dispose(!1),this._camera=e,this._createInstance())}get useRedTextureFormat(){return this._useRedTextureType}set useRedTextureFormat(e){this._useRedTextureType!==e&&(this.dispose(!1),this._useRedTextureType=e,this._createInstance())}constructor(e,t,i,r,s,a=!1){this.onBeforeShadowMapRenderObservable=new ie,this.onAfterShadowMapRenderObservable=new ie,this.onBeforeShadowMapRenderMeshObservable=new ie,this.onAfterShadowMapRenderMeshObservable=new ie,this.doNotSerialize=!1,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=n.FILTER_NONE,this._filteringQuality=n.QUALITY_HIGH,this._contactHardeningLightSizeUVRatio=.1,this._darkness=0,this._transparencyShadow=!1,this.enableSoftTransparentShadow=!1,this.useOpacityTextureForTransparentShadow=!1,this.frustumEdgeFalloff=0,this._shaderLanguage=0,this.forceBackFacesOnly=!1,this._lightDirection=b.Zero(),this._viewMatrix=j.Zero(),this._projectionMatrix=j.Zero(),this._transformMatrix=j.Zero(),this._cachedPosition=new b(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new b(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=j.Identity(),this._shadersLoaded=!1,this._mapSize=e,this._light=t,this._usefullFloatFirst=!!i,this._scene=t.getScene(),this._camera=r!=null?r:null,this._useRedTextureType=!!s,this._forceGLSL=a,this._createInstance()}_createInstance(){this._initShaderSourceAsync(this._forceGLSL);let e=this._light._shadowGenerators;e||(e=this._light._shadowGenerators=new Map),e.set(this._camera,this),this.id=this._light.id,this._useUBO=this._scene.getEngine().supportsUniformBuffers,this._useUBO&&(this._sceneUBOs=[this._scene.createSceneUniformBuffer(`Scene for Shadow Generator (light "${this._light.name}")`,{forceMono:!0})]),n._SceneComponentInitialization(this._scene);let t=this._scene.getEngine().getCaps();this._usefullFloatFirst?t.textureFloatRender&&t.textureFloatLinearFiltering?this._textureType=1:t.textureHalfFloatRender&&t.textureHalfFloatLinearFiltering?this._textureType=2:this._textureType=0:t.textureHalfFloatRender&&t.textureHalfFloatLinearFiltering?this._textureType=2:t.textureFloatRender&&t.textureFloatLinearFiltering?this._textureType=1:this._textureType=0,this._initializeGenerator(),this._applyFilterValues()}_initializeGenerator(){this._light._markMeshesAsLightDirty(),this._initializeShadowMap()}_createTargetRenderTexture(){var t;let e=this._scene.getEngine();(t=this._shadowMap)==null||t.dispose(),e._features.supportDepthStencilTexture?(this._shadowMap=new Br(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube(),void 0,!1,!1,void 0,this._useRedTextureType?6:5),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?516:513,!0,void 0,void 0,void 0,`DepthStencilForShadowGenerator-${this._light.name}`)):this._shadowMap=new Br(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube()),this._shadowMap.noPrePassRenderer=!0}_initializeShadowMap(){if(this._createTargetRenderTexture(),this._shadowMap===null)return;this._shadowMap.wrapU=_e.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=_e.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(_e.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._storedUniqueId&&(this._shadowMap.uniqueId=this._storedUniqueId),this._shadowMap.customRenderFunction=(r,s,a,o)=>this._renderForShadowMap(r,s,a,o),this._shadowMap.customIsReadyFunction=(r,s,a)=>{if(!a||!r.subMeshes)return!0;let o=!0;for(let l of r.subMeshes){let c=l.getRenderingMesh(),h=this._scene.getEngine(),d=l.getMaterial();if(!d||l.verticesCount===0||this.customAllowRendering&&!this.customAllowRendering(l))continue;let u=c._getInstancesRenderList(l._id,!!l.getReplacementMesh());if(u.mustReturn)continue;let m=h.getCaps().instancedArrays&&(u.visibleInstances[l._id]!==null&&u.visibleInstances[l._id]!==void 0||c.hasThinInstances),p=d.needAlphaBlendingForMesh(c);o=this.isReady(l,m,p)&&o}return o};let e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.add(()=>{var r;this._currentSceneUBO=this._scene.getSceneUniformBuffer(),e._enableGPUDebugMarkers&&((r=e._debugPushGroup)==null||r.call(e,`Shadow map generation for pass id ${e.currentRenderPassId}`))}),this._shadowMap.onBeforeRenderObservable.add(r=>{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[0]),this._currentFaceIndex=r,this._filter===n.FILTER_PCF&&e.setColorWrite(!1),this.getTransformMatrix(),Ia.eyeAtCamera=!1,this._scene.setTransformMatrix(this._viewMatrix,this._projectionMatrix),this._sceneUBOs&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())}),this._shadowMap.onAfterUnbindObservable.add(()=>{var s,a;if(this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._currentSceneUBO),Ia.eyeAtCamera=!0,this._scene.updateTransformMatrix(),this._filter===n.FILTER_PCF&&e.setColorWrite(!0),!this.useBlurExponentialShadowMap&&!this.useBlurCloseExponentialShadowMap){(s=e._debugPopGroup)==null||s.call(e);return}let r=this.getShadowMapForRendering();r&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,r.renderTarget,!0),e.unBindFramebuffer(r.renderTarget,!0)),e._enableGPUDebugMarkers&&((a=e._debugPopGroup)==null||a.call(e))});let t=new lt(0,0,0,0),i=new lt(1,1,1,1);this._shadowMap.onClearObservable.add(r=>{this._filter===n.FILTER_PCF?r.clear(i,!1,!0,!1):this.useExponentialShadowMap||this.useBlurExponentialShadowMap?r.clear(t,!0,!0,!1):r.clear(i,!0,!0,!1)}),this._shadowMap.onResizeObservable.add(r=>{this._storedUniqueId=this._shadowMap.uniqueId,this._mapSize=r.getRenderSize(),this._light._markMeshesAsLightDirty(),this.recreateShadowMap()});for(let r=Ta.MIN_RENDERINGGROUPS;r(c4(),l4)),Promise.resolve().then(()=>(v4(),g4)),Promise.resolve().then(()=>(T4(),S4)),Promise.resolve().then(()=>(R4(),x4))])):await Promise.all([Promise.resolve().then(()=>(O4(),L4)),Promise.resolve().then(()=>(q4(),j4)),Promise.resolve().then(()=>($4(),Q4)),Promise.resolve().then(()=>(tX(),eX))]),this._shadersLoaded=!0}_initializeBlurRTTAndPostProcesses(){let e=this._scene.getEngine(),t=this._mapSize/this.blurScale;(!this.useKernelBlur||this.blurScale!==1)&&(this._shadowMap2=new Br(this._light.name+"_shadowMap2",t,this._scene,!1,!0,this._textureType,void 0,void 0,!1),this._shadowMap2.wrapU=_e.CLAMP_ADDRESSMODE,this._shadowMap2.wrapV=_e.CLAMP_ADDRESSMODE,this._shadowMap2.updateSamplingMode(_e.BILINEAR_SAMPLINGMODE)),this.useKernelBlur?(this._kernelBlurXPostprocess=new wa(this._light.name+"KernelBlurX",new we(1,0),this.blurKernel,1,null,_e.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.width=t,this._kernelBlurXPostprocess.height=t,this._kernelBlurXPostprocess.externalTextureSamplerBinding=!0,this._kernelBlurXPostprocess.onApplyObservable.add(i=>{i.setTexture("textureSampler",this._shadowMap)}),this._kernelBlurYPostprocess=new wa(this._light.name+"KernelBlurY",new we(0,1),this.blurKernel,1,null,_e.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.autoClear=!1,this._kernelBlurYPostprocess.autoClear=!1,this._textureType===0&&(this._kernelBlurXPostprocess.packedFloat=!0,this._kernelBlurYPostprocess.packedFloat=!0),this._blurPostProcesses=[this._kernelBlurXPostprocess,this._kernelBlurYPostprocess]):(this._boxBlurPostprocess=new xi(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,_e.BILINEAR_SAMPLINGMODE,e,!1,"#define OFFSET "+this._blurBoxOffset,this._textureType,void 0,void 0,void 0,void 0,this._shaderLanguage),this._boxBlurPostprocess.externalTextureSamplerBinding=!0,this._boxBlurPostprocess.onApplyObservable.add(i=>{i.setFloat2("screenSize",t,t),i.setTexture("textureSampler",this._shadowMap)}),this._boxBlurPostprocess.autoClear=!1,this._blurPostProcesses=[this._boxBlurPostprocess])}_renderForShadowMap(e,t,i,r){let s;if(r.length)for(s=0;s{r!==i&&!S?(i.getMeshUniformBuffer().bindToEffect(v,"Mesh"),i.transferToEffect(E)):(r.getMeshUniformBuffer().bindToEffect(v,"Mesh"),r.transferToEffect(S?E:A))}),this.forceBackFacesOnly&&a.setState(!0,0,!1,!1,o.cullBackFaces),this.onAfterShadowMapRenderObservable.notifyObservers(v),this.onAfterShadowMapRenderMeshObservable.notifyObservers(i)}else this._shadowMap&&this._shadowMap.resetRefreshCounter()}_applyFilterValues(){this._shadowMap&&(this.filter===n.FILTER_NONE||this.filter===n.FILTER_PCSS?this._shadowMap.updateSamplingMode(_e.NEAREST_SAMPLINGMODE):this._shadowMap.updateSamplingMode(_e.BILINEAR_SAMPLINGMODE))}forceCompilation(e,t){let i={useInstances:!1,...t},r=this.getShadowMap();if(!r){e&&e(this);return}let s=r.renderList;if(!s){e&&e(this);return}let a=[];for(let c of s)a.push(...c.subMeshes);if(a.length===0){e&&e(this);return}let o=0,l=()=>{var c,f;if(!(!this._scene||!this._scene.getEngine())){for(;this.isReady(a[o],i.useInstances,(f=(c=a[o].getMaterial())==null?void 0:c.needAlphaBlendingForMesh(a[o].getMesh()))!=null?f:!1);)if(o++,o>=a.length){e&&e(this);return}setTimeout(l,16)}};l()}async forceCompilationAsync(e){return await new Promise(t=>{this.forceCompilation(()=>{t()},e)})}_isReadyCustomDefines(e,t,i){}_prepareShadowDefines(e,t,i,r){i.push("#define SM_LIGHTTYPE_"+this._light.getClassName().toUpperCase()),i.push("#define SM_FLOAT "+(this._textureType!==0?"1":"0")),i.push("#define SM_ESM "+(this.useExponentialShadowMap||this.useBlurExponentialShadowMap?"1":"0")),i.push("#define SM_DEPTHTEXTURE "+(this.usePercentageCloserFiltering||this.useContactHardeningShadow?"1":"0"));let s=e.getMesh();return i.push("#define SM_NORMALBIAS "+(this.normalBias&&s.isVerticesDataPresent(L.NormalKind)?"1":"0")),i.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===Xt.LIGHTTYPEID_DIRECTIONALLIGHT?"1":"0")),i.push("#define SM_USEDISTANCE "+(this._light.needCube()?"1":"0")),i.push("#define SM_SOFTTRANSPARENTSHADOW "+(this.enableSoftTransparentShadow&&r?"1":"0")),this._isReadyCustomDefines(i,e,t),i}isReady(e,t,i){var o;if(!this._shadersLoaded)return!1;let r=e.getMaterial(),s=r==null?void 0:r.shadowDepthWrapper;if(this._opacityTexture=null,!r)return!1;let a=[];if(this._prepareShadowDefines(e,t,a,i),s){if(!s.isReadyForSubMesh(e,a,this,t,this._scene.getEngine().currentRenderPassId))return!1}else{let l=e._getDrawWrapper(void 0,!0),c=l.effect,f=l.defines,h=[L.PositionKind],d=e.getMesh(),u=!1,m=!1,p=!1,_=!1;this.normalBias&&d.isVerticesDataPresent(L.NormalKind)&&(h.push(L.NormalKind),a.push("#define NORMAL"),u=!0,d.nonUniformScaling&&a.push("#define NONUNIFORMSCALING"));let g=r.needAlphaTestingForMesh(d);if((g||r.needAlphaBlendingForMesh(d))&&(this.useOpacityTextureForTransparentShadow?this._opacityTexture=r.opacityTexture:this._opacityTexture=r.getAlphaTestTexture(),this._opacityTexture)){if(!this._opacityTexture.isReady())return!1;let E=(o=r.alphaCutOff)!=null?o:n.DEFAULT_ALPHA_CUTOFF;a.push("#define ALPHATEXTURE"),g&&a.push(`#define ALPHATESTVALUE ${E}${E%1===0?".":""}`),d.isVerticesDataPresent(L.UVKind)&&(h.push(L.UVKind),a.push("#define UV1"),m=!0),d.isVerticesDataPresent(L.UV2Kind)&&this._opacityTexture.coordinatesIndex===1&&(h.push(L.UV2Kind),a.push("#define UV2"),p=!0)}let v=new Wn;if(d.useBones&&d.computeBonesUsingShaders&&d.skeleton){h.push(L.MatricesIndicesKind),h.push(L.MatricesWeightsKind),d.numBoneInfluencers>4&&(h.push(L.MatricesIndicesExtraKind),h.push(L.MatricesWeightsExtraKind));let E=d.skeleton;a.push("#define NUM_BONE_INFLUENCERS "+d.numBoneInfluencers),d.numBoneInfluencers>0&&v.addCPUSkinningFallback(0,d),E.isUsingTextureForMatrices?a.push("#define BONETEXTURE"):a.push("#define BonesPerMesh "+(E.bones.length+1))}else a.push("#define NUM_BONE_INFLUENCERS 0");let x=d.morphTargetManager?ll(d.morphTargetManager,a,h,d,!0,u,!1,m,p,_):0;if(al(r,this._scene,a),t&&(a.push("#define INSTANCES"),mo(h),e.getRenderingMesh().hasThinInstances&&a.push("#define THIN_INSTANCES")),this.customShaderOptions&&this.customShaderOptions.defines)for(let E of this.customShaderOptions.defines)a.indexOf(E)===-1&&a.push(E);let A=d.bakedVertexAnimationManager;A&&A.isEnabled&&(a.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),t&&h.push("bakedVertexAnimationSettingsInstanced"));let S=a.join(` -`);if(f!==S){f=S;let E="shadowMap",R=["world","mBones","viewProjection","diffuseMatrix","lightDataSM","depthValuesSM","biasAndScaleSM","morphTargetInfluences","morphTargetCount","boneTextureInfo","softTransparentShadowSM","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture"],I=["diffuseSampler","boneSampler","morphTargets","bakedVertexAnimationTexture"],y=["Scene","Mesh"];if(wn(R),this.customShaderOptions){if(E=this.customShaderOptions.shaderName,this.customShaderOptions.attributes)for(let D of this.customShaderOptions.attributes)h.indexOf(D)===-1&&h.push(D);if(this.customShaderOptions.uniforms)for(let D of this.customShaderOptions.uniforms)R.indexOf(D)===-1&&R.push(D);if(this.customShaderOptions.samplers)for(let D of this.customShaderOptions.samplers)I.indexOf(D)===-1&&I.push(D)}let M=this._scene.getEngine();c=M.createEffect(E,{attributes:h,uniformsNames:R,uniformBuffersNames:y,samplers:I,defines:S,fallbacks:v,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:x},shaderLanguage:this._shaderLanguage},M),l.setEffect(c,f)}if(!c.isReady())return!1}return(this.useBlurExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(!this._blurPostProcesses||!this._blurPostProcesses.length)&&this._initializeBlurRTTAndPostProcesses(),!(this._kernelBlurXPostprocess&&!this._kernelBlurXPostprocess.isReady()||this._kernelBlurYPostprocess&&!this._kernelBlurYPostprocess.isReady()||this._boxBlurPostprocess&&!this._boxBlurPostprocess.isReady())}prepareDefines(e,t){let i=this._scene,r=this._light;!i.shadowsEnabled||!r.shadowEnabled||(e["SHADOW"+t]=!0,this.useContactHardeningShadow?(e["SHADOWPCSS"+t]=!0,this._filteringQuality===n.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===n.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePercentageCloserFiltering?(e["SHADOWPCF"+t]=!0,this._filteringQuality===n.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===n.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePoissonSampling?e["SHADOWPOISSON"+t]=!0:this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e["SHADOWESM"+t]=!0:(this.useCloseExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(e["SHADOWCLOSEESM"+t]=!0),r.needCube()&&(e["SHADOWCUBE"+t]=!0))}bindShadowLight(e,t){let i=this._light,r=this._scene;if(!r.shadowsEnabled||!i.shadowEnabled)return;let s=this._getCamera(),a=this.getShadowMap();if(!a)return;if(!i.needCube()){let l=r.floatingOriginOffset,c=this.getTransformMatrix(),f=r.floatingOriginMode?TC(l,this._viewMatrix,this._projectionMatrix,$.Matrix[0]):c;t.setMatrix("lightMatrix"+e,f)}let o=this.getShadowMapForRendering();this._filter===n.FILTER_PCF?(t.setDepthStencilTexture("shadowTexture"+e,o),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),a.getSize().width,1/a.getSize().width,this.frustumEdgeFalloff,e)):this._filter===n.FILTER_PCSS?(t.setDepthStencilTexture("shadowTexture"+e,o),t.setTexture("depthTexture"+e,o),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/a.getSize().width,this._contactHardeningLightSizeUVRatio*a.getSize().width,this.frustumEdgeFalloff,e)):(t.setTexture("shadowTexture"+e,o),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/a.getSize().width,this.depthScale,this.frustumEdgeFalloff,e)),i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(s),this.getLight().getDepthMinZ(s)+this.getLight().getDepthMaxZ(s),e)}get viewMatrix(){return this._viewMatrix}get projectionMatrix(){return this._projectionMatrix}getTransformMatrix(){let e=this._scene;if(this._currentRenderId===e.getRenderId()&&this._currentFaceIndexCache===this._currentFaceIndex)return this._transformMatrix;this._currentRenderId=e.getRenderId(),this._currentFaceIndexCache=this._currentFaceIndex;let t=this._light.position;if(this._light.computeTransformedInformation()&&(t=this._light.transformedPosition),b.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),Math.abs(b.Dot(this._lightDirection,b.Up()))===1&&(this._lightDirection.z=1e-13),this._light.needProjectionMatrixCompute()||!this._cachedPosition||!this._cachedDirection||!t.equals(this._cachedPosition)||!this._lightDirection.equals(this._cachedDirection)){this._cachedPosition.copyFrom(t),this._cachedDirection.copyFrom(this._lightDirection),j.LookAtLHToRef(t,t.add(this._lightDirection),b.Up(),this._viewMatrix);let i=this.getShadowMap();if(i){let r=i.renderList;r&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,r)}this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix)}return this._transformMatrix}recreateShadowMap(){let e=this._shadowMap;if(!e)return;let t=e.renderList;if(this._disposeRTTandPostProcesses(),this._initializeGenerator(),this.filter=this._filter,this._applyFilterValues(),t){this._shadowMap.renderList||(this._shadowMap.renderList=[]);for(let i of t)this._shadowMap.renderList.push(i)}else this._shadowMap.renderList=null}_disposeBlurPostProcesses(){this._shadowMap2&&(this._shadowMap2.dispose(),this._shadowMap2=null),this._boxBlurPostprocess&&(this._boxBlurPostprocess.dispose(),this._boxBlurPostprocess=null),this._kernelBlurXPostprocess&&(this._kernelBlurXPostprocess.dispose(),this._kernelBlurXPostprocess=null),this._kernelBlurYPostprocess&&(this._kernelBlurYPostprocess.dispose(),this._kernelBlurYPostprocess=null),this._blurPostProcesses=[]}_disposeRTTandPostProcesses(){this._shadowMap&&(this._shadowMap.dispose(),this._shadowMap=null),this._disposeBlurPostProcesses()}_disposeSceneUBOs(){if(this._sceneUBOs){for(let e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}dispose(e=!0){if(this._disposeRTTandPostProcesses(),this._disposeSceneUBOs(),this._light){if(this._light._shadowGenerators){let t=this._light._shadowGenerators.entries();for(let i=t.next();i.done!==!0;i=t.next()){let[r,s]=i.value;s===this&&this._light._shadowGenerators.delete(r)}this._light._shadowGenerators.size===0&&(this._light._shadowGenerators=null)}this._light._markMeshesAsLightDirty()}e&&(this.onBeforeShadowMapRenderMeshObservable.clear(),this.onBeforeShadowMapRenderObservable.clear(),this.onAfterShadowMapRenderMeshObservable.clear(),this.onAfterShadowMapRenderObservable.clear())}serialize(){var i;let e={},t=this.getShadowMap();if(!t)return e;if(e.className=this.getClassName(),e.lightId=this._light.id,e.cameraId=(i=this._camera)==null?void 0:i.id,e.id=this.id,e.mapSize=t.getRenderSize(),e.forceBackFacesOnly=this.forceBackFacesOnly,e.darkness=this.getDarkness(),e.transparencyShadow=this._transparencyShadow,e.frustumEdgeFalloff=this.frustumEdgeFalloff,e.bias=this.bias,e.normalBias=this.normalBias,e.usePercentageCloserFiltering=this.usePercentageCloserFiltering,e.useContactHardeningShadow=this.useContactHardeningShadow,e.contactHardeningLightSizeUVRatio=this.contactHardeningLightSizeUVRatio,e.filteringQuality=this.filteringQuality,e.useExponentialShadowMap=this.useExponentialShadowMap,e.useBlurExponentialShadowMap=this.useBlurExponentialShadowMap,e.useCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.useBlurCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.usePoissonSampling=this.usePoissonSampling,e.depthScale=this.depthScale,e.blurBoxOffset=this.blurBoxOffset,e.blurKernel=this.blurKernel,e.blurScale=this.blurScale,e.useKernelBlur=this.useKernelBlur,e.renderList=[],t.renderList)for(let r=0;r{throw Ze("ShadowGeneratorSceneComponent")}});var rX={};tt(rX,{depthPixelShader:()=>Zle});var uD,iX,Zle,mD=C(()=>{W();Ec();Jx();Sc();uD="depthPixelShader",iX=`#ifdef ALPHATEST +`;T.IncludesShadersStore[dD]||(T.IncludesShadersStore[dD]=J4);qle={name:dD,shader:J4}});var Ci,tR=C(()=>{Ge();zt();ki();yf();Fr();_f();Yl();rD();di();hn();Df();QT();Gh();ol();Un();J_();Ci=class n{get bias(){return this._bias}set bias(e){this._bias=e}get normalBias(){return this._normalBias}set normalBias(e){this._normalBias=e}get blurBoxOffset(){return this._blurBoxOffset}set blurBoxOffset(e){this._blurBoxOffset!==e&&(this._blurBoxOffset=e,this._disposeBlurPostProcesses())}get blurScale(){return this._blurScale}set blurScale(e){this._blurScale!==e&&(this._blurScale=e,this._disposeBlurPostProcesses())}get blurKernel(){return this._blurKernel}set blurKernel(e){this._blurKernel!==e&&(this._blurKernel=e,this._disposeBlurPostProcesses())}get useKernelBlur(){return this._useKernelBlur}set useKernelBlur(e){this._useKernelBlur!==e&&(this._useKernelBlur=e,this._disposeBlurPostProcesses())}get depthScale(){return this._depthScale!==void 0?this._depthScale:this._light.getDepthScale()}set depthScale(e){this._depthScale=e}_validateFilter(e){return e}get filter(){return this._filter}set filter(e){if(e=this._validateFilter(e),this._light.needCube()){if(e===n.FILTER_BLUREXPONENTIALSHADOWMAP){this.useExponentialShadowMap=!0;return}else if(e===n.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP){this.useCloseExponentialShadowMap=!0;return}else if(e===n.FILTER_PCF||e===n.FILTER_PCSS){this.usePoissonSampling=!0;return}}if((e===n.FILTER_PCF||e===n.FILTER_PCSS)&&!this._scene.getEngine()._features.supportShadowSamplers){this.usePoissonSampling=!0;return}this._filter!==e&&(this._filter=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())}get usePoissonSampling(){return this.filter===n.FILTER_POISSONSAMPLING}set usePoissonSampling(e){let t=this._validateFilter(n.FILTER_POISSONSAMPLING);!e&&this.filter!==n.FILTER_POISSONSAMPLING||(this.filter=e?t:n.FILTER_NONE)}get useExponentialShadowMap(){return this.filter===n.FILTER_EXPONENTIALSHADOWMAP}set useExponentialShadowMap(e){let t=this._validateFilter(n.FILTER_EXPONENTIALSHADOWMAP);!e&&this.filter!==n.FILTER_EXPONENTIALSHADOWMAP||(this.filter=e?t:n.FILTER_NONE)}get useBlurExponentialShadowMap(){return this.filter===n.FILTER_BLUREXPONENTIALSHADOWMAP}set useBlurExponentialShadowMap(e){let t=this._validateFilter(n.FILTER_BLUREXPONENTIALSHADOWMAP);!e&&this.filter!==n.FILTER_BLUREXPONENTIALSHADOWMAP||(this.filter=e?t:n.FILTER_NONE)}get useCloseExponentialShadowMap(){return this.filter===n.FILTER_CLOSEEXPONENTIALSHADOWMAP}set useCloseExponentialShadowMap(e){let t=this._validateFilter(n.FILTER_CLOSEEXPONENTIALSHADOWMAP);!e&&this.filter!==n.FILTER_CLOSEEXPONENTIALSHADOWMAP||(this.filter=e?t:n.FILTER_NONE)}get useBlurCloseExponentialShadowMap(){return this.filter===n.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP}set useBlurCloseExponentialShadowMap(e){let t=this._validateFilter(n.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);!e&&this.filter!==n.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP||(this.filter=e?t:n.FILTER_NONE)}get usePercentageCloserFiltering(){return this.filter===n.FILTER_PCF}set usePercentageCloserFiltering(e){let t=this._validateFilter(n.FILTER_PCF);!e&&this.filter!==n.FILTER_PCF||(this.filter=e?t:n.FILTER_NONE)}get filteringQuality(){return this._filteringQuality}set filteringQuality(e){this._filteringQuality!==e&&(this._filteringQuality=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())}get useContactHardeningShadow(){return this.filter===n.FILTER_PCSS}set useContactHardeningShadow(e){let t=this._validateFilter(n.FILTER_PCSS);!e&&this.filter!==n.FILTER_PCSS||(this.filter=e?t:n.FILTER_NONE)}get contactHardeningLightSizeUVRatio(){return this._contactHardeningLightSizeUVRatio}set contactHardeningLightSizeUVRatio(e){this._contactHardeningLightSizeUVRatio=e}get darkness(){return this._darkness}set darkness(e){this.setDarkness(e)}getDarkness(){return this._darkness}setDarkness(e){return e>=1?this._darkness=1:e<=0?this._darkness=0:this._darkness=e,this}get transparencyShadow(){return this._transparencyShadow}set transparencyShadow(e){this.setTransparencyShadow(e)}setTransparencyShadow(e){return this._transparencyShadow=e,this}getShadowMap(){return this._shadowMap}getShadowMapForRendering(){return this._shadowMap2?this._shadowMap2:this._shadowMap}getClassName(){return n.CLASSNAME}addShadowCaster(e,t=!0){if(!this._shadowMap)return this;if(this._shadowMap.renderList||(this._shadowMap.renderList=[]),this._shadowMap.renderList.indexOf(e)===-1&&this._shadowMap.renderList.push(e),t)for(let i of e.getChildMeshes())this._shadowMap.renderList.indexOf(i)===-1&&this._shadowMap.renderList.push(i);return this}removeShadowCaster(e,t=!0){if(!this._shadowMap||!this._shadowMap.renderList)return this;let i=this._shadowMap.renderList.indexOf(e);if(i!==-1&&this._shadowMap.renderList.splice(i,1),t)for(let r of e.getChildren())this.removeShadowCaster(r);return this}getLight(){return this._light}get shaderLanguage(){return this._shaderLanguage}_getCamera(){var e;return(e=this._camera)!=null?e:this._scene.activeCamera}get mapSize(){return this._mapSize}set mapSize(e){this._mapSize=e,this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}get light(){return this._light}set light(e){this._light!==e&&(this.dispose(!1),this._light=e,this._createInstance())}get useFloat32TextureType(){return this._usefullFloatFirst}set useFloat32TextureType(e){this._usefullFloatFirst!==e&&(this.dispose(!1),this._usefullFloatFirst=e,this._createInstance())}get camera(){return this._camera}set camera(e){this._camera!==e&&(this.dispose(!1),this._camera=e,this._createInstance())}get useRedTextureFormat(){return this._useRedTextureType}set useRedTextureFormat(e){this._useRedTextureType!==e&&(this.dispose(!1),this._useRedTextureType=e,this._createInstance())}constructor(e,t,i,r,s,a=!1){this.onBeforeShadowMapRenderObservable=new ie,this.onAfterShadowMapRenderObservable=new ie,this.onBeforeShadowMapRenderMeshObservable=new ie,this.onAfterShadowMapRenderMeshObservable=new ie,this.doNotSerialize=!1,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=n.FILTER_NONE,this._filteringQuality=n.QUALITY_HIGH,this._contactHardeningLightSizeUVRatio=.1,this._darkness=0,this._transparencyShadow=!1,this.enableSoftTransparentShadow=!1,this.useOpacityTextureForTransparentShadow=!1,this.frustumEdgeFalloff=0,this._shaderLanguage=0,this.forceBackFacesOnly=!1,this._lightDirection=b.Zero(),this._viewMatrix=K.Zero(),this._projectionMatrix=K.Zero(),this._transformMatrix=K.Zero(),this._cachedPosition=new b(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new b(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=K.Identity(),this._shadersLoaded=!1,this._mapSize=e,this._light=t,this._usefullFloatFirst=!!i,this._scene=t.getScene(),this._camera=r!=null?r:null,this._useRedTextureType=!!s,this._forceGLSL=a,this._createInstance()}_createInstance(){this._initShaderSourceAsync(this._forceGLSL);let e=this._light._shadowGenerators;e||(e=this._light._shadowGenerators=new Map),e.set(this._camera,this),this.id=this._light.id,this._useUBO=this._scene.getEngine().supportsUniformBuffers,this._useUBO&&(this._sceneUBOs=[this._scene.createSceneUniformBuffer(`Scene for Shadow Generator (light "${this._light.name}")`,{forceMono:!0})]),n._SceneComponentInitialization(this._scene);let t=this._scene.getEngine().getCaps();this._usefullFloatFirst?t.textureFloatRender&&t.textureFloatLinearFiltering?this._textureType=1:t.textureHalfFloatRender&&t.textureHalfFloatLinearFiltering?this._textureType=2:this._textureType=0:t.textureHalfFloatRender&&t.textureHalfFloatLinearFiltering?this._textureType=2:t.textureFloatRender&&t.textureFloatLinearFiltering?this._textureType=1:this._textureType=0,this._initializeGenerator(),this._applyFilterValues()}_initializeGenerator(){this._light._markMeshesAsLightDirty(),this._initializeShadowMap()}_createTargetRenderTexture(){var t;let e=this._scene.getEngine();(t=this._shadowMap)==null||t.dispose(),e._features.supportDepthStencilTexture?(this._shadowMap=new Br(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube(),void 0,!1,!1,void 0,this._useRedTextureType?6:5),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?516:513,!0,void 0,void 0,void 0,`DepthStencilForShadowGenerator-${this._light.name}`)):this._shadowMap=new Br(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube()),this._shadowMap.noPrePassRenderer=!0}_initializeShadowMap(){if(this._createTargetRenderTexture(),this._shadowMap===null)return;this._shadowMap.wrapU=ge.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=ge.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(ge.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._storedUniqueId&&(this._shadowMap.uniqueId=this._storedUniqueId),this._shadowMap.customRenderFunction=(r,s,a,o)=>this._renderForShadowMap(r,s,a,o),this._shadowMap.customIsReadyFunction=(r,s,a)=>{if(!a||!r.subMeshes)return!0;let o=!0;for(let l of r.subMeshes){let c=l.getRenderingMesh(),h=this._scene.getEngine(),d=l.getMaterial();if(!d||l.verticesCount===0||this.customAllowRendering&&!this.customAllowRendering(l))continue;let u=c._getInstancesRenderList(l._id,!!l.getReplacementMesh());if(u.mustReturn)continue;let m=h.getCaps().instancedArrays&&(u.visibleInstances[l._id]!==null&&u.visibleInstances[l._id]!==void 0||c.hasThinInstances),p=d.needAlphaBlendingForMesh(c);o=this.isReady(l,m,p)&&o}return o};let e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.add(()=>{var r;this._currentSceneUBO=this._scene.getSceneUniformBuffer(),e._enableGPUDebugMarkers&&((r=e._debugPushGroup)==null||r.call(e,`Shadow map generation for pass id ${e.currentRenderPassId}`))}),this._shadowMap.onBeforeRenderObservable.add(r=>{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[0]),this._currentFaceIndex=r,this._filter===n.FILTER_PCF&&e.setColorWrite(!1),this.getTransformMatrix(),ba.eyeAtCamera=!1,this._scene.setTransformMatrix(this._viewMatrix,this._projectionMatrix),this._sceneUBOs&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())}),this._shadowMap.onAfterUnbindObservable.add(()=>{var s,a;if(this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._currentSceneUBO),ba.eyeAtCamera=!0,this._scene.updateTransformMatrix(),this._filter===n.FILTER_PCF&&e.setColorWrite(!0),!this.useBlurExponentialShadowMap&&!this.useBlurCloseExponentialShadowMap){(s=e._debugPopGroup)==null||s.call(e);return}let r=this.getShadowMapForRendering();r&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,r.renderTarget,!0),e.unBindFramebuffer(r.renderTarget,!0)),e._enableGPUDebugMarkers&&((a=e._debugPopGroup)==null||a.call(e))});let t=new lt(0,0,0,0),i=new lt(1,1,1,1);this._shadowMap.onClearObservable.add(r=>{this._filter===n.FILTER_PCF?r.clear(i,!1,!0,!1):this.useExponentialShadowMap||this.useBlurExponentialShadowMap?r.clear(t,!0,!0,!1):r.clear(i,!0,!0,!1)}),this._shadowMap.onResizeObservable.add(r=>{this._storedUniqueId=this._shadowMap.uniqueId,this._mapSize=r.getRenderSize(),this._light._markMeshesAsLightDirty(),this.recreateShadowMap()});for(let r=Sa.MIN_RENDERINGGROUPS;r(c4(),l4)),Promise.resolve().then(()=>(v4(),g4)),Promise.resolve().then(()=>(T4(),S4)),Promise.resolve().then(()=>(R4(),x4))])):await Promise.all([Promise.resolve().then(()=>(O4(),L4)),Promise.resolve().then(()=>(q4(),j4)),Promise.resolve().then(()=>($4(),Q4)),Promise.resolve().then(()=>(tX(),eX))]),this._shadersLoaded=!0}_initializeBlurRTTAndPostProcesses(){let e=this._scene.getEngine(),t=this._mapSize/this.blurScale;(!this.useKernelBlur||this.blurScale!==1)&&(this._shadowMap2=new Br(this._light.name+"_shadowMap2",t,this._scene,!1,!0,this._textureType,void 0,void 0,!1),this._shadowMap2.wrapU=ge.CLAMP_ADDRESSMODE,this._shadowMap2.wrapV=ge.CLAMP_ADDRESSMODE,this._shadowMap2.updateSamplingMode(ge.BILINEAR_SAMPLINGMODE)),this.useKernelBlur?(this._kernelBlurXPostprocess=new Na(this._light.name+"KernelBlurX",new we(1,0),this.blurKernel,1,null,ge.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.width=t,this._kernelBlurXPostprocess.height=t,this._kernelBlurXPostprocess.externalTextureSamplerBinding=!0,this._kernelBlurXPostprocess.onApplyObservable.add(i=>{i.setTexture("textureSampler",this._shadowMap)}),this._kernelBlurYPostprocess=new Na(this._light.name+"KernelBlurY",new we(0,1),this.blurKernel,1,null,ge.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.autoClear=!1,this._kernelBlurYPostprocess.autoClear=!1,this._textureType===0&&(this._kernelBlurXPostprocess.packedFloat=!0,this._kernelBlurYPostprocess.packedFloat=!0),this._blurPostProcesses=[this._kernelBlurXPostprocess,this._kernelBlurYPostprocess]):(this._boxBlurPostprocess=new Ri(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,ge.BILINEAR_SAMPLINGMODE,e,!1,"#define OFFSET "+this._blurBoxOffset,this._textureType,void 0,void 0,void 0,void 0,this._shaderLanguage),this._boxBlurPostprocess.externalTextureSamplerBinding=!0,this._boxBlurPostprocess.onApplyObservable.add(i=>{i.setFloat2("screenSize",t,t),i.setTexture("textureSampler",this._shadowMap)}),this._boxBlurPostprocess.autoClear=!1,this._blurPostProcesses=[this._boxBlurPostprocess])}_renderForShadowMap(e,t,i,r){let s;if(r.length)for(s=0;s{r!==i&&!S?(i.getMeshUniformBuffer().bindToEffect(v,"Mesh"),i.transferToEffect(E)):(r.getMeshUniformBuffer().bindToEffect(v,"Mesh"),r.transferToEffect(S?E:A))}),this.forceBackFacesOnly&&a.setState(!0,0,!1,!1,o.cullBackFaces),this.onAfterShadowMapRenderObservable.notifyObservers(v),this.onAfterShadowMapRenderMeshObservable.notifyObservers(i)}else this._shadowMap&&this._shadowMap.resetRefreshCounter()}_applyFilterValues(){this._shadowMap&&(this.filter===n.FILTER_NONE||this.filter===n.FILTER_PCSS?this._shadowMap.updateSamplingMode(ge.NEAREST_SAMPLINGMODE):this._shadowMap.updateSamplingMode(ge.BILINEAR_SAMPLINGMODE))}forceCompilation(e,t){let i={useInstances:!1,...t},r=this.getShadowMap();if(!r){e&&e(this);return}let s=r.renderList;if(!s){e&&e(this);return}let a=[];for(let c of s)a.push(...c.subMeshes);if(a.length===0){e&&e(this);return}let o=0,l=()=>{var c,f;if(!(!this._scene||!this._scene.getEngine())){for(;this.isReady(a[o],i.useInstances,(f=(c=a[o].getMaterial())==null?void 0:c.needAlphaBlendingForMesh(a[o].getMesh()))!=null?f:!1);)if(o++,o>=a.length){e&&e(this);return}setTimeout(l,16)}};l()}async forceCompilationAsync(e){return await new Promise(t=>{this.forceCompilation(()=>{t()},e)})}_isReadyCustomDefines(e,t,i){}_prepareShadowDefines(e,t,i,r){i.push("#define SM_LIGHTTYPE_"+this._light.getClassName().toUpperCase()),i.push("#define SM_FLOAT "+(this._textureType!==0?"1":"0")),i.push("#define SM_ESM "+(this.useExponentialShadowMap||this.useBlurExponentialShadowMap?"1":"0")),i.push("#define SM_DEPTHTEXTURE "+(this.usePercentageCloserFiltering||this.useContactHardeningShadow?"1":"0"));let s=e.getMesh();return i.push("#define SM_NORMALBIAS "+(this.normalBias&&s.isVerticesDataPresent(L.NormalKind)?"1":"0")),i.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===Xt.LIGHTTYPEID_DIRECTIONALLIGHT?"1":"0")),i.push("#define SM_USEDISTANCE "+(this._light.needCube()?"1":"0")),i.push("#define SM_SOFTTRANSPARENTSHADOW "+(this.enableSoftTransparentShadow&&r?"1":"0")),this._isReadyCustomDefines(i,e,t),i}isReady(e,t,i){var o;if(!this._shadersLoaded)return!1;let r=e.getMaterial(),s=r==null?void 0:r.shadowDepthWrapper;if(this._opacityTexture=null,!r)return!1;let a=[];if(this._prepareShadowDefines(e,t,a,i),s){if(!s.isReadyForSubMesh(e,a,this,t,this._scene.getEngine().currentRenderPassId))return!1}else{let l=e._getDrawWrapper(void 0,!0),c=l.effect,f=l.defines,h=[L.PositionKind],d=e.getMesh(),u=!1,m=!1,p=!1,_=!1;this.normalBias&&d.isVerticesDataPresent(L.NormalKind)&&(h.push(L.NormalKind),a.push("#define NORMAL"),u=!0,d.nonUniformScaling&&a.push("#define NONUNIFORMSCALING"));let g=r.needAlphaTestingForMesh(d);if((g||r.needAlphaBlendingForMesh(d))&&(this.useOpacityTextureForTransparentShadow?this._opacityTexture=r.opacityTexture:this._opacityTexture=r.getAlphaTestTexture(),this._opacityTexture)){if(!this._opacityTexture.isReady())return!1;let E=(o=r.alphaCutOff)!=null?o:n.DEFAULT_ALPHA_CUTOFF;a.push("#define ALPHATEXTURE"),g&&a.push(`#define ALPHATESTVALUE ${E}${E%1===0?".":""}`),d.isVerticesDataPresent(L.UVKind)&&(h.push(L.UVKind),a.push("#define UV1"),m=!0),d.isVerticesDataPresent(L.UV2Kind)&&this._opacityTexture.coordinatesIndex===1&&(h.push(L.UV2Kind),a.push("#define UV2"),p=!0)}let v=new Wn;if(d.useBones&&d.computeBonesUsingShaders&&d.skeleton){h.push(L.MatricesIndicesKind),h.push(L.MatricesWeightsKind),d.numBoneInfluencers>4&&(h.push(L.MatricesIndicesExtraKind),h.push(L.MatricesWeightsExtraKind));let E=d.skeleton;a.push("#define NUM_BONE_INFLUENCERS "+d.numBoneInfluencers),d.numBoneInfluencers>0&&v.addCPUSkinningFallback(0,d),E.isUsingTextureForMatrices?a.push("#define BONETEXTURE"):a.push("#define BonesPerMesh "+(E.bones.length+1))}else a.push("#define NUM_BONE_INFLUENCERS 0");let x=d.morphTargetManager?ll(d.morphTargetManager,a,h,d,!0,u,!1,m,p,_):0;if(al(r,this._scene,a),t&&(a.push("#define INSTANCES"),mo(h),e.getRenderingMesh().hasThinInstances&&a.push("#define THIN_INSTANCES")),this.customShaderOptions&&this.customShaderOptions.defines)for(let E of this.customShaderOptions.defines)a.indexOf(E)===-1&&a.push(E);let A=d.bakedVertexAnimationManager;A&&A.isEnabled&&(a.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),t&&h.push("bakedVertexAnimationSettingsInstanced"));let S=a.join(` +`);if(f!==S){f=S;let E="shadowMap",R=["world","mBones","viewProjection","diffuseMatrix","lightDataSM","depthValuesSM","biasAndScaleSM","morphTargetInfluences","morphTargetCount","boneTextureInfo","softTransparentShadowSM","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture"],I=["diffuseSampler","boneSampler","morphTargets","bakedVertexAnimationTexture"],y=["Scene","Mesh"];if(wn(R),this.customShaderOptions){if(E=this.customShaderOptions.shaderName,this.customShaderOptions.attributes)for(let D of this.customShaderOptions.attributes)h.indexOf(D)===-1&&h.push(D);if(this.customShaderOptions.uniforms)for(let D of this.customShaderOptions.uniforms)R.indexOf(D)===-1&&R.push(D);if(this.customShaderOptions.samplers)for(let D of this.customShaderOptions.samplers)I.indexOf(D)===-1&&I.push(D)}let M=this._scene.getEngine();c=M.createEffect(E,{attributes:h,uniformsNames:R,uniformBuffersNames:y,samplers:I,defines:S,fallbacks:v,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:x},shaderLanguage:this._shaderLanguage},M),l.setEffect(c,f)}if(!c.isReady())return!1}return(this.useBlurExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(!this._blurPostProcesses||!this._blurPostProcesses.length)&&this._initializeBlurRTTAndPostProcesses(),!(this._kernelBlurXPostprocess&&!this._kernelBlurXPostprocess.isReady()||this._kernelBlurYPostprocess&&!this._kernelBlurYPostprocess.isReady()||this._boxBlurPostprocess&&!this._boxBlurPostprocess.isReady())}prepareDefines(e,t){let i=this._scene,r=this._light;!i.shadowsEnabled||!r.shadowEnabled||(e["SHADOW"+t]=!0,this.useContactHardeningShadow?(e["SHADOWPCSS"+t]=!0,this._filteringQuality===n.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===n.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePercentageCloserFiltering?(e["SHADOWPCF"+t]=!0,this._filteringQuality===n.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===n.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePoissonSampling?e["SHADOWPOISSON"+t]=!0:this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e["SHADOWESM"+t]=!0:(this.useCloseExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(e["SHADOWCLOSEESM"+t]=!0),r.needCube()&&(e["SHADOWCUBE"+t]=!0))}bindShadowLight(e,t){let i=this._light,r=this._scene;if(!r.shadowsEnabled||!i.shadowEnabled)return;let s=this._getCamera(),a=this.getShadowMap();if(!a)return;if(!i.needCube()){let l=r.floatingOriginOffset,c=this.getTransformMatrix(),f=r.floatingOriginMode?TC(l,this._viewMatrix,this._projectionMatrix,$.Matrix[0]):c;t.setMatrix("lightMatrix"+e,f)}let o=this.getShadowMapForRendering();this._filter===n.FILTER_PCF?(t.setDepthStencilTexture("shadowTexture"+e,o),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),a.getSize().width,1/a.getSize().width,this.frustumEdgeFalloff,e)):this._filter===n.FILTER_PCSS?(t.setDepthStencilTexture("shadowTexture"+e,o),t.setTexture("depthTexture"+e,o),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/a.getSize().width,this._contactHardeningLightSizeUVRatio*a.getSize().width,this.frustumEdgeFalloff,e)):(t.setTexture("shadowTexture"+e,o),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/a.getSize().width,this.depthScale,this.frustumEdgeFalloff,e)),i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(s),this.getLight().getDepthMinZ(s)+this.getLight().getDepthMaxZ(s),e)}get viewMatrix(){return this._viewMatrix}get projectionMatrix(){return this._projectionMatrix}getTransformMatrix(){let e=this._scene;if(this._currentRenderId===e.getRenderId()&&this._currentFaceIndexCache===this._currentFaceIndex)return this._transformMatrix;this._currentRenderId=e.getRenderId(),this._currentFaceIndexCache=this._currentFaceIndex;let t=this._light.position;if(this._light.computeTransformedInformation()&&(t=this._light.transformedPosition),b.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),Math.abs(b.Dot(this._lightDirection,b.Up()))===1&&(this._lightDirection.z=1e-13),this._light.needProjectionMatrixCompute()||!this._cachedPosition||!this._cachedDirection||!t.equals(this._cachedPosition)||!this._lightDirection.equals(this._cachedDirection)){this._cachedPosition.copyFrom(t),this._cachedDirection.copyFrom(this._lightDirection),K.LookAtLHToRef(t,t.add(this._lightDirection),b.Up(),this._viewMatrix);let i=this.getShadowMap();if(i){let r=i.renderList;r&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,r)}this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix)}return this._transformMatrix}recreateShadowMap(){let e=this._shadowMap;if(!e)return;let t=e.renderList;if(this._disposeRTTandPostProcesses(),this._initializeGenerator(),this.filter=this._filter,this._applyFilterValues(),t){this._shadowMap.renderList||(this._shadowMap.renderList=[]);for(let i of t)this._shadowMap.renderList.push(i)}else this._shadowMap.renderList=null}_disposeBlurPostProcesses(){this._shadowMap2&&(this._shadowMap2.dispose(),this._shadowMap2=null),this._boxBlurPostprocess&&(this._boxBlurPostprocess.dispose(),this._boxBlurPostprocess=null),this._kernelBlurXPostprocess&&(this._kernelBlurXPostprocess.dispose(),this._kernelBlurXPostprocess=null),this._kernelBlurYPostprocess&&(this._kernelBlurYPostprocess.dispose(),this._kernelBlurYPostprocess=null),this._blurPostProcesses=[]}_disposeRTTandPostProcesses(){this._shadowMap&&(this._shadowMap.dispose(),this._shadowMap=null),this._disposeBlurPostProcesses()}_disposeSceneUBOs(){if(this._sceneUBOs){for(let e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}dispose(e=!0){if(this._disposeRTTandPostProcesses(),this._disposeSceneUBOs(),this._light){if(this._light._shadowGenerators){let t=this._light._shadowGenerators.entries();for(let i=t.next();i.done!==!0;i=t.next()){let[r,s]=i.value;s===this&&this._light._shadowGenerators.delete(r)}this._light._shadowGenerators.size===0&&(this._light._shadowGenerators=null)}this._light._markMeshesAsLightDirty()}e&&(this.onBeforeShadowMapRenderMeshObservable.clear(),this.onBeforeShadowMapRenderObservable.clear(),this.onAfterShadowMapRenderMeshObservable.clear(),this.onAfterShadowMapRenderObservable.clear())}serialize(){var i;let e={},t=this.getShadowMap();if(!t)return e;if(e.className=this.getClassName(),e.lightId=this._light.id,e.cameraId=(i=this._camera)==null?void 0:i.id,e.id=this.id,e.mapSize=t.getRenderSize(),e.forceBackFacesOnly=this.forceBackFacesOnly,e.darkness=this.getDarkness(),e.transparencyShadow=this._transparencyShadow,e.frustumEdgeFalloff=this.frustumEdgeFalloff,e.bias=this.bias,e.normalBias=this.normalBias,e.usePercentageCloserFiltering=this.usePercentageCloserFiltering,e.useContactHardeningShadow=this.useContactHardeningShadow,e.contactHardeningLightSizeUVRatio=this.contactHardeningLightSizeUVRatio,e.filteringQuality=this.filteringQuality,e.useExponentialShadowMap=this.useExponentialShadowMap,e.useBlurExponentialShadowMap=this.useBlurExponentialShadowMap,e.useCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.useBlurCloseExponentialShadowMap=this.useBlurExponentialShadowMap,e.usePoissonSampling=this.usePoissonSampling,e.depthScale=this.depthScale,e.blurBoxOffset=this.blurBoxOffset,e.blurKernel=this.blurKernel,e.blurScale=this.blurScale,e.useKernelBlur=this.useKernelBlur,e.renderList=[],t.renderList)for(let r=0;r{throw qe("ShadowGeneratorSceneComponent")}});var rX={};tt(rX,{depthPixelShader:()=>Zle});var uD,iX,Zle,mD=C(()=>{k();vc();eR();Ec();uD="depthPixelShader",iX=`#ifdef ALPHATEST varying vec2 vUV;uniform sampler2D diffuseSampler; #endif #include @@ -10501,10 +10501,10 @@ gl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0); #endif #endif #endif -}`;T.ShadersStore[uD]||(T.ShadersStore[uD]=iX);Zle={name:uD,shader:iX}});var nX,Qle,sX=C(()=>{W();nX="pointCloudVertexDeclaration",Qle=`#ifdef POINTSIZE +}`;T.ShadersStore[uD]||(T.ShadersStore[uD]=iX);Zle={name:uD,shader:iX}});var nX,Qle,sX=C(()=>{k();nX="pointCloudVertexDeclaration",Qle=`#ifdef POINTSIZE uniform float pointSize; #endif -`;T.IncludesShadersStore[nX]||(T.IncludesShadersStore[nX]=Qle)});var oX={};tt(oX,{depthVertexShader:()=>$le});var pD,aX,$le,_D=C(()=>{W();dc();uc();Wf();Hf();mc();Ff();sX();zf();Xf();pc();_c();gc();vc();NP();pD="depthVertexShader",aX=`attribute vec3 position; +`;T.IncludesShadersStore[nX]||(T.IncludesShadersStore[nX]=Qle)});var oX={};tt(oX,{depthVertexShader:()=>$le});var pD,aX,$le,_D=C(()=>{k();hc();dc();kf();Wf();uc();wf();sX();Hf();zf();mc();pc();_c();gc();NP();pD="depthVertexShader",aX=`attribute vec3 position; #include #include #include @@ -10562,7 +10562,7 @@ vUV=vec2(diffuseMatrix*vec4(uv2Updated,1.0,0.0)); #endif #include } -`;T.ShadersStore[pD]||(T.ShadersStore[pD]=aX);$le={name:pD,shader:aX}});var cX={};tt(cX,{depthVertexShaderWGSL:()=>Jle});var gD,lX,Jle,fX=C(()=>{W();rc();nc();Uf();Vf();sc();wf();Gf();kf();ac();oc();lc();cc();gD="depthVertexShader",lX=`attribute position: vec3f; +`;T.ShadersStore[pD]||(T.ShadersStore[pD]=aX);$le={name:pD,shader:aX}});var cX={};tt(cX,{depthVertexShaderWGSL:()=>Jle});var gD,lX,Jle,fX=C(()=>{k();ic();rc();Bf();Uf();nc();Nf();Vf();Gf();sc();ac();oc();lc();gD="depthVertexShader",lX=`attribute position: vec3f; #include #include #include @@ -10618,7 +10618,7 @@ vertexOutputs.vUV= (uniforms.diffuseMatrix* vec4f(uv2Updated,1.0,0.0)).xy; #endif #endif } -`;T.ShadersStoreWGSL[gD]||(T.ShadersStoreWGSL[gD]=lX);Jle={name:gD,shader:lX}});var dX={};tt(dX,{depthPixelShaderWGSL:()=>ece});var vD,hX,ece,uX=C(()=>{W();fc();$x();hc();vD="depthPixelShader",hX=`#ifdef ALPHATEST +`;T.ShadersStoreWGSL[gD]||(T.ShadersStoreWGSL[gD]=lX);Jle={name:gD,shader:lX}});var dX={};tt(dX,{depthPixelShaderWGSL:()=>ece});var vD,hX,ece,uX=C(()=>{k();cc();Jx();fc();vD="depthPixelShader",hX=`#ifdef ALPHATEST varying vUV: vec2f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d; #endif #include @@ -10657,8 +10657,8 @@ fragmentOutputs.color= vec4f(input.vDepthMetric,0.0,0.0,1.0); #endif #endif #endif -}`;T.ShadersStoreWGSL[vD]||(T.ShadersStoreWGSL[vD]=hX);ece={name:vD,shader:hX}});var Qm,mX=C(()=>{zt();Gi();Fr();gf();sl();mD();_D();hn();ol();Un();Lf();Qm=class n{get shaderLanguage(){return this._shaderLanguage}get alphaBlendedDepth(){return this._alphaBlendedDepth}set alphaBlendedDepth(e){this._alphaBlendedDepth!==e&&(this._alphaBlendedDepth=e,this._alphaBlendedDepthMaterialCache.clear())}setMaterialForRendering(e,t){this._depthMap.setMaterialForRendering(e,t)}_ensureGaussianSplattingDepthMaterial(e,t){var s;let i=(s=e._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:s[t],r=this._alphaBlendedDepthMaterialCache.get(e.uniqueId);if(i===void 0||r!==this.alphaBlendedDepth){let a=e.material;if(!a)return null;let o=e.isCompound;i=a.makeDepthRenderingMaterial(this._scene,this._shaderLanguage,this.alphaBlendedDepth,o),this.setMaterialForRendering(e,i),this._alphaBlendedDepthMaterialCache.set(e.uniqueId,this.alphaBlendedDepth)}return i}constructor(e,t=1,i=null,r=!1,s=_e.TRILINEAR_SAMPLINGMODE,a=!1,o,l){this._shaderLanguage=0,this.enabled=!0,this.forceDepthWriteTransparentMeshes=!1,this._alphaBlendedDepth=!1,this._alphaBlendedDepthMaterialCache=new Map,this.useOnlyInActiveCamera=!1,this.reverseCulling=!1,this._shadersLoaded=!1,this._scene=e,this._storeNonLinearDepth=r,this._storeCameraSpaceZ=a,this.isPacked=t===0,this.isPacked?this.clearColor=new lt(1,1,1,1):this.clearColor=new lt(a?0:1,0,0,1),this._initShaderSourceAsync(),n._SceneComponentInitialization(this._scene);let c=e.getEngine();this._camera=i,s!==_e.NEAREST_SAMPLINGMODE&&(t===1&&!c._caps.textureFloatLinearFiltering&&(s=_e.NEAREST_SAMPLINGMODE),t===2&&!c._caps.textureHalfFloatLinearFiltering&&(s=_e.NEAREST_SAMPLINGMODE));let f=this.isPacked||!c._features.supportExtendedTextureFormats?5:6;this._depthMap=l!=null?l:new Br(o!=null?o:"DepthRenderer",{width:c.getRenderWidth(),height:c.getRenderHeight()},this._scene,!1,!0,t,!1,s,void 0,void 0,void 0,f),this._depthMap.wrapU=_e.CLAMP_ADDRESSMODE,this._depthMap.wrapV=_e.CLAMP_ADDRESSMODE,this._depthMap.refreshRate=1,this._depthMap.renderParticles=!1,this._depthMap.renderList=null,this._depthMap.noPrePassRenderer=!0,this._depthMap.activeCamera=this._camera,this._depthMap.ignoreCameraViewport=!0,this._depthMap.useCameraPostProcesses=!1,this._depthMap.onClearObservable.add(d=>{d.clear(this.clearColor,!0,!0,!0)}),this._depthMap.customIsReadyFunction=(d,u,m)=>{if((m||u===0)&&d.subMeshes)for(let p=0;p{var I;let u=d.getRenderingMesh(),m=d.getEffectiveMesh(),p=this._scene,_=p.getEngine(),g=d.getMaterial();if(m._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!g||m.infiniteDistance||g.disableDepthWrite||d.verticesCount===0||d._renderId===p.getRenderId())return;let v=m._getWorldMatrixDeterminant()<0,x=g._getEffectiveOrientation(u);v&&(x=x===0?1:0);let A=x===0;_.setState(g.backFaceCulling,0,!1,A,this.reverseCulling?!g.cullBackFaces:g.cullBackFaces);let S=u._getInstancesRenderList(d._id,!!d.getReplacementMesh());if(S.mustReturn)return;let E=_.getCaps().instancedArrays&&(S.visibleInstances[d._id]!==null&&S.visibleInstances[d._id]!==void 0||u.hasThinInstances),R=this._camera||p.activeCamera;if(this.isReady(d,E)&&R){if(d._renderId=p.getRenderId(),m.getClassName()==="GaussianSplattingMesh"){let U=this._ensureGaussianSplattingDepthMaterial(m,_.currentRenderPassId);if(U&&!U.isReadyForSubMesh(m,d,E))return;this.alphaBlendedDepth&&g.needAlphaBlendingForMesh(m)?_.setAlphaMode(2):_.setAlphaMode(0),m.render(d,!1);return}let M=(I=m._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:I[_.currentRenderPassId],D=d._getDrawWrapper();!D&&M&&(D=M._getDrawWrapper());let O=R.mode===ut.ORTHOGRAPHIC_CAMERA;if(!D)return;let V=D.effect;_.enableEffect(D),E||u._bind(d,V,g.fillMode),M?M.bindForSubMesh(m.getWorldMatrix(),m,d):(V.setMatrix("viewProjection",p.getTransformMatrix()),V.setMatrix("world",m.getWorldMatrix()),this._storeCameraSpaceZ&&V.setMatrix("view",p.getViewMatrix()));let N,F;if(O?(N=!_.useReverseDepthBuffer&&_.isNDCHalfZRange?0:1,F=_.useReverseDepthBuffer&&_.isNDCHalfZRange?0:1):(N=_.useReverseDepthBuffer&&_.isNDCHalfZRange?R.minZ:_.isNDCHalfZRange?0:R.minZ,F=_.useReverseDepthBuffer&&_.isNDCHalfZRange?0:R.maxZ),V.setFloat2("depthValues",N,N+F),!M){if(g.needAlphaTestingForMesh(m)){let k=g.getAlphaTestTexture();k&&(V.setTexture("diffuseSampler",k),V.setMatrix("diffuseMatrix",k.getTextureMatrix()))}bs(u,V),Fn(V,g,p),Bn(u,V),u.morphTargetManager&&u.morphTargetManager.isUsingTextureForTargets&&u.morphTargetManager._bind(V);let U=d.getMesh().bakedVertexAnimationManager;U&&U.isEnabled&&U.bind(V,E),g.pointsCloud&&V.setFloat("pointSize",g.pointSize)}this.alphaBlendedDepth&&g.needAlphaBlendingForMesh(m)?_.setAlphaMode(2):_.setAlphaMode(0),u._processRendering(m,d,V,g.fillMode,S,E,(U,k)=>V.setMatrix("world",k))}};this._depthMap.customRenderFunction=(d,u,m,p)=>{let _=this._scene.getEngine(),g=_.getAlphaMode(),v;if(p.length)for(v=0;v(fX(),cX)),Promise.resolve().then(()=>(uX(),dX))])):await Promise.all([Promise.resolve().then(()=>(_D(),oX)),Promise.resolve().then(()=>(mD(),rX))]),this._shadersLoaded=!0}isReady(e,t){var R,I;if(!this._shadersLoaded)return!1;let i=this._scene.getEngine(),r=e.getMesh(),s=r.getScene(),a=this._depthMap.renderPassId,o=(I=(R=r._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:R[a])!=null?I:null;if(r.getClassName()==="GaussianSplattingMesh"&&(o=this._ensureGaussianSplattingDepthMaterial(r,a)),o)return o.isReadyForSubMesh(r,e,t);let l=e.getMaterial();if(!l||l.disableDepthWrite)return!1;let c=[],f=[L.PositionKind],h=!1,d=!1,u=!1;l.needAlphaTestingForMesh(r)&&l.getAlphaTestTexture()&&(c.push("#define ALPHATEST"),r.isVerticesDataPresent(L.UVKind)&&(f.push(L.UVKind),c.push("#define UV1"),h=!0),r.isVerticesDataPresent(L.UV2Kind)&&(f.push(L.UV2Kind),c.push("#define UV2"),d=!0));let m=new Wn;if(r.useBones&&r.computeBonesUsingShaders&&r.skeleton){f.push(L.MatricesIndicesKind),f.push(L.MatricesWeightsKind),r.numBoneInfluencers>4&&(f.push(L.MatricesIndicesExtraKind),f.push(L.MatricesWeightsExtraKind)),c.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers),r.numBoneInfluencers>0&&m.addCPUSkinningFallback(0,r);let y=r.skeleton;y.isUsingTextureForMatrices?c.push("#define BONETEXTURE"):c.push("#define BonesPerMesh "+(y.bones.length+1))}else c.push("#define NUM_BONE_INFLUENCERS 0");let p=r.morphTargetManager?ll(r.morphTargetManager,c,f,r,!0,!1,!1,h,d,u):0;l.pointsCloud&&c.push("#define POINTSIZE"),t&&(c.push("#define INSTANCES"),mo(f),e.getRenderingMesh().hasThinInstances&&c.push("#define THIN_INSTANCES"));let _=r.bakedVertexAnimationManager;_&&_.isEnabled&&(c.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),t&&f.push("bakedVertexAnimationSettingsInstanced")),this._storeNonLinearDepth&&c.push("#define NONLINEARDEPTH"),this._storeCameraSpaceZ&&c.push("#define STORE_CAMERASPACE_Z"),this.isPacked&&c.push("#define PACKED"),al(l,s,c);let g=i.currentRenderPassId,x=this._depthMap.renderPassIds.includes(g)?g:this._depthMap.renderPassId,A=e._getDrawWrapper(x,!0),S=A.defines,E=c.join(` -`);if(S!==E){let y=["world","mBones","boneTextureInfo","pointSize","viewProjection","view","diffuseMatrix","depthValues","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture"],M=["diffuseSampler","morphTargets","boneSampler","bakedVertexAnimationTexture"];wn(y),A.setEffect(i.createEffect("depth",{attributes:f,uniformsNames:y,uniformBuffersNames:[],samplers:M,defines:E,fallbacks:m,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:p},shaderLanguage:this._shaderLanguage},i),E)}return A.effect.isReady()}getDepthMap(){return this._depthMap}dispose(){let e=[];for(let t in this._scene._depthRenderer)this._scene._depthRenderer[t]===this&&e.push(t);if(e.length>0){this._depthMap.dispose();for(let t of e)delete this._scene._depthRenderer[t]}}};Qm.ForceGLSL=!1;Qm._SceneComponentInitialization=n=>{throw Ze("DepthRendererSceneComponent")}});var _X={};tt(_X,{minmaxReduxPixelShaderWGSL:()=>tce});var ED,pX,tce,SD=C(()=>{W();ED="minmaxReduxPixelShader",pX=`varying vUV: vec2f;var textureSampler: texture_2d; +}`;T.ShadersStoreWGSL[vD]||(T.ShadersStoreWGSL[vD]=hX);ece={name:vD,shader:hX}});var Zm,mX=C(()=>{zt();ki();Fr();_f();sl();mD();_D();hn();ol();Un();Df();Zm=class n{get shaderLanguage(){return this._shaderLanguage}get alphaBlendedDepth(){return this._alphaBlendedDepth}set alphaBlendedDepth(e){this._alphaBlendedDepth!==e&&(this._alphaBlendedDepth=e,this._alphaBlendedDepthMaterialCache.clear())}setMaterialForRendering(e,t){this._depthMap.setMaterialForRendering(e,t)}_ensureGaussianSplattingDepthMaterial(e,t){var s;let i=(s=e._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:s[t],r=this._alphaBlendedDepthMaterialCache.get(e.uniqueId);if(i===void 0||r!==this.alphaBlendedDepth){let a=e.material;if(!a)return null;let o=e.isCompound;i=a.makeDepthRenderingMaterial(this._scene,this._shaderLanguage,this.alphaBlendedDepth,o),this.setMaterialForRendering(e,i),this._alphaBlendedDepthMaterialCache.set(e.uniqueId,this.alphaBlendedDepth)}return i}constructor(e,t=1,i=null,r=!1,s=ge.TRILINEAR_SAMPLINGMODE,a=!1,o,l){this._shaderLanguage=0,this.enabled=!0,this.forceDepthWriteTransparentMeshes=!1,this._alphaBlendedDepth=!1,this._alphaBlendedDepthMaterialCache=new Map,this.useOnlyInActiveCamera=!1,this.reverseCulling=!1,this._shadersLoaded=!1,this._scene=e,this._storeNonLinearDepth=r,this._storeCameraSpaceZ=a,this.isPacked=t===0,this.isPacked?this.clearColor=new lt(1,1,1,1):this.clearColor=new lt(a?0:1,0,0,1),this._initShaderSourceAsync(),n._SceneComponentInitialization(this._scene);let c=e.getEngine();this._camera=i,s!==ge.NEAREST_SAMPLINGMODE&&(t===1&&!c._caps.textureFloatLinearFiltering&&(s=ge.NEAREST_SAMPLINGMODE),t===2&&!c._caps.textureHalfFloatLinearFiltering&&(s=ge.NEAREST_SAMPLINGMODE));let f=this.isPacked||!c._features.supportExtendedTextureFormats?5:6;this._depthMap=l!=null?l:new Br(o!=null?o:"DepthRenderer",{width:c.getRenderWidth(),height:c.getRenderHeight()},this._scene,!1,!0,t,!1,s,void 0,void 0,void 0,f),this._depthMap.wrapU=ge.CLAMP_ADDRESSMODE,this._depthMap.wrapV=ge.CLAMP_ADDRESSMODE,this._depthMap.refreshRate=1,this._depthMap.renderParticles=!1,this._depthMap.renderList=null,this._depthMap.noPrePassRenderer=!0,this._depthMap.activeCamera=this._camera,this._depthMap.ignoreCameraViewport=!0,this._depthMap.useCameraPostProcesses=!1,this._depthMap.onClearObservable.add(d=>{d.clear(this.clearColor,!0,!0,!0)}),this._depthMap.customIsReadyFunction=(d,u,m)=>{if((m||u===0)&&d.subMeshes)for(let p=0;p{var I;let u=d.getRenderingMesh(),m=d.getEffectiveMesh(),p=this._scene,_=p.getEngine(),g=d.getMaterial();if(m._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!g||m.infiniteDistance||g.disableDepthWrite||d.verticesCount===0||d._renderId===p.getRenderId())return;let v=m._getWorldMatrixDeterminant()<0,x=g._getEffectiveOrientation(u);v&&(x=x===0?1:0);let A=x===0;_.setState(g.backFaceCulling,0,!1,A,this.reverseCulling?!g.cullBackFaces:g.cullBackFaces);let S=u._getInstancesRenderList(d._id,!!d.getReplacementMesh());if(S.mustReturn)return;let E=_.getCaps().instancedArrays&&(S.visibleInstances[d._id]!==null&&S.visibleInstances[d._id]!==void 0||u.hasThinInstances),R=this._camera||p.activeCamera;if(this.isReady(d,E)&&R){if(d._renderId=p.getRenderId(),m.getClassName()==="GaussianSplattingMesh"){let U=this._ensureGaussianSplattingDepthMaterial(m,_.currentRenderPassId);if(U&&!U.isReadyForSubMesh(m,d,E))return;this.alphaBlendedDepth&&g.needAlphaBlendingForMesh(m)?_.setAlphaMode(2):_.setAlphaMode(0),m.render(d,!1);return}let M=(I=m._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:I[_.currentRenderPassId],D=d._getDrawWrapper();!D&&M&&(D=M._getDrawWrapper());let O=R.mode===mt.ORTHOGRAPHIC_CAMERA;if(!D)return;let V=D.effect;_.enableEffect(D),E||u._bind(d,V,g.fillMode),M?M.bindForSubMesh(m.getWorldMatrix(),m,d):(V.setMatrix("viewProjection",p.getTransformMatrix()),V.setMatrix("world",m.getWorldMatrix()),this._storeCameraSpaceZ&&V.setMatrix("view",p.getViewMatrix()));let N,F;if(O?(N=!_.useReverseDepthBuffer&&_.isNDCHalfZRange?0:1,F=_.useReverseDepthBuffer&&_.isNDCHalfZRange?0:1):(N=_.useReverseDepthBuffer&&_.isNDCHalfZRange?R.minZ:_.isNDCHalfZRange?0:R.minZ,F=_.useReverseDepthBuffer&&_.isNDCHalfZRange?0:R.maxZ),V.setFloat2("depthValues",N,N+F),!M){if(g.needAlphaTestingForMesh(m)){let G=g.getAlphaTestTexture();G&&(V.setTexture("diffuseSampler",G),V.setMatrix("diffuseMatrix",G.getTextureMatrix()))}Rs(u,V),Fn(V,g,p),Bn(u,V),u.morphTargetManager&&u.morphTargetManager.isUsingTextureForTargets&&u.morphTargetManager._bind(V);let U=d.getMesh().bakedVertexAnimationManager;U&&U.isEnabled&&U.bind(V,E),g.pointsCloud&&V.setFloat("pointSize",g.pointSize)}this.alphaBlendedDepth&&g.needAlphaBlendingForMesh(m)?_.setAlphaMode(2):_.setAlphaMode(0),u._processRendering(m,d,V,g.fillMode,S,E,(U,G)=>V.setMatrix("world",G))}};this._depthMap.customRenderFunction=(d,u,m,p)=>{let _=this._scene.getEngine(),g=_.getAlphaMode(),v;if(p.length)for(v=0;v(fX(),cX)),Promise.resolve().then(()=>(uX(),dX))])):await Promise.all([Promise.resolve().then(()=>(_D(),oX)),Promise.resolve().then(()=>(mD(),rX))]),this._shadersLoaded=!0}isReady(e,t){var R,I;if(!this._shadersLoaded)return!1;let i=this._scene.getEngine(),r=e.getMesh(),s=r.getScene(),a=this._depthMap.renderPassId,o=(I=(R=r._internalAbstractMeshDataInfo._materialForRenderPass)==null?void 0:R[a])!=null?I:null;if(r.getClassName()==="GaussianSplattingMesh"&&(o=this._ensureGaussianSplattingDepthMaterial(r,a)),o)return o.isReadyForSubMesh(r,e,t);let l=e.getMaterial();if(!l||l.disableDepthWrite)return!1;let c=[],f=[L.PositionKind],h=!1,d=!1,u=!1;l.needAlphaTestingForMesh(r)&&l.getAlphaTestTexture()&&(c.push("#define ALPHATEST"),r.isVerticesDataPresent(L.UVKind)&&(f.push(L.UVKind),c.push("#define UV1"),h=!0),r.isVerticesDataPresent(L.UV2Kind)&&(f.push(L.UV2Kind),c.push("#define UV2"),d=!0));let m=new Wn;if(r.useBones&&r.computeBonesUsingShaders&&r.skeleton){f.push(L.MatricesIndicesKind),f.push(L.MatricesWeightsKind),r.numBoneInfluencers>4&&(f.push(L.MatricesIndicesExtraKind),f.push(L.MatricesWeightsExtraKind)),c.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers),r.numBoneInfluencers>0&&m.addCPUSkinningFallback(0,r);let y=r.skeleton;y.isUsingTextureForMatrices?c.push("#define BONETEXTURE"):c.push("#define BonesPerMesh "+(y.bones.length+1))}else c.push("#define NUM_BONE_INFLUENCERS 0");let p=r.morphTargetManager?ll(r.morphTargetManager,c,f,r,!0,!1,!1,h,d,u):0;l.pointsCloud&&c.push("#define POINTSIZE"),t&&(c.push("#define INSTANCES"),mo(f),e.getRenderingMesh().hasThinInstances&&c.push("#define THIN_INSTANCES"));let _=r.bakedVertexAnimationManager;_&&_.isEnabled&&(c.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),t&&f.push("bakedVertexAnimationSettingsInstanced")),this._storeNonLinearDepth&&c.push("#define NONLINEARDEPTH"),this._storeCameraSpaceZ&&c.push("#define STORE_CAMERASPACE_Z"),this.isPacked&&c.push("#define PACKED"),al(l,s,c);let g=i.currentRenderPassId,x=this._depthMap.renderPassIds.includes(g)?g:this._depthMap.renderPassId,A=e._getDrawWrapper(x,!0),S=A.defines,E=c.join(` +`);if(S!==E){let y=["world","mBones","boneTextureInfo","pointSize","viewProjection","view","diffuseMatrix","depthValues","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture"],M=["diffuseSampler","morphTargets","boneSampler","bakedVertexAnimationTexture"];wn(y),A.setEffect(i.createEffect("depth",{attributes:f,uniformsNames:y,uniformBuffersNames:[],samplers:M,defines:E,fallbacks:m,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:p},shaderLanguage:this._shaderLanguage},i),E)}return A.effect.isReady()}getDepthMap(){return this._depthMap}dispose(){let e=[];for(let t in this._scene._depthRenderer)this._scene._depthRenderer[t]===this&&e.push(t);if(e.length>0){this._depthMap.dispose();for(let t of e)delete this._scene._depthRenderer[t]}}};Zm.ForceGLSL=!1;Zm._SceneComponentInitialization=n=>{throw qe("DepthRendererSceneComponent")}});var _X={};tt(_X,{minmaxReduxPixelShaderWGSL:()=>tce});var ED,pX,tce,SD=C(()=>{k();ED="minmaxReduxPixelShader",pX=`varying vUV: vec2f;var textureSampler: texture_2d; #if defined(INITIAL) uniform texSize: vec2f;@fragment fn main(input: FragmentInputs)->FragmentOutputs {let coord=vec2i(fragmentInputs.vUV*(uniforms.texSize-1.0));let f1=textureLoad(textureSampler,coord,0).r;let f2=textureLoad(textureSampler,coord+vec2i(1,0),0).r;let f3=textureLoad(textureSampler,coord+vec2i(1,1),0).r;let f4=textureLoad(textureSampler,coord+vec2i(0,1),0).r; @@ -10687,7 +10687,7 @@ fn main(input: FragmentInputs)->FragmentOutputs {let coord=vec2i(fragmentInputs. fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=vec4f(0.);if (true) { discard;}} #endif -`;T.ShadersStoreWGSL[ED]||(T.ShadersStoreWGSL[ED]=pX);tce={name:ED,shader:pX}});var vX={};tt(vX,{minmaxReduxPixelShader:()=>ice});var TD,gX,ice,AD=C(()=>{W();TD="minmaxReduxPixelShader",gX=`varying vec2 vUV;uniform sampler2D textureSampler; +`;T.ShadersStoreWGSL[ED]||(T.ShadersStoreWGSL[ED]=pX);tce={name:ED,shader:pX}});var vX={};tt(vX,{minmaxReduxPixelShader:()=>ice});var TD,gX,ice,AD=C(()=>{k();TD="minmaxReduxPixelShader",gX=`varying vec2 vUV;uniform sampler2D textureSampler; #if defined(INITIAL) uniform vec2 texSize;void main(void) {ivec2 coord=ivec2(vUV*(texSize-1.0));float f1=texelFetch(textureSampler,coord,0).r;float f2=texelFetch(textureSampler,coord+ivec2(1,0),0).r;float f3=texelFetch(textureSampler,coord+ivec2(1,1),0).r;float f4=texelFetch(textureSampler,coord+ivec2(0,1),0).r; @@ -10716,12 +10716,12 @@ void main(void) {glFragColor=vec4(0.);if (true) { discard;}} #endif -`;T.ShadersStore[TD]||(T.ShadersStore[TD]=gX);ice={name:TD,shader:gX}});var EX,Yf,rce,nce,Eo,tR,SX=C(()=>{hi();kh();Pi();(function(n){n[n.NormalizedViewDepth=0]="NormalizedViewDepth",n[n.ViewDepth=1]="ViewDepth",n[n.ScreenDepth=2]="ScreenDepth"})(EX||(EX={}));Yf=class n extends zr{_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.resolve().then(()=>(SD(),_X)))):t.push(Promise.resolve().then(()=>(AD(),vX)))}constructor(e,t=null,i="",r){super({...r,name:e,engine:t||Le.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:n.FragmentUrl,uniforms:n.Uniforms,defines:i}),this.textureWidth=0,this.textureHeight=0}bind(e=!1){super.bind(e);let t=this.drawWrapper.effect;this.textureWidth===1||this.textureHeight===1?t.setInt2("texSize",this.textureWidth,this.textureHeight):t.setFloat2("texSize",this.textureWidth,this.textureHeight)}};Yf.FragmentUrl="minmaxRedux";Yf.Uniforms=["texSize"];rce=new Float32Array(4),nce=new Uint8Array(4),Eo={min:0,max:0},tR=class{get depthRedux(){return this._depthRedux}set depthRedux(e){this._depthRedux!==e&&(this._depthRedux=e,this._recreatePostProcesses())}get textureWidth(){return this._textureWidth}get textureHeight(){return this._textureHeight}constructor(e,t=!0){this.onAfterReductionPerformed=new ie,this._textureWidth=0,this._textureHeight=0,this._scene=e,this._depthRedux=t,this.reductionSteps=[]}setTextureDimensions(e,t,i=0){return e===this._textureWidth&&t===this._textureHeight&&i===this._depthTextureType?!1:(this._textureWidth=e,this._textureHeight=t,this._depthTextureType=i,this._recreatePostProcesses(),!0)}readMinMax(e){let t=e.type===1||e.type===2,i=t?rce:nce;this._scene.getEngine()._readTexturePixels(e,1,1,-1,0,i,!1),Eo.min=i[0],Eo.max=i[1],t||(Eo.min=Eo.min/255,Eo.max=Eo.max/255),Eo.min>=Eo.max&&(Eo.min=0,Eo.max=1),this.onAfterReductionPerformed.notifyObservers(Eo)}dispose(e=!0){e&&(this.onAfterReductionPerformed.clear(),this._textureWidth=0,this._textureHeight=0);for(let t=0;t{di();kh();Di();(function(n){n[n.NormalizedViewDepth=0]="NormalizedViewDepth",n[n.ViewDepth=1]="ViewDepth",n[n.ScreenDepth=2]="ScreenDepth"})(EX||(EX={}));Xf=class n extends zr{_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.resolve().then(()=>(SD(),_X)))):t.push(Promise.resolve().then(()=>(AD(),vX)))}constructor(e,t=null,i="",r){super({...r,name:e,engine:t||Oe.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:n.FragmentUrl,uniforms:n.Uniforms,defines:i}),this.textureWidth=0,this.textureHeight=0}bind(e=!1){super.bind(e);let t=this.drawWrapper.effect;this.textureWidth===1||this.textureHeight===1?t.setInt2("texSize",this.textureWidth,this.textureHeight):t.setFloat2("texSize",this.textureWidth,this.textureHeight)}};Xf.FragmentUrl="minmaxRedux";Xf.Uniforms=["texSize"];rce=new Float32Array(4),nce=new Uint8Array(4),Eo={min:0,max:0},iR=class{get depthRedux(){return this._depthRedux}set depthRedux(e){this._depthRedux!==e&&(this._depthRedux=e,this._recreatePostProcesses())}get textureWidth(){return this._textureWidth}get textureHeight(){return this._textureHeight}constructor(e,t=!0){this.onAfterReductionPerformed=new ie,this._textureWidth=0,this._textureHeight=0,this._scene=e,this._depthRedux=t,this.reductionSteps=[]}setTextureDimensions(e,t,i=0){return e===this._textureWidth&&t===this._textureHeight&&i===this._depthTextureType?!1:(this._textureWidth=e,this._textureHeight=t,this._depthTextureType=i,this._recreatePostProcesses(),!0)}readMinMax(e){let t=e.type===1||e.type===2,i=t?rce:nce;this._scene.getEngine()._readTexturePixels(e,1,1,-1,0,i,!1),Eo.min=i[0],Eo.max=i[1],t||(Eo.min=Eo.min/255,Eo.max=Eo.max/255),Eo.min>=Eo.max&&(Eo.min=0,Eo.max=1),this.onAfterReductionPerformed.notifyObservers(Eo)}dispose(e=!0){e&&(this.onAfterReductionPerformed.clear(),this._textureWidth=0,this._textureHeight=0);for(let t=0;t1||i>1;){t=Math.max(Math.round(t/2),1),i=Math.max(Math.round(i/2),1);let a=new Yf("Reduction phase "+s,e.getEngine(),"#define "+(t==1&&i==1?"LAST":t==1||i==1?"ONEBEFORELAST":"MAIN"));a.textureWidth=t,a.textureHeight=i,this.reductionSteps.push(a),s++}}}});var iR,TX=C(()=>{Kl();jT();SX();AD();SD();iR=class{get onAfterReductionPerformed(){return this._thinMinMaxReducer.onAfterReductionPerformed}constructor(e){this._onAfterUnbindObserver=null,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=e,this._postProcessManager=new Yl(e.getScene()),this._thinMinMaxReducer=new tR(e.getScene()),this._reductionSteps=[],this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add(()=>{this._postProcessManager._rebuild()})}get sourceTexture(){return this._sourceTexture}setSourceTexture(e,t,i=2,r=!0){if(e!==this._sourceTexture&&(this._thinMinMaxReducer.depthRedux=t,this.deactivate(),this._sourceTexture=e,this._forceFullscreenViewport=r,this._thinMinMaxReducer.setTextureDimensions(e.getRenderWidth(),e.getRenderHeight()))){this._disposePostProcesses();let s=this._thinMinMaxReducer.reductionSteps;for(let a=0;a{c.setTexture("textureSampler",this._sourceTexture)})),a===s.length-1&&this._reductionSteps[a-1].onAfterRenderObservable.add(()=>{this._thinMinMaxReducer.readMinMax(l.inputTexture.texture)})}}}get refreshRate(){return this._sourceTexture?this._sourceTexture.refreshRate:-1}set refreshRate(e){this._sourceTexture&&(this._sourceTexture.refreshRate=e)}get activated(){return this._activated}activate(){this._onAfterUnbindObserver||!this._sourceTexture||(this._onAfterUnbindObserver=this._sourceTexture.onAfterUnbindObservable.add(()=>{var t,i;let e=this._camera.getScene().getEngine();(t=e._debugPushGroup)==null||t.call(e,"min max reduction"),this._reductionSteps[0].activate(this._camera),this._postProcessManager.directRender(this._reductionSteps,this._reductionSteps[0].inputTexture,this._forceFullscreenViewport,0,0,!0,this._reductionSteps.length-1),e.unBindFramebuffer(this._reductionSteps[this._reductionSteps.length-1].inputTexture,!1),(i=e._debugPopGroup)==null||i.call(e)}),this._activated=!0)}deactivate(){!this._onAfterUnbindObserver||!this._sourceTexture||(this._sourceTexture.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=null,this._activated=!1)}dispose(e=!0){e&&(this.onAfterReductionPerformed.clear(),this._camera.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=void 0,this._disposePostProcesses(),this._postProcessManager.dispose(),this._postProcessManager=void 0,this._thinMinMaxReducer.dispose(),this._thinMinMaxReducer=void 0,this._sourceTexture=null)}_disposePostProcesses(){for(let e=0;e{mX();TX();rR=class extends iR{get depthRenderer(){return this._depthRenderer}constructor(e){super(e)}setDepthRenderer(e=null,t=2,i=!0){let r=this._camera.getScene();this._depthRenderer&&(delete r._depthRenderer[this._depthRendererId],this._depthRenderer.dispose(),this._depthRenderer=null),e===null&&(r._depthRenderer||(r._depthRenderer={}),this._depthRendererId="minmax_"+this._camera.uniqueId,e=this._depthRenderer=new Qm(r,t,this._camera,!1,1,!1,`DepthRenderer ${this._depthRendererId}`),e.enabled=!1,r._depthRenderer[this._depthRendererId]=e),super.setSourceTexture(e.getDepthMap(),!0,t,i)}setSourceTexture(e,t,i=2,r=!0){super.setSourceTexture(e,t,i,r)}activate(){this._depthRenderer&&(this._depthRenderer.enabled=!0),super.activate()}deactivate(){super.deactivate(),this._depthRenderer&&(this._depthRenderer.enabled=!1)}dispose(e=!0){super.dispose(e),this._depthRenderer&&e&&(this._depthRenderer.dispose(),this._depthRenderer=null)}}});var xX,sce,Rr,$m,nR,So,RX=C(()=>{Ve();gf();hn();eR();pm();AX();yt();Pi();J_();xX=b.Up(),sce=b.Zero(),Rr=new b,$m=new b,nR=new j,So=class n extends Mi{_validateFilter(e){return e===Mi.FILTER_NONE||e===Mi.FILTER_PCF||e===Mi.FILTER_PCSS?e:(te.Error('Unsupported filter "'+e+'"!'),Mi.FILTER_NONE)}get numCascades(){return this._numCascades}set numCascades(e){e=Math.min(Math.max(e,n.MIN_CASCADES_COUNT),n.MAX_CASCADES_COUNT),e!==this._numCascades&&(this._numCascades=e,this.recreateShadowMap(),this._recreateSceneUBOs())}get freezeShadowCastersBoundingInfo(){return this._freezeShadowCastersBoundingInfo}set freezeShadowCastersBoundingInfo(e){this._freezeShadowCastersBoundingInfoObservable&&e&&(this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable),this._freezeShadowCastersBoundingInfoObservable=null),!this._freezeShadowCastersBoundingInfoObservable&&!e&&(this._freezeShadowCastersBoundingInfoObservable=this._scene.onBeforeRenderObservable.add(()=>this._computeShadowCastersBoundingInfo())),this._freezeShadowCastersBoundingInfo=e,e&&this._computeShadowCastersBoundingInfo()}_computeShadowCastersBoundingInfo(){if(this._scbiMin.copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._scbiMax.copyFromFloats(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),this._shadowMap&&this._shadowMap.renderList){let e=this._shadowMap.renderList;for(let t=0;tt&&(e=0,t=1),e<0&&(e=0),t>1&&(t=1),this._minDistance=e,this._maxDistance=t,this._breaksAreDirty=!0)}get minDistance(){return this._minDistance}get maxDistance(){return this._maxDistance}getClassName(){return n.CLASSNAME}getCascadeMinExtents(e){return e>=0&&e=0&&et.maxZ&&t.maxZ!==0||(this._shadowMaxZ=e,this._light._markMeshesAsLightDirty(),this._breaksAreDirty=!0)}get debug(){return this._debug}set debug(e){this._debug=e,this._light._markMeshesAsLightDirty()}get depthClamp(){return this._depthClamp}set depthClamp(e){this._depthClamp=e}get cascadeBlendPercentage(){return this._cascadeBlendPercentage}set cascadeBlendPercentage(e){this._cascadeBlendPercentage=e,this._light._markMeshesAsLightDirty()}get lambda(){return this._lambda}set lambda(e){let t=Math.min(Math.max(e,0),1);this._lambda!=t&&(this._lambda=t,this._breaksAreDirty=!0)}getCascadeViewMatrix(e){return e>=0&&e=0&&e=0&&e{let r=i.min,s=i.max;r>=s&&(r=0,s=1),(r!=this._minDistance||s!=this._maxDistance)&&this.setMinMaxDistance(r,s)}),this._depthReducer.setDepthRenderer(this._depthRenderer)),this._depthReducer.activate()}}get autoCalcDepthBoundsRefreshRate(){var e,t,i;return(i=(t=(e=this._depthReducer)==null?void 0:e.depthRenderer)==null?void 0:t.getDepthMap().refreshRate)!=null?i:-1}set autoCalcDepthBoundsRefreshRate(e){var t;(t=this._depthReducer)!=null&&t.depthRenderer&&(this._depthReducer.depthRenderer.getDepthMap().refreshRate=e)}splitFrustum(){this._breaksAreDirty=!0}_splitFrustum(){let e=this._getCamera();if(!e)return;let t=e.minZ,i=e.maxZ||this._shadowMaxZ,r=i-t,s=this._minDistance,a=this._shadowMaxZ=t?Math.min((this._shadowMaxZ-t)/(i-t),this._maxDistance):this._maxDistance,o=t+s*r,l=t+a*r,c=l-o,f=l/o;for(let h=0;ha||(!this._depthClamp||this.filter===Mi.FILTER_PCSS?(s=Math.min(s,l),this.filter!==Mi.FILTER_PCSS&&(a=Math.min(a,c))):(a=Math.min(a,c),s=Math.max(s,l),a=Math.max(s+1,a))),j.OrthoOffCenterLHToRef(this._cascadeMinExtents[r].x,this._cascadeMaxExtents[r].x,this._cascadeMinExtents[r].y,this._cascadeMaxExtents[r].y,i?a:s,i?s:a,this._projectionMatrices[r],e.getEngine().isNDCHalfZRange),this._cascadeMinExtents[r].z=s,this._cascadeMaxExtents[r].z=a,this._viewMatrices[r].multiplyToRef(this._projectionMatrices[r],this._transformMatrices[r]),b.TransformCoordinatesToRef(sce,this._transformMatrices[r],Rr),Rr.scaleInPlace(this._mapSize/2),$m.copyFromFloats(Math.round(Rr.x),Math.round(Rr.y),Math.round(Rr.z)),$m.subtractInPlace(Rr).scaleInPlace(2/this._mapSize),j.TranslationToRef($m.x,$m.y,0,nR),this._projectionMatrices[r].multiplyToRef(nR,this._projectionMatrices[r]),this._viewMatrices[r].multiplyToRef(this._projectionMatrices[r],this._transformMatrices[r]),this._transformMatrices[r].copyToArray(this._transformMatricesAsArray,r*16)}}_computeFrustumInWorldSpace(e){let t=this._getCamera();if(!t)return;let i=this._cascades[e].prevBreakDistance,r=this._cascades[e].breakDistance,s=this._scene.getEngine().isNDCHalfZRange;t.getViewMatrix();let a=t.maxZ===0,o=t.maxZ;a&&(t.maxZ=this._shadowMaxZ,t.getProjectionMatrix(!0));let l=j.Invert(t.getTransformationMatrix());a&&(t.maxZ=o,t.getProjectionMatrix(!0));let c=this._scene.getEngine().useReverseDepthBuffer?4:0;for(let f=0;f{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[t]),this._currentLayer=t,this._filter===Mi.FILTER_PCF&&e.setColorWrite(!1),Ia.eyeAtCamera=!1,this._scene.setTransformMatrix(this.getCascadeViewMatrix(t),this.getCascadeProjectionMatrix(t)),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())}),this._shadowMap.onBeforeBindObservable.add(()=>{var t;this._currentSceneUBO=this._scene.getSceneUniformBuffer(),e._enableGPUDebugMarkers&&((t=e._debugPushGroup)==null||t.call(e,`Cascaded shadow map generation for pass id ${e.currentRenderPassId}`)),this._breaksAreDirty&&this._splitFrustum(),this._computeMatrices()}),this._splitFrustum()}_bindCustomEffectForRenderSubMeshForShadowMap(e,t){t.setMatrix("viewProjection",this.getCascadeTransformMatrix(this._currentLayer))}_isReadyCustomDefines(e){e.push("#define SM_DEPTHCLAMP "+(this._depthClamp&&this._filter!==Mi.FILTER_PCSS?"1":"0"))}prepareDefines(e,t){super.prepareDefines(e,t);let i=this._scene,r=this._light;if(!i.shadowsEnabled||!r.shadowEnabled)return;e["SHADOWCSM"+t]=!0,e["SHADOWCSMDEBUG"+t]=this.debug,e["SHADOWCSMNUM_CASCADES"+t]=this.numCascades,e["SHADOWCSM_RIGHTHANDED"+t]=i.useRightHandedSystem;let s=this._getCamera();s&&this._shadowMaxZ<=(s.maxZ||this._shadowMaxZ)&&(e["SHADOWCSMUSESHADOWMAXZ"+t]=!0),this.cascadeBlendPercentage===0&&(e["SHADOWCSMNOBLEND"+t]=!0)}bindShadowLight(e,t){let i=this._light,r=this._scene;if(!r.shadowsEnabled||!i.shadowEnabled)return;let s=this._getCamera();if(!s)return;let a=this.getShadowMap();if(!a)return;let o=a.getSize().width,l=this._transformMatricesAsArray,c=r.floatingOriginMode?OB(this._scene.floatingOriginOffset,this._viewMatrices,this._projectionMatrices,this._numCascades,this._tempTransformMatricesAsArray):l;if(t.setMatrices("lightMatrix"+e,c),t.setArray("viewFrustumZ"+e,this._viewSpaceFrustumsZ),t.setFloat("cascadeBlendFactor"+e,this.cascadeBlendPercentage===0?1e4:1/this.cascadeBlendPercentage),t.setArray("frustumLengths"+e,this._frustumLengths),this._filter===Mi.FILTER_PCF)t.setDepthStencilTexture("shadowTexture"+e,a),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),o,1/o,this.frustumEdgeFalloff,e);else if(this._filter===Mi.FILTER_PCSS){for(let f=0;fnew n(r,s,void 0,a));return e.numCascades!==void 0&&(i.numCascades=e.numCascades),e.debug!==void 0&&(i.debug=e.debug),e.stabilizeCascades!==void 0&&(i.stabilizeCascades=e.stabilizeCascades),e.lambda!==void 0&&(i.lambda=e.lambda),e.cascadeBlendPercentage!==void 0&&(i.cascadeBlendPercentage=e.cascadeBlendPercentage),e.depthClamp!==void 0&&(i.depthClamp=e.depthClamp),e.autoCalcDepthBounds!==void 0&&(i.autoCalcDepthBounds=e.autoCalcDepthBounds),e.shadowMaxZ!==void 0&&(i.shadowMaxZ=e.shadowMaxZ),e.penumbraDarkness!==void 0&&(i.penumbraDarkness=e.penumbraDarkness),e.freezeShadowCastersBoundingInfo!==void 0&&(i.freezeShadowCastersBoundingInfo=e.freezeShadowCastersBoundingInfo),e.minDistance!==void 0&&e.maxDistance!==void 0&&i.setMinMaxDistance(e.minDistance,e.maxDistance),i}};So._FrustumCornersNdcSpace=[new b(-1,1,-1),new b(1,1,-1),new b(1,-1,-1),new b(-1,-1,-1),new b(-1,1,1),new b(1,1,1),new b(1,-1,1),new b(-1,-1,1)];So.CLASSNAME="CascadedShadowGenerator";So.DEFAULT_CASCADES_COUNT=4;So.MIN_CASCADES_COUNT=2;So.MAX_CASCADES_COUNT=4;So._SceneComponentInitialization=n=>{throw Ze("ShadowGeneratorSceneComponent")}});function sR(n,e){ace[n]=e}var ace,xD=C(()=>{ace={}});var RD,bX=C(()=>{eR();RX();om();xD();sR($e.NAME_SHADOWGENERATOR,(n,e)=>{if(n.shadowGenerators!==void 0&&n.shadowGenerators!==null)for(let t=0,i=n.shadowGenerators.length;t{let e=n._getComponent($e.NAME_SHADOWGENERATOR);e||(e=new RD(n),n._addComponent(e))}});async function IX(n,e){let t=e.method||"GET";return await new Promise((i,r)=>{let s=new Ir;s.addEventListener("readystatechange",()=>{if(s.readyState==4)if(s.status==200){let a={};if(e.responseHeaders)for(let o of e.responseHeaders)a[o]=s.getResponseHeader(o)||"";i({response:s.response,headerValues:a})}else r(`Unable to fetch data from ${n}. Error code: ${s.status}`)}),s.open(t,n),s.send()})}var MX=C(()=>{Bh()});function oce(n){return!!n.createPlugin}function lce(n){return!!n.name}function aR(){return dl[".babylon"]}function cce(n){for(let e in dl){let t=dl[e];if(t.mimeType===n)return t}}function ID(n,e){let t=dl[n];return t||(te.Warn("Unable to find a plugin to load "+n+" files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: https://doc.babylonjs.com/features/featuresDeepDive/importers/loadingFileTypes"),e?aR():void 0)}function fce(n){return!!dl[n]}function hce(n){for(let e in dl){let t=dl[e].plugin;if(t.canDirectLoad&&t.canDirectLoad(n))return dl[e]}return aR()}function dce(n){let e=n.indexOf("?");e!==-1&&(n=n.substring(0,e));let t=n.lastIndexOf(".");return n.substring(t,n.length).toLowerCase()}function uce(n){return n.substring(0,5)==="data:"?n.substring(5):null}function MD(n,e,t){let r="Unable to load from "+(n.rawData?"binary data":n.url);return e?r+=`: ${e}`:t&&(r+=`: ${t}`),r}async function CD(n,e,t,i,r,s,a,o,l){var u;let c=uce(n.url);if(n.rawData&&!a)throw"When using ArrayBufferView to load data the file extension must be provided.";let f=!c&&!a?dce(n.url):"",h=a?ID(a,!0):c?hce(n.url):ID(f,!1);if(!h&&f){if(n.url&&!n.url.startsWith("blob:")){let m=await IX(n.url,{method:"HEAD",responseHeaders:["Content-Type"]}),p=m.headerValues?m.headerValues["Content-Type"]:"";p&&(h=cce(p))}h||(h=aR())}if(!h)throw new Error(`No plugin or fallback for ${a!=null?a:n.url}`);if(((u=l==null?void 0:l[h.plugin.name])==null?void 0:u.enabled)===!1)throw new Error(`The '${h.plugin.name}' plugin is disabled via the loader options passed to the loading operation.`);if(n.rawData&&!h.isBinary)throw"Loading from ArrayBufferView can not be used with plugins that don't support binary loading.";return(m=>{if(oce(h.plugin)){let _=h.plugin.createPlugin(l!=null?l:{});return _ instanceof Promise?(_.then(m).catch(g=>{r("Error instantiating plugin.",g)}),null):(m(_),_)}else return m(h.plugin),h.plugin})(m=>{var E;if(!m)throw`The loader plugin corresponding to the '${a}' file type has not been found. If using es6, please import the plugin you wish to use before.`;if(yX.notifyObservers(m),c&&(m.canDirectLoad&&m.canDirectLoad(n.url)||!hf(n.url))){if(m.directLoad){let R=m.directLoad(e,c);R instanceof Promise?R.then(I=>{t(m,I)}).catch(I=>{r("Error in directLoad of _loadData: "+I,I)}):t(m,R)}else t(m,c);return}let p=h.isBinary,_=(R,I)=>{if(e.isDisposed){r("Scene has been disposed");return}t(m,R,I)},g=null,v=!1;(E=m.onDisposeObservable)==null||E.add(()=>{v=!0,g&&(g.abort(),g=null),s()});let x=()=>{if(v)return;let R=(I,y)=>{r(I==null?void 0:I.statusText,y)};if(!m.loadFile&&n.rawData)throw"Plugin does not support loading ArrayBufferView.";g=m.loadFile?m.loadFile(e,n.rawData||n.file||n.url,n.rootUrl,_,i,p,R,o):e._loadFile(n.file||n.url,_,i,!0,p,R)},A=e.getEngine(),S=A.enableOfflineSupport;if(S){let R=!1;for(let I of e.disableOfflineSupportExceptionRules)if(I.test(n.url)){R=!0;break}S=!R}S&&Ie.OfflineProviderFactory?e.offlineProvider=Ie.OfflineProviderFactory(n.url,x,A.disableManifestCheck):x()})}function yD(n,e){let t,i,r=null,s=null;if(!e)t=n,i=pe.GetFilename(n),n=pe.GetFolderPath(n);else if(lce(e))t=`file:${e.name}`,i=e.name,r=e;else if(ArrayBuffer.isView(e))t="",i=cf(),s=e;else if(e.startsWith("data:"))t=e,i="";else if(n){let a=e;if(a.substring(0,1)==="/")return pe.Error("Wrong sceneFilename parameter"),null;t=n+a,i=a}else t=e,i=pe.GetFilename(e),n=pe.GetFolderPath(e);return{url:t,rootUrl:n,name:i,file:r,rawData:s}}function Kf(n){if(typeof n.extensions=="string"){let e=n.extensions;dl[e.toLowerCase()]={plugin:n,isBinary:!1}}else{let e=n.extensions,t=Object.keys(e);for(let i of t)dl[i.toLowerCase()]={plugin:n,isBinary:e[i].isBinary,mimeType:e[i].mimeType}}}async function Bg(n,e,t){let{meshNames:i,rootUrl:r="",onProgress:s,pluginExtension:a,name:o,pluginOptions:l}=t!=null?t:{};return await DX(i,r,n,e,s,a,o,l)}async function PX(n,e,t="",i=Le.LastCreatedScene,r=null,s=null,a=null,o=null,l="",c={}){if(!i)return te.Error("No scene available to import mesh to"),null;let f=yD(e,t);if(!f)return null;let h={};i.addPendingData(h);let d=()=>{i.removePendingData(h)},u=(_,g)=>{let v=MD(f,_,g);a?a(i,v,new As(v,Sa.SceneLoaderError,g)):te.Error(v),d()},m=s?_=>{try{s(_)}catch(g){u("Error in onProgress callback: "+g,g)}}:void 0,p=(_,g,v,x,A,S,E,R)=>{if(i.importedMeshesFiles.push(f.url),r)try{r(_,g,v,x,A,S,E,R)}catch(I){u("Error in onSuccess callback: "+I,I)}i.removePendingData(h)};return await CD(f,i,(_,g,v)=>{if(_.rewriteRootURL&&(f.rootUrl=_.rewriteRootURL(f.rootUrl,v)),_.importMesh){let x=_,A=[],S=[],E=[];if(!x.importMesh(n,i,g,f.rootUrl,A,S,E,u))return;i.loadingPluginName=_.name,p(A,S,E,[],[],[],[],[])}else _.importMeshAsync(n,i,g,f.rootUrl,m,f.name).then(A=>{i.loadingPluginName=_.name,p(A.meshes,A.particleSystems,A.skeletons,A.animationGroups,A.transformNodes,A.geometries,A.lights,A.spriteManagers)}).catch(A=>{u(A.message,A)})},m,u,d,o,l,c)}async function DX(n,e,t,i,r,s,a,o){return await new Promise((l,c)=>{try{PX(n,e,t,i,(f,h,d,u,m,p,_,g)=>{l({meshes:f,particleSystems:h,skeletons:d,animationGroups:u,transformNodes:m,geometries:p,lights:_,spriteManagers:g})},r,(f,h,d)=>{c(d||new Error(h))},s,a,o).catch(c)}catch(f){c(f)}})}async function LX(n,e="",t=Le.LastCreatedEngine,i=null,r=null,s=null,a=null,o="",l={}){if(!t){pe.Error("No engine available");return}await PD(n,e,new $t(t),i,r,s,a,o,l)}async function mce(n,e,t,i,r,s,a){return await new Promise((o,l)=>{LX(n,e,t,c=>{o(c)},i,(c,f,h)=>{l(h||new Error(f))},r,s,a)})}async function PD(n,e="",t=Le.LastCreatedScene,i=null,r=null,s=null,a=null,o="",l={}){if(!t)return te.Error("No scene available to append to"),null;let c=yD(n,e);if(!c)return null;let f={};t.addPendingData(f);let h=()=>{t.removePendingData(f)};Xr.ShowLoadingScreen&&!bD&&(bD=!0,t.getEngine().displayLoadingUI(),t.executeWhenReady(()=>{t.getEngine().hideLoadingUI(),bD=!1}));let d=(p,_)=>{let g=MD(c,p,_);s?s(t,g,new As(g,Sa.SceneLoaderError,_)):te.Error(g),h()},u=r?p=>{try{r(p)}catch(_){d("Error in onProgress callback",_)}}:void 0,m=()=>{if(i)try{i(t)}catch(p){d("Error in onSuccess callback",p)}t.removePendingData(f)};return await CD(c,t,(p,_)=>{if(p.load){if(!p.load(t,_,c.rootUrl,d))return;t.loadingPluginName=p.name,m()}else p.loadAsync(t,_,c.rootUrl,u,c.name).then(()=>{t.loadingPluginName=p.name,m()}).catch(v=>{d(v.message,v)})},u,d,h,a,o,l)}async function pce(n,e,t,i,r,s,a){return await new Promise((o,l)=>{try{PD(n,e,t,c=>{o(c)},i,(c,f,h)=>{l(h||new Error(f))},r,s,a).catch(l)}catch(c){l(c)}})}async function DD(n,e="",t=Le.LastCreatedScene,i=null,r=null,s=null,a=null,o="",l={}){if(!t)return te.Error("No scene available to load asset container to"),null;let c=yD(n,e);if(!c)return null;let f={};t.addPendingData(f);let h=()=>{t.removePendingData(f)},d=(p,_)=>{let g=MD(c,p,_);s?s(t,g,new As(g,Sa.SceneLoaderError,_)):te.Error(g),h()},u=r?p=>{try{r(p)}catch(_){d("Error in onProgress callback",_)}}:void 0,m=p=>{if(i)try{i(p)}catch(_){d("Error in onSuccess callback",_)}t.removePendingData(f)};return await CD(c,t,(p,_)=>{if(p.loadAssetContainer){let v=p.loadAssetContainer(t,_,c.rootUrl,d);if(!v)return;v.populateRootNodes(),t.loadingPluginName=p.name,m(v)}else p.loadAssetContainerAsync?p.loadAssetContainerAsync(t,_,c.rootUrl,u,c.name).then(v=>{v.populateRootNodes(),t.loadingPluginName=p.name,m(v)}).catch(v=>{d(v.message,v)}):d("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")},u,d,h,a,o,l)}async function _ce(n,e,t,i,r,s,a){return await new Promise((o,l)=>{try{DD(n,e,t,c=>{o(c)},i,(c,f,h)=>{l(h||new Error(f))},r,s,a).catch(l)}catch(c){l(c)}})}async function OX(n,e="",t=Le.LastCreatedScene,i=!0,r=0,s=null,a=null,o=null,l=null,c=null,f="",h={}){if(!t){te.Error("No scene available to load animations to");return}if(i){for(let _ of t.animatables)_.reset();t.stopAllAnimations();let m=t.animationGroups.slice();for(let _ of m)_.dispose();let p=t.getNodes();for(let _ of p)_.animations&&(_.animations=[])}else switch(r){case 0:let m=t.animationGroups.slice();for(let p of m)p.dispose();break;case 1:for(let p of t.animationGroups)p.stop();break;case 2:for(let p of t.animationGroups)p.reset(),p.restart();break;case 3:break;default:te.Error("Unknown animation group loading mode value '"+r+"'");return}let d=t.animatables.length;await DD(n,e,t,m=>{m.mergeAnimationsTo(t,t.animatables.slice(d),s),m.dispose(),t.onAnimationFileImportedObservable.notifyObservers(t),a&&a(t)},o,l,c,f,h)}async function gce(n,e,t,i,r,s,a,o,l,c){return await new Promise((f,h)=>{try{OX(n,e,t,i,r,s,d=>{f(d)},a,(d,u,m)=>{h(m||new Error(u))},o,l,c).catch(h)}catch(d){h(d)}})}var CX,yX,dl,bD,ad,Jm=C(()=>{bi();hi();xs();Pi();yt();MA();Hl();U_();B_();wr();MX();(function(n){n[n.Clean=0]="Clean",n[n.Stop=1]="Stop",n[n.Sync=2]="Sync",n[n.NoSync=3]="NoSync"})(CX||(CX={}));yX=new ie,dl={},bD=!1;ad=class{static get ForceFullSceneLoadingForIncremental(){return Xr.ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){Xr.ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return Xr.ShowLoadingScreen}static set ShowLoadingScreen(e){Xr.ShowLoadingScreen=e}static get loggingLevel(){return Xr.loggingLevel}static set loggingLevel(e){Xr.loggingLevel=e}static get CleanBoneMatrixWeights(){return Xr.CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){Xr.CleanBoneMatrixWeights=e}static GetDefaultPlugin(){return aR()}static GetPluginForExtension(e){var t;return(t=ID(e,!0))==null?void 0:t.plugin}static IsPluginForExtensionAvailable(e){return fce(e)}static RegisterPlugin(e){Kf(e)}static ImportMesh(e,t,i,r,s,a,o,l,c,f){PX(e,t,i,r,s,a,o,l,c,f).catch(h=>o==null?void 0:o(Le.LastCreatedScene,h==null?void 0:h.message,h))}static async ImportMeshAsync(e,t,i,r,s,a,o){return await DX(e,t,i,r,s,a,o)}static Load(e,t,i,r,s,a,o,l){LX(e,t,i,r,s,a,o,l).catch(c=>a==null?void 0:a(Le.LastCreatedScene,c==null?void 0:c.message,c))}static async LoadAsync(e,t,i,r,s,a){return await mce(e,t,i,r,s,a)}static Append(e,t,i,r,s,a,o,l){PD(e,t,i,r,s,a,o,l).catch(c=>a==null?void 0:a(i!=null?i:Le.LastCreatedScene,c==null?void 0:c.message,c))}static async AppendAsync(e,t,i,r,s,a){return await pce(e,t,i,r,s,a)}static LoadAssetContainer(e,t,i,r,s,a,o,l){DD(e,t,i,r,s,a,o,l).catch(c=>a==null?void 0:a(i!=null?i:Le.LastCreatedScene,c==null?void 0:c.message,c))}static async LoadAssetContainerAsync(e,t,i,r,s,a){return await _ce(e,t,i,r,s,a)}static ImportAnimations(e,t,i,r,s,a,o,l,c,f,h){OX(e,t,i,r,s,a,o,l,c,f,h).catch(d=>c==null?void 0:c(i!=null?i:Le.LastCreatedScene,d==null?void 0:d.message,d))}static async ImportAnimationsAsync(e,t,i,r,s,a,o,l,c,f,h){return await gce(e,t,i,r,s,a,l,f,h)}};ad.NO_LOGGING=0;ad.MINIMAL_LOGGING=1;ad.SUMMARY_LOGGING=2;ad.DETAILED_LOGGING=3;ad.OnPluginActivatedObservable=yX});var oR,LD,OD,ul,Ug=C(()=>{Ii();qh();gm();yt();Pi();Qy();Pf();sl();bi();uf();oR=class{constructor(){this.rootNodes=[],this.cameras=[],this.lights=[],this.meshes=[],this.skeletons=[],this.particleSystems=[],this.animations=[],this.animationGroups=[],this.multiMaterials=[],this.materials=[],this.morphTargetManagers=[],this.geometries=[],this.transformNodes=[],this.actionManagers=[],this.textures=[],this._environmentTexture=null,this.postProcesses=[],this.sounds=null,this.effectLayers=[],this.layers=[],this.reflectionProbes=[],this.spriteManagers=[]}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e}getNodes(){let e=[];e=e.concat(this.meshes),e=e.concat(this.lights),e=e.concat(this.cameras),e=e.concat(this.transformNodes);for(let t of this.skeletons)e=e.concat(t.bones);return e}},LD=class extends oR{},OD=class{constructor(){this.rootNodes=[],this.skeletons=[],this.animationGroups=[]}dispose(){let e=this.rootNodes;for(let r of e)r.dispose();e.length=0;let t=this.skeletons;for(let r of t)r.dispose();t.length=0;let i=this.animationGroups;for(let r of i)r.dispose();i.length=0}},ul=class extends oR{constructor(e){super(),this._wasAddedToScene=!1,e=e||Le.LastCreatedScene,e&&(this.scene=e,this.proceduralTextures=[],e.onDisposeObservable.add(()=>{this._wasAddedToScene||this.dispose()}),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add(()=>{for(let t of this.geometries)t._rebuild();for(let t of this.meshes)t._rebuild();for(let t of this.particleSystems)t.rebuild();for(let t of this.textures)t._rebuild();for(let t of this.spriteManagers)t.rebuild()}))}_topologicalSort(e){let t=new Map;for(let o of e)t.set(o.uniqueId,o);let i={dependsOn:new Map,dependedBy:new Map};for(let o of e){let l=o.uniqueId;i.dependsOn.set(l,new Set),i.dependedBy.set(l,new Set)}for(let o of e){let l=o.uniqueId,c=i.dependsOn.get(l);if(o instanceof ic){let h=o.sourceMesh;t.has(h.uniqueId)&&(c.add(h.uniqueId),i.dependedBy.get(h.uniqueId).add(l))}let f=i.dependedBy.get(l);for(let h of o.getDescendants()){let d=h.uniqueId;t.has(d)&&(f.add(d),i.dependsOn.get(d).add(l))}}let r=[],s=[];for(let o of e){let l=o.uniqueId;i.dependsOn.get(l).size===0&&(s.push(o),t.delete(l))}let a=s;for(;a.length>0;){let o=a.shift();r.push(o);let l=i.dependedBy.get(o.uniqueId);for(let c of Array.from(l.values())){let f=i.dependsOn.get(c);f.delete(o.uniqueId),f.size===0&&t.get(c)&&(a.push(t.get(c)),t.delete(c))}}return t.size>0&&(te.Error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach(o=>{te.Error(o.name)})),r}_addNodeAndDescendantsToList(e,t,i,r){if(!(!i||r&&!r(i)||t.has(i.uniqueId))){e.push(i),t.add(i.uniqueId);for(let s of i.getDescendants(!0))this._addNodeAndDescendantsToList(e,t,s,r)}}_isNodeInContainer(e){return e instanceof gr&&this.meshes.indexOf(e)!==-1||e instanceof Jt&&this.transformNodes.indexOf(e)!==-1||e instanceof Xt&&this.lights.indexOf(e)!==-1||e instanceof ut&&this.cameras.indexOf(e)!==-1}_isValidHierarchy(){for(let e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return te.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(let e of this.transformNodes)if(e.parent&&!this._isNodeInContainer(e.parent))return te.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(let e of this.lights)if(e.parent&&!this._isNodeInContainer(e.parent))return te.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(let e of this.cameras)if(e.parent&&!this._isNodeInContainer(e.parent))return te.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||pe.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");let r={},s={},a=new OD,o=[],l=[],c={doNotInstantiate:!0,...i},f=(p,_)=>{if(r[p.uniqueId]=_.uniqueId,s[_.uniqueId]=_,e&&(_.name=e(p.name)),_ instanceof Z){let g=_;if(g.morphTargetManager){let v=p.morphTargetManager;g.morphTargetManager=v.clone();for(let x=0;x{if(f(p,_),p.parent){let g=r[p.parent.uniqueId],v=s[g];v?_.parent=v:_.parent=p.parent}if(_.position&&p.position&&_.position.copyFrom(p.position),_.rotationQuaternion&&p.rotationQuaternion&&_.rotationQuaternion.copyFrom(p.rotationQuaternion),_.rotation&&p.rotation&&_.rotation.copyFrom(p.rotation),_.scaling&&p.scaling&&_.scaling.copyFrom(p.scaling),_.material){let g=_;if(g.material)if(t){let v=p.material;if(l.indexOf(v)===-1){let x=v.clone(e?e(v.name):"Clone of "+v.name);if(l.push(v),r[v.uniqueId]=x.uniqueId,s[x.uniqueId]=x,v.getClassName()==="MultiMaterial"){let A=v;for(let S of A.subMaterials)S&&(x=S.clone(e?e(S.name):"Clone of "+S.name),l.push(S),r[S.uniqueId]=x.uniqueId,s[x.uniqueId]=x);A.subMaterials=A.subMaterials.map(S=>S&&s[r[S.uniqueId]])}}g.getClassName()!=="InstancedMesh"&&(g.material=s[r[v.uniqueId]])}else g.material.getClassName()==="MultiMaterial"?this.scene.multiMaterials.indexOf(g.material)===-1&&this.scene.addMultiMaterial(g.material):this.scene.materials.indexOf(g.material)===-1&&this.scene.addMaterial(g.material)}_.parent===null&&a.rootNodes.push(_)};for(let p of u)if(p.getClassName()==="InstancedMesh"){let _=p,g=_.sourceMesh,v=r[g.uniqueId],A=(typeof v=="number"?s[v]:g).createInstance(_.name);m(_,A)}else{let _=!0;p.getClassName()==="TransformNode"||p.getClassName()==="Node"||p.skeleton||!p.getTotalVertices||p.getTotalVertices()===0?_=!1:c.doNotInstantiate&&(typeof c.doNotInstantiate=="function"?_=!c.doNotInstantiate(p):_=!c.doNotInstantiate);let g=_?p.createInstance(`instance of ${p.name}`):p.clone(`Clone of ${p.name}`,null,!0);if(!g)throw new Error(`Could not clone or instantiate node on Asset Container ${p.name}`);m(p,g)}for(let p of this.skeletons){if(c.predicate&&!c.predicate(p))continue;let _=p.clone(e?e(p.name):"Clone of "+p.name);for(let g of this.meshes)if(g.skeleton===p&&!g.isAnInstance){let v=s[r[g.uniqueId]];if(!v||v.isAnInstance||(v.skeleton=_,o.indexOf(_)!==-1))continue;o.push(_);for(let x of _.bones)x._linkedTransformNode&&(x._linkedTransformNode=s[r[x._linkedTransformNode.uniqueId]])}a.skeletons.push(_)}for(let p of this.animationGroups){if(c.predicate&&!c.predicate(p))continue;let _=p.clone(e?e(p.name):"Clone of "+p.name,g=>s[r[g.uniqueId]]||g);a.animationGroups.push(_)}return a}addAllToScene(){if(!this._wasAddedToScene){this._isValidHierarchy()||pe.Warn("SceneSerializer.addAllToScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!0,this.addToScene(null),this.environmentTexture&&(this.scene.environmentTexture=this.environmentTexture);for(let e of this.scene._serializableComponents)e.addFromContainer(this);this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null}}addToScene(e=null){let t=[];for(let i of this.cameras)e&&!e(i)||(this.scene.addCamera(i),t.push(i));for(let i of this.lights)e&&!e(i)||(this.scene.addLight(i),t.push(i));for(let i of this.meshes)e&&!e(i)||(this.scene.addMesh(i),t.push(i));for(let i of this.skeletons)e&&!e(i)||this.scene.addSkeleton(i);for(let i of this.animations)e&&!e(i)||this.scene.addAnimation(i);for(let i of this.animationGroups)e&&!e(i)||this.scene.addAnimationGroup(i);for(let i of this.multiMaterials)e&&!e(i)||this.scene.addMultiMaterial(i);for(let i of this.materials)e&&!e(i)||this.scene.addMaterial(i);for(let i of this.morphTargetManagers)e&&!e(i)||this.scene.addMorphTargetManager(i);for(let i of this.geometries)e&&!e(i)||this.scene.addGeometry(i);for(let i of this.transformNodes)e&&!e(i)||(this.scene.addTransformNode(i),t.push(i));for(let i of this.actionManagers)e&&!e(i)||this.scene.addActionManager(i);for(let i of this.textures)e&&!e(i)||this.scene.addTexture(i);for(let i of this.reflectionProbes)e&&!e(i)||this.scene.addReflectionProbe(i);for(let i of this.spriteManagers)e&&!e(i)||(this.scene.spriteManagers||(this.scene.spriteManagers=[]),this.scene.spriteManagers.push(i));if(t.length){let i=new Set(this.scene.meshes);for(let r of this.scene.lights)i.add(r);for(let r of this.scene.cameras)i.add(r);for(let r of this.scene.transformNodes)i.add(r);for(let r of this.skeletons)for(let s of r.bones)i.add(s);for(let r of t)r.parent&&!i.has(r.parent)&&(r.setParent?r.setParent(null):r.parent=null)}}removeAllFromScene(){this._isValidHierarchy()||pe.Warn("SceneSerializer.removeAllFromScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!1,this.removeFromScene(null),this.environmentTexture===this.scene.environmentTexture&&(this.scene.environmentTexture=null);for(let e of this.scene._serializableComponents)e.removeFromContainer(this)}removeFromScene(e=null){for(let t of this.cameras)e&&!e(t)||this.scene.removeCamera(t);for(let t of this.lights)e&&!e(t)||this.scene.removeLight(t);for(let t of this.meshes)e&&!e(t)||this.scene.removeMesh(t,!0);for(let t of this.skeletons)e&&!e(t)||this.scene.removeSkeleton(t);for(let t of this.animations)e&&!e(t)||this.scene.removeAnimation(t);for(let t of this.animationGroups)e&&!e(t)||this.scene.removeAnimationGroup(t);for(let t of this.multiMaterials)e&&!e(t)||this.scene.removeMultiMaterial(t);for(let t of this.materials)e&&!e(t)||this.scene.removeMaterial(t);for(let t of this.morphTargetManagers)e&&!e(t)||this.scene.removeMorphTargetManager(t);for(let t of this.geometries)e&&!e(t)||this.scene.removeGeometry(t);for(let t of this.transformNodes)e&&!e(t)||this.scene.removeTransformNode(t);for(let t of this.actionManagers)e&&!e(t)||this.scene.removeActionManager(t);for(let t of this.textures)e&&!e(t)||this.scene.removeTexture(t);for(let t of this.reflectionProbes)e&&!e(t)||this.scene.removeReflectionProbe(t);for(let t of this.spriteManagers)if(!(e&&!e(t))&&this.scene.spriteManagers){let i=this.scene.spriteManagers.indexOf(t);i!==-1&&this.scene.spriteManagers.splice(i,1)}}dispose(){let e=this.cameras.slice(0);for(let p of e)p.dispose();this.cameras.length=0;let t=this.lights.slice(0);for(let p of t)p.dispose();this.lights.length=0;let i=this.meshes.slice(0);for(let p of i)p.dispose();this.meshes.length=0;let r=this.skeletons.slice(0);for(let p of r)p.dispose();this.skeletons.length=0;let s=this.animationGroups.slice(0);for(let p of s)p.dispose();this.animationGroups.length=0;let a=this.multiMaterials.slice(0);for(let p of a)p.dispose();this.multiMaterials.length=0;let o=this.materials.slice(0);for(let p of o)p.dispose();this.materials.length=0;let l=this.geometries.slice(0);for(let p of l)p.dispose();this.geometries.length=0;let c=this.transformNodes.slice(0);for(let p of c)p.dispose();this.transformNodes.length=0;let f=this.actionManagers.slice(0);for(let p of f)p.dispose();this.actionManagers.length=0;let h=this.textures.slice(0);for(let p of h)p.dispose();this.textures.length=0;let d=this.reflectionProbes.slice(0);for(let p of d)p.dispose();this.reflectionProbes.length=0;let u=this.morphTargetManagers.slice(0);for(let p of u)p.dispose();this.morphTargetManagers.length=0;let m=this.spriteManagers.slice(0);for(let p of m)p.dispose();this.spriteManagers.length=0,this.environmentTexture&&(this.environmentTexture.dispose(),this.environmentTexture=null);for(let p of this.scene._serializableComponents)p.removeFromContainer(this,!0);this._onContextRestoredObserver&&(this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}_moveAssets(e,t,i){if(!(!e||!t))for(let r of e){let s=!0;if(i){for(let a of i)if(r===a){s=!1;break}}s&&(t.push(r),r._parentContainer=this)}}moveAllFromScene(e){this._wasAddedToScene=!1,e===void 0&&(e=new LD);for(let t in this)Object.prototype.hasOwnProperty.call(this,t)&&(this[t]=this[t]||(t==="_environmentTexture"?null:[]),this._moveAssets(this.scene[t],this[t],e[t]));this.environmentTexture=this.scene.environmentTexture,this.removeAllFromScene()}createRootMesh(){let e=new Z("assetContainerRootMesh",this.scene);for(let t of this.meshes)t.parent||e.addChild(t);return this.meshes.unshift(e),e}mergeAnimationsTo(e=Le.LastCreatedScene,t,i=null){if(!e)return te.Error("No scene available to merge animations to"),[];let r=i||(l=>{let c,f=l.animations.length?l.animations[0].targetProperty:"",h=l.name.split(".").join("").split("_primitive")[0];switch(f){case"position":case"rotationQuaternion":c=e.getTransformNodeByName(l.name)||e.getTransformNodeByName(h);break;case"influence":c=e.getMorphTargetByName(l.name)||e.getMorphTargetByName(h);break;default:c=e.getNodeByName(l.name)||e.getNodeByName(h)}return c}),s=this.getNodes();for(let l of s){let c=r(l);if(c!==null){for(let f of l.animations){let h=c.animations.filter(d=>d.targetProperty===f.targetProperty);for(let d of h){let u=c.animations.indexOf(d,0);u>-1&&c.animations.splice(u,1)}}c.animations=c.animations.concat(l.animations)}}let a=[],o=this.animationGroups.slice();for(let l of o){a.push(l.clone(l.name,r));for(let c of l.animatables)c.stop()}for(let l of t){let c=r(l.target);c&&(e.beginAnimation(c,l.fromFrame,l.toFrame,l.loopAnimation,l.speedRatio,l.onAnimationEnd?l.onAnimationEnd:void 0,void 0,!0,void 0,l.onAnimationLoop?l.onAnimationLoop:void 0),e.stopAnimation(l.target))}return a}populateRootNodes(){this.rootNodes.length=0;for(let e of this.meshes)!e.parent&&this.rootNodes.indexOf(e)===-1&&this.rootNodes.push(e);for(let e of this.transformNodes)!e.parent&&this.rootNodes.indexOf(e)===-1&&this.rootNodes.push(e);for(let e of this.lights)!e.parent&&this.rootNodes.indexOf(e)===-1&&this.rootNodes.push(e);for(let e of this.cameras)!e.parent&&this.rootNodes.indexOf(e)===-1&&this.rootNodes.push(e)}addAllAssetsToContainer(e){if(!e)return;let t=[],i=new Set;for(t.push(e);t.length>0;){let r=t.pop();if(r instanceof Z?(r.geometry&&this.geometries.indexOf(r.geometry)===-1&&this.geometries.push(r.geometry),this.meshes.push(r)):r instanceof ic?this.meshes.push(r):r instanceof Jt?this.transformNodes.push(r):r instanceof Xt?this.lights.push(r):r instanceof ut&&this.cameras.push(r),r instanceof gr){if(r.material&&this.materials.indexOf(r.material)===-1){this.materials.push(r.material);for(let s of r.material.getActiveTextures())this.textures.indexOf(s)===-1&&this.textures.push(s)}r.skeleton&&this.skeletons.indexOf(r.skeleton)===-1&&this.skeletons.push(r.skeleton),r.morphTargetManager&&this.morphTargetManagers.indexOf(r.morphTargetManager)===-1&&this.morphTargetManagers.push(r.morphTargetManager)}for(let s of r.getChildren())i.has(s)||t.push(s);i.add(r)}this.populateRootNodes()}_getByTags(e,t,i){if(t===void 0)return e;let r=[];for(let s in e){let a=e[s];qt&&qt.MatchesQuery(a,t)&&(!i||i(a))&&r.push(a)}return r}getMeshesByTags(e,t){return this._getByTags(this.meshes,e,t)}getCamerasByTags(e,t){return this._getByTags(this.cameras,e,t)}getLightsByTags(e,t){return this._getByTags(this.lights,e,t)}getMaterialsByTags(e,t){return this._getByTags(this.materials,e,t).concat(this._getByTags(this.multiMaterials,e,t))}getTransformNodesByTags(e,t){return this._getByTags(this.transformNodes,e,t)}}});var od,NX=C(()=>{V_();od=class{constructor(e){this.byteOffset=0,this.buffer=e}async loadAsync(e){let t=await this.buffer.readAsync(this.byteOffset,e);this._dataView=new DataView(t.buffer,t.byteOffset,t.byteLength),this._dataByteOffset=0}readUint32(){let e=this._dataView.getUint32(this._dataByteOffset,!0);return this._dataByteOffset+=4,this.byteOffset+=4,e}readUint8Array(e){let t=new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+this._dataByteOffset,e);return this._dataByteOffset+=e,this.byteOffset+=e,t}readString(e){return P2(this.readUint8Array(e))}skipBytes(e){this._dataByteOffset+=e,this.byteOffset+=e}}});function ND(n,e,t,i){let r={externalResourceFunction:i};return t&&(r.uri=e==="file:"?t:e+t),ArrayBuffer.isView(n)?GLTFValidator.validateBytes(n,r):GLTFValidator.validateString(n,r)}function vce(){let n=[];onmessage=e=>{let t=e.data;switch(t.id){case"init":{importScripts(t.url);break}case"validate":{ND(t.data,t.rootUrl,t.fileName,i=>new Promise((r,s)=>{let a=n.length;n.push({resolve:r,reject:s}),postMessage({id:"getExternalResource",index:a,uri:i})})).then(i=>{postMessage({id:"validate.resolve",value:i})},i=>{postMessage({id:"validate.reject",reason:i})});break}case"getExternalResource.resolve":{n[t.index].resolve(t.value);break}case"getExternalResource.reject":{n[t.index].reject(t.reason);break}}}}var ep,wX=C(()=>{bi();ep=class n{static ValidateAsync(e,t,i,r){return typeof Worker=="function"?new Promise((s,a)=>{let o=`${ND}(${vce})()`,l=URL.createObjectURL(new Blob([o],{type:"application/javascript"})),c=new Worker(l),f=d=>{c.removeEventListener("error",f),c.removeEventListener("message",h),a(d)},h=d=>{let u=d.data;switch(u.id){case"getExternalResource":{r(u.uri).then(m=>{c.postMessage({id:"getExternalResource.resolve",index:u.index,value:m},[m.buffer])},m=>{c.postMessage({id:"getExternalResource.reject",index:u.index,reason:m})});break}case"validate.resolve":{c.removeEventListener("error",f),c.removeEventListener("message",h),n._LastResults=u.value,s(u.value),c.terminate();break}case"validate.reject":c.removeEventListener("error",f),c.removeEventListener("message",h),a(u.reason),c.terminate()}};if(c.addEventListener("error",f),c.addEventListener("message",h),c.postMessage({id:"init",url:pe.GetBabylonScriptURL(this.Configuration.url)}),ArrayBuffer.isView(e)){let d=e.slice();c.postMessage({id:"validate",data:d,rootUrl:t,fileName:i},[d.buffer])}else c.postMessage({id:"validate",data:e,rootUrl:t,fileName:i})}):(this._LoadScriptPromise||(this._LoadScriptPromise=pe.LoadBabylonScriptAsync(this.Configuration.url)),this._LoadScriptPromise.then(()=>ND(e,t,i,r)))}};ep.Configuration={url:`${pe._DefaultCdnUrl}/gltf_validator.js`};ep._LastResults=null});var Ac,Vg,FX=C(()=>{Ac="Z2xURg",Vg={name:"gltf",extensions:{".gltf":{isBinary:!1,mimeType:"model/gltf+json"},".glb":{isBinary:!0,mimeType:"model/gltf-binary"}},canDirectLoad(n){return n.indexOf("asset")!==-1&&n.indexOf("version")!==-1||n.startsWith("data:base64,"+Ac)||n.startsWith("data:;base64,"+Ac)||n.startsWith("data:application/octet-stream;base64,"+Ac)||n.startsWith("data:model/gltf-binary;base64,"+Ac)}}});function BX(n,e,t){try{return Promise.resolve(new Uint8Array(n,e,t))}catch(i){return Promise.reject(i)}}function Ece(n,e,t){try{if(e<0||e>=n.byteLength)throw new RangeError("Offset is out of range.");if(e+t>n.byteLength)throw new RangeError("Length is out of range.");return Promise.resolve(new Uint8Array(n.buffer,n.byteOffset+e,t))}catch(i){return Promise.reject(i)}}var tp,ld,ns,lR,Sce,wD,jf,FD=C(()=>{hi();bi();Jm();Ug();yt();NX();wX();FX();Hl();U_();(function(n){n[n.AUTO=0]="AUTO",n[n.FORCE_RIGHT_HANDED=1]="FORCE_RIGHT_HANDED"})(tp||(tp={}));(function(n){n[n.NONE=0]="NONE",n[n.FIRST=1]="FIRST",n[n.ALL=2]="ALL"})(ld||(ld={}));(function(n){n[n.LOADING=0]="LOADING",n[n.READY=1]="READY",n[n.COMPLETE=2]="COMPLETE"})(ns||(ns={}));lR=class{constructor(){this.alwaysComputeBoundingBox=!1,this.alwaysComputeSkeletonRootNode=!1,this.animationStartMode=ld.FIRST,this.compileMaterials=!1,this.compileShadowGenerators=!1,this.coordinateSystemMode=tp.AUTO,this.createInstances=!0,this.loadAllMaterials=!1,this.loadMorphTargets=!0,this.loadNodeAnimations=!0,this.loadOnlyMaterials=!1,this.loadSkins=!0,this.skipMaterials=!1,this.targetFps=60,this.transparencyAsCoverage=!1,this.useClipPlane=!1,this.useGltfTextureNames=!1,this.useRangeRequests=!1,this.useSRGBBuffers=!0,this.validate=!1,this.useOpenPBR=!1,this.dontUseTransmissionHelper=!1}},Sce=new lR,wD=class extends lR{constructor(){super(...arguments),this.extensionOptions={},this.preprocessUrlAsync=e=>Promise.resolve(e)}copyFrom(e){var t,i,r,s,a,o,l,c,f,h,d,u,m,p,_,g,v,x,A,S,E,R,I,y,M,D;e&&(this.alwaysComputeBoundingBox=(t=e.alwaysComputeBoundingBox)!=null?t:this.alwaysComputeBoundingBox,this.alwaysComputeSkeletonRootNode=(i=e.alwaysComputeSkeletonRootNode)!=null?i:this.alwaysComputeSkeletonRootNode,this.animationStartMode=(r=e.animationStartMode)!=null?r:this.animationStartMode,this.capturePerformanceCounters=(s=e.capturePerformanceCounters)!=null?s:this.capturePerformanceCounters,this.compileMaterials=(a=e.compileMaterials)!=null?a:this.compileMaterials,this.compileShadowGenerators=(o=e.compileShadowGenerators)!=null?o:this.compileShadowGenerators,this.coordinateSystemMode=(l=e.coordinateSystemMode)!=null?l:this.coordinateSystemMode,this.createInstances=(c=e.createInstances)!=null?c:this.createInstances,this.customRootNode=e.customRootNode,this.extensionOptions=(f=e.extensionOptions)!=null?f:this.extensionOptions,this.loadAllMaterials=(h=e.loadAllMaterials)!=null?h:this.loadAllMaterials,this.loadMorphTargets=(d=e.loadMorphTargets)!=null?d:this.loadMorphTargets,this.loadNodeAnimations=(u=e.loadNodeAnimations)!=null?u:this.loadNodeAnimations,this.loadOnlyMaterials=(m=e.loadOnlyMaterials)!=null?m:this.loadOnlyMaterials,this.loadSkins=(p=e.loadSkins)!=null?p:this.loadSkins,this.loggingEnabled=(_=e.loggingEnabled)!=null?_:this.loggingEnabled,this.onCameraLoaded=e.onCameraLoaded,this.onMaterialLoaded=e.onMaterialLoaded,this.onMeshLoaded=e.onMeshLoaded,this.onParsed=e.onParsed,this.onSkinLoaded=e.onSkinLoaded,this.onTextureLoaded=e.onTextureLoaded,this.onValidated=e.onValidated,this.preprocessUrlAsync=(g=e.preprocessUrlAsync)!=null?g:this.preprocessUrlAsync,this.skipMaterials=(v=e.skipMaterials)!=null?v:this.skipMaterials,this.targetFps=(x=e.targetFps)!=null?x:this.targetFps,this.transparencyAsCoverage=(A=e.transparencyAsCoverage)!=null?A:this.transparencyAsCoverage,this.useClipPlane=(S=e.useClipPlane)!=null?S:this.useClipPlane,this.useGltfTextureNames=(E=e.useGltfTextureNames)!=null?E:this.useGltfTextureNames,this.useOpenPBR=(R=e.useOpenPBR)!=null?R:this.useOpenPBR,this.useRangeRequests=(I=e.useRangeRequests)!=null?I:this.useRangeRequests,this.useSRGBBuffers=(y=e.useSRGBBuffers)!=null?y:this.useSRGBBuffers,this.validate=(M=e.validate)!=null?M:this.validate,this.dontUseTransmissionHelper=(D=e.dontUseTransmissionHelper)!=null?D:this.dontUseTransmissionHelper)}},jf=class n extends wD{constructor(e){super(),this.onParsedObservable=new ie,this.onMeshLoadedObservable=new ie,this.onSkinLoadedObservable=new ie,this.onTextureLoadedObservable=new ie,this.onMaterialLoadedObservable=new ie,this.onCameraLoadedObservable=new ie,this.onCompleteObservable=new ie,this.onErrorObservable=new ie,this.onDisposeObservable=new ie,this.onExtensionLoadedObservable=new ie,this.onValidatedObservable=new ie,this._loader=null,this._state=null,this._requests=new Array,this.name=Vg.name,this.extensions=Vg.extensions,this.onLoaderStateChangedObservable=new ie,this._logIndentLevel=0,this._loggingEnabled=!1,this._log=this._logDisabled,this._capturePerformanceCounters=!1,this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled,this.copyFrom(Object.assign({...Sce},e))}set onParsed(e){this._onParsedObserver&&this.onParsedObservable.remove(this._onParsedObserver),e&&(this._onParsedObserver=this.onParsedObservable.add(e))}set onMeshLoaded(e){this._onMeshLoadedObserver&&this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver),e&&(this._onMeshLoadedObserver=this.onMeshLoadedObservable.add(e))}set onSkinLoaded(e){this._onSkinLoadedObserver&&this.onSkinLoadedObservable.remove(this._onSkinLoadedObserver),e&&(this._onSkinLoadedObserver=this.onSkinLoadedObservable.add(t=>e(t.node,t.skinnedNode)))}set onTextureLoaded(e){this._onTextureLoadedObserver&&this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver),e&&(this._onTextureLoadedObserver=this.onTextureLoadedObservable.add(e))}set onMaterialLoaded(e){this._onMaterialLoadedObserver&&this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver),e&&(this._onMaterialLoadedObserver=this.onMaterialLoadedObservable.add(e))}set onCameraLoaded(e){this._onCameraLoadedObserver&&this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver),e&&(this._onCameraLoadedObserver=this.onCameraLoadedObservable.add(e))}set onComplete(e){this._onCompleteObserver&&this.onCompleteObservable.remove(this._onCompleteObserver),this._onCompleteObserver=this.onCompleteObservable.add(e)}set onError(e){this._onErrorObserver&&this.onErrorObservable.remove(this._onErrorObserver),this._onErrorObserver=this.onErrorObservable.add(e)}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set onExtensionLoaded(e){this._onExtensionLoadedObserver&&this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver),this._onExtensionLoadedObserver=this.onExtensionLoadedObservable.add(e)}get loggingEnabled(){return this._loggingEnabled}set loggingEnabled(e){this._loggingEnabled!==e&&(this._loggingEnabled=e,this._loggingEnabled?this._log=this._logEnabled:this._log=this._logDisabled)}get capturePerformanceCounters(){return this._capturePerformanceCounters}set capturePerformanceCounters(e){this._capturePerformanceCounters!==e&&(this._capturePerformanceCounters=e,this._capturePerformanceCounters?(this._startPerformanceCounter=this._startPerformanceCounterEnabled,this._endPerformanceCounter=this._endPerformanceCounterEnabled):(this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled))}set onValidated(e){this._onValidatedObserver&&this.onValidatedObservable.remove(this._onValidatedObserver),this._onValidatedObserver=this.onValidatedObservable.add(e)}dispose(){this._loader&&(this._loader.dispose(),this._loader=null);for(let e of this._requests)e.abort();this._requests.length=0,delete this._progressCallback,this.preprocessUrlAsync=e=>Promise.resolve(e),this.onMeshLoadedObservable.clear(),this.onSkinLoadedObservable.clear(),this.onTextureLoadedObservable.clear(),this.onMaterialLoadedObservable.clear(),this.onCameraLoadedObservable.clear(),this.onCompleteObservable.clear(),this.onExtensionLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(void 0),this.onDisposeObservable.clear()}loadFile(e,t,i,r,s,a,o,l){if(ArrayBuffer.isView(t))return this._loadBinary(e,t,i,r,o,l),null;this._progressCallback=s;let c=t.name||pe.GetFilename(t);if(a){if(this.useRangeRequests){this.validate&&te.Warn("glTF validation is not supported when range requests are enabled");let f={abort:()=>{},onCompleteObservable:new ie},h={readAsync:(d,u)=>new Promise((m,p)=>{this._loadFile(e,t,_=>{m(new Uint8Array(_))},!0,_=>{p(_)},_=>{_.setRequestHeader("Range",`bytes=${d}-${d+u-1}`)})}),byteLength:0};return this._unpackBinaryAsync(new od(h)).then(d=>{f.onCompleteObservable.notifyObservers(f),r(d)},o?d=>o(void 0,d):void 0),f}return this._loadFile(e,t,f=>{this._validate(e,new Uint8Array(f,0,f.byteLength),i,c),this._unpackBinaryAsync(new od({readAsync:(h,d)=>BX(f,h,d),byteLength:f.byteLength})).then(h=>{r(h)},o?h=>o(void 0,h):void 0)},!0,o)}else return this._loadFile(e,t,f=>{try{this._validate(e,f,i,c),r({json:this._parseJson(f)})}catch(h){o&&o()}},!1,o)}_loadBinary(e,t,i,r,s,a){this._validate(e,new Uint8Array(t.buffer,t.byteOffset,t.byteLength),i,a),this._unpackBinaryAsync(new od({readAsync:(o,l)=>Ece(t,o,l),byteLength:t.byteLength})).then(o=>{r(o)},s?o=>s(void 0,o):void 0)}importMeshAsync(e,t,i,r,s,a){return Promise.resolve().then(()=>(this.onParsedObservable.notifyObservers(i),this.onParsedObservable.clear(),this._log(`Loading ${a||""}`),this._loader=this._getLoader(i),this._loader.importMeshAsync(e,t,null,i,r,s,a)))}loadAsync(e,t,i,r,s){return Promise.resolve().then(()=>(this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${s||""}`),this._loader=this._getLoader(t),this._loader.loadAsync(e,t,i,r,s)))}loadAssetContainerAsync(e,t,i,r,s){return Promise.resolve().then(()=>{this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${s||""}`),this._loader=this._getLoader(t);let a=new ul(e),o=[];this.onMaterialLoadedObservable.add(h=>{o.push(h)});let l=[];this.onTextureLoadedObservable.add(h=>{l.push(h)});let c=[];this.onCameraLoadedObservable.add(h=>{c.push(h)});let f=[];return this.onMeshLoadedObservable.add(h=>{h.morphTargetManager&&f.push(h.morphTargetManager)}),this._loader.importMeshAsync(null,e,a,t,i,r,s).then(h=>(Array.prototype.push.apply(a.geometries,h.geometries),Array.prototype.push.apply(a.meshes,h.meshes),Array.prototype.push.apply(a.particleSystems,h.particleSystems),Array.prototype.push.apply(a.skeletons,h.skeletons),Array.prototype.push.apply(a.animationGroups,h.animationGroups),Array.prototype.push.apply(a.materials,o),Array.prototype.push.apply(a.textures,l),Array.prototype.push.apply(a.lights,h.lights),Array.prototype.push.apply(a.transformNodes,h.transformNodes),Array.prototype.push.apply(a.cameras,c),Array.prototype.push.apply(a.morphTargetManagers,f),a))})}canDirectLoad(e){return Vg.canDirectLoad(e)}directLoad(e,t){if(t.startsWith("base64,"+Ac)||t.startsWith(";base64,"+Ac)||t.startsWith("application/octet-stream;base64,"+Ac)||t.startsWith("model/gltf-binary;base64,"+Ac)){let i=df(t);return this._validate(e,new Uint8Array(i,0,i.byteLength)),this._unpackBinaryAsync(new od({readAsync:(r,s)=>BX(i,r,s),byteLength:i.byteLength}))}return this._validate(e,t),Promise.resolve({json:this._parseJson(t)})}createPlugin(e){return new n(e[Vg.name])}get loaderState(){return this._state}whenCompleteAsync(){return new Promise((e,t)=>{this.onCompleteObservable.addOnce(()=>{e()}),this.onErrorObservable.addOnce(i=>{t(i)})})}_setState(e){this._state!==e&&(this._state=e,this.onLoaderStateChangedObservable.notifyObservers(this._state),this._log(ns[this._state]))}_loadFile(e,t,i,r,s,a){let o=e._loadFile(t,i,l=>{this._onProgress(l,o)},!0,r,s,a);return o.onCompleteObservable.add(()=>{o._lengthComputable=!0,o._total=o._loaded}),this._requests.push(o),o}_onProgress(e,t){if(!this._progressCallback)return;t._lengthComputable=e.lengthComputable,t._loaded=e.loaded,t._total=e.total;let i=!0,r=0,s=0;for(let a of this._requests){if(a._lengthComputable===void 0||a._loaded===void 0||a._total===void 0)return;i=i&&a._lengthComputable,r+=a._loaded,s+=a._total}this._progressCallback({lengthComputable:i,loaded:r,total:i?s:0})}_validate(e,t,i="",r=""){this.validate&&(this._startPerformanceCounter("Validate JSON"),ep.ValidateAsync(t,i,r,s=>this.preprocessUrlAsync(i+s).then(a=>e._loadFileAsync(a,void 0,!0,!0).then(o=>new Uint8Array(o,0,o.byteLength)))).then(s=>{this._endPerformanceCounter("Validate JSON"),this.onValidatedObservable.notifyObservers(s),this.onValidatedObservable.clear()},s=>{this._endPerformanceCounter("Validate JSON"),pe.Warn(`Failed to validate: ${s.message}`),this.onValidatedObservable.clear()}))}_getLoader(e){let t=e.json.asset||{};this._log(`Asset version: ${t.version}`),t.minVersion&&this._log(`Asset minimum version: ${t.minVersion}`),t.generator&&this._log(`Asset generator: ${t.generator}`);let i=n._parseVersion(t.version);if(!i)throw new Error("Invalid version: "+t.version);if(t.minVersion!==void 0){let a=n._parseVersion(t.minVersion);if(!a)throw new Error("Invalid minimum version: "+t.minVersion);if(n._compareVersion(a,{major:2,minor:0})>0)throw new Error("Incompatible minimum version: "+t.minVersion)}let s={1:n._CreateGLTF1Loader,2:n._CreateGLTF2Loader}[i.major];if(!s)throw new Error("Unsupported version: "+t.version);return s(this)}_parseJson(e){this._startPerformanceCounter("Parse JSON"),this._log(`JSON length: ${e.length}`);let t=JSON.parse(e);return this._endPerformanceCounter("Parse JSON"),t}_unpackBinaryAsync(e){return this._startPerformanceCounter("Unpack Binary"),e.loadAsync(20).then(()=>{let t={Magic:1179937895},i=e.readUint32();if(i!==t.Magic)throw new As("Unexpected magic: "+i,Sa.GLTFLoaderUnexpectedMagicError);let r=e.readUint32();this.loggingEnabled&&this._log(`Binary version: ${r}`);let s=e.readUint32();!this.useRangeRequests&&s!==e.buffer.byteLength&&te.Warn(`Length in header does not match actual data length: ${s} != ${e.buffer.byteLength}`);let a;switch(r){case 1:{a=this._unpackBinaryV1Async(e,s);break}case 2:{a=this._unpackBinaryV2Async(e,s);break}default:throw new Error("Unsupported version: "+r)}return this._endPerformanceCounter("Unpack Binary"),a})}_unpackBinaryV1Async(e,t){let i={JSON:0},r=e.readUint32(),s=e.readUint32();if(s!==i.JSON)throw new Error(`Unexpected content format: ${s}`);let a=t-e.byteOffset,o={json:this._parseJson(e.readString(r)),bin:null};if(a!==0){let l=e.byteOffset;o.bin={readAsync:(c,f)=>e.buffer.readAsync(l+c,f),byteLength:a}}return Promise.resolve(o)}_unpackBinaryV2Async(e,t){let i={JSON:1313821514,BIN:5130562},r=e.readUint32();if(e.readUint32()!==i.JSON)throw new Error("First chunk format is not JSON");return e.byteOffset+r===t?e.loadAsync(r).then(()=>({json:this._parseJson(e.readString(r)),bin:null})):e.loadAsync(r+8).then(()=>{let a={json:this._parseJson(e.readString(r)),bin:null},o=()=>{let l=e.readUint32();switch(e.readUint32()){case i.JSON:throw new Error("Unexpected JSON chunk");case i.BIN:{let f=e.byteOffset;a.bin={readAsync:(h,d)=>e.buffer.readAsync(f+h,d),byteLength:l},e.skipBytes(l);break}default:{e.skipBytes(l);break}}return e.byteOffset!==t?e.loadAsync(8).then(o):Promise.resolve(a)};return o()})}static _parseVersion(e){if(e==="1.0"||e==="1.0.1")return{major:1,minor:0};let t=(e+"").match(/^(\d+)\.(\d+)/);return t?{major:parseInt(t[1]),minor:parseInt(t[2])}:null}static _compareVersion(e,t){return e.major>t.major?1:e.majort.minor?1:e.minor{cR=class{get resolve(){return this._resolve}get reject(){return this._reject}constructor(){this.promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}}});var zn,VX=C(()=>{Gt();Ut();fl();oA();Ve();bi();zn=class{constructor(){this.keysUp=[38],this.keysUpward=[33],this.keysDown=[40],this.keysDownward=[34],this.keysLeft=[37],this.keysRight=[39],this.rotationSpeed=.5,this.keysRotateLeft=[],this.keysRotateRight=[],this.keysRotateUp=[],this.keysRotateDown=[],this._keys=new Array}attachControl(e){e=pe.BackCompatCameraNoPreventDefault(arguments),!this._onCanvasBlurObserver&&(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add(()=>{this._keys.length=0}),this._onKeyboardObserver=this._scene.onKeyboardObservable.add(t=>{let i=t.event;if(!i.metaKey){if(t.type===lo.KEYDOWN)(this.keysUp.indexOf(i.keyCode)!==-1||this.keysDown.indexOf(i.keyCode)!==-1||this.keysLeft.indexOf(i.keyCode)!==-1||this.keysRight.indexOf(i.keyCode)!==-1||this.keysUpward.indexOf(i.keyCode)!==-1||this.keysDownward.indexOf(i.keyCode)!==-1||this.keysRotateLeft.indexOf(i.keyCode)!==-1||this.keysRotateRight.indexOf(i.keyCode)!==-1||this.keysRotateUp.indexOf(i.keyCode)!==-1||this.keysRotateDown.indexOf(i.keyCode)!==-1)&&(this._keys.indexOf(i.keyCode)===-1&&this._keys.push(i.keyCode),e||i.preventDefault());else if(this.keysUp.indexOf(i.keyCode)!==-1||this.keysDown.indexOf(i.keyCode)!==-1||this.keysLeft.indexOf(i.keyCode)!==-1||this.keysRight.indexOf(i.keyCode)!==-1||this.keysUpward.indexOf(i.keyCode)!==-1||this.keysDownward.indexOf(i.keyCode)!==-1||this.keysRotateLeft.indexOf(i.keyCode)!==-1||this.keysRotateRight.indexOf(i.keyCode)!==-1||this.keysRotateUp.indexOf(i.keyCode)!==-1||this.keysRotateDown.indexOf(i.keyCode)!==-1){let r=this._keys.indexOf(i.keyCode);r>=0&&this._keys.splice(r,1),e||i.preventDefault()}}}))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){if(this._onKeyboardObserver){let e=this.camera;for(let t=0;t{Gt();hi();Ut();fl();oo();bi();cd=class{constructor(e=!0){this.touchEnabled=e,this.buttons=[0,1,2],this.angularSensibility=2e3,this._previousPosition=null,this.onPointerMovedObservable=new ie,this._allowCameraRotation=!0,this._currentActiveButton=-1,this._activePointerId=-1}attachControl(e){e=pe.BackCompatCameraNoPreventDefault(arguments);let t=this.camera.getEngine(),i=t.getInputElement();this._pointerInput||(this._pointerInput=r=>{let s=r.event,a=s.pointerType==="touch";if(!this.touchEnabled&&a||r.type!==st.POINTERMOVE&&this.buttons.indexOf(s.button)===-1)return;let o=s.target;if(r.type===st.POINTERDOWN){if(a&&this._activePointerId!==-1||!a&&this._currentActiveButton!==-1)return;this._activePointerId=s.pointerId;try{o==null||o.setPointerCapture(s.pointerId)}catch(l){}this._currentActiveButton===-1&&(this._currentActiveButton=s.button),this._previousPosition={x:s.clientX,y:s.clientY},e||(s.preventDefault(),i&&i.focus()),t.isPointerLock&&this._onMouseMove&&this._onMouseMove(r.event)}else if(r.type===st.POINTERUP){if(a&&this._activePointerId!==s.pointerId||!a&&this._currentActiveButton!==s.button)return;try{o==null||o.releasePointerCapture(s.pointerId)}catch(l){}this._currentActiveButton=-1,this._previousPosition=null,e||s.preventDefault(),this._activePointerId=-1}else if(r.type===st.POINTERMOVE&&(this._activePointerId===s.pointerId||!a)){if(t.isPointerLock&&this._onMouseMove)this._onMouseMove(r.event);else if(this._previousPosition){let l=this.camera._calculateHandednessMultiplier(),c=(s.clientX-this._previousPosition.x)*l,f=(s.clientY-this._previousPosition.y)*l;this._allowCameraRotation&&(this.camera.cameraRotation.y+=c/this.angularSensibility,this.camera.cameraRotation.x+=f/this.angularSensibility),this.onPointerMovedObservable.notifyObservers({offsetX:c,offsetY:f}),this._previousPosition={x:s.clientX,y:s.clientY},e||s.preventDefault()}}}),this._onMouseMove=r=>{if(!t.isPointerLock)return;let s=this.camera._calculateHandednessMultiplier();this.camera.cameraRotation.y+=r.movementX*s/this.angularSensibility,this.camera.cameraRotation.x+=r.movementY*s/this.angularSensibility,this._previousPosition=null,e||r.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,st.POINTERDOWN|st.POINTERUP|st.POINTERMOVE),i&&(this._contextMenuBind=r=>this.onContextMenu(r),i.addEventListener("contextmenu",this._contextMenuBind,!1))}onContextMenu(e){e.preventDefault()}detachControl(){if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._contextMenuBind){let t=this.camera.getEngine().getInputElement();t&&t.removeEventListener("contextmenu",this._contextMenuBind)}this.onPointerMovedObservable&&this.onPointerMovedObservable.clear(),this._observer=null,this._onMouseMove=null,this._previousPosition=null}this._activePointerId=-1,this._currentActiveButton=-1}getClassName(){return"FreeCameraMouseInput"}getSimpleName(){return"mouse"}};P([w()],cd.prototype,"buttons",void 0);P([w()],cd.prototype,"angularSensibility",void 0);Gn.FreeCameraMouseInput=cd});var fd,kX=C(()=>{Gt();Ut();hi();oo();lA();bi();fd=class{constructor(){this.wheelPrecisionX=3,this.wheelPrecisionY=3,this.wheelPrecisionZ=3,this.onChangedObservable=new ie,this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0,this._ffMultiplier=12,this._normalize=120}attachControl(e){e=pe.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==st.POINTERWHEEL)return;let i=t.event,r=i.deltaMode===co.DOM_DELTA_LINE?this._ffMultiplier:1;this._wheelDeltaX+=this.wheelPrecisionX*r*i.deltaX/this._normalize,this._wheelDeltaY-=this.wheelPrecisionY*r*i.deltaY/this._normalize,this._wheelDeltaZ+=this.wheelPrecisionZ*r*i.deltaZ/this._normalize,i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,st.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null),this.onChangedObservable&&this.onChangedObservable.clear()}checkInputs(){this.onChangedObservable.notifyObservers({wheelDeltaX:this._wheelDeltaX,wheelDeltaY:this._wheelDeltaY,wheelDeltaZ:this._wheelDeltaZ}),this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0}getClassName(){return"BaseCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}};P([w()],fd.prototype,"wheelPrecisionX",void 0);P([w()],fd.prototype,"wheelPrecisionY",void 0);P([w()],fd.prototype,"wheelPrecisionZ",void 0)});var Di,Ps,WX=C(()=>{Gt();Ut();fl();kX();Ve();(function(n){n[n.MoveRelative=0]="MoveRelative",n[n.RotateRelative=1]="RotateRelative",n[n.MoveScene=2]="MoveScene"})(Di||(Di={}));Ps=class extends fd{constructor(){super(...arguments),this._moveRelative=b.Zero(),this._rotateRelative=b.Zero(),this._moveScene=b.Zero(),this._wheelXAction=Di.MoveRelative,this._wheelXActionCoordinate=0,this._wheelYAction=Di.MoveRelative,this._wheelYActionCoordinate=2,this._wheelZAction=null,this._wheelZActionCoordinate=null}getClassName(){return"FreeCameraMouseWheelInput"}set wheelXMoveRelative(e){e===null&&this._wheelXAction!==Di.MoveRelative||(this._wheelXAction=Di.MoveRelative,this._wheelXActionCoordinate=e)}get wheelXMoveRelative(){return this._wheelXAction!==Di.MoveRelative?null:this._wheelXActionCoordinate}set wheelYMoveRelative(e){e===null&&this._wheelYAction!==Di.MoveRelative||(this._wheelYAction=Di.MoveRelative,this._wheelYActionCoordinate=e)}get wheelYMoveRelative(){return this._wheelYAction!==Di.MoveRelative?null:this._wheelYActionCoordinate}set wheelZMoveRelative(e){e===null&&this._wheelZAction!==Di.MoveRelative||(this._wheelZAction=Di.MoveRelative,this._wheelZActionCoordinate=e)}get wheelZMoveRelative(){return this._wheelZAction!==Di.MoveRelative?null:this._wheelZActionCoordinate}set wheelXRotateRelative(e){e===null&&this._wheelXAction!==Di.RotateRelative||(this._wheelXAction=Di.RotateRelative,this._wheelXActionCoordinate=e)}get wheelXRotateRelative(){return this._wheelXAction!==Di.RotateRelative?null:this._wheelXActionCoordinate}set wheelYRotateRelative(e){e===null&&this._wheelYAction!==Di.RotateRelative||(this._wheelYAction=Di.RotateRelative,this._wheelYActionCoordinate=e)}get wheelYRotateRelative(){return this._wheelYAction!==Di.RotateRelative?null:this._wheelYActionCoordinate}set wheelZRotateRelative(e){e===null&&this._wheelZAction!==Di.RotateRelative||(this._wheelZAction=Di.RotateRelative,this._wheelZActionCoordinate=e)}get wheelZRotateRelative(){return this._wheelZAction!==Di.RotateRelative?null:this._wheelZActionCoordinate}set wheelXMoveScene(e){e===null&&this._wheelXAction!==Di.MoveScene||(this._wheelXAction=Di.MoveScene,this._wheelXActionCoordinate=e)}get wheelXMoveScene(){return this._wheelXAction!==Di.MoveScene?null:this._wheelXActionCoordinate}set wheelYMoveScene(e){e===null&&this._wheelYAction!==Di.MoveScene||(this._wheelYAction=Di.MoveScene,this._wheelYActionCoordinate=e)}get wheelYMoveScene(){return this._wheelYAction!==Di.MoveScene?null:this._wheelYActionCoordinate}set wheelZMoveScene(e){e===null&&this._wheelZAction!==Di.MoveScene||(this._wheelZAction=Di.MoveScene,this._wheelZActionCoordinate=e)}get wheelZMoveScene(){return this._wheelZAction!==Di.MoveScene?null:this._wheelZActionCoordinate}checkInputs(){if(this._wheelDeltaX===0&&this._wheelDeltaY===0&&this._wheelDeltaZ==0)return;this._moveRelative.setAll(0),this._rotateRelative.setAll(0),this._moveScene.setAll(0),this._updateCamera(),this.camera.getScene().useRightHandedSystem&&(this._moveRelative.z*=-1);let e=j.Zero();this.camera.getViewMatrix().invertToRef(e);let t=b.Zero();b.TransformNormalToRef(this._moveRelative,e,t),this.camera.cameraRotation.x+=this._rotateRelative.x/200,this.camera.cameraRotation.y+=this._rotateRelative.y/200,this.camera.cameraDirection.addInPlace(t),this.camera.cameraDirection.addInPlace(this._moveScene),super.checkInputs()}_updateCamera(){this._updateCameraProperty(this._wheelDeltaX,this._wheelXAction,this._wheelXActionCoordinate),this._updateCameraProperty(this._wheelDeltaY,this._wheelYAction,this._wheelYActionCoordinate),this._updateCameraProperty(this._wheelDeltaZ,this._wheelZAction,this._wheelZActionCoordinate)}_updateCameraProperty(e,t,i){if(e===0||t===null||i===null)return;let r=null;switch(t){case Di.MoveRelative:r=this._moveRelative;break;case Di.RotateRelative:r=this._rotateRelative;break;case Di.MoveScene:r=this._moveScene;break}switch(i){case 0:r.set(e,0,0);break;case 1:r.set(0,e,0);break;case 2:r.set(0,0,e);break}}};P([w()],Ps.prototype,"wheelXMoveRelative",null);P([w()],Ps.prototype,"wheelYMoveRelative",null);P([w()],Ps.prototype,"wheelZMoveRelative",null);P([w()],Ps.prototype,"wheelXRotateRelative",null);P([w()],Ps.prototype,"wheelYRotateRelative",null);P([w()],Ps.prototype,"wheelZRotateRelative",null);P([w()],Ps.prototype,"wheelXMoveScene",null);P([w()],Ps.prototype,"wheelYMoveScene",null);P([w()],Ps.prototype,"wheelZMoveScene",null);Gn.FreeCameraMouseWheelInput=Ps});var hd,HX=C(()=>{Gt();Ut();fl();oo();Ve();bi();hd=class{constructor(e=!1){this.allowMouse=e,this.touchAngularSensibility=2e5,this.touchMoveSensibility=250,this.singleFingerRotate=!1,this._offsetX=null,this._offsetY=null,this._pointerPressed=new Array,this._isSafari=pe.IsSafari()}attachControl(e){e=pe.BackCompatCameraNoPreventDefault(arguments);let t=null;if(this._pointerInput===void 0&&(this._onLostFocus=()=>{this._offsetX=null,this._offsetY=null},this._pointerInput=i=>{let r=i.event,s=r.pointerType==="mouse"||this._isSafari&&typeof r.pointerType=="undefined";if(!(!this.allowMouse&&s)){if(i.type===st.POINTERDOWN){if(e||r.preventDefault(),this._pointerPressed.push(r.pointerId),this._pointerPressed.length!==1)return;t={x:r.clientX,y:r.clientY}}else if(i.type===st.POINTERUP){e||r.preventDefault();let a=this._pointerPressed.indexOf(r.pointerId);if(a===-1||(this._pointerPressed.splice(a,1),a!=0))return;t=null,this._offsetX=null,this._offsetY=null}else if(i.type===st.POINTERMOVE){if(e||r.preventDefault(),!t||this._pointerPressed.indexOf(r.pointerId)!=0)return;this._offsetX=r.clientX-t.x,this._offsetY=-(r.clientY-t.y)}}}),this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,st.POINTERDOWN|st.POINTERUP|st.POINTERMOVE),this._onLostFocus){let r=this.camera.getEngine().getInputElement();r&&r.addEventListener("blur",this._onLostFocus)}}detachControl(){if(this._pointerInput){if(this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null),this._onLostFocus){let t=this.camera.getEngine().getInputElement();t&&t.removeEventListener("blur",this._onLostFocus),this._onLostFocus=null}this._pointerPressed.length=0,this._offsetX=null,this._offsetY=null}}checkInputs(){if(this._offsetX===null||this._offsetY===null||this._offsetX===0&&this._offsetY===0)return;let e=this.camera,t=e._calculateHandednessMultiplier();if(e.cameraRotation.y=this._offsetX*t/this.touchAngularSensibility,this.singleFingerRotate&&this._pointerPressed.length===1||!this.singleFingerRotate&&this._pointerPressed.length>1)e.cameraRotation.x=-(this._offsetY*t)/this.touchAngularSensibility;else{let r=e._computeLocalCameraSpeed(),s=$.Vector3[0];s.copyFromFloats(0,0,this.touchMoveSensibility!==0?r*this._offsetY/this.touchMoveSensibility:0),j.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),b.TransformCoordinatesToRef(s,e._cameraRotationMatrix,s),e.cameraDirection.addInPlace(s)}}getClassName(){return"FreeCameraTouchInput"}getSimpleName(){return"touch"}};P([w()],hd.prototype,"touchAngularSensibility",void 0);P([w()],hd.prototype,"touchMoveSensibility",void 0);Gn.FreeCameraTouchInput=hd});var fR,zX=C(()=>{fl();VX();GX();WX();HX();fR=class extends Vm{constructor(e){super(e),this._mouseInput=null,this._mouseWheelInput=null}addKeyboard(){return this.add(new zn),this}addMouse(e=!0){return this._mouseInput||(this._mouseInput=new cd(e),this.add(this._mouseInput)),this}removeMouse(){return this._mouseInput&&this.remove(this._mouseInput),this}addMouseWheel(){return this._mouseWheelInput||(this._mouseWheelInput=new Ps,this.add(this._mouseWheelInput)),this}removeMouseWheel(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this}addTouch(){return this.add(new hd),this}clear(){super.clear(),this._mouseInput=null}}});var xc,XX=C(()=>{Gt();Ut();Ve();wy();zX();bi();Hi();wr();xc=class extends Is{get angularSensibility(){let e=this.inputs.attached.mouse;return e?e.angularSensibility:0}set angularSensibility(e){let t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)}get keysUp(){let e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){let t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysUpward(){let e=this.inputs.attached.keyboard;return e?e.keysUpward:[]}set keysUpward(e){let t=this.inputs.attached.keyboard;t&&(t.keysUpward=e)}get keysDown(){let e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){let t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysDownward(){let e=this.inputs.attached.keyboard;return e?e.keysDownward:[]}set keysDownward(e){let t=this.inputs.attached.keyboard;t&&(t.keysDownward=e)}get keysLeft(){let e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){let t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){let e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){let t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}get keysRotateLeft(){let e=this.inputs.attached.keyboard;return e?e.keysRotateLeft:[]}set keysRotateLeft(e){let t=this.inputs.attached.keyboard;t&&(t.keysRotateLeft=e)}get keysRotateRight(){let e=this.inputs.attached.keyboard;return e?e.keysRotateRight:[]}set keysRotateRight(e){let t=this.inputs.attached.keyboard;t&&(t.keysRotateRight=e)}get keysRotateUp(){let e=this.inputs.attached.keyboard;return e?e.keysRotateUp:[]}set keysRotateUp(e){let t=this.inputs.attached.keyboard;t&&(t.keysRotateUp=e)}get keysRotateDown(){let e=this.inputs.attached.keyboard;return e?e.keysRotateDown:[]}set keysRotateDown(e){let t=this.inputs.attached.keyboard;t&&(t.keysRotateDown=e)}constructor(e,t,i,r=!0){super(e,t,i,r),this.ellipsoid=new b(.5,1,.5),this.ellipsoidOffset=new b(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this._needMoveForGravity=!1,this._oldPosition=b.Zero(),this._diffPosition=b.Zero(),this._newPosition=b.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(s,a,o=null)=>{this._newPosition.copyFrom(a),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>Ie.CollisionsEpsilon&&(this.position.addToRef(this._diffPosition,this._deferredPositionUpdate),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate),this.onCollide&&o&&this.onCollide(o))},this.inputs=new fR(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=pe.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new b(0,0,0),this.cameraRotation=new we(0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;this.parent?t=b.TransformCoordinates(this.position,this.parent.getWorldMatrix()):t=this.position,t.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);let i=this.getScene().collisionCoordinator;this._collider||(this._collider=i.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let r=e;this.applyGravity&&(r=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,r,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=b.Zero(),this._transformedDirection=b.Zero()),this.inputs.checkInputs(),super._checkInputs()}set needMoveForGravity(e){this._needMoveForGravity=e}get needMoveForGravity(){return this._needMoveForGravity}_decideIfNeedsToMove(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):super._updatePosition()}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FreeCamera"}};P([Hr()],xc.prototype,"ellipsoid",void 0);P([Hr()],xc.prototype,"ellipsoidOffset",void 0);P([w()],xc.prototype,"checkCollisions",void 0);P([w()],xc.prototype,"applyGravity",void 0);wt("BABYLON.FreeCamera",xc)});var Fa,hR=C(()=>{Ve();Zo();qs();Fa=class n extends _i{get _matrix(){return this._compose(),this._localMatrix}set _matrix(e){e.updateFlag===this._localMatrix.updateFlag&&!this._needToCompose||(this._needToCompose=!1,this._localMatrix.copyFrom(e),this._markAsDirtyAndDecompose())}constructor(e,t,i=null,r=null,s=null,a=null,o=null){var l;super(e,t.getScene(),!1),this.name=e,this.children=[],this.animations=[],this._index=null,this._scalingDeterminant=1,this._needToDecompose=!0,this._needToCompose=!1,this._linkedTransformNode=null,this._waitingTransformNodeId=null,this._waitingTransformNodeUniqueId=null,this._skeleton=t,this._localMatrix=(l=r==null?void 0:r.clone())!=null?l:j.Identity(),this._restMatrix=s!=null?s:this._localMatrix.clone(),this._bindMatrix=a!=null?a:this._localMatrix.clone(),this._index=o,this._absoluteMatrix=new j,this._absoluteBindMatrix=new j,this._absoluteInverseBindMatrix=new j,this._finalMatrix=new j,t.bones.push(this),this.setParent(i,!1),this._updateAbsoluteBindMatrices()}getClassName(){return"Bone"}getSkeleton(){return this._skeleton}get parent(){return this._parentNode}getParent(){return this.parent}getChildren(){return this.children}getIndex(){return this._index===null?this.getSkeleton().bones.indexOf(this):this._index}set parent(e){this.setParent(e)}setParent(e,t=!0){if(this.parent!==e){if(this.parent){let i=this.parent.children.indexOf(this);i!==-1&&this.parent.children.splice(i,1)}this._parentNode=e,this.parent&&this.parent.children.push(this),t&&this._updateAbsoluteBindMatrices(),this.markAsDirty()}}getLocalMatrix(){return this._compose(),this._localMatrix}getBindMatrix(){return this._bindMatrix}getBaseMatrix(){return this.getBindMatrix()}getRestMatrix(){return this._restMatrix}getRestPose(){return this.getRestMatrix()}setRestMatrix(e){this._restMatrix.copyFrom(e)}setRestPose(e){this.setRestMatrix(e)}getBindPose(){return this.getBindMatrix()}setBindMatrix(e){this.updateMatrix(e)}setBindPose(e){this.setBindMatrix(e)}getFinalMatrix(){return this._finalMatrix}getWorldMatrix(){return this.getFinalMatrix()}returnToRest(){var e;if(this._linkedTransformNode){let t=$.Vector3[0],i=$.Quaternion[0],r=$.Vector3[1];this.getRestMatrix().decompose(t,i,r),this._linkedTransformNode.position.copyFrom(r),this._linkedTransformNode.rotationQuaternion=(e=this._linkedTransformNode.rotationQuaternion)!=null?e:Ye.Identity(),this._linkedTransformNode.rotationQuaternion.copyFrom(i),this._linkedTransformNode.scaling.copyFrom(t)}else this._matrix=this._restMatrix}getAbsoluteInverseBindMatrix(){return this._absoluteInverseBindMatrix}getInvertedAbsoluteTransform(){return this.getAbsoluteInverseBindMatrix()}getAbsoluteMatrix(){return this._skeleton.computeAbsoluteMatrices(),this._absoluteMatrix}getAbsoluteTransform(){return this.getAbsoluteMatrix()}linkTransformNode(e){this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode--,this._linkedTransformNode=e,this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode++}getTransformNode(){return this._linkedTransformNode}get position(){return this._decompose(),this._localPosition}set position(e){this._decompose(),this._localPosition.copyFrom(e),this._markAsDirtyAndCompose()}get rotation(){return this.getRotation()}set rotation(e){this.setRotation(e)}get rotationQuaternion(){return this._decompose(),this._localRotation}set rotationQuaternion(e){this.setRotationQuaternion(e)}get scaling(){return this.getScale()}set scaling(e){this.setScale(e)}get animationPropertiesOverride(){return this._skeleton.animationPropertiesOverride}_decompose(){this._needToDecompose&&(this._needToDecompose=!1,this._localScaling||(this._localScaling=b.Zero(),this._localRotation=Ye.Zero(),this._localPosition=b.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))}_compose(){if(this._needToCompose){if(!this._localScaling){this._needToCompose=!1;return}this._needToCompose=!1,j.ComposeToRef(this._localScaling,this._localRotation,this._localPosition,this._localMatrix)}}updateMatrix(e,t=!0,i=!0){this._bindMatrix.copyFrom(e),t&&this._updateAbsoluteBindMatrices(),i?this._matrix=e:this.markAsDirty()}_updateAbsoluteBindMatrices(e,t=!0){if(e||(e=this._bindMatrix),this.parent?e.multiplyToRef(this.parent._absoluteBindMatrix,this._absoluteBindMatrix):this._absoluteBindMatrix.copyFrom(e),this._absoluteBindMatrix.invertToRef(this._absoluteInverseBindMatrix),t)for(let i=0;i{Fr();Gg=class n extends _e{constructor(e,t,i,r,s,a=!0,o=!1,l=3,c=0,f,h,d,u){super(null,s,!a,o,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,f),this.format=r,this._engine&&(!this._engine._caps.textureFloatLinearFiltering&&c===1&&(l=1),!this._engine._caps.textureHalfFloatLinearFiltering&&c===2&&(l=1),this._texture=this._engine.createRawTexture(e,t,i,r,a,o,l,null,c,f!=null?f:0,h!=null?h:!1,u),this.wrapU=_e.CLAMP_ADDRESSMODE,this.wrapV=_e.CLAMP_ADDRESSMODE,this._waitingForData=!!d&&!e)}update(e){this.updateMipLevel(e,0)}updateMipLevel(e,t){this._getEngine().updateRawTexture(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type,this._texture._useSRGBBuffer,t),this._waitingForData=!1}clone(){if(!this._texture)return super.clone();let e=new n(null,this.getSize().width,this.getSize().height,this.format,this.getScene(),this._texture.generateMipMaps,this._invertY,this.samplingMode,this._texture.type,this._texture._creationFlags,this._useSRGBBuffer);return e._texture=this._texture,this._texture.incrementReferences(),e}isReady(){return super.isReady()&&!this._waitingForData}static CreateLuminanceTexture(e,t,i,r,s=!0,a=!1,o=3){return new n(e,t,i,1,r,s,a,o)}static CreateLuminanceAlphaTexture(e,t,i,r,s=!0,a=!1,o=3){return new n(e,t,i,2,r,s,a,o)}static CreateAlphaTexture(e,t,i,r,s=!0,a=!1,o=3){return new n(e,t,i,0,r,s,a,o)}static CreateRGBTexture(e,t,i,r,s=!0,a=!1,o=3,l=0,c=0,f=!1){return new n(e,t,i,4,r,s,a,o,l,c,f)}static CreateRGBATexture(e,t,i,r,s=!0,a=!1,o=3,l=0,c=0,f=!1,h=!1){return new n(e,t,i,5,r,s,a,o,l,c,f,h)}static CreateRGBAStorageTexture(e,t,i,r,s=!0,a=!1,o=3,l=0,c=!1){return new n(e,t,i,5,r,s,a,o,l,1,c)}static CreateRTexture(e,t,i,r,s=!0,a=!1,o=_e.TRILINEAR_SAMPLINGMODE,l=1){return new n(e,t,i,6,r,s,a,o,l)}static CreateRStorageTexture(e,t,i,r,s=!0,a=!1,o=_e.TRILINEAR_SAMPLINGMODE,l=1){return new n(e,t,i,6,r,s,a,o,l,1)}}});var dR,KX=C(()=>{hR();hi();Ve();YX();Mf();My();Pi();yt();W_();dR=class n{get useTextureToStoreBoneMatrices(){return this._useTextureToStoreBoneMatrices}set useTextureToStoreBoneMatrices(e){this._useTextureToStoreBoneMatrices=e,this._markAsDirty()}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}get isUsingTextureForMatrices(){return this.useTextureToStoreBoneMatrices&&this._canUseTextureForBones}get uniqueId(){return this._uniqueId}constructor(e,t,i){this.name=e,this.id=t,this.bones=[],this.needInitialSkinMatrix=!1,this._isDirty=!0,this._meshesWithPoseMatrix=new Array,this._identity=j.Identity(),this._currentRenderId=-1,this._textureWidth=0,this._textureHeight=1,this._ranges={},this._absoluteTransformIsDirty=!0,this._canUseTextureForBones=!1,this._uniqueId=0,this._numBonesWithLinkedTransformNode=0,this._hasWaitingData=null,this._parentContainer=null,this.doNotSerialize=!1,this._useTextureToStoreBoneMatrices=!0,this._animationPropertiesOverride=null,this.onBeforeComputeObservable=new ie,this.metadata=null,this.bones=[],this._scene=i||Le.LastCreatedScene,this._uniqueId=this._scene.getUniqueId(),this._scene.addSkeleton(this),this._isDirty=!0;let r=this._scene.getEngine().getCaps();this._canUseTextureForBones=r.textureFloat&&r.maxVertexTextureImageUnits>0}getClassName(){return"Skeleton"}getChildren(){return this.bones.filter(e=>!e.getParent())}getTransformMatrices(e){if(this.needInitialSkinMatrix){if(!e)throw new Error("getTransformMatrices: When using the needInitialSkinMatrix flag, a mesh must be provided");return e._bonesTransformMatrices||this.prepare(!0),e._bonesTransformMatrices}return(!this._transformMatrices||this._isDirty)&&this.prepare(!this._transformMatrices),this._transformMatrices}getTransformMatrixTexture(e){return this.needInitialSkinMatrix&&e._transformMatrixTexture?e._transformMatrixTexture:this._transformMatrixTexture}getScene(){return this._scene}toString(e){let t=`Name: ${this.name}, nBones: ${this.bones.length}`;if(t+=`, nAnimationRanges: ${this._ranges?Object.keys(this._ranges).length:"none"}`,e){t+=", Ranges: {";let i=!0;for(let r in this._ranges)i&&(t+=", ",i=!1),t+=r;t+="}"}return t}getBoneIndexByName(e){for(let t=0,i=this.bones.length;t-1&&this._meshesWithPoseMatrix.splice(t,1)}_computeTransformMatrices(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(let i=0;i0){for(let r of this.bones)if(r._linkedTransformNode){let s=r._linkedTransformNode;r.position=s.position,s.rotationQuaternion?r.rotationQuaternion=s.rotationQuaternion:r.rotation=s.rotation,r.scaling=s.scaling}}let t=null;if(this.needInitialSkinMatrix)for(let r of this._meshesWithPoseMatrix){let s=r.getPoseMatrix(),a=this._isDirty;if(t===null&&(t=this._computeTextureSize()),(!r._bonesTransformMatrices||r._bonesTransformMatrices.length!==t)&&(r._bonesTransformMatrices=new Float32Array(t),a=!0),!!a){if(this._synchronizedWithMesh!==r){this._synchronizedWithMesh=r;for(let o of this.bones)o.getParent()||(o.getBindMatrix().multiplyToRef(s,$.Matrix[1]),o._updateAbsoluteBindMatrices($.Matrix[1]));if(this.isUsingTextureForMatrices){let o=(i=r._transformMatrixTexture)==null?void 0:i.getSize(),l=o?o.width*o.height*4:0;(!r._transformMatrixTexture||l!==t)&&(r._transformMatrixTexture&&r._transformMatrixTexture.dispose(),r._transformMatrixTexture=Gg.CreateRGBATexture(r._bonesTransformMatrices,this._textureWidth,this._textureHeight,this._scene,!1,!1,1,1))}}this._computeTransformMatrices(r._bonesTransformMatrices,s),this.isUsingTextureForMatrices&&r._transformMatrixTexture&&r._transformMatrixTexture.update(r._bonesTransformMatrices)}}else{if(!this._isDirty)return;t===null&&(t=this._computeTextureSize()),(!this._transformMatrices||this._transformMatrices.length!==t)&&(this._transformMatrices=new Float32Array(t),this.isUsingTextureForMatrices&&(this._transformMatrixTexture&&this._transformMatrixTexture.dispose(),this._transformMatrixTexture=Gg.CreateRGBATexture(this._transformMatrices,this._textureWidth,this._textureHeight,this._scene,!1,!1,1,1))),this._computeTransformMatrices(this._transformMatrices,null),this.isUsingTextureForMatrices&&this._transformMatrixTexture&&this._transformMatrixTexture.update(this._transformMatrices)}this._isDirty=!1}getAnimatables(){if(!this._animatables||this._animatables.length!==this.bones.length){this._animatables=[];for(let e=0;e-1&&this._parentContainer.skeletons.splice(e,1),this._parentContainer=null}this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null)}serialize(){var t,i;let e={};e.name=this.name,e.id=this.id,e.uniqueId=this.uniqueId,this.dimensionsAtRest&&(e.dimensionsAtRest=this.dimensionsAtRest.asArray()),e.bones=[],e.needInitialSkinMatrix=this.needInitialSkinMatrix,this.metadata&&(e.metadata=this.metadata);for(let r=0;r0&&(o.animation=s.animations[0].serialize()),e.ranges=[];for(let l in this._ranges){let c=this._ranges[l];if(!c)continue;let f={};f.name=l,f.from=c.from,f.to=c.to,e.ranges.push(f)}}return e}static Parse(e,t){let i=new n(e.name,e.id,t);e.dimensionsAtRest&&(i.dimensionsAtRest=b.FromArray(e.dimensionsAtRest)),i.needInitialSkinMatrix=e.needInitialSkinMatrix,e.metadata&&(i.metadata=e.metadata);let r;for(r=0;r-1&&(o=i.bones[s.parentBoneIndex]);let l=s.rest?j.FromArray(s.rest):null,c=new Fa(s.name,i,o,j.FromArray(s.matrix),l,null,a);s.id!==void 0&&s.id!==null&&(c.id=s.id),s.length&&(c.length=s.length),s.metadata&&(c.metadata=s.metadata),s.animation&&c.animations.push(ft.Parse(s.animation)),s.linkedTransformNodeId!==void 0&&s.linkedTransformNodeId!==null&&(i._hasWaitingData=!0,c._waitingTransformNodeId=s.linkedTransformNodeId),s.linkedTransformNodeUniqueId!==void 0&&s.linkedTransformNodeUniqueId!==null&&(i._hasWaitingData=!0,c._waitingTransformNodeUniqueId=s.linkedTransformNodeUniqueId)}if(e.ranges)for(r=0;r0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e}sortBones(){let e=[],t=new Array(this.bones.length);for(let i=0;i{Gt();hi();Pi();Gi();Ut();Tr();Hi();qf=class n{get influence(){return this._influence}set influence(e){if(this._influence===e)return;let t=this._influence;this._influence=e,this.onInfluenceChanged.hasObservers()&&this.onInfluenceChanged.notifyObservers(t===0||e===0)}get animationPropertiesOverride(){return!this._animationPropertiesOverride&&this._scene?this._scene.animationPropertiesOverride:this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}constructor(e,t=0,i=null,r=null){this.name=e,this.animations=[],this._positions=null,this._normals=null,this._tangents=null,this._uvs=null,this._uv2s=null,this._colors=null,this._uniqueId=0,this.onInfluenceChanged=new ie,this._onDataLayoutChanged=new ie,this.morphTargetManager=null,this._animationPropertiesOverride=null,this.id=e,this.morphTargetManager=r,this._scene=i||Le.LastCreatedScene,this.influence=t,this._scene&&(this._uniqueId=this._scene.getUniqueId())}get uniqueId(){return this._uniqueId}get hasPositions(){return!!this._positions}get hasNormals(){return!!this._normals}get hasTangents(){return!!this._tangents}get hasUVs(){return!!this._uvs}get hasUV2s(){return!!this._uv2s}get hasColors(){return!!this._colors}get vertexCount(){return this._positions?this._positions.length/3:this._normals?this._normals.length/3:this._tangents?this._tangents.length/3:this._uvs?this._uvs.length/2:this._uv2s?this._uv2s.length/2:this._colors?this._colors.length/4:0}setPositions(e){let t=this.hasPositions;this._positions=e,t!==this.hasPositions&&this._onDataLayoutChanged.notifyObservers(void 0)}getPositions(){return this._positions}setNormals(e){let t=this.hasNormals;this._normals=e,t!==this.hasNormals&&this._onDataLayoutChanged.notifyObservers(void 0)}getNormals(){return this._normals}setTangents(e){let t=this.hasTangents;this._tangents=e,t!==this.hasTangents&&this._onDataLayoutChanged.notifyObservers(void 0)}getTangents(){return this._tangents}setUVs(e){let t=this.hasUVs;this._uvs=e,t!==this.hasUVs&&this._onDataLayoutChanged.notifyObservers(void 0)}getUVs(){return this._uvs}setUV2s(e){let t=this.hasUV2s;this._uv2s=e,t!==this.hasUV2s&&this._onDataLayoutChanged.notifyObservers(void 0)}getUV2s(){return this._uv2s}setColors(e){let t=this.hasColors;this._colors=e,t!==this.hasColors&&this._onDataLayoutChanged.notifyObservers(void 0)}getColors(){return this._colors}clone(){let e=it.Clone(()=>new n(this.name,this.influence,this._scene,this.morphTargetManager),this);return e._positions=this._positions,e._normals=this._normals,e._tangents=this._tangents,e._uvs=this._uvs,e._uv2s=this._uv2s,e._colors=this._colors,e}serialize(){let e={};return e.name=this.name,e.influence=this.influence,this.id!=null&&(e.id=this.id),e.uniqueId=this.uniqueId,e.positions=Array.prototype.slice.call(this.getPositions()),this.hasNormals&&(e.normals=Array.prototype.slice.call(this.getNormals())),this.hasTangents&&(e.tangents=Array.prototype.slice.call(this.getTangents())),this.hasUVs&&(e.uvs=Array.prototype.slice.call(this.getUVs())),this.hasUV2s&&(e.uv2s=Array.prototype.slice.call(this.getUV2s())),this.hasColors&&(e.colors=Array.prototype.slice.call(this.getColors())),it.AppendSerializedAnimations(this,e),e}getClassName(){return"MorphTarget"}static Parse(e,t,i=null){let r=new n(e.name,e.influence,t,i);if(r.setPositions(e.positions),e.id!=null&&(r.id=e.id),e.normals&&r.setNormals(e.normals),e.tangents&&r.setTangents(e.tangents),e.uvs&&r.setUVs(e.uvs),e.uv2s&&r.setUV2s(e.uv2s),e.colors&&r.setColors(e.colors),e.animations){for(let s=0;s{Fr();uR=class n extends _e{get depth(){return this._depth}constructor(e,t,i,r,s,a,o=!0,l=!1,c=_e.TRILINEAR_SAMPLINGMODE,f=0,h,d){super(null,a,!o,l),this.format=s,this._texture=a.getEngine().createRawTexture2DArray(e,t,i,r,s,o,l,c,null,f,h!=null?h:0,d),this._depth=r,this.is2DArray=!0}update(e){this.updateMipLevel(e,0)}updateMipLevel(e,t){this._texture&&this._getEngine().updateRawTexture2DArray(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type,t)}static CreateRGBATexture(e,t,i,r,s,a=!0,o=!1,l=3,c=0){return new n(e,t,i,r,5,s,a,o,l,c)}}});var dd,qX=C(()=>{so();yt();Pi();BD();jX();dd=class n{set areUpdatesFrozen(e){e?this._blockCounter++:(this._blockCounter--,this._blockCounter<=0&&(this._blockCounter=0,this._syncActiveTargets(this._forceUpdateWhenUnfrozen),this._forceUpdateWhenUnfrozen=!1))}get areUpdatesFrozen(){return this._blockCounter>0}constructor(e=null,t){if(this.meshName=t,this._targets=new Array,this._targetInfluenceChangedObservers=new Array,this._targetDataLayoutChangedObservers=new Array,this._activeTargets=new wi(16),this._supportsPositions=!1,this._supportsNormals=!1,this._supportsTangents=!1,this._supportsUVs=!1,this._supportsUV2s=!1,this._supportsColors=!1,this._vertexCount=0,this._uniqueId=0,this._tempInfluences=new Array,this._canUseTextureForTargets=!1,this._blockCounter=0,this._mustSynchronize=!0,this._forceUpdateWhenUnfrozen=!1,this._textureVertexStride=0,this._textureWidth=0,this._textureHeight=1,this._parentContainer=null,this.optimizeInfluencers=!0,this.enablePositionMorphing=!0,this.enableNormalMorphing=!0,this.enableTangentMorphing=!0,this.enableUVMorphing=!0,this.enableUV2Morphing=!0,this.enableColorMorphing=!0,this._numMaxInfluencers=0,this._useTextureToStoreTargets=!0,this.metadata=null,this._influencesAreDirty=!1,this._needUpdateInfluences=!1,e||(e=Le.LastCreatedScene),this._scene=e,this._scene){this._scene.addMorphTargetManager(this),this._uniqueId=this._scene.getUniqueId();let i=this._scene.getEngine().getCaps();this._canUseTextureForTargets=i.canUseGLVertexID&&i.textureFloat&&i.maxVertexTextureImageUnits>0&&i.texture2DArrayMaxLayerCount>1}}get numMaxInfluencers(){return n.ConstantTargetCountForTextureMode>0&&this.isUsingTextureForTargets?n.ConstantTargetCountForTextureMode:this._numMaxInfluencers}set numMaxInfluencers(e){this._numMaxInfluencers!==e&&(this._numMaxInfluencers=e,this._mustSynchronize=!0,this._syncActiveTargets())}get uniqueId(){return this._uniqueId}get vertexCount(){return this._vertexCount}get supportsPositions(){return this._supportsPositions&&this.enablePositionMorphing}get supportsNormals(){return this._supportsNormals&&this.enableNormalMorphing}get supportsTangents(){return this._supportsTangents&&this.enableTangentMorphing}get supportsUVs(){return this._supportsUVs&&this.enableUVMorphing}get supportsUV2s(){return this._supportsUV2s&&this.enableUV2Morphing}get supportsColors(){return this._supportsColors&&this.enableColorMorphing}get hasPositions(){return this._supportsPositions}get hasNormals(){return this._supportsNormals}get hasTangents(){return this._supportsTangents}get hasUVs(){return this._supportsUVs}get hasUV2s(){return this._supportsUV2s}get hasColors(){return this._supportsColors}get numTargets(){return this._targets.length}get numInfluencers(){return this._influencesAreDirty&&this._syncActiveTargets(),this._activeTargets.length}get influences(){return this._influencesAreDirty&&this._syncActiveTargets(),this._influences}get useTextureToStoreTargets(){return this._useTextureToStoreTargets}set useTextureToStoreTargets(e){this._useTextureToStoreTargets!==e&&(this._useTextureToStoreTargets=e,this._mustSynchronize=!0,this._syncActiveTargets())}get isUsingTextureForTargets(){var e;return n.EnableTextureStorage&&this.useTextureToStoreTargets&&this._canUseTextureForTargets&&!((e=this._scene)!=null&&e.getEngine().getCaps().disableMorphTargetTexture)}getActiveTarget(e){return this._influencesAreDirty&&this._syncActiveTargets(),this._activeTargets.data[e]}getTarget(e){return this._targets[e]}getTargetByName(e){for(let t of this._targets)if(t.name===e)return t;return null}addTarget(e){this._targets.push(e),this._targetInfluenceChangedObservers.push(e.onInfluenceChanged.add(t=>{this.areUpdatesFrozen&&t&&(this._forceUpdateWhenUnfrozen=!0),this._influencesAreDirty=!0,this._needUpdateInfluences=this._needUpdateInfluences||t})),this._targetDataLayoutChangedObservers.push(e._onDataLayoutChanged.add(()=>{this._mustSynchronize=!0,this._syncActiveTargets()})),this._mustSynchronize=!0,this._syncActiveTargets()}removeTarget(e){let t=this._targets.indexOf(e);t>=0&&(this._targets.splice(t,1),e.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(t,1)[0]),e._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(t,1)[0]),this._mustSynchronize=!0,this._syncActiveTargets()),this._scene&&this._scene.stopAnimation(e)}_bind(e){this._influencesAreDirty&&this._syncActiveTargets(),e.setFloat3("morphTargetTextureInfo",this._textureVertexStride,this._textureWidth,this._textureHeight),e.setFloatArray("morphTargetTextureIndices",this._morphTargetTextureIndices),e.setTexture("morphTargets",this._targetStoreTexture),e.setFloat("morphTargetCount",this.numInfluencers)}clone(){let e=new n(this._scene);e.areUpdatesFrozen=!0;for(let t of this._targets)e.addTarget(t.clone());return e.areUpdatesFrozen=!1,e.enablePositionMorphing=this.enablePositionMorphing,e.enableNormalMorphing=this.enableNormalMorphing,e.enableTangentMorphing=this.enableTangentMorphing,e.enableUVMorphing=this.enableUVMorphing,e.enableUV2Morphing=this.enableUV2Morphing,e.enableColorMorphing=this.enableColorMorphing,e.metadata=this.metadata,e}serialize(){let e={};e.id=this.uniqueId,e.meshName=this.meshName,e.targets=[];for(let t of this._targets)e.targets.push(t.serialize());return this.metadata&&(e.metadata=this.metadata),e}_syncActiveTargets(e=!1){if(this.areUpdatesFrozen)return;e=e||this._needUpdateInfluences,this._needUpdateInfluences=!1,this._influencesAreDirty=!1;let t=!!this._targetStoreTexture,i=this.isUsingTextureForTargets;(this._mustSynchronize||t!==i)&&(this._mustSynchronize=!1,this.synchronize());let r=0;this._activeTargets.reset(),(!this._morphTargetTextureIndices||this._morphTargetTextureIndices.length!==this._targets.length)&&(this._morphTargetTextureIndices=new Float32Array(this._targets.length));let s=-1;for(let a of this._targets)if(s++,!(a.influence===0&&this.optimizeInfluencers)){if(this._activeTargets.length>=n.MaxActiveMorphTargetsInVertexAttributeMode&&!this.isUsingTextureForTargets)break;this._activeTargets.push(a),this._morphTargetTextureIndices[r]=s,this._tempInfluences[r++]=a.influence}this._morphTargetTextureIndices.length!==r&&(this._morphTargetTextureIndices=this._morphTargetTextureIndices.slice(0,r)),(!this._influences||this._influences.length!==r)&&(this._influences=new Float32Array(r));for(let a=0;ae.getCaps().texture2DArrayMaxLayerCount&&(this.useTextureToStoreTargets=!1);for(let i of this._targets){this._supportsPositions=this._supportsPositions&&i.hasPositions,this._supportsNormals=this._supportsNormals&&i.hasNormals,this._supportsTangents=this._supportsTangents&&i.hasTangents,this._supportsUVs=this._supportsUVs&&i.hasUVs,this._supportsUV2s=this._supportsUV2s&&i.hasUV2s,this._supportsColors=this._supportsColors&&i.hasColors;let r=i.vertexCount;if(this._vertexCount===0)this._vertexCount=r;else if(this._vertexCount!==r){te.Error(`Incompatible target. Targets must all have the same vertices count. Current vertex count: ${this._vertexCount}, vertex count for target "${i.name}": ${r}`);return}}if(this.isUsingTextureForTargets){this._textureVertexStride=0,this._supportsPositions&&this._textureVertexStride++,this._supportsNormals&&this._textureVertexStride++,this._supportsTangents&&this._textureVertexStride++,this._supportsUVs&&this._textureVertexStride++,this._supportsUV2s&&this._textureVertexStride++,this._supportsColors&&this._textureVertexStride++,this._textureWidth=this._vertexCount*this._textureVertexStride||1,this._textureHeight=1;let i=e.getCaps().maxTextureSize;this._textureWidth>i&&(this._textureHeight=Math.ceil(this._textureWidth/i),this._textureWidth=i);let r=this._targets.length,s=new Float32Array(r*this._textureWidth*this._textureHeight*4),a;for(let o=0;o-1&&this._parentContainer.morphTargetManagers.splice(e,1),this._parentContainer=null}for(let e of this._targets)this._scene.stopAnimation(e)}}static Parse(e,t){let i=new n(t);for(let r of e.targets)i.addTarget(qf.Parse(r,t,i));return e.metadata&&(i.metadata=e.metadata),i}};dd.EnableTextureStorage=!0;dd.MaxActiveMorphTargetsInVertexAttributeMode=8;dd.ConstantTargetCountForTextureMode=0});function mR(n,e,t){kg(n)&&te.Warn(`Extension with the name '${n}' already exists`),UD.set(n,{isGLTFExtension:e,factory:t})}function kg(n){return UD.delete(n)}var UD,ZX,VD=C(()=>{yt();UD=new Map,ZX=UD});var H,GD=C(()=>{H=class{};H.AUTOSAMPLERSUFFIX="Sampler";H.DISABLEUA="#define DISABLE_UNIFORMITY_ANALYSIS";H.ALPHA_DISABLE=0;H.ALPHA_ADD=1;H.ALPHA_COMBINE=2;H.ALPHA_SUBTRACT=3;H.ALPHA_MULTIPLY=4;H.ALPHA_MAXIMIZED=5;H.ALPHA_ONEONE=6;H.ALPHA_PREMULTIPLIED=7;H.ALPHA_PREMULTIPLIED_PORTERDUFF=8;H.ALPHA_INTERPOLATE=9;H.ALPHA_SCREENMODE=10;H.ALPHA_ONEONE_ONEONE=11;H.ALPHA_ALPHATOCOLOR=12;H.ALPHA_REVERSEONEMINUS=13;H.ALPHA_SRC_DSTONEMINUSSRCALPHA=14;H.ALPHA_ONEONE_ONEZERO=15;H.ALPHA_EXCLUSION=16;H.ALPHA_LAYER_ACCUMULATE=17;H.ALPHA_MIN=18;H.ALPHA_MAX=19;H.ALPHA_DUAL_SRC0_ADD_SRC1xDST=20;H.ALPHA_EQUATION_ADD=0;H.ALPHA_EQUATION_SUBSTRACT=1;H.ALPHA_EQUATION_REVERSE_SUBTRACT=2;H.ALPHA_EQUATION_MAX=3;H.ALPHA_EQUATION_MIN=4;H.ALPHA_EQUATION_DARKEN=5;H.DELAYLOADSTATE_NONE=0;H.DELAYLOADSTATE_LOADED=1;H.DELAYLOADSTATE_LOADING=2;H.DELAYLOADSTATE_NOTLOADED=4;H.NEVER=512;H.ALWAYS=519;H.LESS=513;H.EQUAL=514;H.LEQUAL=515;H.GREATER=516;H.GEQUAL=518;H.NOTEQUAL=517;H.KEEP=7680;H.ZERO=0;H.REPLACE=7681;H.INCR=7682;H.DECR=7683;H.INVERT=5386;H.INCR_WRAP=34055;H.DECR_WRAP=34056;H.TEXTURE_CLAMP_ADDRESSMODE=0;H.TEXTURE_WRAP_ADDRESSMODE=1;H.TEXTURE_MIRROR_ADDRESSMODE=2;H.TEXTURE_CREATIONFLAG_STORAGE=1;H.TEXTUREFORMAT_ALPHA=0;H.TEXTUREFORMAT_LUMINANCE=1;H.TEXTUREFORMAT_LUMINANCE_ALPHA=2;H.TEXTUREFORMAT_RGB=4;H.TEXTUREFORMAT_RGBA=5;H.TEXTUREFORMAT_RED=6;H.TEXTUREFORMAT_R=6;H.TEXTUREFORMAT_R16_UNORM=33322;H.TEXTUREFORMAT_RG16_UNORM=33324;H.TEXTUREFORMAT_RGB16_UNORM=32852;H.TEXTUREFORMAT_RGBA16_UNORM=32859;H.TEXTUREFORMAT_R16_SNORM=36760;H.TEXTUREFORMAT_RG16_SNORM=36761;H.TEXTUREFORMAT_RGB16_SNORM=36762;H.TEXTUREFORMAT_RGBA16_SNORM=36763;H.TEXTUREFORMAT_RG=7;H.TEXTUREFORMAT_RED_INTEGER=8;H.TEXTUREFORMAT_R_INTEGER=8;H.TEXTUREFORMAT_RG_INTEGER=9;H.TEXTUREFORMAT_RGB_INTEGER=10;H.TEXTUREFORMAT_RGBA_INTEGER=11;H.TEXTUREFORMAT_BGRA=12;H.TEXTUREFORMAT_DEPTH24_STENCIL8=13;H.TEXTUREFORMAT_DEPTH32_FLOAT=14;H.TEXTUREFORMAT_DEPTH16=15;H.TEXTUREFORMAT_DEPTH24=16;H.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8=17;H.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8=18;H.TEXTUREFORMAT_STENCIL8=19;H.TEXTUREFORMAT_UNDEFINED=4294967295;H.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM=36492;H.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM=36493;H.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT=36495;H.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT=36494;H.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5=33779;H.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919;H.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3=33778;H.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918;H.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1=33777;H.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1=33776;H.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917;H.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT=35916;H.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4=37808;H.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_5x4=37809;H.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_5x5=37810;H.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_6x5=37811;H.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_6x6=37812;H.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_8x5=37813;H.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_8x6=37814;H.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_8x8=37815;H.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_10x5=37816;H.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_10x6=37817;H.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_10x8=37818;H.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_10x10=37819;H.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_12x10=37820;H.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_12x12=37821;H.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=37840;H.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR=37841;H.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR=37842;H.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR=37843;H.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR=37844;H.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR=37845;H.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR=37846;H.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR=37847;H.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR=37848;H.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR=37849;H.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR=37850;H.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR=37851;H.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR=37852;H.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR=37853;H.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL=36196;H.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2=37492;H.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2=37493;H.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=37494;H.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=37495;H.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC=37496;H.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=37497;H.TEXTURETYPE_UNSIGNED_BYTE=0;H.TEXTURETYPE_UNSIGNED_INT=0;H.TEXTURETYPE_FLOAT=1;H.TEXTURETYPE_HALF_FLOAT=2;H.TEXTURETYPE_BYTE=3;H.TEXTURETYPE_SHORT=4;H.TEXTURETYPE_UNSIGNED_SHORT=5;H.TEXTURETYPE_INT=6;H.TEXTURETYPE_UNSIGNED_INTEGER=7;H.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8;H.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9;H.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10;H.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11;H.TEXTURETYPE_UNSIGNED_INT_24_8=12;H.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13;H.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14;H.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15;H.TEXTURETYPE_UNDEFINED=16;H.TEXTURE_2D=3553;H.TEXTURE_2D_ARRAY=35866;H.TEXTURE_CUBE_MAP=34067;H.TEXTURE_CUBE_MAP_ARRAY=3735928559;H.TEXTURE_3D=32879;H.TEXTURE_NEAREST_SAMPLINGMODE=1;H.TEXTURE_NEAREST_NEAREST=1;H.TEXTURE_BILINEAR_SAMPLINGMODE=2;H.TEXTURE_LINEAR_LINEAR=2;H.TEXTURE_TRILINEAR_SAMPLINGMODE=3;H.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3;H.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4;H.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5;H.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6;H.TEXTURE_NEAREST_LINEAR=7;H.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8;H.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9;H.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10;H.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11;H.TEXTURE_LINEAR_NEAREST=12;H.TEXTURE_EXPLICIT_MODE=0;H.TEXTURE_SPHERICAL_MODE=1;H.TEXTURE_PLANAR_MODE=2;H.TEXTURE_CUBIC_MODE=3;H.TEXTURE_PROJECTION_MODE=4;H.TEXTURE_SKYBOX_MODE=5;H.TEXTURE_INVCUBIC_MODE=6;H.TEXTURE_EQUIRECTANGULAR_MODE=7;H.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8;H.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;H.TEXTURE_FILTERING_QUALITY_OFFLINE=4096;H.TEXTURE_FILTERING_QUALITY_HIGH=64;H.TEXTURE_FILTERING_QUALITY_MEDIUM=16;H.TEXTURE_FILTERING_QUALITY_LOW=8;H.SCALEMODE_FLOOR=1;H.SCALEMODE_NEAREST=2;H.SCALEMODE_CEILING=3;H.MATERIAL_TextureDirtyFlag=1;H.MATERIAL_LightDirtyFlag=2;H.MATERIAL_FresnelDirtyFlag=4;H.MATERIAL_AttributesDirtyFlag=8;H.MATERIAL_MiscDirtyFlag=16;H.MATERIAL_PrePassDirtyFlag=32;H.MATERIAL_ImageProcessingDirtyFlag=64;H.MATERIAL_AllDirtyFlag=127;H.MATERIAL_TriangleFillMode=0;H.MATERIAL_WireFrameFillMode=1;H.MATERIAL_PointFillMode=2;H.MATERIAL_PointListDrawMode=3;H.MATERIAL_LineListDrawMode=4;H.MATERIAL_LineLoopDrawMode=5;H.MATERIAL_LineStripDrawMode=6;H.MATERIAL_TriangleStripDrawMode=7;H.MATERIAL_TriangleFanDrawMode=8;H.MATERIAL_ClockWiseSideOrientation=0;H.MATERIAL_CounterClockWiseSideOrientation=1;H.MATERIAL_DIFFUSE_MODEL_E_OREN_NAYAR=0;H.MATERIAL_DIFFUSE_MODEL_BURLEY=1;H.MATERIAL_DIFFUSE_MODEL_LAMBERT=2;H.MATERIAL_DIFFUSE_MODEL_LEGACY=3;H.MATERIAL_DIELECTRIC_SPECULAR_MODEL_GLTF=0;H.MATERIAL_DIELECTRIC_SPECULAR_MODEL_OPENPBR=1;H.MATERIAL_CONDUCTOR_SPECULAR_MODEL_GLTF=0;H.MATERIAL_CONDUCTOR_SPECULAR_MODEL_OPENPBR=1;H.ACTION_NothingTrigger=0;H.ACTION_OnPickTrigger=1;H.ACTION_OnLeftPickTrigger=2;H.ACTION_OnRightPickTrigger=3;H.ACTION_OnCenterPickTrigger=4;H.ACTION_OnPickDownTrigger=5;H.ACTION_OnDoublePickTrigger=6;H.ACTION_OnPickUpTrigger=7;H.ACTION_OnPickOutTrigger=16;H.ACTION_OnLongPressTrigger=8;H.ACTION_OnPointerOverTrigger=9;H.ACTION_OnPointerOutTrigger=10;H.ACTION_OnEveryFrameTrigger=11;H.ACTION_OnIntersectionEnterTrigger=12;H.ACTION_OnIntersectionExitTrigger=13;H.ACTION_OnKeyDownTrigger=14;H.ACTION_OnKeyUpTrigger=15;H.PARTICLES_BILLBOARDMODE_Y=2;H.PARTICLES_BILLBOARDMODE_ALL=7;H.PARTICLES_BILLBOARDMODE_STRETCHED=8;H.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL=9;H.MESHES_CULLINGSTRATEGY_STANDARD=0;H.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1;H.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2;H.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3;H.SCENELOADER_NO_LOGGING=0;H.SCENELOADER_MINIMAL_LOGGING=1;H.SCENELOADER_SUMMARY_LOGGING=2;H.SCENELOADER_DETAILED_LOGGING=3;H.PREPASS_IRRADIANCE_LEGACY_TEXTURE_TYPE=0;H.PREPASS_POSITION_TEXTURE_TYPE=1;H.PREPASS_VELOCITY_TEXTURE_TYPE=2;H.PREPASS_REFLECTIVITY_TEXTURE_TYPE=3;H.PREPASS_COLOR_TEXTURE_TYPE=4;H.PREPASS_DEPTH_TEXTURE_TYPE=5;H.PREPASS_NORMAL_TEXTURE_TYPE=6;H.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE=7;H.PREPASS_WORLD_NORMAL_TEXTURE_TYPE=8;H.PREPASS_LOCAL_POSITION_TEXTURE_TYPE=9;H.PREPASS_SCREENSPACE_DEPTH_TEXTURE_TYPE=10;H.PREPASS_VELOCITY_LINEAR_TEXTURE_TYPE=11;H.PREPASS_ALBEDO_TEXTURE_TYPE=12;H.PREPASS_NORMALIZED_VIEW_DEPTH_TEXTURE_TYPE=13;H.PREPASS_IRRADIANCE_TEXTURE_TYPE=14;H.BUFFER_CREATIONFLAG_READ=1;H.BUFFER_CREATIONFLAG_WRITE=2;H.BUFFER_CREATIONFLAG_READWRITE=3;H.BUFFER_CREATIONFLAG_UNIFORM=4;H.BUFFER_CREATIONFLAG_VERTEX=8;H.BUFFER_CREATIONFLAG_INDEX=16;H.BUFFER_CREATIONFLAG_STORAGE=32;H.BUFFER_CREATIONFLAG_INDIRECT=64;H.RENDERPASS_MAIN=0;H.INPUT_ALT_KEY=18;H.INPUT_CTRL_KEY=17;H.INPUT_META_KEY1=91;H.INPUT_META_KEY2=92;H.INPUT_META_KEY3=93;H.INPUT_SHIFT_KEY=16;H.SNAPSHOTRENDERING_STANDARD=0;H.SNAPSHOTRENDERING_FAST=1;H.PERSPECTIVE_CAMERA=0;H.ORTHOGRAPHIC_CAMERA=1;H.FOVMODE_VERTICAL_FIXED=0;H.FOVMODE_HORIZONTAL_FIXED=1;H.RIG_MODE_NONE=0;H.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10;H.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11;H.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12;H.RIG_MODE_STEREOSCOPIC_OVERUNDER=13;H.RIG_MODE_STEREOSCOPIC_INTERLACED=14;H.RIG_MODE_VR=20;H.RIG_MODE_CUSTOM=22;H.MAX_SUPPORTED_UV_SETS=6;H.GL_ALPHA_EQUATION_ADD=32774;H.GL_ALPHA_EQUATION_MIN=32775;H.GL_ALPHA_EQUATION_MAX=32776;H.GL_ALPHA_EQUATION_SUBTRACT=32778;H.GL_ALPHA_EQUATION_REVERSE_SUBTRACT=32779;H.GL_ALPHA_FUNCTION_SRC=768;H.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR=769;H.GL_ALPHA_FUNCTION_SRC_ALPHA=770;H.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA=771;H.GL_ALPHA_FUNCTION_DST_ALPHA=772;H.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA=773;H.GL_ALPHA_FUNCTION_DST_COLOR=774;H.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR=775;H.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED=776;H.GL_ALPHA_FUNCTION_CONSTANT_COLOR=32769;H.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR=32770;H.GL_ALPHA_FUNCTION_CONSTANT_ALPHA=32771;H.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA=32772;H.GL_ALPHA_FUNCTION_SRC1_COLOR=35065;H.GL_ALPHA_FUNCTION_ONE_MINUS_SRC1_COLOR=35066;H.GL_ALPHA_FUNCTION_SRC1_ALPHA=34185;H.GL_ALPHA_FUNCTION_ONE_MINUS_SRC1_ALPHA=35067;H.SnippetUrl="https://snippet.babylonjs.com";H.FOGMODE_NONE=0;H.FOGMODE_EXP=1;H.FOGMODE_EXP2=2;H.FOGMODE_LINEAR=3;H.BYTE=5120;H.UNSIGNED_BYTE=5121;H.SHORT=5122;H.UNSIGNED_SHORT=5123;H.INT=5124;H.UNSIGNED_INT=5125;H.FLOAT=5126;H.PositionKind="position";H.NormalKind="normal";H.TangentKind="tangent";H.UVKind="uv";H.UV2Kind="uv2";H.UV3Kind="uv3";H.UV4Kind="uv4";H.UV5Kind="uv5";H.UV6Kind="uv6";H.ColorKind="color";H.ColorInstanceKind="instanceColor";H.MatricesIndicesKind="matricesIndices";H.MatricesWeightsKind="matricesWeights";H.MatricesIndicesExtraKind="matricesIndicesExtra";H.MatricesWeightsExtraKind="matricesWeightsExtra";H.ANIMATIONTYPE_FLOAT=0;H.ANIMATIONTYPE_VECTOR3=1;H.ANIMATIONTYPE_QUATERNION=2;H.ANIMATIONTYPE_MATRIX=3;H.ANIMATIONTYPE_COLOR3=4;H.ANIMATIONTYPE_COLOR4=7;H.ANIMATIONTYPE_VECTOR2=5;H.ANIMATIONTYPE_SIZE=6;H.ShadowMinZ=0;H.ShadowMaxZ=1e4;H.OUTLINELAYER_SAMPLING_TRIDIRECTIONAL=0;H.OUTLINELAYER_SAMPLING_OCTADIRECTIONAL=1});var _Ke,QX=C(()=>{_Ke=[{regex:new RegExp("^/nodes/\\d+/extensions/")}]});function Zf(n,e,t,i){let r=at(n,e);return i?r[t][i]:r[t]}function at(n,e,t){var i,r,s;return(s=(r=n._data)==null?void 0:r[(i=t==null?void 0:t.fillMode)!=null?i:H.MATERIAL_TriangleFillMode])==null?void 0:s.babylonMaterial}function nn(n,e){return{offset:{componentsCount:2,type:"Vector2",get:(t,i,r)=>{let s=Zf(t,r,n,e);return new we(s==null?void 0:s.uOffset,s==null?void 0:s.vOffset)},getTarget:at,set:(t,i,r,s)=>{let a=Zf(i,s,n,e);a.uOffset=t.x,a.vOffset=t.y},getPropertyName:[()=>`${n}${e?"."+e:""}.uOffset`,()=>`${n}${e?"."+e:""}.vOffset`]},rotation:{type:"number",get:(t,i,r)=>{var s;return(s=Zf(t,r,n,e))==null?void 0:s.wAng},getTarget:at,set:(t,i,r,s)=>Zf(i,s,n,e).wAng=t,getPropertyName:[()=>`${n}${e?"."+e:""}.wAng`]},scale:{componentsCount:2,type:"Vector2",get:(t,i,r)=>{let s=Zf(t,r,n,e);return new we(s==null?void 0:s.uScale,s==null?void 0:s.vScale)},getTarget:at,set:(t,i,r,s)=>{let a=Zf(i,s,n,e);a.uScale=t.x,a.vScale=t.y},getPropertyName:[()=>`${n}${e?"."+e:""}.uScale`,()=>`${n}${e?"."+e:""}.vScale`]}}}function Wg(n){let e=n.split("/").map(i=>i.replace(/{}/g,"__array__")),t=$X;for(let i of e)i&&(t=t[i]);if(t&&t.type&&t.get)return t}function Hg(n,e){let t=n.split("/").map(r=>r.replace(/{}/g,"__array__")),i=$X;for(let r of t)r&&(i=i[r]);i&&i.type&&i.get&&(i.interpolation=e)}var Tce,Ace,xce,Rce,bce,Ice,$X,kD=C(()=>{Ve();GD();zt();Fy();QX();Tce={length:{type:"number",get:n=>n.length,getTarget:n=>n.map(e=>e._babylonTransformNode),getPropertyName:[()=>"length"]},__array__:{__target__:!0,translation:{type:"Vector3",get:n=>{var e;return(e=n._babylonTransformNode)==null?void 0:e.position},set:(n,e)=>{var t;return(t=e._babylonTransformNode)==null?void 0:t.position.copyFrom(n)},getTarget:n=>n._babylonTransformNode,getPropertyName:[()=>"position"]},rotation:{type:"Quaternion",get:n=>{var e;return(e=n._babylonTransformNode)==null?void 0:e.rotationQuaternion},set:(n,e)=>{var t,i;return(i=(t=e._babylonTransformNode)==null?void 0:t.rotationQuaternion)==null?void 0:i.copyFrom(n)},getTarget:n=>n._babylonTransformNode,getPropertyName:[()=>"rotationQuaternion"]},scale:{type:"Vector3",get:n=>{var e;return(e=n._babylonTransformNode)==null?void 0:e.scaling},set:(n,e)=>{var t;return(t=e._babylonTransformNode)==null?void 0:t.scaling.copyFrom(n)},getTarget:n=>n._babylonTransformNode,getPropertyName:[()=>"scaling"]},weights:{length:{type:"number",get:n=>n._numMorphTargets,getTarget:n=>n._babylonTransformNode,getPropertyName:[()=>"influence"]},__array__:{__target__:!0,type:"number",get:(n,e)=>{var t,i;return e!==void 0?(i=(t=n._primitiveBabylonMeshes)==null?void 0:t[0].morphTargetManager)==null?void 0:i.getTarget(e).influence:void 0},getTarget:n=>n._babylonTransformNode,getPropertyName:[()=>"influence"]},type:"number[]",get:(n,e)=>[0],getTarget:n=>n._babylonTransformNode,getPropertyName:[()=>"influence"]},matrix:{type:"Matrix",get:n=>{var e,t,i;return j.Compose((e=n._babylonTransformNode)==null?void 0:e.scaling,(t=n._babylonTransformNode)==null?void 0:t.rotationQuaternion,(i=n._babylonTransformNode)==null?void 0:i.position)},getTarget:n=>n._babylonTransformNode,isReadOnly:!0},globalMatrix:{type:"Matrix",get:n=>{var r,s,a,o,l,c,f;let e=j.Identity(),t=n.parent;for(;t&&t.parent;)t=t.parent;let i=((r=n._babylonTransformNode)==null?void 0:r.position._isDirty)||((a=(s=n._babylonTransformNode)==null?void 0:s.rotationQuaternion)==null?void 0:a._isDirty)||((o=n._babylonTransformNode)==null?void 0:o.scaling._isDirty);if(t){let h=(l=t._babylonTransformNode)==null?void 0:l.computeWorldMatrix(!0).invert();h&&((f=(c=n._babylonTransformNode)==null?void 0:c.computeWorldMatrix(i))==null||f.multiplyToRef(h,e))}else n._babylonTransformNode&&e.copyFrom(n._babylonTransformNode.computeWorldMatrix(i));return e},getTarget:n=>n._babylonTransformNode,isReadOnly:!0},extensions:{EXT_lights_ies:{multiplier:{type:"number",get:n=>{var e,t;return(t=(e=n._babylonTransformNode)==null?void 0:e.getChildren(i=>i instanceof Ur,!0)[0])==null?void 0:t.intensity},getTarget:n=>{var e;return(e=n._babylonTransformNode)==null?void 0:e.getChildren(t=>t instanceof Ur,!0)[0]},set:(n,e)=>{if(e._babylonTransformNode){let t=e._babylonTransformNode.getChildren(i=>i instanceof Ur,!0)[0];t&&(t.intensity=n)}}},color:{type:"Color3",get:n=>{var e,t;return(t=(e=n._babylonTransformNode)==null?void 0:e.getChildren(i=>i instanceof Ur,!0)[0])==null?void 0:t.diffuse},getTarget:n=>{var e;return(e=n._babylonTransformNode)==null?void 0:e.getChildren(t=>t instanceof Ur,!0)[0]},set:(n,e)=>{if(e._babylonTransformNode){let t=e._babylonTransformNode.getChildren(i=>i instanceof Ur,!0)[0];t&&(t.diffuse=n)}}}},KHR_node_visibility:{visible:{type:"boolean",get:n=>n._primitiveBabylonMeshes?n._primitiveBabylonMeshes[0].isVisible:!1,getTarget:()=>{},set:(n,e)=>{e._primitiveBabylonMeshes&&e._primitiveBabylonMeshes.forEach(t=>t.isVisible=n)}}}}}},Ace={length:{type:"number",get:n=>n.length,getTarget:n=>n.map(e=>e._babylonAnimationGroup),getPropertyName:[()=>"length"]},__array__:{}},xce={length:{type:"number",get:n=>n.length,getTarget:n=>n.map(e=>{var t;return(t=e.primitives[0]._instanceData)==null?void 0:t.babylonSourceMesh}),getPropertyName:[()=>"length"]},__array__:{}},Rce={__array__:{__target__:!0,orthographic:{xmag:{componentsCount:2,type:"Vector2",get:n=>{var e,t,i,r;return new we((t=(e=n._babylonCamera)==null?void 0:e.orthoLeft)!=null?t:0,(r=(i=n._babylonCamera)==null?void 0:i.orthoRight)!=null?r:0)},set:(n,e)=>{e._babylonCamera&&(e._babylonCamera.orthoLeft=n.x,e._babylonCamera.orthoRight=n.y)},getTarget:n=>n,getPropertyName:[()=>"orthoLeft",()=>"orthoRight"]},ymag:{componentsCount:2,type:"Vector2",get:n=>{var e,t,i,r;return new we((t=(e=n._babylonCamera)==null?void 0:e.orthoBottom)!=null?t:0,(r=(i=n._babylonCamera)==null?void 0:i.orthoTop)!=null?r:0)},set:(n,e)=>{e._babylonCamera&&(e._babylonCamera.orthoBottom=n.x,e._babylonCamera.orthoTop=n.y)},getTarget:n=>n,getPropertyName:[()=>"orthoBottom",()=>"orthoTop"]},zfar:{type:"number",get:n=>{var e;return(e=n._babylonCamera)==null?void 0:e.maxZ},set:(n,e)=>{e._babylonCamera&&(e._babylonCamera.maxZ=n)},getTarget:n=>n,getPropertyName:[()=>"maxZ"]},znear:{type:"number",get:n=>{var e;return(e=n._babylonCamera)==null?void 0:e.minZ},set:(n,e)=>{e._babylonCamera&&(e._babylonCamera.minZ=n)},getTarget:n=>n,getPropertyName:[()=>"minZ"]}},perspective:{aspectRatio:{type:"number",get:n=>{var e;return(e=n._babylonCamera)==null?void 0:e.getEngine().getAspectRatio(n._babylonCamera)},getTarget:n=>n,getPropertyName:[()=>"aspectRatio"],isReadOnly:!0},yfov:{type:"number",get:n=>{var e;return(e=n._babylonCamera)==null?void 0:e.fov},set:(n,e)=>{e._babylonCamera&&(e._babylonCamera.fov=n)},getTarget:n=>n,getPropertyName:[()=>"fov"]},zfar:{type:"number",get:n=>{var e;return(e=n._babylonCamera)==null?void 0:e.maxZ},set:(n,e)=>{e._babylonCamera&&(e._babylonCamera.maxZ=n)},getTarget:n=>n,getPropertyName:[()=>"maxZ"]},znear:{type:"number",get:n=>{var e;return(e=n._babylonCamera)==null?void 0:e.minZ},set:(n,e)=>{e._babylonCamera&&(e._babylonCamera.minZ=n)},getTarget:n=>n,getPropertyName:[()=>"minZ"]}}}},bce={__array__:{__target__:!0,emissiveFactor:{type:"Color3",get:(n,e,t)=>at(n,e,t).emissiveColor,set:(n,e,t,i)=>at(e,t,i).emissiveColor.copyFrom(n),getTarget:(n,e,t)=>at(n,e,t),getPropertyName:[()=>"emissiveColor"]},emissiveTexture:{extensions:{KHR_texture_transform:nn("emissiveTexture")}},normalTexture:{scale:{type:"number",get:(n,e,t)=>{var i;return(i=Zf(n,t,"bumpTexture"))==null?void 0:i.level},set:(n,e,t,i)=>{let r=Zf(e,i,"bumpTexture");r&&(r.level=n)},getTarget:(n,e,t)=>at(n,e,t),getPropertyName:[()=>"level"]},extensions:{KHR_texture_transform:nn("bumpTexture")}},occlusionTexture:{strength:{type:"number",get:(n,e,t)=>at(n,e,t).ambientTextureStrength,set:(n,e,t,i)=>{let r=at(e,t,i);r&&(r.ambientTextureStrength=n)},getTarget:(n,e,t)=>at(n,e,t),getPropertyName:[()=>"ambientTextureStrength"]},extensions:{KHR_texture_transform:nn("ambientTexture")}},pbrMetallicRoughness:{baseColorFactor:{type:"Color4",get:(n,e,t)=>{let i=at(n,e,t);return lt.FromColor3(i.albedoColor,i.alpha)},set:(n,e,t,i)=>{let r=at(e,t,i);r.albedoColor.set(n.r,n.g,n.b),r.alpha=n.a},getTarget:(n,e,t)=>at(n,e,t),getPropertyName:[()=>"albedoColor",()=>"alpha"]},baseColorTexture:{extensions:{KHR_texture_transform:nn("albedoTexture")}},metallicFactor:{type:"number",get:(n,e,t)=>at(n,e,t).metallic,set:(n,e,t,i)=>{let r=at(e,t,i);r&&(r.metallic=n)},getTarget:(n,e,t)=>at(n,e,t),getPropertyName:[()=>"metallic"]},roughnessFactor:{type:"number",get:(n,e,t)=>at(n,e,t).roughness,set:(n,e,t,i)=>{let r=at(e,t,i);r&&(r.roughness=n)},getTarget:(n,e,t)=>at(n,e,t),getPropertyName:[()=>"roughness"]},metallicRoughnessTexture:{extensions:{KHR_texture_transform:nn("metallicTexture")}}},extensions:{KHR_materials_anisotropy:{anisotropyStrength:{type:"number",get:(n,e,t)=>at(n,e,t).anisotropy.intensity,set:(n,e,t,i)=>{at(e,t,i).anisotropy.intensity=n},getTarget:(n,e,t)=>at(n,e,t),getPropertyName:[()=>"anisotropy.intensity"]},anisotropyRotation:{type:"number",get:(n,e,t)=>at(n,e,t).anisotropy.angle,set:(n,e,t,i)=>{at(e,t,i).anisotropy.angle=n},getTarget:(n,e,t)=>at(n,e,t),getPropertyName:[()=>"anisotropy.angle"]},anisotropyTexture:{extensions:{KHR_texture_transform:nn("anisotropy","texture")}}},KHR_materials_clearcoat:{clearcoatFactor:{type:"number",get:(n,e,t)=>at(n,e,t).clearCoat.intensity,set:(n,e,t,i)=>{at(e,t,i).clearCoat.intensity=n},getTarget:(n,e,t)=>at(n,e,t),getPropertyName:[()=>"clearCoat.intensity"]},clearcoatRoughnessFactor:{type:"number",get:(n,e,t)=>at(n,e,t).clearCoat.roughness,set:(n,e,t,i)=>{at(e,t,i).clearCoat.roughness=n},getTarget:(n,e,t)=>at(n,e,t),getPropertyName:[()=>"clearCoat.roughness"]},clearcoatTexture:{extensions:{KHR_texture_transform:nn("clearCoat","texture")}},clearcoatNormalTexture:{scale:{type:"number",get:(n,e,t)=>{var i;return(i=at(n,e,t).clearCoat.bumpTexture)==null?void 0:i.level},getTarget:at,set:(n,e,t,i)=>at(e,t,i).clearCoat.bumpTexture.level=n},extensions:{KHR_texture_transform:nn("clearCoat","bumpTexture")}},clearcoatRoughnessTexture:{extensions:{KHR_texture_transform:nn("clearCoat","textureRoughness")}}},KHR_materials_dispersion:{dispersion:{type:"number",get:(n,e,t)=>at(n,e,t).subSurface.dispersion,getTarget:at,set:(n,e,t,i)=>at(e,t,i).subSurface.dispersion=n}},KHR_materials_emissive_strength:{emissiveStrength:{type:"number",get:(n,e,t)=>at(n,e,t).emissiveIntensity,getTarget:at,set:(n,e,t,i)=>at(e,t,i).emissiveIntensity=n}},KHR_materials_ior:{ior:{type:"number",get:(n,e,t)=>at(n,e,t).indexOfRefraction,getTarget:at,set:(n,e,t,i)=>at(e,t,i).indexOfRefraction=n}},KHR_materials_iridescence:{iridescenceFactor:{type:"number",get:(n,e,t)=>at(n,e,t).iridescence.intensity,getTarget:at,set:(n,e,t,i)=>at(e,t,i).iridescence.intensity=n},iridescenceIor:{type:"number",get:(n,e,t)=>at(n,e,t).iridescence.indexOfRefraction,getTarget:at,set:(n,e,t,i)=>at(e,t,i).iridescence.indexOfRefraction=n},iridescenceTexture:{extensions:{KHR_texture_transform:nn("iridescence","texture")}},iridescenceThicknessMaximum:{type:"number",get:(n,e,t)=>at(n,e,t).iridescence.maximumThickness,getTarget:at,set:(n,e,t,i)=>at(e,t,i).iridescence.maximumThickness=n},iridescenceThicknessMinimum:{type:"number",get:(n,e,t)=>at(n,e,t).iridescence.minimumThickness,getTarget:at,set:(n,e,t,i)=>at(e,t,i).iridescence.minimumThickness=n},iridescenceThicknessTexture:{extensions:{KHR_texture_transform:nn("iridescence","thicknessTexture")}}},KHR_materials_sheen:{sheenColorFactor:{type:"Color3",get:(n,e,t)=>at(n,e,t).sheen.color,getTarget:at,set:(n,e,t,i)=>at(e,t,i).sheen.color.copyFrom(n)},sheenColorTexture:{extensions:{KHR_texture_transform:nn("sheen","texture")}},sheenRoughnessFactor:{type:"number",get:(n,e,t)=>at(n,e,t).sheen.intensity,getTarget:at,set:(n,e,t,i)=>at(e,t,i).sheen.intensity=n},sheenRoughnessTexture:{extensions:{KHR_texture_transform:nn("sheen","thicknessTexture")}}},KHR_materials_specular:{specularFactor:{type:"number",get:(n,e,t)=>at(n,e,t).metallicF0Factor,getTarget:at,set:(n,e,t,i)=>at(e,t,i).metallicF0Factor=n,getPropertyName:[()=>"metallicF0Factor"]},specularColorFactor:{type:"Color3",get:(n,e,t)=>at(n,e,t).metallicReflectanceColor,getTarget:at,set:(n,e,t,i)=>at(e,t,i).metallicReflectanceColor.copyFrom(n),getPropertyName:[()=>"metallicReflectanceColor"]},specularTexture:{extensions:{KHR_texture_transform:nn("metallicReflectanceTexture")}},specularColorTexture:{extensions:{KHR_texture_transform:nn("reflectanceTexture")}}},KHR_materials_transmission:{transmissionFactor:{type:"number",get:(n,e,t)=>at(n,e,t).subSurface.refractionIntensity,getTarget:at,set:(n,e,t,i)=>at(e,t,i).subSurface.refractionIntensity=n,getPropertyName:[()=>"subSurface.refractionIntensity"]},transmissionTexture:{extensions:{KHR_texture_transform:nn("subSurface","refractionIntensityTexture")}}},KHR_materials_diffuse_transmission:{diffuseTransmissionFactor:{type:"number",get:(n,e,t)=>at(n,e,t).subSurface.translucencyIntensity,getTarget:at,set:(n,e,t,i)=>at(e,t,i).subSurface.translucencyIntensity=n},diffuseTransmissionTexture:{extensions:{KHR_texture_transform:nn("subSurface","translucencyIntensityTexture")}},diffuseTransmissionColorFactor:{type:"Color3",get:(n,e,t)=>at(n,e,t).subSurface.translucencyColor,getTarget:at,set:(n,e,t,i)=>{var r;return n&&((r=at(e,t,i).subSurface.translucencyColor)==null?void 0:r.copyFrom(n))}},diffuseTransmissionColorTexture:{extensions:{KHR_texture_transform:nn("subSurface","translucencyColorTexture")}}},KHR_materials_volume:{attenuationColor:{type:"Color3",get:(n,e,t)=>at(n,e,t).subSurface.tintColor,getTarget:at,set:(n,e,t,i)=>at(e,t,i).subSurface.tintColor.copyFrom(n)},attenuationDistance:{type:"number",get:(n,e,t)=>at(n,e,t).subSurface.tintColorAtDistance,getTarget:at,set:(n,e,t,i)=>at(e,t,i).subSurface.tintColorAtDistance=n},thicknessFactor:{type:"number",get:(n,e,t)=>at(n,e,t).subSurface.maximumThickness,getTarget:at,set:(n,e,t,i)=>at(e,t,i).subSurface.maximumThickness=n},thicknessTexture:{extensions:{KHR_texture_transform:nn("subSurface","thicknessTexture")}}}}}},Ice={KHR_lights_punctual:{lights:{length:{type:"number",get:n=>n.length,getTarget:n=>n.map(e=>e._babylonLight),getPropertyName:[n=>"length"]},__array__:{__target__:!0,color:{type:"Color3",get:n=>{var e;return(e=n._babylonLight)==null?void 0:e.diffuse},set:(n,e)=>{var t;return(t=e._babylonLight)==null?void 0:t.diffuse.copyFrom(n)},getTarget:n=>n._babylonLight,getPropertyName:[n=>"diffuse"]},intensity:{type:"number",get:n=>{var e;return(e=n._babylonLight)==null?void 0:e.intensity},set:(n,e)=>e._babylonLight?e._babylonLight.intensity=n:void 0,getTarget:n=>n._babylonLight,getPropertyName:[n=>"intensity"]},range:{type:"number",get:n=>{var e;return(e=n._babylonLight)==null?void 0:e.range},set:(n,e)=>e._babylonLight?e._babylonLight.range=n:void 0,getTarget:n=>n._babylonLight,getPropertyName:[n=>"range"]},spot:{innerConeAngle:{type:"number",get:n=>{var e;return(e=n._babylonLight)==null?void 0:e.innerAngle},set:(n,e)=>e._babylonLight?e._babylonLight.innerAngle=n:void 0,getTarget:n=>n._babylonLight,getPropertyName:[n=>"innerConeAngle"]},outerConeAngle:{type:"number",get:n=>{var e;return(e=n._babylonLight)==null?void 0:e.angle},set:(n,e)=>e._babylonLight?e._babylonLight.angle=n:void 0,getTarget:n=>n._babylonLight,getPropertyName:[n=>"outerConeAngle"]}}}}},EXT_lights_area:{lights:{length:{type:"number",get:n=>n.length,getTarget:n=>n.map(e=>e._babylonLight),getPropertyName:[n=>"length"]},__array__:{__target__:!0,color:{type:"Color3",get:n=>{var e;return(e=n._babylonLight)==null?void 0:e.diffuse},set:(n,e)=>{var t;return(t=e._babylonLight)==null?void 0:t.diffuse.copyFrom(n)},getTarget:n=>n._babylonLight,getPropertyName:[n=>"diffuse"]},intensity:{type:"number",get:n=>{var e;return(e=n._babylonLight)==null?void 0:e.intensity},set:(n,e)=>e._babylonLight?e._babylonLight.intensity=n:void 0,getTarget:n=>n._babylonLight,getPropertyName:[n=>"intensity"]},size:{type:"number",get:n=>{var e;return(e=n._babylonLight)==null?void 0:e.height},set:(n,e)=>e._babylonLight?e._babylonLight.height=n:void 0,getTarget:n=>n._babylonLight,getPropertyName:[n=>"size"]},rect:{aspect:{type:"number",get:n=>{var e,t;return((e=n._babylonLight)==null?void 0:e.width)/((t=n._babylonLight)==null?void 0:t.height)},set:(n,e)=>e._babylonLight?e._babylonLight.width=n*e._babylonLight.height:void 0,getTarget:n=>n._babylonLight,getPropertyName:[n=>"aspect"]}}}}},EXT_lights_ies:{lights:{length:{type:"number",get:n=>n.length,getTarget:n=>n.map(e=>e._babylonLight),getPropertyName:[n=>"length"]}}},EXT_lights_image_based:{lights:{length:{type:"number",get:n=>n.length,getTarget:n=>n.map(e=>e._babylonTexture),getPropertyName:[n=>"length"]},__array__:{__target__:!0,intensity:{type:"number",get:n=>{var e;return(e=n._babylonTexture)==null?void 0:e.level},set:(n,e)=>{e._babylonTexture&&(e._babylonTexture.level=n)},getTarget:n=>n._babylonTexture},rotation:{type:"Quaternion",get:n=>{var e;return n._babylonTexture&&Ye.FromRotationMatrix((e=n._babylonTexture)==null?void 0:e.getReflectionTextureMatrix())},set:(n,e)=>{var t;e._babylonTexture&&((t=e._babylonTexture.getScene())!=null&&t.useRightHandedSystem||(n=Ye.Inverse(n)),j.FromQuaternionToRef(n,e._babylonTexture.getReflectionTextureMatrix()))},getTarget:n=>n._babylonTexture}}}}};$X={cameras:Rce,nodes:Tce,materials:bce,extensions:Ice,animations:Ace,meshes:xce}});function WD(...n){let e=t=>!!t&&typeof t=="object";return n.reduce((t,i)=>{let r=Object.keys(i);for(let s of r){let a=t[s],o=i[s];Array.isArray(a)&&Array.isArray(o)?t[s]=a.concat(...o):e(a)&&e(o)?t[s]=WD(a,o):t[s]=o}return t},{})}var JX=C(()=>{});var zg,e5=C(()=>{zg=class{constructor(e){this._factory=e}get value(){return this._factory&&(this._value=this._factory(),this._factory=void 0),this._value}}});var pR,t5=C(()=>{Ve();Mf();pR=class{get currentFrame(){return this._currentFrame}get weight(){return this._weight}get currentValue(){return this._currentValue}get targetPath(){return this._targetPath}get target(){return this._currentActiveTarget}get isAdditive(){return this._host&&this._host.isAdditive}constructor(e,t,i,r){if(this._events=new Array,this._currentFrame=0,this._originalValue=new Array,this._originalBlendValue=null,this._offsetsCache={},this._highLimitsCache={},this._stopped=!1,this._blendingFactor=0,this._currentValue=null,this._currentActiveTarget=null,this._directTarget=null,this._targetPath="",this._weight=1,this._absoluteFrameOffset=0,this._previousElapsedTime=0,this._yoyoDirection=1,this._previousAbsoluteFrame=0,this._targetIsArray=!1,this._coreRuntimeAnimation=null,this._animation=t,this._target=e,this._scene=i,this._host=r,this._activeTargets=[],t._runtimeAnimations.push(this),this._animationState={key:0,repeatCount:0,loopMode:this._getCorrectLoopMode()},this._animation.dataType===ft.ANIMATIONTYPE_MATRIX&&(this._animationState.workValue=j.Zero()),this._keys=this._animation.getKeys(),this._minFrame=this._keys[0].frame,this._maxFrame=this._keys[this._keys.length-1].frame,this._minFrame!==0){let a={frame:0,value:this._keys[0].value};this._keys.splice(0,0,a)}if(this._target instanceof Array){let a=0;for(let o of this._target)this._preparePath(o,a),this._getOriginalValues(a),a++;this._targetIsArray=!0}else this._preparePath(this._target),this._getOriginalValues(),this._targetIsArray=!1,this._directTarget=this._activeTargets[0];let s=t.getEvents();if(s&&s.length>0)for(let a of s)this._events.push(a._clone());this._enableBlending=e&&e.animationPropertiesOverride?e.animationPropertiesOverride.enableBlending:this._animation.enableBlending}_preparePath(e,t=0){let i=this._animation.targetPropertyPath;if(i.length>1){let r=e;for(let s=0;s-1&&this._animation.runtimeAnimations.splice(e,1)}setValue(e,t){if(this._targetIsArray){for(let i=0;ii[i.length-1].frame&&(e=i[i.length-1].frame);let r=this._events;if(r.length)for(let a=0;athis._maxFrame)&&(t=this._minFrame),(ithis._maxFrame)&&(i=this._maxFrame),d=i-t;let m,p=e*(o.framePerSecond*s)/1e3+this._absoluteFrameOffset,_=0,g=!1,v=r&&this._animationState.loopMode===ft.ANIMATIONLOOPMODE_YOYO;if(v){let x=(p-t)/d,A=Math.sin(x*Math.PI);p=Math.abs(A)*d+t;let E=A>=0?1:-1;this._yoyoDirection!==E&&(g=!0),this._yoyoDirection=E}if(this._previousElapsedTime=e,this._previousAbsoluteFrame=p,!r&&i>=t&&(p>=d&&s>0||p<=0&&s<0))c=!1,_=o.evaluate(i);else if(!r&&t>=i&&(p<=d&&s<0||p>=0&&s>0))c=!1,_=o.evaluate(t);else if(this._animationState.loopMode!==ft.ANIMATIONLOOPMODE_CYCLE){let x=i.toString()+t.toString();if(!this._offsetsCache[x]){this._animationState.repeatCount=0,this._animationState.loopMode=ft.ANIMATIONLOOPMODE_CYCLE;let A=o._interpolate(t,this._animationState),S=o._interpolate(i,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),o.dataType){case ft.ANIMATIONTYPE_FLOAT:this._offsetsCache[x]=S-A;break;case ft.ANIMATIONTYPE_QUATERNION:this._offsetsCache[x]=S.subtract(A);break;case ft.ANIMATIONTYPE_VECTOR3:this._offsetsCache[x]=S.subtract(A);break;case ft.ANIMATIONTYPE_VECTOR2:this._offsetsCache[x]=S.subtract(A);break;case ft.ANIMATIONTYPE_SIZE:this._offsetsCache[x]=S.subtract(A);break;case ft.ANIMATIONTYPE_COLOR3:this._offsetsCache[x]=S.subtract(A);break;default:break}this._highLimitsCache[x]=S}_=this._highLimitsCache[x],m=this._offsetsCache[x]}if(m===void 0)switch(o.dataType){case ft.ANIMATIONTYPE_FLOAT:m=0;break;case ft.ANIMATIONTYPE_QUATERNION:m=Cy;break;case ft.ANIMATIONTYPE_VECTOR3:m=yy;break;case ft.ANIMATIONTYPE_VECTOR2:m=Py;break;case ft.ANIMATIONTYPE_SIZE:m=Dy;break;case ft.ANIMATIONTYPE_COLOR3:m=Ly;break;case ft.ANIMATIONTYPE_COLOR4:m=Oy;break}if(this._host&&this._host.syncRoot){let x=this._host.syncRoot,A=(x.masterFrame-x.fromFrame)/(x.toFrame-x.fromFrame);f=t+d*A}else p>0&&t>i||p<0&&t0&&this.currentFrame>f||s<0&&this.currentFrame0?0:o.getKeys().length-1}this._currentFrame=f,this._animationState.repeatCount=d===0?0:p/d>>0,this._animationState.highLimitValue=_,this._animationState.offsetValue=m}let u=o._interpolate(f,this._animationState);if(this.setValue(u,a),h.length){for(let m=0;m=0&&f>=h[m].frame&&h[m].frame>=t||d<0&&f<=h[m].frame&&h[m].frame<=t){let p=h[m];p.isDone||(p.onlyOnce&&(h.splice(m,1),m--),p.isDone=!0,p.action(f))}}return c||(this._stopped=!0),c}}});function Mce(n){if(n.totalWeight===0&&n.totalAdditiveWeight===0)return n.originalValue;let e=1,t=$.Vector3[0],i=$.Vector3[1],r=$.Quaternion[0],s=0,a=n.animations[0],o=n.originalValue,l,c=!1;if(n.totalWeight<1)l=1-n.totalWeight,o.decompose(i,r,t);else{if(s=1,e=n.totalWeight,l=a.weight/e,l==1)if(n.totalAdditiveWeight)c=!0;else return a.currentValue;a.currentValue.decompose(i,r,t)}if(!c){i.scaleInPlace(l),t.scaleInPlace(l),r.scaleInPlace(l);for(let h=s;h0?l:-l,r),u.scaleAndAddToRef(l,t)}r.normalize()}for(let h=0;h0)r.copyFrom(i);else if(n.animations.length===1){if(Ye.SlerpToRef(i,t.currentValue,Math.min(1,n.totalWeight),r),n.totalAdditiveWeight===0)return r}else if(n.animations.length>1){let s=1,a,o;if(n.totalWeight<1){let c=1-n.totalWeight;a=[],o=[],a.push(i),o.push(c)}else{if(n.animations.length===2&&(Ye.SlerpToRef(n.animations[0].currentValue,n.animations[1].currentValue,n.animations[1].weight/n.totalWeight,e),n.totalAdditiveWeight===0))return e;a=[],o=[],s=n.totalWeight}for(let c=0;c=l&&v.frame<=c&&(s?(A=v.value.clone(),m?(x=A.getTranslation(),A.setTranslation(x.scaleInPlace(p))):_&&a?(x=A.getTranslation(),A.setTranslation(x.multiplyInPlace(a))):A=v.value):A=v.value,g.push({frame:v.frame+r,value:A}));return this.animations[0].createRange(i,l+r,c+r),!0}),n&&(n.prototype._animate=function(t){if(!this.animationsEnabled)return;let i=mr.Now;if(!this._animationTimeLast){if(this._pendingData.length>0)return;this._animationTimeLast=i}this.deltaTime=t!==void 0?t:this.useConstantAnimationDeltaTime?16:(i-this._animationTimeLast)*this.animationTimeScale,this._animationTimeLast=i;let r=this._activeAnimatables;if(r.length===0)return;this._animationTime+=this.deltaTime;let s=this._animationTime;for(let a=0;at.playOrder-i.playOrder)},n.prototype.beginWeightedAnimation=function(t,i,r,s=1,a,o=1,l,c,f,h,d=!1){let u=this.beginAnimation(t,i,r,a,o,l,c,!1,f,h,d);return u.weight=s,u},n.prototype.beginAnimation=function(t,i,r,s,a=1,o,l,c=!0,f,h,d=!1){if(a<0){let m=i;i=r,r=m,a=-a}i>r&&(a=-a),c&&this.stopAnimation(t,void 0,f),l||(l=new Xg(this,t,i,r,s,a,o,void 0,h,d));let u=f?f(t):!0;if(t.animations&&u&&l.appendAnimations(t,t.animations),t.getAnimatables){let m=t.getAnimatables();for(let p=0;ps&&(o=-o),new Xg(this,t,r,s,a,o,l,i,c,f)},n.prototype.beginDirectHierarchyAnimation=function(t,i,r,s,a,o,l,c,f,h=!1){let d=t.getDescendants(i),u=[];u.push(this.beginDirectAnimation(t,r,s,a,o,l,c,f,h));for(let m of d)u.push(this.beginDirectAnimation(m,r,s,a,o,l,c,f,h));return u},n.prototype.getAnimatableByTarget=function(t){for(let i=0;i{hi();t5();Mf();Fl();Ve();Xg=class n{get syncRoot(){return this._syncRoot}get masterFrame(){return this._runtimeAnimations.length===0?0:this._runtimeAnimations[0].currentFrame}get weight(){return this._weight}set weight(e){if(e===-1){this._weight=-1;return}this._weight=Math.min(Math.max(e,0),1)}get speedRatio(){return this._speedRatio}set speedRatio(e){for(let t=0;t-1&&(this._scene._activeAnimatables.splice(t,1),this._scene._activeAnimatables.push(this))}return this}getAnimations(){return this._runtimeAnimations}appendAnimations(e,t){for(let i=0;i{this.onAnimationLoopObservable.notifyObservers(this),this.onAnimationLoop&&this.onAnimationLoop()},this._runtimeAnimations.push(s)}}getAnimationByTargetProperty(e){let t=this._runtimeAnimations;for(let i=0;i-1){let a=this._runtimeAnimations;for(let o=a.length-1;o>=0;o--){let l=a[o];e&&l.animation.name!=e||t&&!t(l.target)||(l.dispose(),a.splice(o,1))}a.length==0&&(i||this._scene._activeAnimatables.splice(s,1),r||this._raiseOnAnimationEnd())}}else{let s=this._scene._activeAnimatables.indexOf(this);if(s>-1){i||this._scene._activeAnimatables.splice(s,1);let a=this._runtimeAnimations;for(let o=0;o{this.onAnimationEndObservable.add(()=>{e(this)},void 0,void 0,this,!0)})}_animate(e){if(this._paused)return this.animationStarted=!1,this._pausedDelay===null&&(this._pausedDelay=e),!0;if(this._localDelayOffset===null?(this._localDelayOffset=e,this._pausedDelay=null):this._pausedDelay!==null&&(this._localDelayOffset+=e-this._pausedDelay,this._pausedDelay=null),this._manualJumpDelay!==null&&(this._localDelayOffset+=this.speedRatio<0?-this._manualJumpDelay:this._manualJumpDelay,this._manualJumpDelay=null,this._frameToSyncFromJump=null),this._goToFrame=null,!n.ProcessPausedAnimatables&&this._weight===0&&this._previousWeight===0)return!0;this._previousWeight=this._weight;let t=!1,i=this._runtimeAnimations,r;for(r=0;r{hR();HD();xs();HD();i5($t,Fa)});var n5={};tt(n5,{AnimationGroup:()=>zD,TargetedAnimation:()=>_R});var _R,zD,s5=C(()=>{Mf();hi();Pi();uf();r5();mA();_R=class{getClassName(){return"TargetedAnimation"}constructor(e){this.parent=e,this.uniqueId=$l.UniqueId}serialize(){let e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e.targetUniqueId=this.target.uniqueId,e}},zD=class n{get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this.syncWithMask(!0))}syncWithMask(e=!1){if(!this.mask&&!e){this._numActiveAnimatables=this._targetedAnimations.length;return}this._numActiveAnimatables=0;for(let t=0;t0)){for(let t=0;ta&&(a=l.to);let o=new n(e[0].name+"_merged",e[0]._scene,r);for(let l of e){i&&l.normalize(s,a);for(let c of l.targetedAnimations)o.addTargetedAnimation(c.animation,c.target);t&&l.dispose()}return o}getScene(){return this._scene}constructor(e,t=null,i=-1,r=0){this.name=e,this._targetedAnimations=new Array,this._animatables=new Array,this._from=Number.MAX_VALUE,this._to=-Number.MAX_VALUE,this._speedRatio=1,this._loopAnimation=!1,this._isAdditive=!1,this._weight=-1,this._playOrder=0,this._enableBlending=null,this._blendingSpeed=null,this._numActiveAnimatables=0,this._shouldStart=!0,this._parentContainer=null,this.onAnimationEndObservable=new ie,this.onAnimationLoopObservable=new ie,this.onAnimationGroupLoopObservable=new ie,this.onAnimationGroupEndObservable=new ie,this.onAnimationGroupPauseObservable=new ie,this.onAnimationGroupPlayObservable=new ie,this.metadata=null,this._mask=null,this._animationLoopFlags=[],this._scene=t||Le.LastCreatedScene,this._weight=i,this._playOrder=r,this.uniqueId=this._scene.getUniqueId(),this._scene.addAnimationGroup(this)}addTargetedAnimation(e,t){let i=new _R(this);i.animation=e,i.target=t;let r=e.getKeys();return this._from>r[0].frame&&(this._from=r[0].frame),this._to-1;t--)this._targetedAnimations[t].animation===e&&this._targetedAnimations.splice(t,1)}normalize(e=null,t=null){e==null&&(e=this._from),t==null&&(t=this._to);for(let i=0;ie){let l={frame:e,value:a.value,inTangent:a.inTangent,outTangent:a.outTangent,interpolation:a.interpolation};s.splice(0,0,l)}if(o.frame{this.onAnimationLoopObservable.notifyObservers(t),!this._animationLoopFlags[i]&&(this._animationLoopFlags[i]=!0,this._animationLoopCount++,this._animationLoopCount===this._numActiveAnimatables&&(this.onAnimationGroupLoopObservable.notifyObservers(this),this._animationLoopCount=0,this._animationLoopFlags.length=0))}}start(e=!1,t=1,i,r,s){if(this._isStarted||this._targetedAnimations.length===0)return this;this._loopAnimation=e,this._shouldStart=!1,this._animationLoopCount=0,this._animationLoopFlags.length=0;for(let a=0;a{this.onAnimationEndObservable.notifyObservers(o),this._checkAnimationGroupEnded(l)},this._processLoop(l,o,a),this._animatables.push(l)}return this.syncWithMask(),this._scene.sortActiveAnimatables(),this._speedRatio=t,this._isStarted=!0,this._isPaused=!1,this.onAnimationGroupPlayObservable.notifyObservers(this),this}pause(){if(!this._isStarted)return this;this._isPaused=!0;for(let e=0;e0?this._scene._activeAnimatables[i++]=s:e&&this._checkAnimationGroupEnded(s,e)}return this._scene._activeAnimatables.length=i,this._isStarted=!1,this}setWeightForAllAnimatables(e){for(let t=0;t-1&&this._parentContainer.animationGroups.splice(e,1),this._parentContainer=null}this.onAnimationEndObservable.clear(),this.onAnimationGroupEndObservable.clear(),this.onAnimationGroupPauseObservable.clear(),this.onAnimationGroupPlayObservable.clear(),this.onAnimationLoopObservable.clear(),this.onAnimationGroupLoopObservable.clear()}_checkAnimationGroupEnded(e,t=!1){let i=this._animatables.indexOf(e);i>-1&&this._animatables.splice(i,1),this._animatables.length===this._targetedAnimations.length-this._numActiveAnimatables&&(this._isStarted=!1,t||this.onAnimationGroupEndObservable.notifyObservers(this),this._animatables.length=0)}clone(e,t,i=!1,r=!1){let s=new n(e||this.name,this._scene,this._weight,this._playOrder);s._from=this.from,s._to=this.to,s._speedRatio=this.speedRatio,s._loopAnimation=this.loopAnimation,s._isAdditive=this.isAdditive,s._enableBlending=this.enableBlending,s._blendingSpeed=this.blendingSpeed,s.metadata=this.metadata,s.mask=this.mask;for(let a of this._targetedAnimations)s.addTargetedAnimation(i?a.animation.clone(r):a.animation,t?t(a.target):a.target);return s}serialize(){let e={};e.name=this.name,e.from=this.from,e.to=this.to,e.speedRatio=this.speedRatio,e.loopAnimation=this.loopAnimation,e.isAdditive=this.isAdditive,e.weight=this.weight,e.playOrder=this.playOrder,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,e.targetedAnimations=[];for(let t=0;tp[0].frame&&(c=p[0].frame),f=t&&p<=i||s&&_.frame>=t&&_.frame<=i){let g={frame:_.frame,value:_.value.clone?_.value.clone():_.value,inTangent:_.inTangent,outTangent:_.outTangent,interpolation:_.interpolation,lockedTangent:_.lockedTangent};m===Number.MAX_VALUE&&(m=g.frame),g.frame-=m,u.push(g)}}if(u.length===0){l.splice(c,1),c--;continue}a>u[0].frame&&(a=u[0].frame),oYg,TransformNodeAnimationPropertyInfo:()=>ip,WeightAnimationPropertyInfo:()=>gR,getQuaternion:()=>a5,getVector3:()=>XD,getWeights:()=>o5});function XD(n,e,t,i){return b.FromArray(e,t).scaleInPlace(i)}function a5(n,e,t,i){return Ye.FromArray(e,t).scaleInPlace(i)}function o5(n,e,t,i){let r=new Array(n._numMorphTargets);for(let s=0;s{Mf();Ve();kD();Yg=class{constructor(e,t,i,r){this.type=e,this.name=t,this.getValue=i,this.getStride=r}_buildAnimation(e,t,i){let r=new ft(e,this.name,t,this.type);return r.setKeys(i,!0),r}},ip=class extends Yg{buildAnimations(e,t,i,r){let s=[];return s.push({babylonAnimatable:e._babylonTransformNode,babylonAnimation:this._buildAnimation(t,i,r)}),s}},gR=class extends Yg{buildAnimations(e,t,i,r){let s=[];if(e._numMorphTargets)for(let a=0;a({frame:l.frame,inTangent:l.inTangent?l.inTangent[a]:void 0,value:l.value[a],outTangent:l.outTangent?l.outTangent[a]:void 0,interpolation:l.interpolation})),!0),e._primitiveBabylonMeshes){for(let l of e._primitiveBabylonMeshes)if(l.morphTargetManager){let c=l.morphTargetManager.getTarget(a),f=o.clone();c.animations.push(f),s.push({babylonAnimatable:c,babylonAnimation:f})}}}return s}};Hg("/nodes/{}/translation",[new ip(ft.ANIMATIONTYPE_VECTOR3,"position",XD,()=>3)]);Hg("/nodes/{}/rotation",[new ip(ft.ANIMATIONTYPE_QUATERNION,"rotationQuaternion",a5,()=>4)]);Hg("/nodes/{}/scale",[new ip(ft.ANIMATIONTYPE_VECTOR3,"scaling",XD,()=>3)]);Hg("/nodes/{}/weights",[new gR(ft.ANIMATIONTYPE_FLOAT,"influence",o5,n=>n._numMorphTargets)])});var Pce,Dce,Lce,Oce,YD,vR,KD,f5,ER=C(()=>{Fr();OC();Pce="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR42u29yY5tWXIlZnbuiSaTbZFUkZRKrCKhElASQA0EoQABgn6hJvoXzfUP+gP9hWb6Bg00IgRoQJaKqUxmZmTEe8/v0uB2u7Fm2T7HIyIrnz88uPvt3f2a2WrMbOvf/u3PvvzP/sUf/N6//i8vf/lv/3v5H//d//Sb//Uq/5u8yf8hV/m/5Cp/L1f5hVzlG7nKJ7mKyJuIXN/hPwqXI/g++zq6rPI5u8z+WqfLre+zy7PrVv9L8brsMiGvk8XLmM/sdfHXal4e3ad6GXPdyu2ij8u/+uv/5cuf/OSLfdtEfvUr+dnf/d0X//t3H/7bf/hP//N/928h/0Yg/4VA/kogfyGQP5Wr/IFAvhbIlwK5CGQTPP+9z5uPeePJSW+yo2+s/GtN30Rnv1E+f5zxof9R/lSXv/nr//mrr3+i+5dfyX7ZZQP07Tffys//8R/l/9TtX7790T/7r/8G8pdy+/8XAvnnAvkzgfwzgfyxQP5AIL8vkJ8K5KsmMVzu1U7p5PA5AXxOAJ8TwPf7sX/51ZeXfcemqnp9w/W77/S7X/6T/vzf/7383RWCX3/z05/9i3/13/0PX//eX/2FyP8tIv+PiPy9iPy/IvIzEfm5iPxCRH4lIt/c/393//9BRD6KyKf7f488fP74/PH544dJAF9cLl98IZfLBZtuqterXr/7Dt9982v95S9+Lv+gF/3i7Spv/8lf/vnf/vGf/dF/JfKnIvLnIvLvReQ/NEngn0TklyLy6/v/34jIt00iGJOBlxAsdvv54/PH5493SQCXy9t2ueh2ueimKorrFbjq9eNH+fDtb+TXv/ol/vHyhX4Fxfbx7euPf/Lnf/PfiPyeiPyhiPxxkwB+fk8AvxzQgJcIrGTwFsiAEXH4/PH54/PHUgLY7whgu2C7bLqpQgHB2xvePn6SDx8+6G9+84384vKF/IPu8iVU9Y/+7C/+jWxffiHytYj8VER+X0T+oEEBvxqQwCMJeIngo5EI3goIwVMIPn98/vj8ESaAbbtu2ybbvl8u2ybbdtluSECA65u8ffqIDx8+6G++/VZ/efkV/sO261dQXP7wT/7kX8vl8qXIFyLylbySwe/dE0CLAr65B/9vGn0gQwRMMqgmhM/J4fPH548eAezbZd/lsm3YtssNAYiqiogAAkCvb5/k46cP8u2HD/rrb7+R/2/b9Wu9yJe//8d/9Ney6S5yEZFdRL68/38khG/uKOCnAwoYkcCoEXwkEgGDDq7CeQfyOTl8/vhd1QCum26ybZtu2yabbrKpQvXue1yvuF6v+vbpTT5+/CDffviAX1++1V9sO77WXb/66R/+4V/dgkbllQi+aBLBV/dE8LWRALwkYCWCNyMZXElkwLTMeMkga/P4/PH547ccAVwuctkvdxSw6bbdtYDbTfSZBN7e8PHTR/3u4wf55vKd/nL7DX6mu3791U9//5+/gkNFZGuSgZUQvnKowKgLWLTAQgRtEniTuEfwaELw0MJvf3LQzynud+53uG+X6y3gN9kul+2y6XVT1U27JCDAFVc8ksAn/e7jR/nN5YP+avtWfq6Xy9f7Vz/9w1dgRYngiyYhfNkkgzYBWHTg44AEMmqQUYQKOmDaiCIa8TmsfmzB+DnZDQjgcpGLbti2y3bZHjRAdRMVvb/dcYU8kcDbPQlsH/CrbddfbF98+RPZfvLFnAQeieCRDC5DMvju/vmD4JkEvjRQgKULeGggowdHkAHTYxihg89vu88I5UeGAPSOAFTlrgPopiqbKPSmCKreUoAAkCcSePukHz590m8vH+WbD9/JP335k6/+tA86KxFchv8jMvhiogE4JQm8XhfKqOAqx5qRPyeGzx8/cgSwbXcUoLJtim27C4Oi93+4v6VxQwKAvl2v+Hj9pB8+fZJvt4/yzfbF9lPdv/wJnsE2BogmyeCRED40tGFvksIXiSbgiYSRRpDNDZ6BDI6ghM+J4fPHeyKAO+zX7cb9t4tedMMNAQju5V+f1uAtBSiu1zsduMrHy5t8ePsk3376KN98sX/xE5FPAnm7/782o0DiUINXMkCXCB7/P94/e87AWUmARQWVvgMuKej9t1RLBp+Tw+ePgwngsutFFdu26WXbbl+rSvdfbnqAiuA23QcBgCugV1zl7e1NPm5v+LC96XfbJ/1W9y++fgXjA3bDYXV+MuhRwSPwL3JLMFYC+HS/LU8HYrGwIhwyNOF12SvgM4SgztdifP85MXz+KGsA2C6X7aJ6bXSAOwrY5OYIqGy3d5uq4P5GhABXuV6veLvRAf10fZMPb2/y3b7vX7+g+9v98/WOBq7GG7RNAlYy+Dgkhhb+Xxp0sE8IAC4SGAP/TbgVJK/PoJPBnAiwPKxsXfbbnRg+i3s/JAK4Q/4b9NfLtomBAqCickMBjy7BuywAUVyv8na94tMjCVzf9KNcLl/0SeA6oAEYb1i9g+FtSALb/bKL8/+t+wxXFMyswqiHoK4ToIgKqslgpg1qUC0QoYbvJZg/B/q5v4szHmPX7YEAsD0CX25OwEUVm9xag1+agKg+nxQArnKjAtDr9U0+Xd/k4/UqH7bL5YsewrcBBiMJZPRAp6TwQgWfjM9vgRbgUYGL8AvLWH2gqhesCokeUmCSwPsnhs8fP2YNYMO2XeSmAWxy2VQaXeDmDIhApf33rD4PTUCuV+DtCn27XuXT5ir8VmCJ2G5BpBM8/r/dEcJb8/0lEQMtJHA5TAlqNuLRhJChhEpSqFabH3di+G1AGj+W1/dyAR4IYJNNnuLf6+tWC9CHHiAtFhAIFLjK2/Uqn65X+SS67aK+3QeTDoy/IG2ogQ7fb/dAtz5vBgrYGqrwNtCHsVfgIvwK07OTQBURVNCBFpKCOjqCHn5L/67TgTN+fpySAC56nwSUi256kXsSuFGAVyLoUIDo8/Pz7fdoErr/v17lk162HbgHvFpIYDfoAJJfW4sGPjkU4VNAF8ZEcLmLhdc7kljdY1y1Dq9yLiI4IiRqcLujb138KIPn80ejATwRwIbtBvn1cqv+2J78/5EI5N4cJA8qIPcmwRsKAHDF9WYP6mV7VmrgLuTpxYTcMEW0LAmoQxFsuvAI8tv/a/C5fV2ZMMiKg++FCM7RDPRu8ebWY7VG6VJi+Bzk35MI2LsAckMAgwvQ0gC5DQjd3ABg2HQLAPpEAlZ1Bu7VV7MGHDFRAbo3VKsTbAY9sPWC/uvx86gBbDK3D1eEQS8pbAeSgSwmhepnJb6uBv/o/PzHLzxWA/X7TH77De5j6AGQi6o0CUGfCOD2X7cXAlCFQABtEsGLDtxuOyQB2UTQBKZe5GUPXgkUYCUAbZJRhBDeuq8xBf+bgwbehDm+BFQi2IJksOocvA8ysIMfxluVcRsY/eB3JzH8GFDAXQO48X/dcIf9jyDHptIigDsFkEe066tBSETQUYF7ElDdYEBytN4+rk9UcBPfrKaZqFHWcw3i4J8/X4ev2//bSXqAhwTay6OEIPLD2Ipt8OtAGzxkwLw9WVFRjTc/qC6H3+YK/b1oAA0KuOizHfieCLaHHiAb5NYTIC9EMEbZrVEQt1xwhVy1UfBh8PUOquMizwaap3tQXfY5B//tea/NZdfhsvbz+PURQTDSGWB87VX/7WSd4KxjUqrIgE0IUkoKGnhIvwvawpGf6eECXJ7tv4qbA7DJgwpsKthEmmYgfaAAffYF3HLxo0vwNjJ0SwRWMG4db4eh1gPNm18vQ+us/0eGmxDemu/fnM/X4evq/8342ksGHgLY5LyT/zg0wM8lcMjgGFXwqIOVFJBQw99eCvF9oZL9Mfl3QwAvIXDsBRC9R+fz8x0FPBLB0xJEpwUobrfAkARgIAF41h3wQgP6QAmX5E/7eI43IxGwwf/moIkRyWRJQIPgt9CA9b39nzt4bYUWjAlCjWDPgv8IEjgLJfzuaAsrv9VdVG4OwOXW/fdoA35qAdL0BDwvf6AAUVHd8LIEu94A3K+Q+2YxaB84MOH62P//qoo38fCRDERE2zf0JfmDa+MieElAjcDPKz+mRKCOtdgGtXaBjgNJ4H2owSpNeAW/rRH4CaHSpMwnBYYycjgSJwfie9CR6mPu20Uv8kABF206AvXlBMiIBPSlB9wjBW1fwEuSb94296VCqgMaGCt/G1BbExi3IG+r3a3J6P48Gv/J0YmEYoiGY7V/SxwFCwGoE/xa0AJ0CEiV9QPCJb1OJ5F1VTjEY2/MO9AEJvj1BJTQpqLfTlGwjABuzT962e4IoKnyrdh3+/6mzDVJ4PHOxj0JqGKoy20+wBMN6D1gLWi9NQHfVP5MEEPzjGYy8BMAOnTAJgEr8HUIejRo5xrA5xkR5AngmiSHs+zDDAmMgWzTg55GSJEmHE8IvWPAoYTfhWak/Wn/bQ0CGLSAjv83SUEfKp5q24LXuQICpzrjrgWoza8xVE00CQCORdhMJuTUT/rjuls0gO4Iby8BIEgK6gS7BsGuTtDrScH/fR68biUHNVGBnxjeNyHEvQe/ve3LZQqgG3rof6cEclsNflG9J4KtaQ8WHcVBHS1BtHE4QP9OBMS98mpbKTeDW7dJwRsnHpMBTFJpV4I+b0kY/NqInVFSyBLANbnMSgBM8F+Fqfxq/h657/Up+GaBnwV9hRqc9bZ/vA6vu+T9E8KPJWns94UfTeCj2QXwCHS9dNL8Xf3Ho/rfewSeFODGDV69AU0y6NFAE1DP3qK++rdB7/1HRxf86gT376zOr99T/h/ioBiXWQkgQgVeIrCC/WomhDmQK+hASI2ARQZKooHMLdCJwGEBBXC3+uERwg+VOHZ9ioAt9H80AI06wGgJ3nQA3BoCut6AhxYwgcPOFnxuFnrphk+NIKIGrWPQtgz3b0i7Y6D5rs1GKqTop0nQX52vmQC4BkjA+r4a7Kx9WLENGeegkhSETBCrNXIMdi/444Rw1n6E96ry7OPuj8UfLxtQ78NA2iSBbg7gIiIbdDLsb5agPhLC3RkYKv8NDbS2YGsatNRAG2oQwf9ZIOydgy1MAzBkAw8UwEEIDzSAqdPQ6za0PkeJAMH3Z0wXniUSZoHvBXU2mcjQgv56TedIKglCpIoQfgwCIjOytd8WgN0bfxoR8Fn9Gx0Aj5Zgq0lIZbsH/ibSJoFnS+C98g9ooHEELI3gliy25yONIiE6pb0NfBlyNEYyENoodkKwgl6I6s8kARgJ4ZoEfuYWHLEJa0LhSBXm7kImGeSfVdoJ1DO2G7WXsehAptupSOoyrCSF904k+6vt98X/ZcM98Hsd4JYIXhQAIg3/f9AAUYhsLQKAtkHVBnzjCKhOoYl2ym+iBtvzDzQ2DLXJ4PUmbJHAVnBQX4jkxfvHhNDqAdHXGQJgv0aSDGItgOseHIU+K9hXnIJzkoGlEKzNHagTdJ6VWEUH4iCKH4fd2AwDPaYBm4Wgng4gQ9V/CoGiuNmD04AQtNGMGzSAAQ2I2pzfogY9LRh7BrbOh4+D30sAencljFu2CUFrwY8UAWRfWwGvVOVfbx2uIILM0pwDv082dUTw8hYs8L+uIWiHGpWgClnAa1lMPJogovvvbePPs/q3Xr++kgCsfgB5oQF9WYKPJqEn6G+OE3i5AqouF59FQOmahQC8rlPLj38kg1c2f30vw+XaoIX24/pMGIgSBoZqoH3wo0sIIGlA9PWcCPrAtpPB8eBf6x1o6cHra+2+tpIFP4PgBfxZtZUJfo4qxELT948D9ucK8Mt9+ccjIQw6QJcEbrD/1g340ATuDgDkFfx6twSf1f9xvuBECYxq/7ythQQGm+5JDx6Brw4CkMGT3wgscCUoQ4sU2t6DR2ciBjTgtcpenQoZVX9NuL4Owc+dVaDursYVkVALX+shjSBKBuvCYDUZjE5BdNkxdHAUBexyHwB6NP7Iyw7sxUDViwge1t+mz8B/LAvVx/c3PeBBCToB8IUGOgqA3iV4yUg6UAOxaUFHDx6CYS8SorMOue0CCJGAf5YfRhoAI+A1CvwxqNkAY5yAIx2EQmkFfeWOXi+nEdSQQA0ZHMEItiagJArQxDXIrj8nCfQi4HZPAttrIahso9oPQ/2/JwV5JQU8zw+7I4D7/sBn4EO6rjw0FR+i3Z9fHtahzsFvJgM0X+tmVH5vaYiNDGAigewAz+gyNLThnjCURQFR1b9d3lZvnVqmj9mEPDKIUIC4KCCjBXywS4N+otp/Hk3QVthOkwEKlV9PQwXjT7s/zwF4Qf9toAAzFdjuaEB6S7D1//U5FIQu2MevO0rQQH8ZmoXE6B/IkgE60XCjVoq8gt2iCG0S8L5GdxkM1cGsfsCMArSCAnrr7dzAZxCEEpepvB8tqHJ/q+bmJGGts/AcAXFOMMeTwC7Pw0B6CtCtA2vWgonqBQJFSwH0JQK29OB2kvgj2HHXAoyeAIsCQO0kMNECAhFMqCBf8mElAkyBbX1tJQP2RJ/ha0gpAfS9l+/5n00CkrQpq0MZbOdAuxmMvHswog62jZj7BnYQe19b14kxNq2D/ehX/p68HEcF+x3yP7z/V/A/q/5DA3i5A/dzA5pdgbKp3v3/wQF4Bb70WkCTHGRAA6+KL0bFl6FJaFw0ImZwm6igSwbbwPn9RMBWf3sN2JgA/BVh/Rg0kQBgePf6HglAHLFQwqQQOwDjbdVxNZjR4iM6Qa3WxwvNxh0JFb3g/WzFQQS8b/ttKcDWoABtUMAd8j9hf0MB2uDXhzX4CHj03L9DBU3Qjz0C0l4mLSLQPicOOwZoVCB6P6dA7nDbGkVuxcNr8PU2JQO4wX5trEqmccZaHU4q8oCDFOpzAnOwqyMIMktNNNAHouDGxO37DgArQZzlmp/14W1QlqHTMaIIx7SCx0+5yza7AKJ3IXBrNAHVDcMZAU/BT/vgv/ULPOA+XiLggAREDF2g0ci6xNDRglegd7P7TWWH5oJfayliEg7bScQRBVgI4Ookg/F6rvpLWP29swREqA3CaG8/FpKqS8DTAV4TiBqIqtxfzaQRLys5I0XEFIFrPbZRQb+16Fgi2LvJv8EFUPW1gGfQv1T/F/d/HBnccP7rAwnIIyHI4ArgWeGbU4eHy6Tx/EeTZIb5bo/BsMBjmjBE08f/RB0PHYBd9eVRAGY7cHRwiBf8WeCPHY1bgBTa9xKTELzEkQX9CPtl0gJiqsAmCT7I8xbjivh3JGFI+D2nBcSJQJ8agDX+O9iBL7UfG4bzAkcaICrbtYHz1ycSmGmAjJfL3CMgT3tQpmrfB7gxSzC1DnvdhQMieG47u75+kTouKNkM8c/+vq/Q7ZYjO/hhVvRq8F/9gGfhP8aqE9EIdR6LTwJ1h0BItyDqB8iFwuNqASscRnYioxOg9ApvnYA35f8e9Ohbfe8J4rknoFkO0lmA2gmAG0YK0DkB4ieEjiLoMD8wBzom27ANZkzIoU8EMHk/uo1mzeVoEoRWKn8L/62EYAX/lsB7D/LXg74uAMr9oGivJ0CNJCGD6i9DhZdQF+gtOp4S+NODRzsDVbhdgv4BqTMNyIL9SCKwL9/FGPp5oQKxIf8A/UX6r231H7YIqLML0Ae2GtrADOvRQH5b/MPE9dt9BGLNG8jVTAQvIaK5TtvvvWQgDvyXIClUA78S9Nfg7VtIBlO7cbsEYkQDMot+ygQ7QwmOawTHnAM2XUSnJvPIYRYMmYPS+sv3J+cfP3d04JYIXsF/EwMbBKB9Q9AY+BiSwFj9mzrSXmcJhFPVHySTbgHJCPvRQ/z7G/SVUETsg0ZF+i3CRoCjhf7y1A9mOiDD7TwdwEoEXjLwAv+avLE2B7Jnb+OqDpBoAchoQJskxKnss0vu7Q2YhcDv4ySeLOg9GsCKiUIihP7yfW7zbTsBh0TQfN0iAWn9f72Z56/Ax9P7j5OAH/Qvv3/QxKfk0DgDuP+R3USg3bzBC7bO/QT9Eeh9QvDPG7glBQzJwK740lAFFgFk8P88CqDGAa223YckWYhr+c0BPdwetl2ocnsfzePAWcVnnAIp6gDVhDLyfV4nqFEDPxHsbWD3k4BDkN+pARqKMLYBPzYEvxp9xmCHQQdgWH/9EtH2TIFpu3AH/cdGydv1j0TQbRrq+D/mLcX3ZACZ15bF378CG0My6Kq/zoGOQwhASDFwFbxyNGBuSxbCEhQ/uEPe/6gAERWQObCVVfjPpQX+rexxYhYFxIkgpgX7Y/vPs+Pvxf9vwt8kAs7i32t3QCP+3SPaTwIytQXP38u0PESm+YER+o9B3vr8mETAUfDrEkPI80ck0FZ0dXh9U+HRbhey0cAc2H7A4y4egoD6y8JfkBiigLdFP8v2W00E8deT2IeAKujZ/QAVKpAtKI20gLWksHedfgPcb+0+NEHefd9vB9rayi8h7J91gBbaw20MsnWAF5xHkyDUCOoXp+yrOwwxcKj0aL6fFppaaKDv6OpHR5sgx5BAlK/+fYhuP1D196o8e7lFBaKqv5YIMnFQpd0FGVR35RJCnCDaABaXBtgbiSwtICMtalKC+1JQ6bx/PLcDPQL91QFodQNKpwOgF/9eqcBxBBqRcKAAVk+ArQOMx1RYGgB6naDhlK+uQQwJYx4meQbxtNnYQwMjt/d4f3M9ZE4UOld1LAh99fbfzOxiEkKFCkTJIUIMUeVnJ/9sDt8/e1NEJOi9oVHDGYhgnSLss9DX2IAqw1zALUncKcDr0FB5NP+0cBQNrEezDiyiADPkt9qGpwoPdL0AGPx/NOKeyf3b9WJNdfcFv6bKd2cLMJVfJ6Y3B6wB9WFUfWWEwKMfGiQL+3bz9XGQz2EHKhF41GCtZyDi/gUCsNhYoAr3UNJ58YidHKqnMb/6AB5J4N73/4L+t7mAkeeP3P+1LNSB/l0SkMEd8DcEuUlguEw6t2AU/PCE/q++Akw6QFf1u6SBrj1ZnnhG50AfkoGIdf7gJv1KcSfgzWWkQ9U33Z3tHXYASKJ9e/YhU90rvD+q9Ej69/wxYJVs506Eg/r3DkMDzEdDBRGgcZay49XihLA30P+l8N+hf1f57/0AoxbQbwYaan/rBMirE9Dk+sBzTkC8JNDEUlv5McB8PP19Y01Gayep+hC/2zvQ/2HGLAurowsNGlA1cnqGGzeH5weiYLZm7h3QQC4O2tXdhvMMk1ZS5ebpgI8eMrPvPGkwaxayk8Yc6PMOBPEdC1XZ+2UfbfOPtxLMQQAG9BcZFoF0gp/RKjxe7+oAw9T7ZPWhgedodgz0gf5KBtrtIZhQAZpAV1Bi36w6t98qVfH7hqGI318lLCjLCUFlxRHwqYEH9a2qb4XjWvDT7kBwfbZA5P0+PNuRuW1yf4yNQH3zzwv6b70QOJ0G9OT/dhoYRUGT15uQH/71MjQLtQlxfDuiCXrtM+SkA+icQdH6sU/xz7Ze7FlubV4TpoTQ2osdpaEjtqADmEU7OkBEFoLeC3IWFFeswJXKXzkboNL+wzcFHU8hTGKIboO7CLi1/P+5F+gydQhuvRbwEgxvtACmANikhLTbj0gCYk8KdlYgmj+4Ymaod7TwahwadICuX0Cm2fE5iNHPK0x/CDV66Kyg1MnqjNFBnhBoLQCgUULfaVe5nq/6EQWY67bXCszUb+7232fVPz51iGB12owK9peyP1T4raMFF/OEYJP792mgXYfZ04GHMAhBkCSmSj+dKqRPgVFGHbpLEGMiGFeQWfSgrY52VxaeDUPSNJI0P7NoisG729HHl78z6hxfs9rV3m4JjgM/lsui2qmThjCfDFSb+I9vwUqG5wwL55U7C+6ot8B+7N2o6r3q37T9trfpjgmTvv7PSQATLLeRAOZhIJHBQfDQQJPBdUwEbVW3+L08EcEE/9G4ANrCeWcnPKRHDupbNynMx5AA9IRYLmrc/YLSiD5EaEBS/s/TgnU9ILcH19n+CpHwegLejx7Mn/d25fdN+e9U/1vgb7bqf08MOtf8EXxaoh+GY8L6gDfhvs4i6HQ7seYI2sv1GchdMsBIG3xlvxcCRzdgCPTn+6q/TW00VE8Q9FaFv+R2VlOM1vm/hhjhDCdgNflVKME5B47I9xT8z0YgPAJ8myb/LqHy36j/Mwqw9AALxuO1JVjiuQAYLcFzIhiEPe05fk8tRjGw7yWQbsfuLAT2VqOId1osnr0F49VM8INACPHDoBz4B5mqqSnUgyh3ArjXxfQH5BbgUS8gP7aU+w0zHD9GGD0CGHf+P1p/DeivlhU4BbxR9a2kYFR58YaDZCUR2P0DMmgED2eg77puegy6PgDphEB0CwlG/i9d+/Hs34pBEQrBn0W51mqGnJAk3ACCHeiqkQ1XFQA5AlKH7Lk8yJKWY3/nym14h2C3JvxeMwD9ZVMz0BPMi1n1RbKl1cYhIVblF3G0ATsRiCMUvoK9//OgcwYMoe+ZKOLlC6/Xk50br9NFz9fanqA8UIYSpCwlBO4kHc4WLLBfBHVaKwKgLQjmP4Un61Vq+3s7Bsyi0WztmLjJwJwFeE0I2vD/1Q6MVwefxfUf32skCPbCnxQqf+QMPEUDHZ7vGeyj020JgkPXXwsldA7SYR1RE3h94NvNtugswcgxXEkIcBPCGZ1rmrgDC0A4K88nm2fn/eTnpQtWyZfybRoK8Dro4zYDIMGsf7saTBzvX0SMbkAD6o9CYbsfMK38cJKD9l2FJt9/VGs0h5Gib33pxMKWNsigFUh3G2un+/N1WUglI/EEx8fq27vUNnwsiOoKecL7kQS8VnWAGCFUgn6dBtQhv40CmIYggwK0uwDHRGAuBXVdfwzHUjZzATLMAoyJ4FmBhzaWBlrHld9CCWpPHRqofBqMReMGTJ78q9rDes1Tv7/0m0v0AFHXNR6P6g30SHivin7V1BOhh3iWPwvps/yE836L2XiwnUT8x2iHgfqhnwn667QHEE8oLQjEvtEW7GYBZDrDVkwNIO4G5GiBDf9fGoFM6n+vbEtzXwP6u9AduaWnGYSLAlVdl/AU+ikrSeEIKgwdaZ4AACAASURBVKj4/wtgHcHtdO2nWKcBkPfxcvnNQvsj2Me9f02r76T8q0IBn9OLKfz1HX8yVXQYGoAB/2UeBQ5/5kCL6+H/OGGoRnLSwdd3oH8r7KkGTbgIxEwVWvnF8KOpHnyzfF9Jod5Px+IF1h8owyitDw/XEgRb5bPqbt1uvn7qBIQ16vtS/u+DP3cR7CH0WWJgd5mTJKYgNzoGjQrfvu99NDBC+bnyW1x/qhTatv2OaMKgJWPvv5kwnMgxHYGFRtJW8VMl3uP+MgoqSZyWFKr7+KIDw1d6+IiOgZI4+d5iYL3imzbgyO+tph9t2oSBxOM3ugHtPoFZ1LM0hF4kXNEBssvVgPdjdXZWK7uKvyS3q1Xb1WQwtVDqSUggq+Vw3t56JA2cz7PXOwGNW1ecwxPhfe3QEUsDsFaAz8jg0nf+iZMAHNg/XSazDuC18Iq1HBRrOsAQ8NLB+16g614jmuSgs3bROxE55D+WDDQNA4ivdMJ9M1b309UqknaDU8ObV9/PwmMPATvTMAxpABLBzugUtV9bLdhNDQA+7B9tQJ06/7QNDHGSwtgZOCIA47InIoDdROQGtt0U1HI3GaoUnCnC/rzBMQJteN17+VaAzYNA7e+PFqHQUyXPUYB7iQYa5ZFjq1Zqpx8Uqu/XT7+6BWC1Xaj0GlBIwMoHu7UzcI/6/Acb8KIq+hzmGWmAYnADrIpvKP7TZeLaf0LAeQkGgebbq9FToI44p654F47tekKkI0L5PQNZPsDwPBpy/ni+wKMN76Vav4+2cFZFf8+JwAraMt0DFB7beA/u4Zz/a+RXx0M/ct4/jwaNAS8G17eSwmta0Fhx0VRxJkHMivso+onMXr+YwdWKbgioy1jp4x4AzIKg5lEA7wvHEYCRmdx11TAuT6lDLVl4KvXkAET9P4RT8H2u+lg9EPQIpw+/NpJ7RwE8HaDv/Mu4f3OdNkq/EfAiEiOANjEALvcWL9gfFV4NZbgbQc6qPky4Pm35QZxtH1f4j+P/jXuaYPcWwIEH/fmEPBoAO4m4LGxV3txOQqDU+dXgey+UwSzuqP++uImO/u/6ogCb7wTc1n61sL+vZi87rxnrNas+giTg6QLzaUCjIp6JfhwtGI7AjBBB9JjDY4ePYVR6ZPgN4owVv6Q2N5hhVHwNeYrM+w6dN6K1sMHZm/Ce7bHe3dzKr1xw1w4JrSQMZtgnoQHlr18fzunAszD4qurNUg/TDqzx/lfCaO6t4tACMUQ6P6htWjDPC1hCoZ8kpODzJ70MUR9AODcgwyqyPhmE+wfHYB/hvSqt6qeXUShhXH+d9SR8DzrDaZZdpSp/HxqLMQuATgDU/qDPRgOIeT8cvz/h/XC6BtE7ACLOWPE0KIS4UUjmZaJ2grBphiWgT41BUVWZfP3AnEIT6OrfoF122l2rMycBoU5i/OXoUZ4/aglsXwLzHNU++FVF3qikOj5HXm2PBitT1WuvJRAB+6O//W0/PY8vQH5IrAsMs/WuVmAdHBrQgrbOxJShXwRSsu08h8JMBpo0+aDTALwV4tbswgzHrftG/dJKIAQb5h9KCssWIMeto+GYqG12/HWGjx8kzqNJaa0noMWOr2KwW01AMwJoNvhMQda2/RKQP/3ecABM3g9uD6BY68Ntz9+nDOMb5iV+hIE+dP/Zs/wwJhJ9mgBnohBuStABUXjugF3hkXF9ZZJAjefKdHZCc389LoStKvIl7QIEb1d9RyciQgFDI9Cjyccc/23Aam7/PZJBhgDgin5CtQvbCzX8ip9YgIFtOAt+w0owp/hOiCWgEGbVHuYjRigPGR/YOnEoqPDoV5z5YqB3mRq2ox5ICmSSgAP1Ne+XV2NE+/vuFbCTRADxtS70VRBCjgBk2OyDUQiUgfl77b7DwaHm2rAZ7osRSOOUoHgKfNBSLI767+oDYrfwZvqChSpGfj3pFwZFsCJg2jeIQQBUiyI4WgD68ww4qO8khuWkkIuDrxWv2nv+UTBpJYiPd0KemTA8qqFiuUF1jWS3BoG6pADJq751JqBI0wvAVPyMQvjcX1zbELltKK+zBiXRFiRxG+b7q3M9xuLdzR8g0gCGNzSM5gNYfqGO9CBT8OHct6oB3KsSDBisUnwsFuISQaRHxDSv0vptt2oeLHMERfRn/FG/Cx01EpgIQG8LP+/i37PKw53xn6sYCM4/JwSRrCnIeB1ZkLsawDhaPKv/njU3wnZ/dBdGE8+YTHSG8+ofGgIjsC19YnwdM/KAnTSsqj6ig7uGgIPw3nYFzhhIIvriAxFP9CQd4HSlnzgxONIdrE7A8ZDPx9fjib8ifgegNIliRgdx95+E1T7+3nQVNNhEzDgGA3T2rEDLduwtPpuuouPcs8swwXFjdTaMKt+jA5gUAQPcf95KJQxYU0cYxEDvsBSmYuukp7AwnqniC9Afa5z8vboI68ImT0t26CvwBzSggkj447r9IojvCn7U92J/Hw0QSdwZKNNjxPCfSxRqnATkdwpOwh88oc4J8KTSm/wdbZjrc+4iFP8YO0/5JJDCfaijK5xVXevqfg6zGRrQf83chvX4aRfAE//6vv5+6490U4ADdO7QgM/5bcHP/n4OtCQhBEFeDWSvos8DPq8/IwzLzjpa8/U6MMSkBklDm8e0mn3QIY7XG1Om8wzN48y7HwhOK3P0/ZwUQHHv4psbdoVeb9VlAjChBCdtDDpOKTh9ZfcagOYq31RFjN4/gwBYzp8lAwYNwBELhZoxECeZxMlAzWGdCRV0fQWGHo8+8Kx+AAxnCIzowAxy9KvNepWfsfp4RR9kUrD88CPVTuXRybhqqTHcnxEGndsgub1Gdug8yz9fHt3Hpl57x/mfCOC29FOSQ7/noAZR5W3Ob24UMpuPYAYiQrQgk1gnFoUIKr4vKFpV15pHUJO3Y5rfH3UFHU4bGkU+NKJ9f2hJyOMxDBDpjAgwiYqvk5TqNl9EH2Arb6fA3yaA4cBtPWewhkEcIQJBlGzYp6zRmr1v+e3Fv27xpzvyI44NGDkCIi7CGNV9Dw0M8NtHC2vUwHINumCGNG8erxOwtQINsW88Tlwdoc+F85nI559ngEDpt2F/Uu3hiXYrkN/pBFS26hYDAkFgErMK67y9mGBA3L5ore5izf8b3n805MOq/t7XU4WHv1DUF/5gugCSOAIW/59uMwl6CHWAib8bvfxWl9/rBGEMTTwDfG+ezEYG4yk6FvRPuPwE+wvc39IRjENWM+/cm5b0W4Pf4WuKUnw/vD6eDbB1ETs5vl77Dhnm/51g6wPWwQAqxnivgQaeS3gy/u/1H4hpTPrIgHAN0mSgXUX13YP5PMIuQAfBr/f70cdeE+QoCX3i8nFMLcAjInBoAIYqt1LhC1WdtvmSab28AYffaeivCB+ohdYQgfUa/WS4ToMsNLHLc9nnvPZLwn1/EefPVf+U/xvnCVSEQEkEQEnEQJO7S7RvYDxNeNYKrG7DKMhtsQ8cMmhgPKKKj+F7CiHYFR5KIIPxOmg5IVAtu3ACQSPh7CzUQOgAej5CWEkIe3vgxz0ROGO//qYfz/dnLT+ZxDr4QW0eNCJBorCFOVC312Ec2TiY5Bk0cAaQmiA1VH1MOwDHQ0kHdEDDf+2UTWhS4Z8diQMicLx8MLBfverLcP/jQzF0P8EJj5+NGK9RCz755S6F/f1+X/gxeP+Wsedv+vF8/54aSPJYFjIQd624MDz/UDLQnr8HU3ztKHRf8Qeno1vyAQJBaLcMtTV3cvgP56COCqd/QP9xLgBkH4BxO13n4hNUDtACC6G1S3zqooZ6Ba4lp/zcAFb7iERKQwQcF39IFJjdXECGADw0IE4gg674pYAnk4HoHPx54tD5daO5vxrugSkMjgiiqc7TVKAT6AT8R4ckbHEQCYR/IZBxJgA+XZjsR7vaoRpIxWqeqfXuGC2CxwudicwePEB1kNkaZCuwyF0DuKv/4sz9mzP/Qxdg3BDkBTMC8Q+loD6UGBzx0Kz6eAX/KArOQTlPHFoI4vVtf4rNuLrca9edRn4xBP7k8w+9AgZCgBfEUZWfEs8iFNZ3UO7TqmkjCO/rWdgco/yIqHcQWaC2EGTzgz5y/iXQAvyx3riyxxV/JeBriaGB9OrTA5g9/eokM+37GszqfA/UZk9iW5UnCtBqBl3XoNN6Ag/+zy6A5evPAp+TIFDn15gQw9rjrOzFX0s2JBVAxa/nP1a6AsNWYGjPNGPLTQgBsNUFvOA3Ht9o/rGDN0tWOCcxJGp+f7++kkP7PxcGv1+GjkaLt/fawpwwerQxBJNW4b+PJsYEgiAYYdEAGIlDNaAbRkIgK3ut0jKByp+8yz23X6GttmBmjwDvChgiYLP5V/zhH6/110sGcKo5CkggCngxnIPoPja0j2B+1BRkiYJiviaLJqghDI63G2nAgAxMCuDdnoD0wIQm+urMB3VuAwbBrFGgGgnhAFqg9+ujKsLxB3qGCQNEEtPinIQlAj4WgIw7/iXc9V/x/yUWFs2KH504bAh4aYWf4TrTLGTy9YbftyLeVOWNfYNyt/ji29mQnqMAltU3ioTtbX343yv/1u0YPUBz6zB702tQucnX0gWaFh6DgPdmhXaapGotw0SFz1qDiTMdd8h45HfcqCPRUhA3+NmKz1l9teCPaMd4urGaewRitNBDdahR5c3AfQmDCFT9vmtQEwqAYXX4XI2n23Z9B/Yb1FL+LWox6wHGbZSo6FR1LzyG+3hriSZvWT6jfXhl2cmQZJDrAbuYAqAHo1GA/EOgD8eGcU7A8eDvH4fQBuAhBL/Zp/vamPTrRENDGLTV/7E1WEPLDlP/PwzU4YhusIMUgfIPAr6Dhv5R4y2r8ldFwiFoYHnmr8TAHbhRQSZOctH598ZYhqt6wP7q/ouqe77RJxvzFYaji/z4vna4v5cUMDXqDAJ5ytktqtBDckyjvJg04hl16LB0xFfyMfD77PZjErGQRRjYIfSvoAXntks0ok8MsUC4KARWnYPlJBeIgLeFrUgDOHYCag0/XNAbWgRwQuLAsaQwIhC1g7+jCNKuT38JfnYSyTi+QQEwwHeT4/dWHYxJPxfOj5oAnRQqgU3YgGZSOaDyK3n/qkDYBKptzR3oD6B4fyRKjp2AzSl80YR/3P+/1vBjX18Jbu+YsrMRgbqPP8zrDLTAaupphfeZtyPs9BPztpLSBZjowF3woYRwBwOWaqbev15b7X4RWsiqYiY6ZkFEIoUwUA2OrkeEQE8HYNyD/rl3m88jCGgO/nPW3xy8x4Q/HBcM1dYg5q8N+B/SBSYhtD0EY1PRGLDoKIBHF3yLz4H/gSYQJRETgqeB2d4vC8L2NVnQn4PoVJJAcP0inahAfdXVI8CFszjRagCTtRdV7Sr895NBpRKXIT64RMFw/iw5eChhEvmmyUIH+k+Qu3cLzOAN6ILlFvgWnx3YWFDz0f38ze9GlfP6UQ3ojEY0gtqRIEbA5/WgQFhsEuIeL75uTzvqHktAWfj/OD6sQXssROcGiRgFn0QVkld7OznMDT7CJKzhMIqxW9B+LCOQdH4uyxIcE49VTSeLj0wKjzcp2oDXQA8YoDEGBLMW0BJw+eAxXejPV/IXd59/tp5rVyYXDw5BlRetSpQAcvgfOwVM8ObzBq/AQ2wX4lwkQV3vNhYFfn2LFgaoDU1ogqsfqGkJYmrj9Tr22KQwBLzbLuzDeA9yzyJjVRfwegWq0H+FThDPA6ZhZwX2M2Kh4waovCzAWJTzD/qY00c+6PM8coz08VNqglzx54LfHuTJK7z2rwX35ABLg1DzsZ7Qv7l/f2yXDlbf4C/irg0MJ0aCuD0wP74MrxfdFlX7tq+vtRdCpvt599EG9Yz3V+P+Oj/n4zLruZHcJ7oMt/MNp9eD6HEeFb6/TMfbWo85Pb79HJo8t3371/PuIAZqMvjPC34nVV6ZB4hEuA7AzA5cfU0y2n6ux89D/35/n2/vWY5Bf0qwf3tPLISO1Tap9qzFB6eap/beqI94NCCbGwgqOItY3CGl446CaQ8i2Q9g0AvmgJOnBoAA0gu17tsKtKS7D4udgCYERy2QIceCX/P7mBW+g/7D9S6Mn50CS0eAoQPDcBjopIA5+EcxEjLweRjXq0UbLIjcBxsGx2IZvlf0ATjz/6qypAmY7bhrk4ahsIis6ccXKHdueAfUgk+RWPCLh42c6zEeKyJpRTdRAOqBbl/Wq/uT+q+Fx3FoTIuCzc6+hN8j4veGjuAnhSE5gKnco3A3XwYlq2sq+lmP4yEOpqEoG0M+mGDYuYT0pKCFHgLHKt3T7T9p8GcWH+n1UwGa8X6kQt2x4CeqPexegT6o/Z4Cr313PHdgrsS2ZReLfpKIf+IMFnmVmwxQ9AhithYT73+p2s+JIVfrjwiHnpAZrSsr9CMstQXP1+1+510N/q8E/YoekMN9OMFvi5LvkRDsy9rgFCOoPdpgaQIWBZjf5KCSQszZJ1ivTvLokpen6tsJAVND0NFqb6GUGg2Im4Dyx9Pn7/0dm4pADAslJzTv+dKNrAPQ0wyySm7bj1RQgbAXsRa4R+mBJzpaQmHLmy0BLoL+Nh2ZRca8uUc6P37k97n451fvTieAE8BdZ2ItqFEK6oOJIYPsiU4woo140Oh+H/UC++gatHYcOFT+2y3AYvD1rM/fpxdUcsAi70c0OxAEP45X/hymE9XeoC0zfYhbcqfbhs09HpwnKMDR6g0mmYyKth/UcLl9ITGQ8N1S6s+gA1HvQCc2pluPvN2Br8SyZyfyxPP/VhCi1L1HWX2CQCuAE8TIq/sBYdANZmTIwqq0sb0HIzhhugBeUpBZLFyA8y+EErsBUYDZHYN9QAAooQwOws+uQlhdESSSqk5Qsh8LSYI6LDS1AbmOvLlRBqQIeITvM36+TP63VfE5hFClCTr9zEyVFwS3STQBy66DMHB+PJWIrfgGnYBx2dTboPa2X49GaBVlePA7CFx4iaGi4ns0aLVjMGvtPTDtmO4XEE8E5Kb/8qYai+NHl60LgAICcUCoJPVeiYG6Pxw/X9VFNVbFn9FNPzXoIRDTyzcpREYB5Fm1EQQn3KRi9wKApR8Tz48SwxnV3qM0q7ZhpdKvr0zfY+gO4oQf+EGPFYW/Xf5hwWsUgxiBbShGoGIx+D2eH1h2EeR3UQMH4zMaUKr4033nzkSkfQADelFbLOQCalxdxvN8mInhPas9bxtGJw29Fx3Y8429MAS0fL33Oeo7qFZeiToCC3B/VSNYuU0fgDnkhxGgMFdxiYEY7MYel+OHPH30IMeVFK1C79l+QdXVpFqHlMAXEf3EYDyfkkGdNvJ8f3RAXU0jpgM7jMNA5yCrtfzOicKG/M9bgEkEjqqPPDEcDfqVwGZv6zcO9avDfOhf4OmLFd9OLBHHdxp51HvOBlnAoQksYjASA1xnIhPsapTCPjbsGB2YevpPpgM73EYeSYIftgPgte6CWesVBB9QEgfnWYMgoeC8ql69bWoRIqYHvSIv/u26bj/jdqZ9KSGk74JRo6QS9PuTiSHm6Z62kLUGH0UO4rwWrhtRETkR4iKRdI8giJ2D2nUCMjsA0TXiVDb98NAf/rCMlajA9wesWHZrAe1dlwRyVI2jx4KkyUHSx7YDe6YD4tOC6XW01puEdAJwaEJzf1uATHi6ZlSCpBQscsh6C1xRcWEG4bCFeKcAVhVlDu54JQIkTT21hptIT/Afk0kMcS9BKfjBJozcDXCrtgbWXxbMAw3INQIxtQJPAGwXmYaBbYh4SCsuKwLOAQ5awKskCMmRg8P3xwlBfbosQaDqyZqBkyQe1CLQACoTgN4qbyHsPwkTiF2pYaj6MAXBmUosQHnUEYCsBL3MW39SNKMJ5PfoBsT33DVJCEbFnBCMOkHfvj6Xq8uw+dgRIhGgAiUqf5QgKDFyhe8nnYrlqn9sG1GoAfirubygX4H+8IM1CmQrMFAJ5ExzKIp54nPoVU2Auh6eBShDlTV4u5c4HE/fVvjFrsII0Ik6QX+Iq68jB19ziLoKC27FYe0gC+j1RSS+BgB7AvAM3m8HLdy5fV60C8RMVuhD1ieQB32MCCq0QPJuvuw5IHF/geMKwOPdpmsxBwVEfGEOgeincJqNmuSFIPhPq/xM81CWIIi+gCFBqDX3QPYd2OcCRo6GZBoA3AM+00aesAOQ7/2Pe/vBCXoguD4OBD1WfPwClzcui12AuH+gC0gEwW72KfjBCQRBr05D0IQc7N8PzOCMehPWK384MPVDJQim7yDdoiRTItzzFV/ZOX9sYFetP0fsQzb6O7wOoFjxk89YoQXv+BmSN+yYHYO+BsDRAXHhuJXsEFbdIEGZQWUkNVNzGA9NZUVBIQL7jASR0AclE4Pb7JN3BO72mG92+o8UG3nybj+mASh0FsLKn9GPxDrEcS2Au35BzHO1BksriIJdpqWjKR1wlpR4fN977rZqI+XbYjYDgVDpcYQalOYKMiuQbB3G6Pu/HlMbi9a0EMkksXtjvvXTfgMKAEZRN/i/O7yD8Da2S2Bdh3ICWfp8yuMkYl5a4df4vVWt4UF0yyqEnaT6swYyWB8/j111Y1ERS9oB0SLMtBGDEBD1PEHwtdjUEAHnqmoHU4wCDAoAS+lHwtu9eQLUAgmxVvAuMB9cELMV3m8EUtcBYYI9nkNIEEJYrQeUHfnzzRyC39j8CgSkir/E0P2odnAmAqDnDIhqrtV9BDNS2POjv/0pwKr6z1h/PMz3uf9ykFYq9TtoAXSwpz0HljdvBCVAPY6t7osv6gFhMpkX13rcfXQMIpuTsfTibkfOPRAC2meLRipI4mDPwMD5x+v3+Ey+qEfACwoUEkKQSMZxYJDz9R68PyP43yvo2aYf881rNQbZgRU/jp80QnW/hdXqJxMvCFxXQSNHpE8QiF4XI+wFfQcw7VL2Md7RRajsKgh2D+6SLAKPF356+/7yXYBTUgFy/38StUjFHweD+iiHh8/LV/i/TSvGk4L5x7F6AsIKbgb4C0YjgdGRIToGUx7cgS3JKP8pRcgak95BJGQbjaJdBYQ1qHYnYHL8F45QgHx2gLMQ2cDxBD/4SeR0LSDi5XzPQNjM4ySE/HGG6g+ugltLNSARn281BPtNO72eJLjdX4ITSEgpQvJYFEUg24f1qAYQNQdxx6Q/RcB85j9f+03zf2QV33IDPHegNgPABTfqFR8cZK9TA7/ll0EQbUUHW8Gr1d+MSadia+LRHwhunv87yWoJ3h/pRDwJAbDNQQFd2P2mH4kP/wDT/ZeN3CK3+ZjvgVpw4r20AMafb58j4N1UMknuj6iCx883PU9g2VHVH5JX2eEcPghSgRBCKPzK0Q3fknwPN0Hk0CyC0zBkz//7duEetgFjVtypASDI4CsknYJgYDhqsBxxy29+eyxrAZX75EEf8f+CkOcijMDDHx4ASYGGu8WHgPwpHJc0qOG8FgFTuVk0cRZVePFwHEIUEu8xSHoL5qWg4I7/HgOKXe2dcnu2SSdCGIDTA+AcxY1zYL6Q6AAFu+/1GvjKPSe"+"EoJV3NiM4Dz9C6oWkEav+NWjPWXNOIkKgNTi2I8LeBgaZHJxqrC4oNXoB9pzzMws/OW3ghSyQJgjbygOVEDhoj4nHLld8HPD6UUMFVLIgKrTL7cFoBRLQgEdXIseZ2/HhFPKbk4d5tYWwwR0nIFQSD2P5gQhs6meVfB+Bkyz2fOIvX/zxqsSODuAGIOLtPNnmIPCrv6Kqvgz3q4tCwNl9lWYfnsdHj2HTgQw5IBHwULmfSu1jEV3gDFSxTBmqSEVqiYK2IkWcRiAkwV/cyW9YhqHXDw9dkNQAcO6HFNJT7oChfrPUYc3KY17zAd+evAwF2w5SCKLV4EuCEKsKfjBVWHu9Q9Arh4CoBqEMWYBsNX7YgKP/69uC3M7/mOOz232QT+ox4iCyJGEFP4oBHd+GVvXBwX35nqp7qeIbV6L6tdZub3ueJ+gBIKgC6S5gOQFxDoGr+Bv2nzqbknd7ph/EmXzO0o+kZdc/wqvQkAOUffVMzKtYgx5Vob1/+HAfCdzHSiXHenX35/2JTr3KZ9Ruj2lYiMhLIFoNyMq9hFroeYMTE0bSLbhb4l3YlFPa6hMd2jk8dmrDgdQCnC4/+ANFlYTB6ATlx2GDGXP1rvL+SnWHw+cJes5/rRWt4H2pw9GklD4uSMpwasIQiaYR92gIyFX5S8dtRZt/nCAH48VXW3hRE/HKOsGquj8EM85Q9cfeAV4XwNGAlmIFIwPYrfLKuxV476RRetzcdeAsRSZhiHizCKEIOHn3EMOWy5X4uIJnXX6sFiBFLaBm/THOQAkVJK9j6TKwiSDTBWpwHkSPQJX7U959uAkoaTUuug6oQCBz1Zlxm0OJSIoIw04M+7zCGuYiznCfHww9AN6Ir+HXA7lfn2oBSJ2FOOh8SzINfmcAyITq8JX/sOMPx6A9LeYtVfwgCBZhdu25OB9/XmWWNPUEPD5dUuJ68wd1AqD2+w1PI9KxE9BW5t3z/igdYGWiL7L+wPv9jgVY8f0ZcbCKCuLAHN+c5wa69Zpr0J9t2KnpAGzyiAIPiFalJ8/xXrrA6Y+/8NoDnWCPNwFJzf5DpVkHte8hx76P+HU1+HEytEeSEIzAsu5r6wPJGu6oLz8VrKofXLce+ywIHhNa/Dmw8LrptWXZ4NKZm4pr/QQ7Qk8ehMrPtAF7PQCD309QgRgRZMKgAbFREAfBBXNalbHA9cEHMo4IgIUuPjjBWEUFEQpYTkhVO43eRiynJw9Jjj8TOUIlJExK+0wA4gWgQvcFBHAc7P4/u78/Ff4CC5ATB3P3oUwFClYgcALcxzp/B9Ez4DUV8RjBbsCBrMH4dLNwIDaCGhA6o3pXksdBvYBsktrXDgNJKAFy1Z+ZGIy5NXgXoBT8a3ZgVSPIUAMV6DjLxhsV8wX4n4ibbONObHNyCr8Z4FinNFjg8ziiF5zSV8A99u7Zdf5OisvVaAAAG3VJREFU/kIPAJLWX3hUIFD6o7MD4WkHIMXBk4IftSrPNBJVk0OoC7ice8HGS8XBKDoz/YFBLaQi392lGpCMJfhD9xVkx5Xbj73P9V4m1j0v73x9FjDDPlYvATkgFAVWcdNvJBamliOjAwRV0EpeRymAe717kMYRyy/j5FwFBX0fP7Dyx8gq8wn2ZXi8GfGYR+lFcGJSxa3Y84WgzBHetlU4cvKY44Ps4iP9fsgsPGEhQTAcHqwwGCj61SoPexKwasXFqtxq8qhD9SixoBBYcJEDNzmIoi3J7QkoJActVHocTVpPBCDhElAvMDK1PT/Sq3DwB/ygmyB9GNhYDH4so4Foy48kkPtZfZEv1PQTxYpyX0EI3Bu+/5krcN8fgwVdwWu2JNVNWAk+PcOOPMNdGFyAZ5Aj6gicgzNfwuHZg0HrLxBWfjSRl88fVCo/apX/IBrIvf65ZxtEoK9Bec4KZIPLe76osQns46NwW0pUPCPAyMc4A/KXOwZzFLGbAqD5xhhbgBcWfoJBAlarcCSQgdQJ+Movnih4gjZQTw51rz588y/ZgxVUEAQ8soCfX8OR26JwujCLGFAMsOjnwGrlPuQw9D/PPv8BYVR7pG/eeFtQpsLzR2KFI8SwKj9KlX++HeLOPuSBKrKeHBi7L4b+Kx184+ptAp4Trcscv69oARVYzWgaK01H1X0K3zNSmARKtxXYHvwJuT+8gLGGWgpHcWOmBeljFB2Ckg6wiAYOqfxEK3GMCAj6kIiTWdCBCXhkjUKMgJcLk271N9uLSbtvvK0S69OXAvoA5z94VsFubbmZvx4QAnXgBnJxENyQjy38wef81uPhxMpPJIQzr5ckuUTKe0wZyN57iFTWga8GvCwlh5UqvYgmaNV9XSxEVWs40kkosFwA70RgNOu8mLZfR6wDiwRa35y7j08NksqPQhcfkRBK/J8R75Iz+9C8gJpqzwiIeZII3QnYOkJWbVEI5jNuA+o2BwK82ifwnpSgHwaC+GNAdmW2VXfC+vPu6wR6lBj84C9WfvivZyUhZMJlJhjSukDlFJ3g4AvGJfC1iEpQJ/CaEd7G9wds7p71+odruKrHip/C7RdsxeVjzIxhoNkFGOW/+sk/YVAGtltfzZAIfzix8gcHhZCXpcGN2u69qWqD9OlRFAy7x2fQBhHUiETB+DocqvArYt98f+AEAXApsEmEcNLC0t2uPHCqPQIXwHYDfI4/9+8LMpchqr5HK39MJSrBXwnutNqjovjHFdq+fcHLp7YLR4mGgduW5hFpAXUoL4cTTuW5HJSkB5PC0S7A+8c+837DyoM1J9iv/po/o3BunlDqPjOSO/YbLFd+FGy9sxKFeT8b+nLNPrkAyD53FtT27yUS32yqUaEGTMBiASGcZ0FmK8nWxbvjC1q6WQC4VdWdAcBY8eFoAzIrC0b7Wt8wlPcIdE1FhUWeKU1Igv8Q/0dl4k/NnYSxdlDon8diUDeuQB4c8XVzcahRgyyZmNC+LAgeCfSVALde8/t1DCYawNoePGT83wlOpFUdOZKwxn89OsMEf0X8CxJCBN/dwKbFwkSMgx0ACJJDJD4iC1JEYh6XcEqVHpx4+J4I4UiAl26r5x64sttvSlAn3LBuQCz6edU8C+J5epBrC4YP52EFDgHrCw1B0eU9bOaTgh3wmYvQV3Oqqcf53XnVNXUBELX1xtSgFrirlII5d3HFulxBCNEfZx0h7K2f34XwdHpuYQcguN189Ow/nPXclaUcqMH5leCXjKOjbv3F0a7i2ZaRHmBe5zwnhA9S736ZC8AH8LHkg/T5znYgmES1dtuzGo92qwHIquiWX+4KgVLd8utv9Ml1BQNhEJW/FOgweiTguCUoQHkEwYhjfQIgm8eAzPKzHqAG5xGiiPyxeGRRaYetUpDVpHVC1T9bHGyaknb/TQTnuG7rDYwYCUT7/cMjtILzA+Go/FPw581F/mWeTkDuBsBCAK8ki+A29nMzPn4Rzjv6QV7xWW4fzQFUxb9jQQ1qc28kMi4mDl1NBr4usIsz5ltZqNm7AeJXfuTHd7nioLEyPBISU+8/tP1AC4Il/n+YGmjg2NiBRdl6yCw//zG5ph7bqaBuz8B4VMU/TqSsNPbwCeZA1cdxyG9SgKzRZPL+GXFOiH1/SFZ9wX8M3zUgvH8a4rMBjZj/h1W9MrwTiN6MlsCKiI4gycBzgV/xUaQGjGDHwHiYi0VIzeEAasCpNuL76AC7BIEl7i4AIxnAfoMxk35eJbZ68wWEUChs8IPz/EEE9BkUoNA4RCWSLJkY1h0Y/dG9bVCtUVPe7QRhtStXG4nOECDfUxc4Uw/Ik8JkA9o9+a83IrfHH11EdFUWc4phNgVFWkPsIHBnCvCCYBSgqEN9qtoXuwHhByYoJJA7BxIkkRwpDGgAHo+vQ3ZGOwCFJCJKUAx4MBpFZWvReeLgtBBkDDQu2OJxXa7SE/P4ZiUPHABjY1DsFIhPAaygWewiXK72hHjow/k8gCL6gKES8qcDZ7A+EhYlWCPGCX1wXIwzkQEKt8cP6iqkC0FEhFj/ZYtvXCtwuBLcDT5wXN+9H6ZEIkTwV/x/s78fXFX3siWHEKrC3tw7EFZ31Ll7ttknQyEMGgAqCaVe1bGk8r8nFWCQQR0h7CY0dsU/mIeIuA1AGCo02Q0YVXxub36sG1Qgfo0CBBUXxap+ECFEycQVyViBEBFPt14TK9rZHB9EwMG7DPXOv0OVHkdtx7OSCXfb3av4CFZGTwQBwT7/hKPHE4PzpJ4L4+FM9r1n8B+B+9R9I4Fu9brYUZgCunZWNxdQgIs8mASBQ4F8hJpEiaf4GPihk8FdAxin/kybjZjTj+mAQy6ihZ9whDvHAWB6BKrBXQr+5SBfqPaINwiz12UIwoTmbPACZY/fshBBBKNlW8ZCHwH/cVKSOZMm4Mxk4OwE9JeB+EFkn1IzcPQoiSB4vGgNeJSoik1A7m0TCmE/HrggB+/1M12C1Z18ACGoIeH1pH2IhAqFWgBq+kDFEWAvA3X8tpW0cnSD5WAOriOHhnYraF1eLTkS8P/QsHUBdtMPnOrMaANJE9AZiaKWII5Ue/8PTHn/UcCSTgIF2xN4zdmAQYIAKeBFl6FiO0aKfq5jcImHfPwTxcEdRmD3LcFoAva1Hdjm9UgGggI9YOoPkOBYLsT8HlG3nucMDGkOOJ8CkNOELdSO7D5qqAeJYBb2GpABgRi2gxLITgrOQ9C937HgB+0i7MeRx3gfPWCXLtgbLJAu/gCFBPzRX8eADJqCvA3FViC/BlOQC4LZyrBq8BdQAOUKoKjqR7v7EFfVFMojPgEoSlJesNIePyLHwW9NRgq7E6HvUN8A0yj0wyWDHRZ3J2A1jHdMyu3hCGwSDwdRir7h9VP7AKLgPoMCgKziOFLtrUm8aIFHlgxYfz8WBYUU55iAXauo+evJaIK/NTgRJM9sUcZRzcCnMdNKMJc7usnAyrpxHYkTRHK+n1HxS01LheAHqRWwKIDqLvQC0+PupHZgBawfVGsiniTVHwZHRqbUI/D4Cd+ftgyLAR1ehkIiqaKFw7MJEwUIuK5zsu4svoFYCFKgBJZACBuppOId2RDkPZas8H9kULcA9a0KTCQDGtpnzT+RMJiOGseHl4BQ1C29AWUXIIf/OIwwqoNEK3SCuA7FRiBrE9B4/PcrGJ1OQNj83F4Xbol/TgVHfMiIZLAdcaVkgh8sLrd+liNQH/FqsNTfj15m1J0X+ffZuq/gTY7QnvIfJz6UzBJLs83ItQpt3RfZz5iuGfNPajpngUm0R8DoA5jDlzsOTAwZjzsC3Jjxg7H914PjlcskGdghgx9HG4OOQH34uwQyzz61/0qiYNQjXxECuWYbGM/DrjtPH/Mw/K+gBLLSA+cEfPr4MroArzcDuybbr8Zc72i2UnzeHnTgzD4Ug78SzIvCoARVOQxaFFR3TzWnkkHUVFShEuqKxZnKz4p4YYcf8ZhYhuu8wFgSHcuuwCJagI4bgchJQK/qe9c/RT6nGcg6KGREJpb+MI0EY/b0jcsni3AJBeCQNsBOFVYoApcM2Aom4VFgIRdHpeIG8D3YaxBD+qCiQ+rBOSVnci8hzkAG1t/pgHA4uwDzmu8xFKkkkIqCfkIRs204r/hiDgutoAAcowBMZ9+KS0CcXVBOHCvJw2jMQSJyeoeExF2DuTuRcuWAo9sefyUQ6/oBaIjPtiRH1KvQKvygAHb171d+vc4GRMDPoxN/kL5pwlVh1mBQ1quQJAJ5j0TgOAis+h8d3mnC8xTKE34+8sDNjyVXE6nFMN+H39TQDmocHScENvN74LoGScGU4f7g6IG3n3C3qnG6JBS+Z5tHOOzRYQx+u7MZmAl0OSsRLAS/VIKfRAWU92+12aaVPksGDBWQuCMvgNy2M2Mt8EwqbjosZAec5xLEAmXmcFTHiOWARWglpNpjdEtBQRxJJU5VL5/7F1X86XntXgUK4q+KggsUoIIK8oA+kgy4+zLaACqQGTVOX6MBWdehL6BxHn+tlyBMDGAqufd7WOX5WTJwKYDfXJJP2GXDPk7Tj5Ed7BOG7DMFaBRAJgI/+H2Ngeb2SKb0zkoGlQBHkefDr7xMA5HZeJPtKIzyApI9gmnPgf1c3mulfhe0gFekDCdNFnrOwi4Gs6eTACNjB+Uegcgojog4V25P8bctRYY6RL8AJklE9ACFAGZdBEahd4d4CmghFhbzcwaXYH5qTlS6DY+KfNH5Avzjo2JJ0poDkSCMxLn73H/eB+ifvgvyIFCWAji7BWC8hd0qj0FziMdrS70BlVbgamIgcmotGZDNPwm0L9l5iHv7WRoAFx57ScFS2r2iwot8oKu8l+TOCOg2mZ2nFdjTgOFQENzKkJ8OjEnsE8f6AzyXwT6MNF3RDRnuj0Lwo6wTlBMDIyqaz6G+RiLJMg/KUrQV/rh9uH0tWduwoxmky0kSMQ+rnXxZsGadgnxfgk1pCnsIsGYltvfdzTOBIclIsN8MLAGcz5gBwj94AE8DuC9Molip/JGwB57nRyJiyD3pyk6q5ij+3TzRLohcqyqCEQBTepF15+WVmW8SEr5jMUUkx3oMIsrH3ndwAQganKzyMpOJNxMQooGBYwcByw7axIhgPRGEr6GSGJhkAELoQ1YRg+dPeD5IIRDIqq5PA2Jh0Rq0YcS8XBi0ghGRFpCtWTdum5+yLOsQf2EuYY8AfnbQZDgCjHxBSKwTGpt8QCIDVH3/4H5OwEvldhliINwAFLsEyyIfGKV+vm3eEehVqKTdNxtDiPoLHCRiuwTJxCECxMDqDjTvZ63KaPKvRgV2i/F3ohm88V8LN8hgJcXD5pVGIPPNn9EBqSQC0I4AMxBUcQNCkarkFgSn/oCs9GCVep4eUG5BRAOcQOCWlGSc3If0IFqRfURQGRrKewPKEJ9sLnIowKCcw+f48N6UHjqYtgInaCCkBbPSj8VEkCr2g8U43wY1xX/BNkwreQrzg+oaJghOCGTU8RBxuIp6VFOGoEXgEsBLIgV6gBgxoLSI5CgiYNT+GBHsU01GthrceiMUtv9KgAYktgVNeGrBbtiOQVi9x8WjiAW7UNUnm4Vet7WtsFgDCDYEwQ/EVL1PnQf/xCDLTowTh4c4HPRDoQaiwhKIAae4B7xgCBydI/CDPOrevK0FR4p6w3VfoXgQiB3T1N8Y1PCD0X19JqcHGfzB5WkQE4p/kdeXBcEVUXEIFqSij82lMyrWq/7c+LFHA7z5/dwOHHg8s/Y8C2CmhbmALtare+4UWLfb25BmXABKABTniC8gRAP2yvDAiUAsElnrxFzITQa/sAFecAOY7zPV/8jMQHSbWAiUPGkQNABhw85xrSCv+mMSzFR8+7mjw01A8f4F8S/td4jnDHYxpT8/OEyV3gz2+GTfdAeAszswfJNGlQhEIjB0Bls0BKn4Iw7WKu9f1gmSagmvqleEwJwnZwjO7npz1HdCJ1hS/mlBcRXyF3i/M7NxqJFoeH27z7nnJaBmpUZKHsTbGUc1ALEoIGsGYl9ixS50gjAT/VhB8IzvGTrBVfWEz1MzAkRFTtecW731VdjNQPukVdhdn0Y8d/a7WYH6i/TBPBzUFwAlHwtGHOQISrgb1AMUgDETTA3+THAdeRJhg59V/Ektofa9I8wxVICkC7QQSAd2O3cftzPzdMK6aA4iZI4ILfYRbb9RgqICt2AxVnYZ4kkBvHOBxT/zN9ybHx/f5Ql2fkGCX6ANm6F8WCfqAS+Eq5AGcHJd2IFHagTMHAAj+mWBnDXuc81CjhsAi5dL2K8QCYI1aJ/PJtSSxEFXASv7C2I3ZB9/a0j/7nDn/j1pHsz9Jr8fNpxPBUAUUYD4wz5GBlmyAiORjtAIGDFwzSUwqiNZ1d1tPiB7/Q9VeI9KeJU16/knkEeQJEALjY4rkp74fCZiMDSA/PgvT/aT2gYgp5E/P29AKBQAo6TRth5T4VesQFb0i4K7RA2MZpgyFXCEQHCOixuYMPgy2L7+45ezSSKt2oUkURlpXkEMOLSiXPuDQZjk63N5bmzOSxQdLHX7AhwUEA0BAeQPJIQzkAuFlOK/GtyLdiGDKEBdllQ7YouxV2Xdwza9So4Kp5Z0yAgUhTlJgFzSFrznIHYIwKcCu2/L3LsCg6UI1b1/CA+ApIV5/32HqOIjdQusE4azip5Wc1b0q/QGIAlaWEJbXP3r/L+AEipw/+BtkQVY9fIM2i/ZhgVEgJO6DZ1ksVtlYdoQAPhVO0oKmYBmnAYco4DRCRB3TwCziptaE0auER9/VzRqKNOEYINOQg2m1l9GpGNQAhh1v6UmxNQh2M4+LmlUzll0OTjYQOaGlZAEMCrdhmBphaMBwBADrSQQc3//He8KgFETT7p6BHnjj2X9EXsDjrgBS6ihoAmcSQVYmE4JgYWFpp1waAQRoqDzxDhU+HxSnZHz/9JEY6Y5MJA+cwoWrt99+U3Mc/9g/NQTFaigAEtwB1yBzwzucZSX7RZEILhR1d5GDCsBLVUdIQvsldZfEJt5i/MHx2hGJZFkVVyK242iFeh58oBUFqIQbkfp2DV2X0CkAYgv1sU+P+I/HmBu8nErugdRnUWhfp+A/ddlbEH3uQlBsNobUEMHasK1HOYn8BEEvCUaiuigXRIKj+sGOPA4KAWz9/s7WxcgB4+a6/fI2osEwv4yOENAiPf+wQhbc/5f0gGisWuQaRFmGoIqguARWsBQgTTocDLMT5OJUQnhqdCEig+/EShKSEgTVV0MBMnz04BcshPnLk/+OaV0/dwKzB4QUt1NB6uTDfGOP+cNm9mEsBAFiM7AQh9AKVEU75vy68jeOxrUC4mDEuYO0oLqoSdHaEF2eXYYSm0V+oEOwpLmYFOF3Z4CmAeBTIGueiIw2xoKPzDBJVBXQ5g5O8/twwA+QguIjJt3+g0NQEcDfUXgO5gsqlTBLkQLdl86K3CWneitQ8sg/5oWAUJP2C3V3RoEyji5n4b9lB4t9pz2CA+cAFn1Z9I/uzYsU/ELtEBOCHYQQqGcFejV+yeuRJX31zsKV5IGjway9z6PLDxKwNEPsBuOEiqw57jGgOtZ1Y++T50AuMFl7hPIbhskiOwsATtRoc7rS7dXrpcgrMCGJca6ELJo+Y0be0BW5ZKGcFz4y8W9BduwcDnK9iO5fagsKpp9ANnvDPxeP8THNyIVFo1AMas8Qk5v2Ytm0LCCYAXqn+wQsPTBh/5Bcnne14Os3uCQt28vsK1WUESJFviBgAW//3u9PLxusXchcCR2WsNzv/ImvgZzzkUByDUAIrjTvmSHAowpJBQE4SUlxMxnARlQbIqkArVAJ6pBBvELCCKlkyCDAP45BYfEPfcUpfMch3Vn4bheYK4E66BxAxHSVd5INgEPgU/NBCDfNQ8Ho1CoINAPQAW/QT8OCIZlNFCB84XhoDChFByHGjx35v9BLgyhmojqHYb5QYXnuAecvua0hZe6BV9f7v4ibvgvamrmAc1TmaEir0LQ9h97eYAYVoM/nWA60i8Q3Ifezha9BqaaL3zvqd6IAuwwLSCCuCLuJWch4h30giPtyiAphKEBcCu9BV5wwzkMxID8rhMwdwMhcSFgrBT3RUTQboAUg3+p+Qe1IGarOioVnazmefV3lHpwA0AcLWCahUiXwePHWJsP+GH1gnp/we5KfOhJAbsj0H/BIEb04TbrTPsAyb2LLu93KwfCvn5PLAwrOXAa72eEQRo1CNdw5IprsAZ3hApy9zlcITG2vpCihsRSYxNS+J4vdBZ6B52eqRcQ/QXmSjAWSfa/5GA5qEg4iJFtm624AqXLrSA2gx8p1Mdqcghv41S0lSp/xAYs9gakQc4Ie2RTUYwYgt748mV+FU1Xgp14eW3XYZ6cdqGTNHwHICTwEeTPl0jEZwIgP9gDEaogeg5IHWCF+1eoAhvEKPB/EAeTRsM/pSAP5wjWEUMM1/NJRhwJbpJSgK7S7zF3EOsI5jBQBK9DV80Z8Y0COzvmWzJXgDl40KEC6cqvqgi4OB5cpgLFYK/1CvDiItXqC6/S87wfAUfPtxqfGNzlYaOjlf1IsHPPvffHgDAoEeEST4ZLZUd/RSo91/BjXY5ggWgQ4In3fyj4mUqPrInHOCLKO3wUwRsfyXpt1nEIRLrqcWeTuk7bigsbid1zD4iDRQtnIdQsyIXnFCn1I9D7ADgxEhOvR5AJosoUbu1FkJyYCi9OhQERoIx+4AX/YqUXQhtYEwKN4Cy1HntLMmtaAQpqfrT/UCoLSxeswjA5UWPPi0mjajUWxMTdVusNvt/ChMdmILK5IRMFu90BMEzFYHdg2GAgeYVHMMJIBTA7EFTx/5fpgTFXz9w/en0ZjD8kCDoKPNGwlB01BmoWQbh+AxR689mBponGJOr9OwmMu3dtJ/ylW1Tik4ElUPmR9RqII+pVhD9ychABMQ51gOIZg+/G+5mGIzLB1JJC5WhzYjhJ7IWmLDpA8jzsAafUPkB2WnFBF4iSxkq1ty7f25rv/+EQLOxs2oUdTSA9HIR9swdBlCcFe9owPC3XWDDC0ISVzsEVbSCF/sWdA5Fu4HJqankp2SeQCYYrImNalfmhpVxYrGkUS4LeSUjg8dD7+D7w/ybIfy7vlB9/HJ978zr7/45Qgajzj+4EjIK/ULHPRAOlKr/aG0AFcqCyu0GcW45Igh6JMJmhA49/U+cEssHNJhtXDC1MOya3j/sAiAGcrEtqtgjBD6wEzSDc7D8o6C8rIqAZyPk+NQoNLAZ1hR64Yl1FBY648smUYKnSg1Xwk/0DyRyArByMUobyByhCcPnOaPyoegREFS4jNfYAw+IHCjdC1J2WDZBke/OyN85J24WiXwDYPoJyYuCD238ulvuzwt6KgHf0shWKsqCFFGjB/w8HU8eeTED9wAAAAABJRU5ErkJggg==",Dce="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAF9UlEQVR4nGWVy64eVxGF16X27u7/HMcyuZGYAINwmTBigngBXoc34El4B0ZMGDJjFCExQUIKiRKZYBITHdvn/L1rF4P+c+yEUqmH9WmtrrWLkdB4C1/91h/9yn947D8+8CfdlBeGGAMtqwNd6K7VWAJrw9qwLtw2nDaernh6wKuHPD3S1Vs6vaPT97W9r/Wx1seKUWj7Uzz6vX79T//wF/Gbx/7rw/jsFB/39nlrX7q99LKrp5bJZXAtrqW1uJIncbNOXafBU+o0tZW28got0AJ3KACsE4OfYvmzfvDMb/+4//Td9snD9rfr9vHWnyz9361/1fpNLLde0mt5pTZ7a9pCm32SrqQTfZI3aqNXHAwvcAB4BPwnk/oMEcqX8eaz1t9cHjxs7133f5z6p2v/Ylme9eWmLbexjlhnrPBirz3WxWv30rw0L/Yi96PpDrcDcPMEfq+qvQCfsFF1blcv2js3vb2xLNd9O/XT1p8u/Vlfnvd+25bResXC6BFLj2WJpUdv7uEe0exGByPoOAC//BH+cgNqUjfkU4mOEetde+O2vf+y8br71Nva+9q/XpYXvZ97z9ardUXrra3RerQWrUU4myLk4AzYiADwJ+NRQ41i7MSNEBIcM5YR1+f21rnlXcPWtbVYW1/a7dL21mZvbK211lv01lpEtIi0MxTmFGzMAABAN6gF1CTPxI1gkXa5Z5xGPNrbfo6xB/bQubW9nXvkHtXDPfqIJd2bI+1mpZjmNK17QFuxDzhBJued8Fy0KLvcp7fpNzJuM3JE7daIWGKMqAylW0bLiHQ0e1ppTXEK8Qrwkzv8fUIua6oG553wQpRIme7lbfpBxm3GnoEMZ+wZlYGMlu6pNh1pT3nqALCEugCeAB2ohKqYk9hZd4JFS5ThDm/lB9N305nGtKfnNKZiqk23qZhySZOcYhHFewXfI54UMCBDOYlU3TMkSaYWaCtdwXu5yprOKUxrqk9FyUWXNKXiBfCNgucGboGAUBwUJzFYO3G+MCwFtdAn6K6UZZSyXCXBAUVdGCoS5IVxAcQNujAHKCiLLHJqDtWZh1GHV0Et8EYNqOABTUhglKJoyKBBgSwCBC6Ajz7Azz+GiJbwhFTkZCXnEM6EJcuHDmmlztCkBE2IkMGAAhQoSCBBvgYA0G6xN4DgLE5IU5iqZA1hJ8zDqCY2qktJHfEnZSpIk6bE++kEXwHUEBMCmBBBFzE5UzNZuyBRshlSSF0aEg6MaDHIgyFCPAqvA/YdIjTgQ3WBLNZkpWoQPnRIUljdGiIkHd9jumgeO0ESEI97cNTPJj6Z4ISOZh1JUSVLwiAs7pRp02aTypRUhwIzjvhfPCKF1wH/BTqwA5pQlnYyipgs6dDBQVncZatZaZUlsUxZYVq0jyfm8kNeBzz/Gu0ETrjABAURAoTJOVVJpDAoM3ZOc5olfmMK42CYMrRTAr6tIK6QiSA84VtIIEosslSTNYUkUxyS5aEDQ6tMmQ7YDMOmjziYx8E56oPEl8DdDgM2/BLeIJVw9CRSTClZg97ZrDl0BF6m49V0GTIZQL4CvNuxFj47w4ASmqUkAalYU+DBoIbK8hAG506aZTLonWFG0IMa1AAHXlegW9wFGuAJG97hhFkqiuCxUZyqSSWR5GCZHKxB7nSwDcZADHiACQ4eJ/Oot9+BvsaLQD2Hby9RUEEs1cUlcdKpmWKSQ2VyqAY56J0RiEEPOqHxXYv2W4yJuANWxBkBOKEGFcwyjlhMYdLJSjLJpA8FAxqMwXZRQA0wgdQ94Hcf4nqDFnQhBDcY5YJUIqSSpnxpRqone6ol+2Af7Il2MJJxnN/8lgIA8yWQUKItaBMRsGEdDIrQoYNTnGSyBqdZQSY16IEYaANOOKn/A+htXH+OdgLOiB1BBOEGCz5ejmO6JpGEeexVJTmohJNORqIlnVDyO4CvvsT2AGm0BVEHo0IMHeEooeQipzDFY5eSNcigLgwoGYlIKHF/ky9Z+xD/WrCfoQUuRCGAKBhlwIBRQvmSuykkMYHkqx7EAPK+/wdqEbWmfB0bfwAAAABJRU5ErkJggg==",Lce="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAABGSklEQVR42u3cx4tb6brvcf0DmmpUoxrUoAY1KCgwFAZjME1jjGmMTWNs2tjY2MY2DjjinHPOOeec3dXOOeecU2VlaSksSc/9aq1X0pJKqmD3Dn3upvnCSe197v38nlfS2fscW1x+kbCMloAsFY/skEY5KbVySb7JXfkoT+WtvJGX8ol/67s8lDr+o065KW65Jl7+q/zyF3/nWTpJx+gQ/7H94pPd/Oe38yduEZds4E9dK/Wykj95GX/OYvkq8/kz58h7mcmfP41/hMnyTCbIIxkn9/nv5raMlOsyTK7IELkgg6RKBshp6ScnpI8ckd5yQHrJHvmd/3578I/QjX+E32SNdOEfobMskV9lAf+vmiOdZIZ0lKnSQSZKe/7kSv7kdjKchkoFf2q59Ke+UsafWCY9pZQ/rZQ/rUS6Umcp5k8q5k8p5k8p4k8p4k8o4u928Hc7+Dsd/F1mpWLn7zArVhWpHOlsRvYC/Yf++t8A/j8fQCxrADvTA/j6vwH8/zGAaOzX/w3g/+cBaJEuEkqMMQbg/t8A2jiA8n/+AHzB7qLFx8K2zBhAA5Q16QE8+98A/q8PwOXvLYHYePEllsO666cGcPR/A/jnDaDRN0C80Ynija8QV2K3GsBlywDe5h3AVYAvAv0X4IUH4P7fAP7bB9DgGyau0BRx6yvFGd8j9YlTUp24LF+g/gDKGwbwAqwnwD1o5QD2/VcPYMT/BmD9q94/Thq0GeKMrpbG2B6pi5+S78kBJAoNoDFrAFU/PICP/+UD6PL/xwDqAlOlNjBH6sMQ6XulJnZavsWvyGcG8D7BABJvsgZwxxiAK2sAZ9ID8P/gAF78QwbQ/v/eAGqDc6Tav1BqtA1SE90v1fpp+Rq7Ip/id+UdA3jNAJ4nPsnjRGYAN0C9whe8C+kB+BmAP2sAu/jPNx1AjRrAlzwDeNqKARz/3wD+7r+qtSXy1QdLcJN8Dx+Qb9Ez8kW/Ih9id+Vt/Jm8sgzgfqL5ARwxBuBjAN70ADbznSE5gDWMJzWARekBvGsygLFy738D+Hf+9T20Sj77VsuXwFb5oh2SL5Gz8lG/Ku8ZwJvYM3kZfyPP4h/lUeIbA6iV24lGuZ5IDcALjQ8aP4+zOYCD/Pt70wNwqQE0WAbwLWcAr/MM4FbOAP78Bw+g6L97AN/CG+Sjb6N89O+Qj9oR+Rg+J++jV+Wtfk9eMYAXsTfyhAE8jH+TuwzgVqLBGMDlhFvOJ7zyZyI5AB8D8EHjyxrAtjYN4EnWAEYYA7j8XzCAXwoMoOJvHsB/aARfwtvkvS/ZHnkfOCbvtCp5G74mb6L35KX+TJ4xgMexj/IgOYB4rdyMN8i1hFMuGQPwyDlGcJoRHE+YAzgA/l7jn1VwqwE0WgZQLUuNAXxmAB+MAcyQVxClBvCQAdxtxQD25x1A1x8ewB9tGEAljO3+7wzgU2SPvPPvlje+A/LGf0LeBP+S16Fr8jJyT55Hn8kT/Y080j/K/dhXuROvYQD1cjWeHIBL/lIDOEXH6TAdoD0JcwBbGcAmBrCeL4Br+AWQO4DZ/MQ0B/C8mQGczxnA4YIDaM0LUNmqAfz2LxmA/b9xAB8iB+VN4IC88h2Rl/5T8jJwXl5o1+V56L48jTyTx9HX8kD/IHf1r3IrViPXY/VyJd4oF+IuqYq75SzYJ0E/ZgzAI/tpD6/DDgaylZdiE9efHMBqYwDfGcBXBvBJ5uUMYJIxgAeWAVyzDODcv2gAA35oAEV5BpAZwT9sAO+iR+VV4Ii88B2X576z8tx/QZ4Fb8gT7b48Dj+Vh5HXcj/6Qe7oX+SmXi3XYnVyOdbAAJwMwCVnGMHJuEeOAn/IGICbAbiMAWzhC+NGvjOs49fD6kSNrFADWGgM4L0awEs1gMeWAdxUA7jUxgGs+Le8AP+nBvAmelJeBE/IM99peeqrkif+S/I4cFMeMYAHoadyP/xK7kTey63oF7muf5creq1c4hU4H2uUczGXnGYEJxjBETpE+4DfbQzAqQZQzwBqZVWiWlbwS2JJ4ossTHxUA3ijBvDMGMB4YwB3ZFTeAZz6FwzA+gL0+jcN4L/sl8BL/Yw8004Df04e+87LI98Veei/JQ+CD+Se9lTuhF7JrfB7uRH5JNei3+SyXiMX9Hqp0hvkbMwppxjBcTrCEA7SXtrF67Ad/C1c/wauf60awHJjAJ8ZwAeZm3gnsxJvZHrihUxNpAZwvxUDOKQGsJsBbP+bB/A7df/JAfzD/mcBz3WuXvtTHvmr5IHvotz3XZN7DOBu4IHcCT6VW9oruRF6J9fCn+RK5KtcjFbL+Wid/MkITuuNcpIRHKPDjGA/8HtoJ98RtvFrYTNfGDeAv5bnf2XiOwP4KosTn2SBMYC3DOCVMYApiacyKfFIxifuy5hEcgA3YLrKAC7KYPlLBjKA/nKSARzLM4DNagCr/4UD6PRvGsB/YARPda5eOy8PAhfknu+y3PVdlzu+O3LL/0BuBp7Kde2lXNPeyZXQR7kU/irnI9+lKlojZxnBKV6B44zgCB3iI2E/7aEd4G8Ff1O8Tjbw03FNvFpW8jNyGc//Yp7/BYn3lgE8ZwBPZKIxgHsM4LaMSlyXEYkrMjTBABJVDOCsMYC+lgH0VAPo/hMDqGhxAJ1bOYCyf+4AHuuX+Ky/yMVfAv6q3PLdlJsM4Ib/oVxnANeCL+WK9lYuaR/kQuiLVIW/yblItZyO1spJRnCMl+AwQzhAe2kXXxB38B1hC18WN4K/HvzV8e8M4KssjX+WRfGPMp/nfw7P/8zES5mWHsADGZe4ywBuGQMYbgzggjmAxBnpn2AAiaPSJ5EcwD4GsAuubWoA6/83gB/964F+Re6Grsjt4FW56b8uN3y35LrvrlzzPZQr/qdyOfBSLgbfyHntvVRpn+Rc6KucCX+Xk5EaOR6plSOM4FC0XvYzhD20U6+TbeBvidXKBn42rot9l1Vc/4r4FwbwiQF8kHnxtzI7/lpmxl8wgGcyOfE4awAjE9cYwGXLAE4zgBMM4AgDOCi9E3ulZ4IBJBhAYpN0S6QGsByyxX/bAEqyBtDxJwbwX/xL4J5+TW6Hr8nN4HW57r8B/G254rsnl32P5BIDuOB/IecDb6Qq+F7OaR/ljPZFToW+yXFGcJQRHGYEB3gN9tJufiHsoK18UdzET8YN4K+JfZOVsa+yPPZJlsQ+yML4OwbwhgG8khnx5zI1/lQmxx/JhPh9BnBHRiduqgFcYgDnGcCfWQP4Iz2AndkDSKySLgkGkGAAifnyS2K2GsCUv2UAxQUH8A//HwbdiV2Xm2HwtRtyNXAL/DtyyXdfLjCA876n8hcDqAq8lnOBd3Im+EFO8QqcYATHGMFhRnAwXC37GcIe2sl3g+18SdwC/kZ+Mq7Xv8lq/SsD+CzLYh9lcey9LIi9lbmx1zIr/lKmx58xgCcyKf6QAdyTsfHbMjp+Q0bGrxoDGMIABiXOqQEcVwM4wAD2qAFsVQNYl38ACQaQYAAJBpBgAIm2DKDrDwzg7/gp+G8ewc3YTbkevilXtZs897flov8u+PfBfyRVDOCc74Wc9b+S04G3cpJX4ETwoxzTPssR7ascYgT7+U6whyHs4svhDtoa/S6b+Lm4Afi1+hdZpX+WFfpHWap/kEWxdzI/9kbmxF7JzNgLmR57KlPijxnAAxkfv8sAbjEAvgDGr8iw+EUZEv9LBsX5CZjgJ6AxgMMMgF8AxgB2SA9jABuNAXRt7QASDCDBABIMIMEAEgwgwQAShQbQ+n9VUNP/WcA/4HvA9RhXH7nFl7xbciFwR84zgCrfA/mTAZzzPZEzvudy2v9STvrfyHFegaO8AkcYwSFGsJ+XYC/fCXbTDoawLfJNtvBTcSOtj36RNdFPshL85eAv0d/JQv2tzNNfyWzwZ8aeybTYE5kceyQTY/dlfOyOjInflFHxawzgMgO4wACqGMBZGRDnJ2D8mPSNH8oZwBY1gLUMYCUDWMYAFlkGML1tA0gwgAQDSDCARKEBFP7nA/6RA7jCAC5FbssFDfwg+P57wD8A/pGcZgAnGcAJ30s57n8tR/1v5XDgvRxiBPsZwV4+DvYwhJ38OthOW8JfZBNtiHyWtZFPsir6UVZEP8jS6DtZBP4C/bXM1V/KLP25zNCfylT9MQN4IBNid2Vc7LaMid2QUTGe/xif/3E+/+N/MoDTagD8AkgOIM4A4rulZ5wBxJMD2JBnAPPyDGAs+KPyDKBf4QEkGECCASQYQIIBJP5d/7OAf+MILvH/8Rcid+Sv0B35kwGcC9zn4h/IKQZwkgEc9z2TY3wMHPG9kkO8AgcZwX5GsJcR7GEEO/liuJ0hbAl9ks20IfxR1tHqyAdZGXkvyyPvZEn0rSyMvpZ50ZcyR+f69WcyHfwp+kOZpN+XCfodGcsQR/N9ZGTsCgO4KENjf8ngGJ//DKB//DgD4BdAnC+A8X0MgF8A8e3mAOIb5Lf4GukaTw5gqWUAsywDmNDGAXQrPIAEA0gwgAQDSDCABANIMIBEqZE9UaIqVhVZcqSzJf5LBnCep7cqeoefd3flrHaPz/r7PPcPuPpH4D+RowzgMK/AIV6BA3wX2M8I9vJ9YDcfBzv5TrCdIWzVPshm2hj6IOtpTei9rAy/kxW0NPJWFkVeywLw50ZfyOzoM5kRfSLT9EcyWX8gE/W7Ml6/LWP1GzKaXyQjYjz/sQsMoIoBnJWBsZPSP8bnf+wwA+ALYHwvA+ALYHwbA9icPYA4A4gvlF/jc+WXeGoAk/+GAfzSigGUtXEAagS5/bsHUMUAzkXv8tv+Lt/w78lJBnCcARxlAEd8j4F/KgcZwH5egX2MYA8j2M0IdjCC7bQ1+E4200btnayntbQq9FZW0rLwG1kSfiULIy9lXuSFzIk8k1ngT48+lqnRBzI5es+4/nH6TRmjX5dR+hUZoV+SYfp5GRLj+Y/x/BsD4PM/xvMf2y+9Y3z+x3YwgK0MgF8AcX4CxlczgBUMYEn2AOLTpGOcAcStAxje4gBK/5MDSGfL9K/86xwDOM0ATjGAEwzgePC+HAk8kMP+R+A/lgO8Avt5BfYygj2MYBcj2MEItvOdYEvgjWymjcE3sp7Wam9kNa2k5aFXsoQWhV/K/PBzmRt+JrMjT2RG5LFMizyUKdH7Mol/3PHRWzI2al7/SP2yDNe5fr1KhujnZJDOAHSe/9gRywB2mwOI8fzH+AIY4ydgfBUDWK4GsEANYGb2AOIMIM4A4gwgzgDihb4E9rAMoMvfMIDiHxxAzghy+7v+Os0ATgJxnAEcYwBHGMAhBnDQ/xD4R1z9Y+CfyG5GsJMR7GAE22gLvww2M4SNgVeyntYGX8lqWqm9kuXaS1lKi7UXsiD0XOaFnsmc8BOZGX4s08MPZWrkvkyO3JWJfPkcF+X6o9dkVJTrj15kAOcZwJ8yWD8jA/WT5gB0nn/9gPyh8/zHdjGA7WoAfAGMrZXfYiula4wBxBYbA/glPqd1A4gzgDgDiDOAOAOIM4A4A4gzgDgDiDOAeGoAnZoZQL7vAcXNvgI/PYC21NxfJ+N35Difw0cZwJHQPb7h35cDDGA/HwN7eQX2MIBdDGAHbWcEW2kLQ9jECDb4X8h6Wht4IatpZfCFLKelwefgP5eF2jOZrz2VOaHHMiv0SGaEHsi08H2Zwj/WJPAnRG7KuMh1GRO5ygAuMYALMizK9UfN6x+on5D++lHpqx9iAFy/vkd66Tulp87nf2yzGsAaYwBdYvwCiPEFMMZPwNgc6RSbwQCmMoBJDGA8AxhjGcCQtg0gzgDiDCDOAOK5A/iZL4L/xhEU6hgDOMIADnORB/kiuF+7L/sYwR5GsJtXYCevwA5GsI22MILNfCfYxAg20Hpa638uq2ll4LksDzyTpbQ4+EwWBp+A/0Tmao9ltvZIZoI/PQQ+/xiTwuCHwQ9fl7Hgj45clpGRCzI8wvVHuf7oGRkU5fqjxxkAz79+kOvfxwB2MwCef53Pf32TdNfXSzedz39jAEvVAPgFEJttDKBjjAHEGECMAcSSAxj59wwgzgDiDCBeYfZPHsARBnCIL2IHGcB+cPbyMbCHAeziy+AOXoHtvgdc/SPwH4H/WDbSBoawjtbQKlrpfyLLaWngiSymhYHHMj/4WOYGH4H/QGYyqun8uVO1uzI5dFsmhm7K+BD44WsyOnxFRoUvygjwh0W4/shZGRzh+qMnGMBR6Rfl+qP7jee/t87zr/P861sYAJ//Op//Op//Ol8AdT7/db4A6skB8AUwxi+AGD8BYxNpnDmA2EhpFxtGDCDGAGL9pTzGAGIMINaaAXTMGUBqBAwgXqZiAPF/0AAOxW/LAQawL3JH9jCA3SDtDN7jW/592ea/L1sZwRZGsMn3EPhHXP0jWUtrGMIqWknLaan/sSzmI2MhzQ88lLm8ILMZ0kyaEbwr07Q7MkW7JZO0mzJBuy7jQtdkTAj80CUZGT4vw8NVMjR8jgGclkERrj/C9Ue4/uhBcwBRnv/oDukZ3coAeP51nn+dz3+dz3+dz3+dz3+dL4A6XwB1BqAzAJ0B6AxAZwD6aKnUrQMY2HQAMQYQYwCx/AMoNgaQ7xXIMwCjYktFmbIG4PjPDmA/A9jH7/A9DGBX+I7sAGo7I9gWuMu3/Ht80bvP1d8H/z5X/wD8B7KaVjKIFbSMlvLvL6aFjGU+zeXvmc3fO4s/Y0bwjkwL3pYpwQz+eO2qjNWuyOgkfuiCjAhVybAQ+OEzMjh8UgaGjzOAI9Ivckj6RsCPcP2RXQyA649y/dGN0j3K8x9drQawjAEsYgDzGQBfAHW+AOp8AdT5AqjzBTA9gBHSTmcA+mCp0AeC38wAYgwgxgBi/BSMtXUApc0PIO5IZzOym/0nRrAnfkv26LdkV/S27OCzeXvojmxlBFuA2wTgBv9dvujdBf8eV3+fq78vK733ZQUt499eQotoIc3nv2Yu/7WzaZb/jswI3JZpgVsyJXBTJgevy8TgNRkfTOJfljHaRRmlga/9JcNDf8rQ0BkZEjolg0I8/eGj0j98WPqFuf7wPgawhwFw/ZFt8ntkMwPYwADWMgCe/yjPf5TP/yjPf5TnPzqb+AKo8/mvT1IDGEujmg5AZwA6A9AZgJ4aQPecAfxqDiDGAGIMIMYAYgwg1poBlLRtAAWzFe5nB7ArflN2MoAd/B7fFr4lW/iM3qzd5rf9HdkQuAP+Hb7o3eHq73L1Zsu9d2UpLaFF/PsLaL7vjsyl2b7b4N+SGTTNfxP8GzI5AH4giX9FxgUvyZhgEv+8jNSqZLj2pwzTzsoQ7bQMDnH9oWMyIMT1h7j+8H4GAH6Y6w9vZwBbGABf/iJcf4Rv/xGuP8LzH+H5j/L8R3n+ozz/0enEAKIMIDo+ZwBDCw9AZwA6A9AZgN6KAcQYQIwBxMpVDCBWavT3DqCFEfzMQHYwgO36TdnK7/EtDGBT6JZs4LN6A0/2Oq53DVe8yn8b+Ns8+be5+js8+Xdksfe2LKQFNM93C/xb4N+Smb6bMoOm+a/LFJrsvyYT/VdkQuCyjAuAH7ggo4PgB6tkRPCcgT80ia+dlEEaT792RPqD3y8Efmiv/BHazQC4/jCf/WGuP8z1h9dJtzDPf2QFA1jKAHj+Izz/EZ7/yExjAB2jU2iiOYAoXwCjDCA63DIAfgHo/ahP4QHoDEBnADoD0Ns4gFiJqlhVZCl3AI5/3QBaalv8hmzRb8jm6A3ZyO/yDXxDX89n9VpaHbwpq3i+V3LNy2kZwEtoMS303pT5NI/m0GzvDfCvy3Sa5rsmU2iy74qJ778k4/wXZWwSPwB+APzAORkePCNDg6dlSNDEH5jE18DXDkhfbZ/00bj+0E7pFeL6Q1x/aKP0CK1nAFx/mOsPc/3hJbRQOofnMQCe/wjPf4TP/wif/5EJDIDP/yif/9GR5gCifAGM8gsgah1A79YNQGcAOgPQGYDOAHQGoLd2AHlGoLIZ2bP7dw1gS/y6bNKvy4YoRa7LOn6br9FuyGpaGbwhK3jCl/tv8C3/BvA3ePJv8OTfAP+6zKU5NItmeq/JdJrmuwr+FfAvy0TfJZnguwj+BRnrPy+j/VUyyv+niR8AP3BKhgROyOAg+MEjMiB4iAFk8P/QdklvbYf00rh+jevXuP4Q1x/i+kMMIMSXvxDPf5jnP8zzH55FPP9hnv/IJHMAEZ7/CAOIjGAAw7IHEGUAUQYQZQDRnj8+AL1cxQD0UiO7/pMDyJvN7O8cwMb4NdmgX5P10WuyNnJN1vDbfBW/0VfybX0FX9yW8fm9hBbznC/kqhfQPJpLswGf5b0qM7xXwL8iU2mK95JMoonAj/ddkHG+8zLW95eM9iXxz8kI/1kZ7j8tw/wnTfzAMRkUAD8AfvCg9Avul75B8IMZ/J4a169x/RrXr62RbtpK+U1bzgC4/hDXH+L6Qzz/YZ7/8DTi+Q/z/Id5/iNjaJQxgHYRBhBhABF+Akb6Nx1AlAFEGUCUAUQZQJQBRFszgArLAMoyAzAqtlRklncAjtYPoFA/MoAN8auyLnZV1uhXZXXkqqwMX5UVoauynJ9qS/nGvoQWBa7yE+8qP/Gugn9F5tBsmgn4DO9lmQb4VJrivQj+BZlI473nZZz3L/CrwP9TRvnA952R4T6F7z8ug/3g+4/IwCR+4ID0C4Af2CN9ArsYAPjBbdIzCH4Q/CDXr/HNX1sFPp/9Gp/9Gtevcf2hucTzH+L5D3H9ockMgOsP8/yH+fwP8/yHef7DfP5HBmcGEOlLfP5HGECEAUR6GAMoif6WPYAoA4gygCgDiLZ1ACVNB2DkSGfT/6YBtKXUANbGr8ia2BVZpV+RlZErsiJ8RZaFrshSfqcvpkV8c18QuAL+ZX7iXQb/ksyimTQd9GmgTwV8Mk0CfQKN91aBXyVjvH/KaO85GeU9A/5p8E/KMN8JGeoD33fUxPcfkgF+8P3g+8H3gx/YIb0D26RXYIv0DGyS3wMbGMBa6R5cLd2CyetfxgC4fo3r17h+jevXZhLPf4jrD/H8h8YTz39otGUAQ4jnP8zzH2YAYQYQTg6gV2YAEQYQYQARBhApMIAoA4gygCgDiFaYNRlAaQsDyDMC3d60f+UIkq2OX5KVMdIvyfLoJVkaviRLQpdkkXZJFtJ8frbN49v7XJrNF7lZPO0zeNqn0zTQpwA+mSZy7RNAHw/6ONDH0GjgR3lPywjvKRnuBd97HPxj4B+RQb7DMtAHvu+A9Pftk74+he8H3w++H3y/wg+sk+4B8APgB3n6g1x/kG/+wQUMgOvXuH6N69f48qdx/RrPv8bzr/H8h3j+Q3z+h3j+Qzz/IQYQSg6A5z/M858cQJgBhHn+wwwg3M0ygM5SHGEAEQYQYQARBhApMIAoA4iWqcCP/k0DaJItu58dwMr4RVkRuyjL9IuyNHpRFkcuyqLQRVmgXZD5NDd4Qebw7X02zeSL3Ayaxuf6VD7Xp4A+CfSJNAH48aCP9Z4F/wz4p2Uk8COAH+49YeJ7j8pgL/jeQzLQe1AGePcb+P3A7+sD3we+D3wf+D7w/eD7wfevMfEDK2ipdA0sli4B8INcf5DrD3L9Qa5f4/o1rl/j+dd4/rXRxPVrXL/G86/x/Id4/kNcf4gBhBhAiOc/xC8A6wDCDCDchRhAOM8AIgwgwgAiDCDSzACiJapiS3/zAFpboQEsj1+QZbELskS/IIujF2Rh5IIsCJ+XeaHzMlc7L7P5zT6LZgb+kun+v/h9XwV+Fd/y/5RJNBH0JPw44MeCPoZGeU7JSM9JGeE5IcM9x2WY55gM8RwB/7DCP2Die/dKPy/43l3Sx7tD/vBuk97eLQxgEwPYIL/71ksP3xoGsEq6+cH38/T7efoDPP2B+TRHfg3wzT/A9QenEtcf5PqDPP9Bnn+N69e4fo3r14aYA9AYgMYANJ7/0B9qADz/IQYQ4gtgiAGEcgYQZgBhBhBmAOE8AzBiAJEyVakaQYEBpHOks/07RpCvpfHzsjh2Xhbp52VB9LzMj/wl88J/yZzQXzJbq5KZNCNYJdP57T6Vn3BT+CY/mS90k2iC7yz4Z8A/beCP5tpHAT8S+BHADwd+GPBDPIdlsOeQDPIclIGe/TLAs0/6e/ZIP89u6evZKX08Fnwv+F7wvQrfB76P6/cpfP8iAt/P0++fbeD/EuCbf4DrD0wirj/I9Qd5/oMMIMgAguYAKjSef43nX+tnDkBjABrPv8YAtB6WAfD8hxhAiAGEGEAoZwBhBhBmAGEGEC4wALJHSlTFZs0NIJ29af/KASyOV8nCWJUs0KtkXrRK5kaqZE64SmaF/gT/T5mhnZNpwXMyld/uUwJnZZL/DD/xzoB/mp95SfhTXP1J8E+Afxz84+Cb8EMN/EPgHwT/gMLfq/B3gb8D/O3yh2er9PaA7wHfo/C94HvB9ybxl9MS6eoD38fT75tn4P/q5+n38/T7uX4/1+/n+gPjCPwA+AGe/wDPf5DnP8j1B7n+INcfTA6A51/rrQbwuzkAjQFoXL/GALScAYQ6SVGIAYQYQChnAEYMIFymKjAAoyJLjjwjsLciW3Y/M4CF8T9lfuxPmaefkznRczI7ck5mhc/JjNA5ma6dlWk0JXhGJgdOyySayG/48f5T/L4/yU+8k+CfAP84X/aOAX+Uqz+i8A8p/AMyyL1fBrr3yQD3Hunv3i393Dulrxt8N/hu8N0WfM866eEB32Pid/OC7+Vz3wu+18Tv7OPp9/H0+7h+H9fvM/E7+nn6/Tz9fj77/Ul8rj/A9Qd4/gNcf2CAGgDXH2QAQQYQtA6A67cOQGMAGvga15/GVwMIMYAQAwhVmOUOgOzhElWxWZMBqBGobEb27FozgNZUaADz4udkbuyszNHPyqzoWZkZOSMzwmdkeui0TNVOyxSaHDwlEwOnZELgJPgnZZz/BPjHZYzPhB/Jl7sRfLkbzlM/DHQT/4AMBn4Q8AOBN/F3gb9D4W8Dfwv4m6WXe6P0dIPvBt9t4nf3gO8B3wO+hy99ngUMAHwv+F7wveB7k/g8/T6efh9Pv4/r93H9fq7fD76f6/dz/X6uPzDQGEB5gOsPMIDAH2oAPP9BBhDk+oMMIJgaQBL/18wANAagga+1V+UMIMQAQmWqUqMmAzAqyslhlh5AnhHkzWYW/cnmxk/L7NhpmaWflpnR0zI9clqmhU/J1NAp8E/KJJoYPCkTgidkfOA4+MD7j8lofseP4ufcSOBH8OVuOOjDeOqHAj+Ep34w8IPcexX+bvB3Sj8X+K7t0se1Vf5wge/aJL1cG8BfD/5aA7+HG3w3+G7w3SZ+V89CBsDnvofPfQ9Pv4en38vT7+Xp93L9Xp5+L9fv4/p9XL+P6/cNJ67fz/X7uX4/A/Bz/f4kPtcfAD/A9QcYQKCHZQDgB7n+IAMIMoBgMwPQGIBWoWIAWs4AQiWqYksFBkC2dPbsmhtAS7U0gNnxUzIzdkpm6KdkevSkTIuclCnhkzI5dEIm0UTtuIwPAh88JmMDx8A/KqP9R0x8fseP4Fv9MK8F3pMfvh/wfV3bwN8C/mbwN5r4LvBd4LtW00rp7loB/jLw+cx3g+8G3w2+ey4pfM90At8DvoenP4nvHUtcv5fr944w8X1cv4/r94Hv4/n39zMH4Of6/QzA35N+NwcQYAABrj/AAAI5AwgygCADCDKAYAq/wACMSo3sWolZ1giKcnKks4UKDCBvNrPITzYzflJmxIDXT8jU6AmZEjkuk8PHZSJNCB2T8doxGacdlbHBIzImALz/sIz0Aw/+cN9B8A/w+34/+PvA38uXvT3g7wZ/F/g71NVvM67exN9kwV8H/ppsfBf4riW0SLq6ePZdFnw3+G7w3eC7JzMAnn4PT7+Hp98DvmcUA+D6vVy/F3wv1+8dpAbA9fsYgK8PMQBfL2MApckB+MH3c/1+BuBXAwgwgAADCDCAAAMIWAYQrFQxgGCFWXMDMCpWFWWXOwAje/7yDaClWhrA9PhxmRY7LlN14PVjMil6TCZGjsqE8FEZHzoiYzXgtcMyOnhIRgUOgX9QRvgPgL9fhtFQ7z4Zwu/5wcAP4mfdQOAHAG/ibwN/a/rq/wC+N/C9uPqeXL2Jv0rhL8+DP4/Ad4Hvmkngu5L4Uwh89wQC383T7+Hp94Dv4fo9XL8HfA/X7wXfy/V7wfdy/d4kfm9zAD7wfVy/jwH4UgMA3w++H3w/+H4T3xhAgAEEGEAA/EA7I3MA5aoyVamRPZhvALkjcKSzpbMXHkE6W3bhH2xq/JhMiR0F/6hM0o/IxOgRGR85IuPCh2Vs6BD4h2Q0jQoelJGBA+Dvl+H+JP4+GerbA/4eGezdDf4ufubtUPjbwd8K/hbwN6ur36Dw10lPJ/hOrt650qi7M4m/FPjFOfhzmuK7wHeB7wLfNd7A7+AG3831u8F3D6OhBn47D9fvAd/D9XuS+H3MAXjB9/L8exmAt4eBX+oD38f1+xiAjwH4LAPwg+/voMoZQIABBMpVZWbWAaQrttSKARSquRE0V6EBTIkfkUkx4MGfoB+W8dFDMi5ySMaGwQ8dBP+AjNT2y4gg8IF9Msy/V4b6gQd/sA94r4I38LeDv5Vv+lsU/qb01fd2rpdewPd0rgF/lcJfAf4y6eYE3wm+c6F0dYLvBN8JvhN8Zwb/l1x8F/gunn4X+C7wXcNNfDfX7wbfzfW7+zOAfuYAPOB7uH4PA/AofC/X7+X6vQzAywC8DMCrBuBjAD4G4GMAPvB97c0B+BmAH3wjBuAvN0sNIFBqZA+UWMoZQDpHOluwFQPIyta0UBubFD8kE2OHwD8k42ls9KCMiRyQ0eH9Miq038TX9snw4F4ZFthj4vt3g79TBvl2yEBvEh94zzYD3sTfDP5G8JNXn4RfR2vAXw3+SoW/XOHz5DsXKfz5FvxZJr4TfCf4TvCd4Dsn5sEfaeK7ePpd4Lu4flcSf4AxgHI3+G6u380A3En8nuYAPAzAwwA84HvA9yh8L/he8L2dVJYB+CpV4PsqzFID8JepwDcqMUsNIF2RJUfTERjZm9aaAbQm6wAmxA/K+NhBGacfkLH6fhkT3S+jI+CH98nI0F7w98hwGhbcLUMDu8DfKYP9OxT+dhng3QY+8NSX3/R9+U3fB3gTf526+tW0SuGbV9+dq+/WyNU3gt+4QLo2gt84l8BvBL9xBmXjd0riO8F3gu8E3wm+cyQDMPErXUMVPtfvAt/F9bu4fhf4riR+b3MAbvDd4LvBd3P9bssAPAzAwwA8DMCj8I0YgJcBeCtVDMCrBuArV5WpwPdZBmBUbKnILDUAS7Z0drNgc9my+5ExjI/vl3Gx/Sa+vk9GR/fKqAjwYeBDwGvAa8AHd8qQwA4T379dBvq2gb9F+nuT+En4TdLHvUHhrwd/bfrqewL/u+XquzcuUfgLFf48hT87G78R/EbwG8FvBL9xPPGlr3EMAxht4jt5+p3gO8F3gu9M4g+04PdVAwDfBb6L63cxABcDcCUHAL4bfDf47s5GxW4G4FYD8IDv6aBiAB7wPe0yAzAqV5Wp1AB8Jari7FIDMHJkZUuVGkCz2ZqOoLnyDWBcfJ+Mie2V0Trw+h4ZGd0jIyK7ZXh4twwL7QIfeA34IPAB4P1bZYB/iwzwJfE3Sz/vJunr2Wjg/+FeD/468NfwZS9z9b9z9T0M+KUKf5HCn6/w5yj8mQp/msKfrPAnZOM3gt8IfiP4jeA3JvGHGPjtnOA7uX4n+E7wneA7uX5nHnwX1+9iAC4G4GIALvBdCt/dScUA3OC726vMATiMwPeUq8pUpeYAjEpUxZl8RTk5skoPwG8vnHUALdXSKMbE98jo2B4TX98tI6K7ZHhkpwwL75ChoR3gb5fB2jYZFNwqAwNbDPz+/s3S37cJ/I3gc/Ue4N3rjKvvDXwvftr1VPC/c/U9LFffTV29ic/VN4DfMEs6N4DfMJ3AbwC/AfwG8BvAbwC/gWe/AfwGK/5wE78R/EauvxH8RvAbuf5G8BtT+L3NATgZgJMBOMF38s3facW3DMDFAFzguzoaFbkYgEvhG4HvrlCVqywDILtRicoyAG9RTg6z1ADS2ZuWdxC2pgXa0Oj4bhkV2wX+Lhmh75Th0R0yLAJ+eLsMCW0Df6sM0rbIwCD4AeD9wPuA922Qvt714K+TPzzAu9cY8L34Td/Tlbn6Hs7k1S82rr6b5eq7NiTxZyv8GRb8KQp/Yn78BvAbwG8Av2Eogd8AfgP4DeA3JPG5fmMAfxD4jeA3gt8IfiPX32gOoCQ5ACcDcILvBN8JvvMXMzWANL5RpYoBuCpU5WbJARiVGtndJZmSA0hXlJMjMwKypbNn8jWXLZO/DaUGMDK+U0bEdshwHXgaGgU+Anx4qwwObTHxtc0yILhJ+gc2Sj//BgO/j2+d9PGuBX8N+Fy9e6XC5+pdyw34HnzD7+40r76b5eq7GlefxJ9pwZ+ajV8Pfj349eDXg18Pfj349SMYQC7+oAx+A/gN4Ddw/Q3gN4DfAH6DBb+R628EvxH8RvAbOxsVN6YGAL6zo1GRkwE426vAd7bLPwBXmarUyO6yDMBdbKkou+QALNnS2c28LWXLHkFL5Q5hRBz82Hbwt8lQGhIFPgJ8GPjQZvA3yQBto/QPbpB+AfD9wPuA966h1dLbs8rAT8L3BP531zKFvxj8RQp/PvjzFL559Sa+efW/1oNfD349T359Cn+cBX9UBr8e/Hrw68GvB7+ez/168OvBrwe/Hvx68Ot5+uutAwDfiAE0cP0NDKCBATQwgAaF3/iLigE0gt/YQQV+Y6UZA3AYge8sV5VlDcCeGkC6YktFZukROLKypbNnRtBcyQG0pkKDGB7fJsNiW8HfIkNocBT8CPBh4EPAaxtM/OB66RtYK338wPtWg78KfK6eerqXg78MfOBdSwz47vyu7+Y0r/63JDxf9LpannwDvz6Jn4SfbMEf3zJ+Hfh14Ncl8Qem8Sss+OVJ/Hrw68Gv5/rrwa8Hv57rrwe/Hvx6E98YQAMDaAC/AfyGjkZFDeA3tDczBtDOyNFYoSo3Sw7AqNTIblSSKd8A0jmysqVKDqCljBHYWq65YQyLb5GhsST+ZhlMg6KbZGBkowwIAx8CXlsP/joTPwC8H3jfSuntTeKvMPB/dy8Ffwn4XL0rib8AfPPqM/iz0k++iT/Vgm9evYFfB34d+HWjCfw68OvAr+Pbfl0Ofh34deDXgV8Hfh34deDXgV8Hfh34deDXgV8Hfp0VXw2gHvx68Ot/UTGAevDrO5gZA6hUtTNyNFSo1AAay1SlRnajkkzOYktFORUYgMvefOkh2JqvpXEMjW+WIbFN4G+SQfpGGRjdIAMi4IeBDwGvrZW+wTXgrwIfeOrlWyG9vFy9Z5nCXww+8K6FGXznXPCB5+ediW/Cd1ZP/q/qyU/j14034DvWjcnBH94Uvxb8WvBrwa8Fvxb8WvBrwa8FvzaDX2bFp5I6BlAHfh34dVx/HfhG4NeBX9fRqKguOYD2qkoV+PUVqnJzAA1llkqN7A0lmRqLcyrKLjkAS7Z09kzNjsFWOHcrGhLfKINjG8HfIANpQHS99I+sk35h4EPAa6ulTxD8QBIfeN9yWiY9vcB7uHp3Eh94F/Cu+eDPU/jANwLPb/sMvgn/q3ryDfy6JP64PPhcfS34teDXgl8Lfm0r8WvBrwW/FnwjBlDLAGrBrwW/FvzazkbFteDXgl/bySyFbwR+XaWqnZGjzjIAozJVqZHdqMTMGEFxTkXZNTrS2bKyZ3I2l83M9YMNjm+QQbEk/noZoK+T/tG14K8BH3htFa2UP4LgB8D3A+9bCv4S8IH3LGIAKfx5BLxzDqXwZ4BvXn02/kQyrz4bf5R0qOXqa5viV6bwa/jCVwN+Dfg14NeAXwN+TW8Cv6aniqe/Bvwa8GvArwG/BvyaLioGUAN+zS9mxgA6GhXVgl/bXlWpAr9WDcCoXFWmKjWyG5WYGUMotlTUtAZHOltW9kyNzWUzc7ay3AEMiq+XgbF14K+V/voa6RdZLX3DwIeAT+JrK6R3kKsPgO8H37dYfvcC71kI/gLw51vwgXfOAn9mDr4J/6u6+mz8McTV1xbArwG/Bvyaga3A79UCftcc/NQAOqnAr+mgAr+mUtXOyFFboSpXlVkqNbIblWRGUFdsqahp9Y50tqzsmRqay2bW2MpyBzEwvlYGxNaAv1r6RVdJ38hK6RMGPrQC/OXSW1smvYLAB5YwAPB94HsXMID50t1twndzcfUuhe8EvnE6mVffFN+E76SuvmNtHvyaYWn4yppB2fjV4Ff3JfCrwa/ubVRWDX41+NU8/dXgV4NfDX71b0Yl1eBXg1/d2ai4Gvxq8Ks7qbj+auCN2qsqzZL4RhWqclWZqtTIblRilhxBbXFORU2rc6SzZWXPVN9ctkwNrcw6iAHx1dI/tkr66SulbxT8CPDh5QxgGfhLpZcGfHAxA1gkv/u5eh9X7wXfA77bhP/NlYSfmQcf+IZJ4JtX3zy+Cd++ZmhT/Grwq1vA/w7+d/C/g/8d/O/dVOB/B/87+N87q8D//osK/O8djYq+d1BZ8KvbGTmqK1TllspUpUZ2o5LMCGqKcyrKCfjaTLas7NnVFcqWXX0rS42hfxz8GPgMoE8U/AhXHwY/lMH/PbAQfK7eB7x3HvhzTXy3wnfNAB945zTwgW/k6hX+L03wzSe/o4LvYLn6LPxq8KtN/HZW/O/gfwf/e2+jsu/N4H8D/xv437qowP8G/rdfVJ1UOfhGlSrwjSpU5aoyS6VG9u8lZtWpii0V5clhjkBlS2dvWm2hbE2ra2XJIfSLgx9bIX10rj4KfGQpA1givUJcvcbVB8EPgO8H3we+d4508wDvngX+TBPfZeJ3dqbwufoG4BsUfL159Xnxa3Lwq/Pgfwf/ewH8b+B/A/8b+N/A/9ZNVQj/1yb4xd+AN2qvqlS1M3J8q1CVWypTlRrZjUrMjCEU51SUJ4c5ApUtnT1/+YZRY8tfbSvrG18ufWLL5A8d+OgSBrBYeoUXSc8Q8NoCBjBfegSA989lAOB7wfeA755pwHd1cfVJeOcU8Ln6xjz49T+I/z0P/jfwvyXh8+HTV/C/gv+1qwr8r+B/Bd4I/K+dVB2Nir52UIH/tVLVzsjxtcJSuarMUqmR3agkM4JvxTkV5clhxhBsWdmbL2sYtsLVtKI+cfBj4OvgR8GPgB8GPwS+Bn4Q/MAcBjBbuvmA985kAFy9W+G7FL5T4Tcq/AYFX6/g+YnXUcF3sDz57S3wlQY8fc/B/wb+tzz4X8H/Cv7X7ioTvzSF/wX8L51V4H/5RQX+l45GRV86qNqrKlXtjBxfKlTllspUpUZ2oxJzAOmKcyrKyZGV7Zs1e8ulB2FrueZG8kcc+NhiBrBIekUXSs8I8OH5DGCe9NC4+iD4AfD9VnwTvosLeNdk8E34XxuT8OPz49e1Al/Bp/G/5cH/miwP/hfwv4D/JQnfEr4awGfgjdqrKlXtjByfKyyVq8oslRrZjUrMERgV51SUJ0dWtmRfU9lb3zdb68s3jj/i4MfA18GPgh8BP6zwNfCDs8AH3jeDAXD1HvDdOfhOhd+Yg1//I/hJ+Bz8r+Cn4RX+F/C/dFdZ8D8nA/9zZxX4n4H/lKyTqqNR0SfwP7VXVaraGTmMKlTlqjJLpUZ2o5KcinMqyu5zMkdWNmtf7G3IZva1jaVG0Tu+UHrFFkhPHfjoPAYwV3qEgddmE/gB8P3g+8D3gu8B353En0TAOycQ8I3jwAe+YQz4wNeb8B3rTPgOtcNaid83g/81g1+ewv9i4pel8D+D/xn8JPynZOB/6qwC36gA/sdk7VWVqnZGjo8VqnJLZZZKjexGJZaK81TUtE+OrGzp7K3rcypb0760oV5x8GPzGQD4UfAj4IcUfhD8wHQGME26+oD3TgGfq3crfJcFv7EAfp3CrzXh2xs/8fLgW66+Cf6XJHwO/meF/wn8T3nwPwJvBP7HTqqORia8Bf9DpaqdkeNDhaVyVZmlUiO7UUlOxTkV5cmR6SPoWdnbGIiffrDkWHrGwY+Br4MfBT4yiwHMlG4aVx8EPwC+H3wf+J48+E4LfoPCr28O34QviG/A5+L/bvYZ/CT8p2Q5+B+7qEz8kjS+GsCHjirgjdqrcvDfJ6tQlVsqs1RqZDcqyak4p6I8ObKypfqQzN7GbE372IZ6xufK77E50kMHPwp+GPwQ+Br4QfAD4PvB94LvmcgAgHeNJ+CdY8EHvnE0+MA3jGwVfuonXrP4Xyz4nxX+pxz8j0n4HPwPvxoVf/hFlYP/Pll7VaWldkZp/HfllsoslRrZjUpyKs6pqECOrGxZ2TO9b022lvvQTL/HwY/NZgDgR8EPgx8CXwM/OIUBTOb6uXov+B7w3QrfBb5T4Tem8EcQ8HXDaKiJX6vwa3Lx++XB750f/1MKv5vZxxz8D8ny4L/vpAL/fQ7+u2SVqnZGjncVlhT+2zJLpensRiWWivNUlCdHVrYm2Qv3Ll+2Hys1jh5x8GPg6+BHpzOAaQxgqnTVwA+C7wffB743D77Tgt+Qiw987eBm8NWXva8W/C8WfAM+B/9jBr/0Q1cFb8F/D/77X1QW/Hd87r/roLLgv03WzsjxtsJSuSXg36QqNbIbleRUnFNRgRxZ2bKy/0A2s7c/WI/4TOkemyHddPAj4IfBD4GvgR8A3w++D3wP+G6F77LgN1rw63PxB6XxK1vE75WD3yOD/9GC/yEH/31nAz4L/10nVUcV8G+TtVdl4xe9YQBvKlTllpriO16Db1Riqbhpr4oK5MjKlpW9cK8LZWu5N83UPT6DAYCvgx8BPwx+CHxtEgMA3w++F3wP8O4x4APvGsUARmbwGyz4dQq/NolvwjfF75Mf/3MO/kcL/gcL/vsuKgv+u19UCv9tR5UF/02ySlW7dAb861TlZq/Kcio1shuV5FSc3ctkRXlyZGVrkr2N2bJ79QN1j4MfA1+fygDADyv8IPgB4P3jGAD4HvDdFnwn8I3DwR9m4tfnwa9J4vc3/gkdA/975vO+IufLnoH/KQ/+Bwv++xz8d78apfHfdlJZ8N90UPAK/3WqdkaOVxWWyi0p+JfJSo3sRiU5FWf3IllRgRxZ2bKy/0C2H8s6mm5x8GPg6+BHwA+Dr02QzsHxDAB8H/heC77Lgt8IfMPQDH5dK/C/tYD/sRX473Lw31rw33RUWfBftzfRX6VqZ5SGf5ms3FKZJfBfmNmNSnIqzu55sqI8OZpky8r+A9l+vm5x8GPg65MZAPgh8DXwg+AHxjIA8L2jGYCJ38kFvtOKD3z94Ax+rcKvSeL3y4Pfuxn87k3x31vw31nw3/6q4BX+mxz81x1M+FftLfD0sp2RiW7Bf5GqzJIF/3mykpyKm/asqECOrGxNsv9Atp/vtzj4MfCjE6VLBPwQ+Br4QfD94PvA94DvVvgu8J3gN4LfkMIfZNQEv7pvC/i/N8VPX70FPw3f2YA3U/hvLPivkwH/qoOCV72sVJn4RS8YwIsKlQX/eVlOpUYG/rOSPBVn97SoQKA/yc6Wlf0Hs/18v8XB17n86AQGAH4IfA38IPh+8L3ge8B358FvAL/egl+bB//7D+C/z4P/Ngf/jQU/Cf8qmQX/ZSqF/6JdujT+82TllkB/lqo0nf2ZGsBTa4A/ya0of48dWdmaZG97j5LZfr6u8UkMAPwo+JFxDAB8DfwA+H7wveB7FL4LfCf4jUMYgMKvB77Ogl+Twu+Tg9+rbfjvCuC/seC/7qTgTfzilx0s8PSiUqXwn7dT6Kpn5ZYs+E9L09mfJCvJSYE/tlaUv0eOJtmaZM/fw+aytb0Heeoa5+nXwY+CHwE/NIYBgB8A3w++F3y3wneB7wS/EfyGHPxaC361Bf/bT+C/teC/seAb8Bb8lxb8F6kU/vN26Uz0VBb8p2VmT5KVpjPwH5fkSaE/slaUv4eOrGzJHlizt637qWx/T13iE9QAwA+DHwJfG8UAwPeNYADgu4cxgBz8BuDrga+z4NdY8L9b8L/+BP4bC/7rXxS8wn9pwX9hwX9eqVL4z9pZ4OlpudmTcoVu6XFpOvtjNYBH1izoD1MVmT3IzdEk2/3c7M13r1C27O7+YF3i4OtcfxT8MPgh8IPgB8D3ge8B3w2+C3wn+I0mfvsUfh34tRb86gx+hRX/S/Zv/Dbhv87Bf2nBf5HEVwN4bsF/VmnAmyXR6UmFQrfgP7YG/CMzu5FCf5gK7Ae5WcDv5+bI7h7gWQF5t43dSWX7e+oSB1/n+o0BgK+BHwTfD74PfI/Cd4HvBL8R/IYB6vot+DU5+N9y8D9n45dZ8d8p/LcK/00O/qs8+C8s+M8t+M8s+E+TpeAV/mNrCv5RWRrewH9YaoI/yA3w+7lZwO9Zuutoks3aHYcFs4Vu58tmdusn6xwHXwc/yvUbAwA/CL4ffC/4HhO/gwt8J/iNwBsD6M8AwK818c3rB/+7Bf+riV+ehd8tD34XKW0J/6XCf2HBf67wn7XPwD+tNOGfJFPwj1Mp+EflCl0FuNED4I0U+H1rFvR7qZLQBQI4N1uq26ksoLda2c1kth/vRk6d4+Dr4EfBD3P9xgDA9w9lAOC7W8Cv7aOu34L/LQ/+pzz47wvgv6ZXzeA/z4P/VPWkXboMfIVCt+A/VD0oM+CN7oNvZIG/V2Ji381XEjpfgN+2dAvsJllBW9ENawrv+k90TfVrfDQDAD8Kfhh8jetXA+igBtBeDaDSGAD49eDX5eBXg/89B//LT+K/VPgv8uA/U/hpeAv+Ywv+Iwv+w3ILuup+aToD/55Cv5vKAn7HmsK+rbplzZHpJth5y0Wl663omj2D15quttCvcfD1kQwA/PBwBgB+AHwf+F7w3eC7uH4n+I3gN4BfD35dH2MAFTU5+N/A/6rwP1vwP7YevyQf/nMTv/hZDv4TC/5jhf+oItNDBf+g3IKeSuHfA/5uqQWd7qSyoN9W3Spq2s1UjuxugJ3qeqpCsM10NZUF70obulwgcwDgR8APga/x9AfA9/H0exS+C3yniV+ZD7+6lxpAHvxP/wL8p+0t8JVp+KJHyVLwFRb48hz4MgPdcdcsjX8npzR4blZw1Y0iA9voeiabtWupCuGqrjRXHsRLbehiTr/ER6YH0DEEvgZ+AHwf+B4LfiP4DX0t1w9+TR78rz3Mf+Wugd89g/8h81Ov9F0L+C8U/vOOaXgD/2kO/uNKC7zCT8I/qMjA3y+3oKvuZvAdd0ot4KpbJdngN61Zwem6NQV/LVMa/WqqFoAvW7qUr2YwL7Sh86pf4uDrXH9kmGUAgxgA+J4BDAB8Zz9jAO2MAYBfB34t+DW9jAGUfwf/2++W6+9uefpbif8yH37HbPwn7S3wOfhp+AoLvMpAT2Wip7LfLrWgW/Bv5nSjOA84XUtlgb9qZruSpxaBVRctXbDWDGZz/ZWnKmMA4OvgR8APgR/k+v1cv5cBuLl+NYB2jbn4vbPxv6Wuv7vl6c/+Z/XMp/9n8Ntn8NPw9MCCnwVfboEvy4J3JOFvlWbQb1pLgdP1VLngqqsqcHOzXVZdStVaZEvnrbWAWtWK/sypkzEA8CNDGAD4QfD94HvBd4Pv4vqd4DeAXw9+XW/L9YP/PQf/cw7+hxz8t23Af9rBAq/wHxXAv1+RA2/Bv6O6bcI7blnwrfA3SnLQ6VqqXHBrgF9WXTKzWbuYqjXIlv6yVGVvPeq5FjprqVN8WHoAHYwBgO/n6feC7wbfBX4j+A1/WAYAfg346QGA/7W7un6F/zEXv0vr8J+1At+AV/j3LaXhyzPoBnyZgZ7KfrM0B52ul+RBVzUBp8uqS47sLlrAL1hrBXRVgf5M1QbYZGdyOp2nTnHwda4/An6I61cDqPRYrl8NoKI+P37m+rsZA8jCf9/F8rmf/YWvJI3fqQl+cSvwi9LwFRl4K74Bb8G/aZaGv24pC1x1pbgp+iVrJrjRhUwG+HlrhS66APS5fP0AbqpTOZ20ZA4A/Ahf/DTwg1y/D3yPun4n+I3J6we/rpcxgHJjAOB/72G5/m6W6++qBtCl6Ze+tuI/UvgPKxU83W9n4hvwFvw75TnwZVnwjhvgJ8uCT2VFV13Og35RdaEoC91+3iyN/pelghddAPus6oyl1uCebKYTOR1XdYwPSQ+gfXIAAfB94HvAd4HvBL+ht3n9xgDAr8mDb1x/U/yCn/vN4T9uI/4dVRZ8WRa843oSvjQHna6WZMNfVl0qLoBuwT9v6S8zW1VOzWGfzYN9Ok+tQc6Hm69jOXWMg69z/WHwtQF5B1BhDAD8OoWvrr/sW3fL9Vs+9z90UQNoBf7zVuLfV6XhKzLwufg3y7Lg0/i58FdKsuEvWcqHfj5VNrq9yswEV51L1VZs1UlrbUC24h7N6UiesgcAfgB8H/hu8F1cfyP4DeDX98xcfzXX/727GkDy+n+zXH8e/Dd5vvQ1we/QFP9BK/Bv061yC3xZFryBf63Ucu0p+JKca0/BFxdAp79UVY7sssBVZx0/iK06oTpubz3ykQIdtnQop45x8HXwwwMyA/BmBlCRGkDy+mvBr+lhuX7wv/xmDCD99BsDsPwrePN97reE/7AZ/DsVGfi8+GUZ/GtmTeFLsuEvpuCLm0FPZYIbncuURj+j+mHsnFoL3RxyqoOWDqg6pAfQnwGAH+jLAMB3c/1O8BvN6y+v+90cQPr6u6UHkPzf0W96/Zl/Tj/7S19T/OKW8IEvysW/pcqCL8uCd1wtbQp/qSTn2i2dL86Gr7L0Z1ETdPtZswy6pULgzWKrjqqO2NsOnQ852f4CdYgPZAADjAFUJgfg5/q94LvAd4Lf2DMzgOT1V4OfGoBx/V3VALpYrj/zr+BN47/M81v/ieVzPx/+vVbgp+HLMvAp/CbwqrzwxXmuXcGfS5VBtwNuP52LrmoNeF7snA7b2wZdCHmfpb2W9qgBtI9y/WHwNa7f3yd7AA3g1yevv4cxgLLq1PX/Zrn+LvmffuP6O2U//Xnx27eMf7vCAt8MPvCOK0n80jzwJU3RDfjiZtDpbFEWujUTPKd86C2BH1YdspaD3dJFF0LO125Vh/gAYwCVagDt/OB7wHeB7+T6G35Xz39yAMnr75YeQPL/KldmAJ0LX39z3/gftbd84au04LdrHf61six4A/9yDr4BX1IAvrh5+DNFTeFBt2eBq447mqK3CZwOqg7YC2Pnu+jmkJPtsrTTUodYcgDgh7n+YJ/sAfD8lxsDAL+2u3n9xgCS19/V+L/MVfDpV9ef/fRn8ItbgV+UDz/r6pviO5L4TeBLCsAXq8/23GtX8KeLmqCnykZXNXflrQKn/al+EDsf9I4Cbaf2sf7mAEJqAL7eDAB8F9ffCH59D3MAyeuvBv/7b5br75K+fuN/T/+d+b+2ZV5/HvxnzXzps+LfycG/mcIvz8a/WpYF77hU2hTeip8Fr2py7Sl4OlXUBN7eBF111NE69ILgqn2qtmDvbAF7u6Vtqq2qzADAD/5hDKDCbQ6gPDWA5PXXdDMHkLz+r10tA8jz9L9Ofe7n/LN7hb70tQX/Whvwz6vywhdnw5/OgT9ZlIVuP54pG52OOLLRm7vyguCqPfafu+xcaCv2ljy1j4Ef7WsZAPhurt8JfmOP7AEkr/+bwv+s8Ft7/blP/8NWPPst4St4Az8vfEkB+OIW4IvywtuboKsKoee78rzglnbb8193a7C3toC9WbXJUmYA4Ae5fusAGpLPP/i13SzPf3IAXTLX/yEH/3Whpz/P5376d34ufkUG/3oO/pV8+KUt46fhi5uHP1GUDX9M1QRddcjxc+i7VbtUhcCbe8Zbi71RtcFS+xj4Ua4/OYAAA/AmBwC+s0fOANT1pwfQ2RhA9vV3Utdv+RdzNvnWn/Ol767l6W8rPvCOC6V54EsKwNPp4mbg6XhRBv6o6ohZNrqqNeh7WkKnHal+4Lpbi51qvaXKrAGA7+X6XakBgF8Hfs1vlgF0ST//qf/TbCXvLNf/Kv/T3+LnfnP4V/9m/ILwRRn4I5aaoKvaim4Fz0JXWdHbct2twV5naa1qjU3+HwuefjlXE4+yAAAAAElFTkSuQmCC",Oce=0,YD=(n,e,t,i)=>{if(!n[t]){let r=n.useDelayedTextureLoading;n.useDelayedTextureLoading=!1;let s=n._blockEntityCollection;n._blockEntityCollection=!1;let a=_e.CreateFromBase64String(e,i+Oce++,n,!0,!1,_e.BILINEAR_SAMPLINGMODE);n._blockEntityCollection=s;let o=n.getEngine().getLoadedTexturesCache(),l=o.indexOf(a.getInternalTexture());l!==-1&&o.splice(l,1),a.isRGBD=!0,a.wrapU=_e.CLAMP_ADDRESSMODE,a.wrapV=_e.CLAMP_ADDRESSMODE,n[t]=a,n.useDelayedTextureLoading=r,cm.ExpandRGBDTexture(a);let c=n.getEngine().onContextRestoredObservable.add(()=>{a.isRGBD=!0;let f=n.onBeforeRenderObservable.add(()=>{a.isReady()&&(n.onBeforeRenderObservable.remove(f),cm.ExpandRGBDTexture(a))})});n.onDisposeObservable.add(()=>{n.getEngine().onContextRestoredObservable.remove(c)})}return n[t]},vR=n=>YD(n,Pce,"environmentBRDFTexture","EnvironmentBRDFTexture"),KD=n=>YD(n,Dce,"environmentFuzzBRDFTexture","EnvironmentFuzzBRDFTexture"),f5=n=>YD(n,Lce,"openPBREnvironmentBRDFTexture","OpenPBREnvironmentBRDFTexture")});function h5(n){return class extends n{constructor(){super(...arguments),this.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.INVERTCUBICMAP=!1,this.USESPHERICALFROMREFLECTIONMAP=!1,this.USEIRRADIANCEMAP=!1,this.USE_IRRADIANCE_DOMINANT_DIRECTION=!1,this.USESPHERICALINVERTEX=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1}}}var d5=C(()=>{});var jD=C(()=>{Es();yt();Qn();Rt.prototype.restoreSingleAttachment=function(){let n=this._gl;this.bindAttachments([n.BACK])};Rt.prototype.restoreSingleAttachmentForRenderTarget=function(){let n=this._gl;this.bindAttachments([n.COLOR_ATTACHMENT0])};Rt.prototype.buildTextureLayout=function(n,e=!1){let t=this._gl,i=[];if(e)i.push(t.BACK);else for(let r=0;r1&&(e.depthTextureFormat===13||e.depthTextureFormat===17||e.depthTextureFormat===16||e.depthTextureFormat===14||e.depthTextureFormat===18)&&(o=e.depthTextureFormat)),o===void 0&&(o=s?13:14);let M=this._gl,D=this._currentFramebuffer,O=M.createFramebuffer();this._bindUnboundFramebuffer(O);let V=(Y=n.width)!=null?Y:n,N=(K=n.height)!=null?K:n,F=[],U=[],k=this.webGLVersion>1&&(o===13||o===17||o===18);y.label=(de=e==null?void 0:e.label)!=null?de:"MultiRenderTargetWrapper",y._framebuffer=O,y._generateDepthBuffer=a||r,y._generateStencilBuffer=a?k:s,y._depthStencilBuffer=this._setupFramebufferDepthAttachments(y._generateStencilBuffer,y._generateDepthBuffer,V,N,1,o),y._attachments=U;for(let se=0;se1||this.isWebGPU);let Et=this.webGLVersion>1,Ke=M[Et?"COLOR_ATTACHMENT"+se:"COLOR_ATTACHMENT"+se+"_WEBGL"];if(U.push(Ke),fe===-1||I)continue;let qe=new yi(this,6);F[se]=qe,M.activeTexture(M["TEXTURE"+se]),M.bindTexture(fe,qe._hardwareTexture.underlyingResource),M.texParameteri(fe,M.TEXTURE_MAG_FILTER,Xe.mag),M.texParameteri(fe,M.TEXTURE_MIN_FILTER,Xe.min),M.texParameteri(fe,M.TEXTURE_WRAP_S,M.CLAMP_TO_EDGE),M.texParameteri(fe,M.TEXTURE_WRAP_T,M.CLAMP_TO_EDGE);let Qt=this._getRGBABufferInternalSizedFormat(re,De,he),Dt=this._getInternalFormat(De),Fi=this._getWebGLTextureType(re);if(Et&&(fe===35866||fe===32879))fe===35866?qe.is2DArray=!0:qe.is3D=!0,qe.baseDepth=qe.depth=be,M.texImage3D(fe,0,Qt,V,N,be,0,Dt,Fi,null);else if(fe===34067){for(let ae=0;ae<6;ae++)M.texImage2D(M.TEXTURE_CUBE_MAP_POSITIVE_X+ae,0,Qt,V,N,0,Dt,Fi,null);qe.isCube=!0}else M.texImage2D(M.TEXTURE_2D,0,Qt,V,N,0,Dt,Fi,null);i&&M.generateMipmap(fe),this._bindTextureDirectly(fe,null),qe.baseWidth=V,qe.baseHeight=N,qe.width=V,qe.height=N,qe.isReady=!0,qe.samples=1,qe.generateMipMaps=i,qe.samplingMode=ue,qe.type=re,qe._useSRGBBuffer=he,qe.format=De,qe.label=(Fe=R[se])!=null?Fe:y.label+"-Texture"+se,this._internalTexturesCache.push(qe)}if(a&&this._caps.depthTextureExtension&&!I){let se=new yi(this,14),ue=5,re=M.DEPTH_COMPONENT16,he=M.DEPTH_COMPONENT,De=M.UNSIGNED_SHORT,fe=M.DEPTH_ATTACHMENT;this.webGLVersion<2?re=M.DEPTH_COMPONENT:o===14?(ue=1,De=M.FLOAT,re=M.DEPTH_COMPONENT32F):o===18?(ue=0,De=M.FLOAT_32_UNSIGNED_INT_24_8_REV,re=M.DEPTH32F_STENCIL8,he=M.DEPTH_STENCIL,fe=M.DEPTH_STENCIL_ATTACHMENT):o===16?(ue=0,De=M.UNSIGNED_INT,re=M.DEPTH_COMPONENT24,fe=M.DEPTH_ATTACHMENT):(o===13||o===17)&&(ue=12,De=M.UNSIGNED_INT_24_8,re=M.DEPTH24_STENCIL8,he=M.DEPTH_STENCIL,fe=M.DEPTH_STENCIL_ATTACHMENT),this._bindTextureDirectly(M.TEXTURE_2D,se,!0),M.texParameteri(M.TEXTURE_2D,M.TEXTURE_MAG_FILTER,M.NEAREST),M.texParameteri(M.TEXTURE_2D,M.TEXTURE_MIN_FILTER,M.NEAREST),M.texParameteri(M.TEXTURE_2D,M.TEXTURE_WRAP_S,M.CLAMP_TO_EDGE),M.texParameteri(M.TEXTURE_2D,M.TEXTURE_WRAP_T,M.CLAMP_TO_EDGE),M.texImage2D(M.TEXTURE_2D,0,re,V,N,0,he,De,null),M.framebufferTexture2D(M.FRAMEBUFFER,fe,M.TEXTURE_2D,se._hardwareTexture.underlyingResource,0),this._bindTextureDirectly(M.TEXTURE_2D,null),y._depthStencilTexture=se,y._depthStencilTextureWithStencil=k,se.baseWidth=V,se.baseHeight=N,se.width=V,se.height=N,se.isReady=!0,se.samples=1,se.generateMipMaps=i,se.samplingMode=1,se.format=o,se.type=ue,se.label=y.label+"-DepthStencil",F[l]=se,this._internalTexturesCache.push(se)}if(y.setTextures(F),t&&M.drawBuffers(U),this._bindUnboundFramebuffer(D),y.setLayerAndFaceIndices(S,A),this.resetTextureCache(),!I)this.updateMultipleRenderTargetTextureSampleCount(y,c,t);else if(c>1){let se=M.createFramebuffer();if(!se)throw new Error("Unable to create multi sampled framebuffer");y._samples=c,y._MSAAFramebuffer=se,l>0&&t&&(this._bindUnboundFramebuffer(se),M.drawBuffers(U),this._bindUnboundFramebuffer(D))}return y};Rt.prototype.updateMultipleRenderTargetTextureSampleCount=function(n,e,t=!0){if(this.webGLVersion<2||!n)return 1;if(n.samples===e)return e;let i=this._gl;e=Math.min(e,this.getCaps().maxMSAASamples),n._depthStencilBuffer&&(i.deleteRenderbuffer(n._depthStencilBuffer),n._depthStencilBuffer=null),n._MSAAFramebuffer&&(i.deleteFramebuffer(n._MSAAFramebuffer),n._MSAAFramebuffer=null);let r=n._attachments.length;for(let a=0;a1&&typeof i.renderbufferStorageMultisample=="function"){let a=i.createFramebuffer();if(!a)throw new Error("Unable to create multi sampled framebuffer");n._MSAAFramebuffer=a,this._bindUnboundFramebuffer(a);let o=[];for(let l=0;l1?"COLOR_ATTACHMENT"+l:"COLOR_ATTACHMENT"+l+"_WEBGL"],d=this._createRenderBuffer(c.width,c.height,e,-1,this._getRGBABufferInternalSizedFormat(c.type,c.format,c._useSRGBBuffer),h);if(!d)throw new Error("Unable to create multi sampled framebuffer");f.addMSAARenderBuffer(d),c.samples=e,o.push(h)}t&&i.drawBuffers(o)}else this._bindUnboundFramebuffer(n._framebuffer);let s=n._depthStencilTexture?n._depthStencilTexture.format:void 0;return n._depthStencilBuffer=this._setupFramebufferDepthAttachments(n._generateStencilBuffer,n._generateDepthBuffer,n.width,n.height,e,s),this._bindUnboundFramebuffer(null),n._samples=e,e};Rt.prototype.generateMipMapsMultiFramebuffer=function(n){let e=n,t=this._gl;if(e.isMulti)for(let i=0;i1?"COLOR_ATTACHMENT"+a:"COLOR_ATTACHMENT"+a+"_WEBGL"],t.readBuffer(r[a]),t.drawBuffers(r),t.blitFramebuffer(0,0,o.width,o.height,0,0,o.width,o.height,i,t.NEAREST)}for(let a=0;a1?"COLOR_ATTACHMENT"+a:"COLOR_ATTACHMENT"+a+"_WEBGL"];t.drawBuffers(r),t.bindFramebuffer(this._gl.FRAMEBUFFER,e._MSAAFramebuffer)}});var SR,u5=C(()=>{Fr();gf();jD();SR=class extends Br{get isSupported(){var e,t;return(t=(e=this._engine)==null?void 0:e.getCaps().drawBuffersExtension)!=null?t:!1}get textures(){return this._textures}get count(){return this._count}get depthTexture(){return this._textures[this._textures.length-1]}set wrapU(e){if(this._textures)for(let t=0;t0&&(this._createInternalTextures(),this._createTextures(a))}_initTypes(e,t,i,r,s,a,o,l,c,f){for(let h=0;h{this.onAfterRenderObservable.notifyObservers(t)})}dispose(e=!1){this._releaseTextures(),e?this._texture=null:this.releaseInternalTextures(),super.dispose()}releaseInternalTextures(){var t,i;let e=(t=this._renderTarget)==null?void 0:t.textures;if(e){for(let r=e.length-1;r>=0;r--)this._textures[r]._texture=null;(i=this._renderTarget)==null||i.dispose(),this._renderTarget=null}}}});var m5,Nce,p5=C(()=>{W();m5="mrtFragmentDeclaration",Nce=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define VIEW_DEPTH`:""));r.textureWidth=t,r.textureHeight=i,this.reductionSteps.push(r);let s=1;for(;t>1||i>1;){t=Math.max(Math.round(t/2),1),i=Math.max(Math.round(i/2),1);let a=new Xf("Reduction phase "+s,e.getEngine(),"#define "+(t==1&&i==1?"LAST":t==1||i==1?"ONEBEFORELAST":"MAIN"));a.textureWidth=t,a.textureHeight=i,this.reductionSteps.push(a),s++}}}});var rR,TX=C(()=>{Yl();qT();SX();AD();SD();rR=class{get onAfterReductionPerformed(){return this._thinMinMaxReducer.onAfterReductionPerformed}constructor(e){this._onAfterUnbindObserver=null,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=e,this._postProcessManager=new Xl(e.getScene()),this._thinMinMaxReducer=new iR(e.getScene()),this._reductionSteps=[],this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add(()=>{this._postProcessManager._rebuild()})}get sourceTexture(){return this._sourceTexture}setSourceTexture(e,t,i=2,r=!0){if(e!==this._sourceTexture&&(this._thinMinMaxReducer.depthRedux=t,this.deactivate(),this._sourceTexture=e,this._forceFullscreenViewport=r,this._thinMinMaxReducer.setTextureDimensions(e.getRenderWidth(),e.getRenderHeight()))){this._disposePostProcesses();let s=this._thinMinMaxReducer.reductionSteps;for(let a=0;a{c.setTexture("textureSampler",this._sourceTexture)})),a===s.length-1&&this._reductionSteps[a-1].onAfterRenderObservable.add(()=>{this._thinMinMaxReducer.readMinMax(l.inputTexture.texture)})}}}get refreshRate(){return this._sourceTexture?this._sourceTexture.refreshRate:-1}set refreshRate(e){this._sourceTexture&&(this._sourceTexture.refreshRate=e)}get activated(){return this._activated}activate(){this._onAfterUnbindObserver||!this._sourceTexture||(this._onAfterUnbindObserver=this._sourceTexture.onAfterUnbindObservable.add(()=>{var t,i;let e=this._camera.getScene().getEngine();(t=e._debugPushGroup)==null||t.call(e,"min max reduction"),this._reductionSteps[0].activate(this._camera),this._postProcessManager.directRender(this._reductionSteps,this._reductionSteps[0].inputTexture,this._forceFullscreenViewport,0,0,!0,this._reductionSteps.length-1),e.unBindFramebuffer(this._reductionSteps[this._reductionSteps.length-1].inputTexture,!1),(i=e._debugPopGroup)==null||i.call(e)}),this._activated=!0)}deactivate(){!this._onAfterUnbindObserver||!this._sourceTexture||(this._sourceTexture.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=null,this._activated=!1)}dispose(e=!0){e&&(this.onAfterReductionPerformed.clear(),this._camera.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=void 0,this._disposePostProcesses(),this._postProcessManager.dispose(),this._postProcessManager=void 0,this._thinMinMaxReducer.dispose(),this._thinMinMaxReducer=void 0,this._sourceTexture=null)}_disposePostProcesses(){for(let e=0;e{mX();TX();nR=class extends rR{get depthRenderer(){return this._depthRenderer}constructor(e){super(e)}setDepthRenderer(e=null,t=2,i=!0){let r=this._camera.getScene();this._depthRenderer&&(delete r._depthRenderer[this._depthRendererId],this._depthRenderer.dispose(),this._depthRenderer=null),e===null&&(r._depthRenderer||(r._depthRenderer={}),this._depthRendererId="minmax_"+this._camera.uniqueId,e=this._depthRenderer=new Zm(r,t,this._camera,!1,1,!1,`DepthRenderer ${this._depthRendererId}`),e.enabled=!1,r._depthRenderer[this._depthRendererId]=e),super.setSourceTexture(e.getDepthMap(),!0,t,i)}setSourceTexture(e,t,i=2,r=!0){super.setSourceTexture(e,t,i,r)}activate(){this._depthRenderer&&(this._depthRenderer.enabled=!0),super.activate()}deactivate(){super.deactivate(),this._depthRenderer&&(this._depthRenderer.enabled=!1)}dispose(e=!0){super.dispose(e),this._depthRenderer&&e&&(this._depthRenderer.dispose(),this._depthRenderer=null)}}});var xX,sce,Rr,Qm,sR,So,RX=C(()=>{Ge();_f();hn();tR();mm();AX();Pt();Di();J_();xX=b.Up(),sce=b.Zero(),Rr=new b,Qm=new b,sR=new K,So=class n extends Ci{_validateFilter(e){return e===Ci.FILTER_NONE||e===Ci.FILTER_PCF||e===Ci.FILTER_PCSS?e:(te.Error('Unsupported filter "'+e+'"!'),Ci.FILTER_NONE)}get numCascades(){return this._numCascades}set numCascades(e){e=Math.min(Math.max(e,n.MIN_CASCADES_COUNT),n.MAX_CASCADES_COUNT),e!==this._numCascades&&(this._numCascades=e,this.recreateShadowMap(),this._recreateSceneUBOs())}get freezeShadowCastersBoundingInfo(){return this._freezeShadowCastersBoundingInfo}set freezeShadowCastersBoundingInfo(e){this._freezeShadowCastersBoundingInfoObservable&&e&&(this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable),this._freezeShadowCastersBoundingInfoObservable=null),!this._freezeShadowCastersBoundingInfoObservable&&!e&&(this._freezeShadowCastersBoundingInfoObservable=this._scene.onBeforeRenderObservable.add(()=>this._computeShadowCastersBoundingInfo())),this._freezeShadowCastersBoundingInfo=e,e&&this._computeShadowCastersBoundingInfo()}_computeShadowCastersBoundingInfo(){if(this._scbiMin.copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._scbiMax.copyFromFloats(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),this._shadowMap&&this._shadowMap.renderList){let e=this._shadowMap.renderList;for(let t=0;tt&&(e=0,t=1),e<0&&(e=0),t>1&&(t=1),this._minDistance=e,this._maxDistance=t,this._breaksAreDirty=!0)}get minDistance(){return this._minDistance}get maxDistance(){return this._maxDistance}getClassName(){return n.CLASSNAME}getCascadeMinExtents(e){return e>=0&&e=0&&et.maxZ&&t.maxZ!==0||(this._shadowMaxZ=e,this._light._markMeshesAsLightDirty(),this._breaksAreDirty=!0)}get debug(){return this._debug}set debug(e){this._debug=e,this._light._markMeshesAsLightDirty()}get depthClamp(){return this._depthClamp}set depthClamp(e){this._depthClamp=e}get cascadeBlendPercentage(){return this._cascadeBlendPercentage}set cascadeBlendPercentage(e){this._cascadeBlendPercentage=e,this._light._markMeshesAsLightDirty()}get lambda(){return this._lambda}set lambda(e){let t=Math.min(Math.max(e,0),1);this._lambda!=t&&(this._lambda=t,this._breaksAreDirty=!0)}getCascadeViewMatrix(e){return e>=0&&e=0&&e=0&&e{let r=i.min,s=i.max;r>=s&&(r=0,s=1),(r!=this._minDistance||s!=this._maxDistance)&&this.setMinMaxDistance(r,s)}),this._depthReducer.setDepthRenderer(this._depthRenderer)),this._depthReducer.activate()}}get autoCalcDepthBoundsRefreshRate(){var e,t,i;return(i=(t=(e=this._depthReducer)==null?void 0:e.depthRenderer)==null?void 0:t.getDepthMap().refreshRate)!=null?i:-1}set autoCalcDepthBoundsRefreshRate(e){var t;(t=this._depthReducer)!=null&&t.depthRenderer&&(this._depthReducer.depthRenderer.getDepthMap().refreshRate=e)}splitFrustum(){this._breaksAreDirty=!0}_splitFrustum(){let e=this._getCamera();if(!e)return;let t=e.minZ,i=e.maxZ||this._shadowMaxZ,r=i-t,s=this._minDistance,a=this._shadowMaxZ=t?Math.min((this._shadowMaxZ-t)/(i-t),this._maxDistance):this._maxDistance,o=t+s*r,l=t+a*r,c=l-o,f=l/o;for(let h=0;ha||(!this._depthClamp||this.filter===Ci.FILTER_PCSS?(s=Math.min(s,l),this.filter!==Ci.FILTER_PCSS&&(a=Math.min(a,c))):(a=Math.min(a,c),s=Math.max(s,l),a=Math.max(s+1,a))),K.OrthoOffCenterLHToRef(this._cascadeMinExtents[r].x,this._cascadeMaxExtents[r].x,this._cascadeMinExtents[r].y,this._cascadeMaxExtents[r].y,i?a:s,i?s:a,this._projectionMatrices[r],e.getEngine().isNDCHalfZRange),this._cascadeMinExtents[r].z=s,this._cascadeMaxExtents[r].z=a,this._viewMatrices[r].multiplyToRef(this._projectionMatrices[r],this._transformMatrices[r]),b.TransformCoordinatesToRef(sce,this._transformMatrices[r],Rr),Rr.scaleInPlace(this._mapSize/2),Qm.copyFromFloats(Math.round(Rr.x),Math.round(Rr.y),Math.round(Rr.z)),Qm.subtractInPlace(Rr).scaleInPlace(2/this._mapSize),K.TranslationToRef(Qm.x,Qm.y,0,sR),this._projectionMatrices[r].multiplyToRef(sR,this._projectionMatrices[r]),this._viewMatrices[r].multiplyToRef(this._projectionMatrices[r],this._transformMatrices[r]),this._transformMatrices[r].copyToArray(this._transformMatricesAsArray,r*16)}}_computeFrustumInWorldSpace(e){let t=this._getCamera();if(!t)return;let i=this._cascades[e].prevBreakDistance,r=this._cascades[e].breakDistance,s=this._scene.getEngine().isNDCHalfZRange;t.getViewMatrix();let a=t.maxZ===0,o=t.maxZ;a&&(t.maxZ=this._shadowMaxZ,t.getProjectionMatrix(!0));let l=K.Invert(t.getTransformationMatrix());a&&(t.maxZ=o,t.getProjectionMatrix(!0));let c=this._scene.getEngine().useReverseDepthBuffer?4:0;for(let f=0;f{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[t]),this._currentLayer=t,this._filter===Ci.FILTER_PCF&&e.setColorWrite(!1),ba.eyeAtCamera=!1,this._scene.setTransformMatrix(this.getCascadeViewMatrix(t),this.getCascadeProjectionMatrix(t)),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())}),this._shadowMap.onBeforeBindObservable.add(()=>{var t;this._currentSceneUBO=this._scene.getSceneUniformBuffer(),e._enableGPUDebugMarkers&&((t=e._debugPushGroup)==null||t.call(e,`Cascaded shadow map generation for pass id ${e.currentRenderPassId}`)),this._breaksAreDirty&&this._splitFrustum(),this._computeMatrices()}),this._splitFrustum()}_bindCustomEffectForRenderSubMeshForShadowMap(e,t){t.setMatrix("viewProjection",this.getCascadeTransformMatrix(this._currentLayer))}_isReadyCustomDefines(e){e.push("#define SM_DEPTHCLAMP "+(this._depthClamp&&this._filter!==Ci.FILTER_PCSS?"1":"0"))}prepareDefines(e,t){super.prepareDefines(e,t);let i=this._scene,r=this._light;if(!i.shadowsEnabled||!r.shadowEnabled)return;e["SHADOWCSM"+t]=!0,e["SHADOWCSMDEBUG"+t]=this.debug,e["SHADOWCSMNUM_CASCADES"+t]=this.numCascades,e["SHADOWCSM_RIGHTHANDED"+t]=i.useRightHandedSystem;let s=this._getCamera();s&&this._shadowMaxZ<=(s.maxZ||this._shadowMaxZ)&&(e["SHADOWCSMUSESHADOWMAXZ"+t]=!0),this.cascadeBlendPercentage===0&&(e["SHADOWCSMNOBLEND"+t]=!0)}bindShadowLight(e,t){let i=this._light,r=this._scene;if(!r.shadowsEnabled||!i.shadowEnabled)return;let s=this._getCamera();if(!s)return;let a=this.getShadowMap();if(!a)return;let o=a.getSize().width,l=this._transformMatricesAsArray,c=r.floatingOriginMode?OB(this._scene.floatingOriginOffset,this._viewMatrices,this._projectionMatrices,this._numCascades,this._tempTransformMatricesAsArray):l;if(t.setMatrices("lightMatrix"+e,c),t.setArray("viewFrustumZ"+e,this._viewSpaceFrustumsZ),t.setFloat("cascadeBlendFactor"+e,this.cascadeBlendPercentage===0?1e4:1/this.cascadeBlendPercentage),t.setArray("frustumLengths"+e,this._frustumLengths),this._filter===Ci.FILTER_PCF)t.setDepthStencilTexture("shadowTexture"+e,a),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),o,1/o,this.frustumEdgeFalloff,e);else if(this._filter===Ci.FILTER_PCSS){for(let f=0;fnew n(r,s,void 0,a));return e.numCascades!==void 0&&(i.numCascades=e.numCascades),e.debug!==void 0&&(i.debug=e.debug),e.stabilizeCascades!==void 0&&(i.stabilizeCascades=e.stabilizeCascades),e.lambda!==void 0&&(i.lambda=e.lambda),e.cascadeBlendPercentage!==void 0&&(i.cascadeBlendPercentage=e.cascadeBlendPercentage),e.depthClamp!==void 0&&(i.depthClamp=e.depthClamp),e.autoCalcDepthBounds!==void 0&&(i.autoCalcDepthBounds=e.autoCalcDepthBounds),e.shadowMaxZ!==void 0&&(i.shadowMaxZ=e.shadowMaxZ),e.penumbraDarkness!==void 0&&(i.penumbraDarkness=e.penumbraDarkness),e.freezeShadowCastersBoundingInfo!==void 0&&(i.freezeShadowCastersBoundingInfo=e.freezeShadowCastersBoundingInfo),e.minDistance!==void 0&&e.maxDistance!==void 0&&i.setMinMaxDistance(e.minDistance,e.maxDistance),i}};So._FrustumCornersNdcSpace=[new b(-1,1,-1),new b(1,1,-1),new b(1,-1,-1),new b(-1,-1,-1),new b(-1,1,1),new b(1,1,1),new b(1,-1,1),new b(-1,-1,1)];So.CLASSNAME="CascadedShadowGenerator";So.DEFAULT_CASCADES_COUNT=4;So.MIN_CASCADES_COUNT=2;So.MAX_CASCADES_COUNT=4;So._SceneComponentInitialization=n=>{throw qe("ShadowGeneratorSceneComponent")}});function aR(n,e){ace[n]=e}var ace,xD=C(()=>{ace={}});var RD,bX=C(()=>{tR();RX();am();xD();aR(et.NAME_SHADOWGENERATOR,(n,e)=>{if(n.shadowGenerators!==void 0&&n.shadowGenerators!==null)for(let t=0,i=n.shadowGenerators.length;t{let e=n._getComponent(et.NAME_SHADOWGENERATOR);e||(e=new RD(n),n._addComponent(e))}});async function IX(n,e){let t=e.method||"GET";return await new Promise((i,r)=>{let s=new Ir;s.addEventListener("readystatechange",()=>{if(s.readyState==4)if(s.status==200){let a={};if(e.responseHeaders)for(let o of e.responseHeaders)a[o]=s.getResponseHeader(o)||"";i({response:s.response,headerValues:a})}else r(`Unable to fetch data from ${n}. Error code: ${s.status}`)}),s.open(t,n),s.send()})}var MX=C(()=>{Bh()});function oce(n){return!!n.createPlugin}function lce(n){return!!n.name}function oR(){return dl[".babylon"]}function cce(n){for(let e in dl){let t=dl[e];if(t.mimeType===n)return t}}function ID(n,e){let t=dl[n];return t||(te.Warn("Unable to find a plugin to load "+n+" files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: https://doc.babylonjs.com/features/featuresDeepDive/importers/loadingFileTypes"),e?oR():void 0)}function fce(n){return!!dl[n]}function hce(n){for(let e in dl){let t=dl[e].plugin;if(t.canDirectLoad&&t.canDirectLoad(n))return dl[e]}return oR()}function dce(n){let e=n.indexOf("?");e!==-1&&(n=n.substring(0,e));let t=n.lastIndexOf(".");return n.substring(t,n.length).toLowerCase()}function uce(n){return n.substring(0,5)==="data:"?n.substring(5):null}function MD(n,e,t){let r="Unable to load from "+(n.rawData?"binary data":n.url);return e?r+=`: ${e}`:t&&(r+=`: ${t}`),r}async function CD(n,e,t,i,r,s,a,o,l){var u;let c=uce(n.url);if(n.rawData&&!a)throw"When using ArrayBufferView to load data the file extension must be provided.";let f=!c&&!a?dce(n.url):"",h=a?ID(a,!0):c?hce(n.url):ID(f,!1);if(!h&&f){if(n.url&&!n.url.startsWith("blob:")){let m=await IX(n.url,{method:"HEAD",responseHeaders:["Content-Type"]}),p=m.headerValues?m.headerValues["Content-Type"]:"";p&&(h=cce(p))}h||(h=oR())}if(!h)throw new Error(`No plugin or fallback for ${a!=null?a:n.url}`);if(((u=l==null?void 0:l[h.plugin.name])==null?void 0:u.enabled)===!1)throw new Error(`The '${h.plugin.name}' plugin is disabled via the loader options passed to the loading operation.`);if(n.rawData&&!h.isBinary)throw"Loading from ArrayBufferView can not be used with plugins that don't support binary loading.";return(m=>{if(oce(h.plugin)){let _=h.plugin.createPlugin(l!=null?l:{});return _ instanceof Promise?(_.then(m).catch(g=>{r("Error instantiating plugin.",g)}),null):(m(_),_)}else return m(h.plugin),h.plugin})(m=>{var E;if(!m)throw`The loader plugin corresponding to the '${a}' file type has not been found. If using es6, please import the plugin you wish to use before.`;if(yX.notifyObservers(m),c&&(m.canDirectLoad&&m.canDirectLoad(n.url)||!ff(n.url))){if(m.directLoad){let R=m.directLoad(e,c);R instanceof Promise?R.then(I=>{t(m,I)}).catch(I=>{r("Error in directLoad of _loadData: "+I,I)}):t(m,R)}else t(m,c);return}let p=h.isBinary,_=(R,I)=>{if(e.isDisposed){r("Scene has been disposed");return}t(m,R,I)},g=null,v=!1;(E=m.onDisposeObservable)==null||E.add(()=>{v=!0,g&&(g.abort(),g=null),s()});let x=()=>{if(v)return;let R=(I,y)=>{r(I==null?void 0:I.statusText,y)};if(!m.loadFile&&n.rawData)throw"Plugin does not support loading ArrayBufferView.";g=m.loadFile?m.loadFile(e,n.rawData||n.file||n.url,n.rootUrl,_,i,p,R,o):e._loadFile(n.file||n.url,_,i,!0,p,R)},A=e.getEngine(),S=A.enableOfflineSupport;if(S){let R=!1;for(let I of e.disableOfflineSupportExceptionRules)if(I.test(n.url)){R=!0;break}S=!R}S&&Me.OfflineProviderFactory?e.offlineProvider=Me.OfflineProviderFactory(n.url,x,A.disableManifestCheck):x()})}function yD(n,e){let t,i,r=null,s=null;if(!e)t=n,i=_e.GetFilename(n),n=_e.GetFolderPath(n);else if(lce(e))t=`file:${e.name}`,i=e.name,r=e;else if(ArrayBuffer.isView(e))t="",i=lf(),s=e;else if(e.startsWith("data:"))t=e,i="";else if(n){let a=e;if(a.substring(0,1)==="/")return _e.Error("Wrong sceneFilename parameter"),null;t=n+a,i=a}else t=e,i=_e.GetFilename(e),n=_e.GetFolderPath(e);return{url:t,rootUrl:n,name:i,file:r,rawData:s}}function Yf(n){if(typeof n.extensions=="string"){let e=n.extensions;dl[e.toLowerCase()]={plugin:n,isBinary:!1}}else{let e=n.extensions,t=Object.keys(e);for(let i of t)dl[i.toLowerCase()]={plugin:n,isBinary:e[i].isBinary,mimeType:e[i].mimeType}}}async function Bg(n,e,t){let{meshNames:i,rootUrl:r="",onProgress:s,pluginExtension:a,name:o,pluginOptions:l}=t!=null?t:{};return await DX(i,r,n,e,s,a,o,l)}async function PX(n,e,t="",i=Oe.LastCreatedScene,r=null,s=null,a=null,o=null,l="",c={}){if(!i)return te.Error("No scene available to import mesh to"),null;let f=yD(e,t);if(!f)return null;let h={};i.addPendingData(h);let d=()=>{i.removePendingData(h)},u=(_,g)=>{let v=MD(f,_,g);a?a(i,v,new Ts(v,Ea.SceneLoaderError,g)):te.Error(v),d()},m=s?_=>{try{s(_)}catch(g){u("Error in onProgress callback: "+g,g)}}:void 0,p=(_,g,v,x,A,S,E,R)=>{if(i.importedMeshesFiles.push(f.url),r)try{r(_,g,v,x,A,S,E,R)}catch(I){u("Error in onSuccess callback: "+I,I)}i.removePendingData(h)};return await CD(f,i,(_,g,v)=>{if(_.rewriteRootURL&&(f.rootUrl=_.rewriteRootURL(f.rootUrl,v)),_.importMesh){let x=_,A=[],S=[],E=[];if(!x.importMesh(n,i,g,f.rootUrl,A,S,E,u))return;i.loadingPluginName=_.name,p(A,S,E,[],[],[],[],[])}else _.importMeshAsync(n,i,g,f.rootUrl,m,f.name).then(A=>{i.loadingPluginName=_.name,p(A.meshes,A.particleSystems,A.skeletons,A.animationGroups,A.transformNodes,A.geometries,A.lights,A.spriteManagers)}).catch(A=>{u(A.message,A)})},m,u,d,o,l,c)}async function DX(n,e,t,i,r,s,a,o){return await new Promise((l,c)=>{try{PX(n,e,t,i,(f,h,d,u,m,p,_,g)=>{l({meshes:f,particleSystems:h,skeletons:d,animationGroups:u,transformNodes:m,geometries:p,lights:_,spriteManagers:g})},r,(f,h,d)=>{c(d||new Error(h))},s,a,o).catch(c)}catch(f){c(f)}})}async function LX(n,e="",t=Oe.LastCreatedEngine,i=null,r=null,s=null,a=null,o="",l={}){if(!t){_e.Error("No engine available");return}await PD(n,e,new Jt(t),i,r,s,a,o,l)}async function mce(n,e,t,i,r,s,a){return await new Promise((o,l)=>{LX(n,e,t,c=>{o(c)},i,(c,f,h)=>{l(h||new Error(f))},r,s,a)})}async function PD(n,e="",t=Oe.LastCreatedScene,i=null,r=null,s=null,a=null,o="",l={}){if(!t)return te.Error("No scene available to append to"),null;let c=yD(n,e);if(!c)return null;let f={};t.addPendingData(f);let h=()=>{t.removePendingData(f)};Xr.ShowLoadingScreen&&!bD&&(bD=!0,t.getEngine().displayLoadingUI(),t.executeWhenReady(()=>{t.getEngine().hideLoadingUI(),bD=!1}));let d=(p,_)=>{let g=MD(c,p,_);s?s(t,g,new Ts(g,Ea.SceneLoaderError,_)):te.Error(g),h()},u=r?p=>{try{r(p)}catch(_){d("Error in onProgress callback",_)}}:void 0,m=()=>{if(i)try{i(t)}catch(p){d("Error in onSuccess callback",p)}t.removePendingData(f)};return await CD(c,t,(p,_)=>{if(p.load){if(!p.load(t,_,c.rootUrl,d))return;t.loadingPluginName=p.name,m()}else p.loadAsync(t,_,c.rootUrl,u,c.name).then(()=>{t.loadingPluginName=p.name,m()}).catch(v=>{d(v.message,v)})},u,d,h,a,o,l)}async function pce(n,e,t,i,r,s,a){return await new Promise((o,l)=>{try{PD(n,e,t,c=>{o(c)},i,(c,f,h)=>{l(h||new Error(f))},r,s,a).catch(l)}catch(c){l(c)}})}async function DD(n,e="",t=Oe.LastCreatedScene,i=null,r=null,s=null,a=null,o="",l={}){if(!t)return te.Error("No scene available to load asset container to"),null;let c=yD(n,e);if(!c)return null;let f={};t.addPendingData(f);let h=()=>{t.removePendingData(f)},d=(p,_)=>{let g=MD(c,p,_);s?s(t,g,new Ts(g,Ea.SceneLoaderError,_)):te.Error(g),h()},u=r?p=>{try{r(p)}catch(_){d("Error in onProgress callback",_)}}:void 0,m=p=>{if(i)try{i(p)}catch(_){d("Error in onSuccess callback",_)}t.removePendingData(f)};return await CD(c,t,(p,_)=>{if(p.loadAssetContainer){let v=p.loadAssetContainer(t,_,c.rootUrl,d);if(!v)return;v.populateRootNodes(),t.loadingPluginName=p.name,m(v)}else p.loadAssetContainerAsync?p.loadAssetContainerAsync(t,_,c.rootUrl,u,c.name).then(v=>{v.populateRootNodes(),t.loadingPluginName=p.name,m(v)}).catch(v=>{d(v.message,v)}):d("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")},u,d,h,a,o,l)}async function _ce(n,e,t,i,r,s,a){return await new Promise((o,l)=>{try{DD(n,e,t,c=>{o(c)},i,(c,f,h)=>{l(h||new Error(f))},r,s,a).catch(l)}catch(c){l(c)}})}async function OX(n,e="",t=Oe.LastCreatedScene,i=!0,r=0,s=null,a=null,o=null,l=null,c=null,f="",h={}){if(!t){te.Error("No scene available to load animations to");return}if(i){for(let _ of t.animatables)_.reset();t.stopAllAnimations();let m=t.animationGroups.slice();for(let _ of m)_.dispose();let p=t.getNodes();for(let _ of p)_.animations&&(_.animations=[])}else switch(r){case 0:let m=t.animationGroups.slice();for(let p of m)p.dispose();break;case 1:for(let p of t.animationGroups)p.stop();break;case 2:for(let p of t.animationGroups)p.reset(),p.restart();break;case 3:break;default:te.Error("Unknown animation group loading mode value '"+r+"'");return}let d=t.animatables.length;await DD(n,e,t,m=>{m.mergeAnimationsTo(t,t.animatables.slice(d),s),m.dispose(),t.onAnimationFileImportedObservable.notifyObservers(t),a&&a(t)},o,l,c,f,h)}async function gce(n,e,t,i,r,s,a,o,l,c){return await new Promise((f,h)=>{try{OX(n,e,t,i,r,s,d=>{f(d)},a,(d,u,m)=>{h(m||new Error(u))},o,l,c).catch(h)}catch(d){h(d)}})}var CX,yX,dl,bD,ad,$m=C(()=>{Ii();di();As();Di();Pt();CA();Wl();U_();B_();wr();MX();(function(n){n[n.Clean=0]="Clean",n[n.Stop=1]="Stop",n[n.Sync=2]="Sync",n[n.NoSync=3]="NoSync"})(CX||(CX={}));yX=new ie,dl={},bD=!1;ad=class{static get ForceFullSceneLoadingForIncremental(){return Xr.ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){Xr.ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return Xr.ShowLoadingScreen}static set ShowLoadingScreen(e){Xr.ShowLoadingScreen=e}static get loggingLevel(){return Xr.loggingLevel}static set loggingLevel(e){Xr.loggingLevel=e}static get CleanBoneMatrixWeights(){return Xr.CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){Xr.CleanBoneMatrixWeights=e}static GetDefaultPlugin(){return oR()}static GetPluginForExtension(e){var t;return(t=ID(e,!0))==null?void 0:t.plugin}static IsPluginForExtensionAvailable(e){return fce(e)}static RegisterPlugin(e){Yf(e)}static ImportMesh(e,t,i,r,s,a,o,l,c,f){PX(e,t,i,r,s,a,o,l,c,f).catch(h=>o==null?void 0:o(Oe.LastCreatedScene,h==null?void 0:h.message,h))}static async ImportMeshAsync(e,t,i,r,s,a,o){return await DX(e,t,i,r,s,a,o)}static Load(e,t,i,r,s,a,o,l){LX(e,t,i,r,s,a,o,l).catch(c=>a==null?void 0:a(Oe.LastCreatedScene,c==null?void 0:c.message,c))}static async LoadAsync(e,t,i,r,s,a){return await mce(e,t,i,r,s,a)}static Append(e,t,i,r,s,a,o,l){PD(e,t,i,r,s,a,o,l).catch(c=>a==null?void 0:a(i!=null?i:Oe.LastCreatedScene,c==null?void 0:c.message,c))}static async AppendAsync(e,t,i,r,s,a){return await pce(e,t,i,r,s,a)}static LoadAssetContainer(e,t,i,r,s,a,o,l){DD(e,t,i,r,s,a,o,l).catch(c=>a==null?void 0:a(i!=null?i:Oe.LastCreatedScene,c==null?void 0:c.message,c))}static async LoadAssetContainerAsync(e,t,i,r,s,a){return await _ce(e,t,i,r,s,a)}static ImportAnimations(e,t,i,r,s,a,o,l,c,f,h){OX(e,t,i,r,s,a,o,l,c,f,h).catch(d=>c==null?void 0:c(i!=null?i:Oe.LastCreatedScene,d==null?void 0:d.message,d))}static async ImportAnimationsAsync(e,t,i,r,s,a,o,l,c,f,h){return await gce(e,t,i,r,s,a,l,f,h)}};ad.NO_LOGGING=0;ad.MINIMAL_LOGGING=1;ad.SUMMARY_LOGGING=2;ad.DETAILED_LOGGING=3;ad.OnPluginActivatedObservable=yX});var lR,LD,OD,ul,Ug=C(()=>{Mi();qh();_m();Pt();Di();Qy();yf();sl();Ii();df();lR=class{constructor(){this.rootNodes=[],this.cameras=[],this.lights=[],this.meshes=[],this.skeletons=[],this.particleSystems=[],this.animations=[],this.animationGroups=[],this.multiMaterials=[],this.materials=[],this.morphTargetManagers=[],this.geometries=[],this.transformNodes=[],this.actionManagers=[],this.textures=[],this._environmentTexture=null,this.postProcesses=[],this.sounds=null,this.effectLayers=[],this.layers=[],this.reflectionProbes=[],this.spriteManagers=[]}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e}getNodes(){let e=[];e=e.concat(this.meshes),e=e.concat(this.lights),e=e.concat(this.cameras),e=e.concat(this.transformNodes);for(let t of this.skeletons)e=e.concat(t.bones);return e}},LD=class extends lR{},OD=class{constructor(){this.rootNodes=[],this.skeletons=[],this.animationGroups=[]}dispose(){let e=this.rootNodes;for(let r of e)r.dispose();e.length=0;let t=this.skeletons;for(let r of t)r.dispose();t.length=0;let i=this.animationGroups;for(let r of i)r.dispose();i.length=0}},ul=class extends lR{constructor(e){super(),this._wasAddedToScene=!1,e=e||Oe.LastCreatedScene,e&&(this.scene=e,this.proceduralTextures=[],e.onDisposeObservable.add(()=>{this._wasAddedToScene||this.dispose()}),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add(()=>{for(let t of this.geometries)t._rebuild();for(let t of this.meshes)t._rebuild();for(let t of this.particleSystems)t.rebuild();for(let t of this.textures)t._rebuild();for(let t of this.spriteManagers)t.rebuild()}))}_topologicalSort(e){let t=new Map;for(let o of e)t.set(o.uniqueId,o);let i={dependsOn:new Map,dependedBy:new Map};for(let o of e){let l=o.uniqueId;i.dependsOn.set(l,new Set),i.dependedBy.set(l,new Set)}for(let o of e){let l=o.uniqueId,c=i.dependsOn.get(l);if(o instanceof tc){let h=o.sourceMesh;t.has(h.uniqueId)&&(c.add(h.uniqueId),i.dependedBy.get(h.uniqueId).add(l))}let f=i.dependedBy.get(l);for(let h of o.getDescendants()){let d=h.uniqueId;t.has(d)&&(f.add(d),i.dependsOn.get(d).add(l))}}let r=[],s=[];for(let o of e){let l=o.uniqueId;i.dependsOn.get(l).size===0&&(s.push(o),t.delete(l))}let a=s;for(;a.length>0;){let o=a.shift();r.push(o);let l=i.dependedBy.get(o.uniqueId);for(let c of Array.from(l.values())){let f=i.dependsOn.get(c);f.delete(o.uniqueId),f.size===0&&t.get(c)&&(a.push(t.get(c)),t.delete(c))}}return t.size>0&&(te.Error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach(o=>{te.Error(o.name)})),r}_addNodeAndDescendantsToList(e,t,i,r){if(!(!i||r&&!r(i)||t.has(i.uniqueId))){e.push(i),t.add(i.uniqueId);for(let s of i.getDescendants(!0))this._addNodeAndDescendantsToList(e,t,s,r)}}_isNodeInContainer(e){return e instanceof vr&&this.meshes.indexOf(e)!==-1||e instanceof ei&&this.transformNodes.indexOf(e)!==-1||e instanceof Xt&&this.lights.indexOf(e)!==-1||e instanceof mt&&this.cameras.indexOf(e)!==-1}_isValidHierarchy(){for(let e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return te.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(let e of this.transformNodes)if(e.parent&&!this._isNodeInContainer(e.parent))return te.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(let e of this.lights)if(e.parent&&!this._isNodeInContainer(e.parent))return te.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(let e of this.cameras)if(e.parent&&!this._isNodeInContainer(e.parent))return te.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||_e.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");let r={},s={},a=new OD,o=[],l=[],c={doNotInstantiate:!0,...i},f=(p,_)=>{if(r[p.uniqueId]=_.uniqueId,s[_.uniqueId]=_,e&&(_.name=e(p.name)),_ instanceof q){let g=_;if(g.morphTargetManager){let v=p.morphTargetManager;g.morphTargetManager=v.clone();for(let x=0;x{if(f(p,_),p.parent){let g=r[p.parent.uniqueId],v=s[g];v?_.parent=v:_.parent=p.parent}if(_.position&&p.position&&_.position.copyFrom(p.position),_.rotationQuaternion&&p.rotationQuaternion&&_.rotationQuaternion.copyFrom(p.rotationQuaternion),_.rotation&&p.rotation&&_.rotation.copyFrom(p.rotation),_.scaling&&p.scaling&&_.scaling.copyFrom(p.scaling),_.material){let g=_;if(g.material)if(t){let v=p.material;if(l.indexOf(v)===-1){let x=v.clone(e?e(v.name):"Clone of "+v.name);if(l.push(v),r[v.uniqueId]=x.uniqueId,s[x.uniqueId]=x,v.getClassName()==="MultiMaterial"){let A=v;for(let S of A.subMaterials)S&&(x=S.clone(e?e(S.name):"Clone of "+S.name),l.push(S),r[S.uniqueId]=x.uniqueId,s[x.uniqueId]=x);A.subMaterials=A.subMaterials.map(S=>S&&s[r[S.uniqueId]])}}g.getClassName()!=="InstancedMesh"&&(g.material=s[r[v.uniqueId]])}else g.material.getClassName()==="MultiMaterial"?this.scene.multiMaterials.indexOf(g.material)===-1&&this.scene.addMultiMaterial(g.material):this.scene.materials.indexOf(g.material)===-1&&this.scene.addMaterial(g.material)}_.parent===null&&a.rootNodes.push(_)};for(let p of u)if(p.getClassName()==="InstancedMesh"){let _=p,g=_.sourceMesh,v=r[g.uniqueId],A=(typeof v=="number"?s[v]:g).createInstance(_.name);m(_,A)}else{let _=!0;p.getClassName()==="TransformNode"||p.getClassName()==="Node"||p.skeleton||!p.getTotalVertices||p.getTotalVertices()===0?_=!1:c.doNotInstantiate&&(typeof c.doNotInstantiate=="function"?_=!c.doNotInstantiate(p):_=!c.doNotInstantiate);let g=_?p.createInstance(`instance of ${p.name}`):p.clone(`Clone of ${p.name}`,null,!0);if(!g)throw new Error(`Could not clone or instantiate node on Asset Container ${p.name}`);m(p,g)}for(let p of this.skeletons){if(c.predicate&&!c.predicate(p))continue;let _=p.clone(e?e(p.name):"Clone of "+p.name);for(let g of this.meshes)if(g.skeleton===p&&!g.isAnInstance){let v=s[r[g.uniqueId]];if(!v||v.isAnInstance||(v.skeleton=_,o.indexOf(_)!==-1))continue;o.push(_);for(let x of _.bones)x._linkedTransformNode&&(x._linkedTransformNode=s[r[x._linkedTransformNode.uniqueId]])}a.skeletons.push(_)}for(let p of this.animationGroups){if(c.predicate&&!c.predicate(p))continue;let _=p.clone(e?e(p.name):"Clone of "+p.name,g=>s[r[g.uniqueId]]||g);a.animationGroups.push(_)}return a}addAllToScene(){if(!this._wasAddedToScene){this._isValidHierarchy()||_e.Warn("SceneSerializer.addAllToScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!0,this.addToScene(null),this.environmentTexture&&(this.scene.environmentTexture=this.environmentTexture);for(let e of this.scene._serializableComponents)e.addFromContainer(this);this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null}}addToScene(e=null){let t=[];for(let i of this.cameras)e&&!e(i)||(this.scene.addCamera(i),t.push(i));for(let i of this.lights)e&&!e(i)||(this.scene.addLight(i),t.push(i));for(let i of this.meshes)e&&!e(i)||(this.scene.addMesh(i),t.push(i));for(let i of this.skeletons)e&&!e(i)||this.scene.addSkeleton(i);for(let i of this.animations)e&&!e(i)||this.scene.addAnimation(i);for(let i of this.animationGroups)e&&!e(i)||this.scene.addAnimationGroup(i);for(let i of this.multiMaterials)e&&!e(i)||this.scene.addMultiMaterial(i);for(let i of this.materials)e&&!e(i)||this.scene.addMaterial(i);for(let i of this.morphTargetManagers)e&&!e(i)||this.scene.addMorphTargetManager(i);for(let i of this.geometries)e&&!e(i)||this.scene.addGeometry(i);for(let i of this.transformNodes)e&&!e(i)||(this.scene.addTransformNode(i),t.push(i));for(let i of this.actionManagers)e&&!e(i)||this.scene.addActionManager(i);for(let i of this.textures)e&&!e(i)||this.scene.addTexture(i);for(let i of this.reflectionProbes)e&&!e(i)||this.scene.addReflectionProbe(i);for(let i of this.spriteManagers)e&&!e(i)||(this.scene.spriteManagers||(this.scene.spriteManagers=[]),this.scene.spriteManagers.push(i));if(t.length){let i=new Set(this.scene.meshes);for(let r of this.scene.lights)i.add(r);for(let r of this.scene.cameras)i.add(r);for(let r of this.scene.transformNodes)i.add(r);for(let r of this.skeletons)for(let s of r.bones)i.add(s);for(let r of t)r.parent&&!i.has(r.parent)&&(r.setParent?r.setParent(null):r.parent=null)}}removeAllFromScene(){this._isValidHierarchy()||_e.Warn("SceneSerializer.removeAllFromScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!1,this.removeFromScene(null),this.environmentTexture===this.scene.environmentTexture&&(this.scene.environmentTexture=null);for(let e of this.scene._serializableComponents)e.removeFromContainer(this)}removeFromScene(e=null){for(let t of this.cameras)e&&!e(t)||this.scene.removeCamera(t);for(let t of this.lights)e&&!e(t)||this.scene.removeLight(t);for(let t of this.meshes)e&&!e(t)||this.scene.removeMesh(t,!0);for(let t of this.skeletons)e&&!e(t)||this.scene.removeSkeleton(t);for(let t of this.animations)e&&!e(t)||this.scene.removeAnimation(t);for(let t of this.animationGroups)e&&!e(t)||this.scene.removeAnimationGroup(t);for(let t of this.multiMaterials)e&&!e(t)||this.scene.removeMultiMaterial(t);for(let t of this.materials)e&&!e(t)||this.scene.removeMaterial(t);for(let t of this.morphTargetManagers)e&&!e(t)||this.scene.removeMorphTargetManager(t);for(let t of this.geometries)e&&!e(t)||this.scene.removeGeometry(t);for(let t of this.transformNodes)e&&!e(t)||this.scene.removeTransformNode(t);for(let t of this.actionManagers)e&&!e(t)||this.scene.removeActionManager(t);for(let t of this.textures)e&&!e(t)||this.scene.removeTexture(t);for(let t of this.reflectionProbes)e&&!e(t)||this.scene.removeReflectionProbe(t);for(let t of this.spriteManagers)if(!(e&&!e(t))&&this.scene.spriteManagers){let i=this.scene.spriteManagers.indexOf(t);i!==-1&&this.scene.spriteManagers.splice(i,1)}}dispose(){let e=this.cameras.slice(0);for(let p of e)p.dispose();this.cameras.length=0;let t=this.lights.slice(0);for(let p of t)p.dispose();this.lights.length=0;let i=this.meshes.slice(0);for(let p of i)p.dispose();this.meshes.length=0;let r=this.skeletons.slice(0);for(let p of r)p.dispose();this.skeletons.length=0;let s=this.animationGroups.slice(0);for(let p of s)p.dispose();this.animationGroups.length=0;let a=this.multiMaterials.slice(0);for(let p of a)p.dispose();this.multiMaterials.length=0;let o=this.materials.slice(0);for(let p of o)p.dispose();this.materials.length=0;let l=this.geometries.slice(0);for(let p of l)p.dispose();this.geometries.length=0;let c=this.transformNodes.slice(0);for(let p of c)p.dispose();this.transformNodes.length=0;let f=this.actionManagers.slice(0);for(let p of f)p.dispose();this.actionManagers.length=0;let h=this.textures.slice(0);for(let p of h)p.dispose();this.textures.length=0;let d=this.reflectionProbes.slice(0);for(let p of d)p.dispose();this.reflectionProbes.length=0;let u=this.morphTargetManagers.slice(0);for(let p of u)p.dispose();this.morphTargetManagers.length=0;let m=this.spriteManagers.slice(0);for(let p of m)p.dispose();this.spriteManagers.length=0,this.environmentTexture&&(this.environmentTexture.dispose(),this.environmentTexture=null);for(let p of this.scene._serializableComponents)p.removeFromContainer(this,!0);this._onContextRestoredObserver&&(this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}_moveAssets(e,t,i){if(!(!e||!t))for(let r of e){let s=!0;if(i){for(let a of i)if(r===a){s=!1;break}}s&&(t.push(r),r._parentContainer=this)}}moveAllFromScene(e){this._wasAddedToScene=!1,e===void 0&&(e=new LD);for(let t in this)Object.prototype.hasOwnProperty.call(this,t)&&(this[t]=this[t]||(t==="_environmentTexture"?null:[]),this._moveAssets(this.scene[t],this[t],e[t]));this.environmentTexture=this.scene.environmentTexture,this.removeAllFromScene()}createRootMesh(){let e=new q("assetContainerRootMesh",this.scene);for(let t of this.meshes)t.parent||e.addChild(t);return this.meshes.unshift(e),e}mergeAnimationsTo(e=Oe.LastCreatedScene,t,i=null){if(!e)return te.Error("No scene available to merge animations to"),[];let r=i||(l=>{let c,f=l.animations.length?l.animations[0].targetProperty:"",h=l.name.split(".").join("").split("_primitive")[0];switch(f){case"position":case"rotationQuaternion":c=e.getTransformNodeByName(l.name)||e.getTransformNodeByName(h);break;case"influence":c=e.getMorphTargetByName(l.name)||e.getMorphTargetByName(h);break;default:c=e.getNodeByName(l.name)||e.getNodeByName(h)}return c}),s=this.getNodes();for(let l of s){let c=r(l);if(c!==null){for(let f of l.animations){let h=c.animations.filter(d=>d.targetProperty===f.targetProperty);for(let d of h){let u=c.animations.indexOf(d,0);u>-1&&c.animations.splice(u,1)}}c.animations=c.animations.concat(l.animations)}}let a=[],o=this.animationGroups.slice();for(let l of o){a.push(l.clone(l.name,r));for(let c of l.animatables)c.stop()}for(let l of t){let c=r(l.target);c&&(e.beginAnimation(c,l.fromFrame,l.toFrame,l.loopAnimation,l.speedRatio,l.onAnimationEnd?l.onAnimationEnd:void 0,void 0,!0,void 0,l.onAnimationLoop?l.onAnimationLoop:void 0),e.stopAnimation(l.target))}return a}populateRootNodes(){this.rootNodes.length=0;for(let e of this.meshes)!e.parent&&this.rootNodes.indexOf(e)===-1&&this.rootNodes.push(e);for(let e of this.transformNodes)!e.parent&&this.rootNodes.indexOf(e)===-1&&this.rootNodes.push(e);for(let e of this.lights)!e.parent&&this.rootNodes.indexOf(e)===-1&&this.rootNodes.push(e);for(let e of this.cameras)!e.parent&&this.rootNodes.indexOf(e)===-1&&this.rootNodes.push(e)}addAllAssetsToContainer(e){if(!e)return;let t=[],i=new Set;for(t.push(e);t.length>0;){let r=t.pop();if(r instanceof q?(r.geometry&&this.geometries.indexOf(r.geometry)===-1&&this.geometries.push(r.geometry),this.meshes.push(r)):r instanceof tc?this.meshes.push(r):r instanceof ei?this.transformNodes.push(r):r instanceof Xt?this.lights.push(r):r instanceof mt&&this.cameras.push(r),r instanceof vr){if(r.material&&this.materials.indexOf(r.material)===-1){this.materials.push(r.material);for(let s of r.material.getActiveTextures())this.textures.indexOf(s)===-1&&this.textures.push(s)}r.skeleton&&this.skeletons.indexOf(r.skeleton)===-1&&this.skeletons.push(r.skeleton),r.morphTargetManager&&this.morphTargetManagers.indexOf(r.morphTargetManager)===-1&&this.morphTargetManagers.push(r.morphTargetManager)}for(let s of r.getChildren())i.has(s)||t.push(s);i.add(r)}this.populateRootNodes()}_getByTags(e,t,i){if(t===void 0)return e;let r=[];for(let s in e){let a=e[s];Zt&&Zt.MatchesQuery(a,t)&&(!i||i(a))&&r.push(a)}return r}getMeshesByTags(e,t){return this._getByTags(this.meshes,e,t)}getCamerasByTags(e,t){return this._getByTags(this.cameras,e,t)}getLightsByTags(e,t){return this._getByTags(this.lights,e,t)}getMaterialsByTags(e,t){return this._getByTags(this.materials,e,t).concat(this._getByTags(this.multiMaterials,e,t))}getTransformNodesByTags(e,t){return this._getByTags(this.transformNodes,e,t)}}});var od,NX=C(()=>{V_();od=class{constructor(e){this.byteOffset=0,this.buffer=e}async loadAsync(e){let t=await this.buffer.readAsync(this.byteOffset,e);this._dataView=new DataView(t.buffer,t.byteOffset,t.byteLength),this._dataByteOffset=0}readUint32(){let e=this._dataView.getUint32(this._dataByteOffset,!0);return this._dataByteOffset+=4,this.byteOffset+=4,e}readUint8Array(e){let t=new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+this._dataByteOffset,e);return this._dataByteOffset+=e,this.byteOffset+=e,t}readString(e){return P2(this.readUint8Array(e))}skipBytes(e){this._dataByteOffset+=e,this.byteOffset+=e}}});function ND(n,e,t,i){let r={externalResourceFunction:i};return t&&(r.uri=e==="file:"?t:e+t),ArrayBuffer.isView(n)?GLTFValidator.validateBytes(n,r):GLTFValidator.validateString(n,r)}function vce(){let n=[];onmessage=e=>{let t=e.data;switch(t.id){case"init":{importScripts(t.url);break}case"validate":{ND(t.data,t.rootUrl,t.fileName,i=>new Promise((r,s)=>{let a=n.length;n.push({resolve:r,reject:s}),postMessage({id:"getExternalResource",index:a,uri:i})})).then(i=>{postMessage({id:"validate.resolve",value:i})},i=>{postMessage({id:"validate.reject",reason:i})});break}case"getExternalResource.resolve":{n[t.index].resolve(t.value);break}case"getExternalResource.reject":{n[t.index].reject(t.reason);break}}}}var Jm,wX=C(()=>{Ii();Jm=class n{static ValidateAsync(e,t,i,r){return typeof Worker=="function"?new Promise((s,a)=>{let o=`${ND}(${vce})()`,l=URL.createObjectURL(new Blob([o],{type:"application/javascript"})),c=new Worker(l),f=d=>{c.removeEventListener("error",f),c.removeEventListener("message",h),a(d)},h=d=>{let u=d.data;switch(u.id){case"getExternalResource":{r(u.uri).then(m=>{c.postMessage({id:"getExternalResource.resolve",index:u.index,value:m},[m.buffer])},m=>{c.postMessage({id:"getExternalResource.reject",index:u.index,reason:m})});break}case"validate.resolve":{c.removeEventListener("error",f),c.removeEventListener("message",h),n._LastResults=u.value,s(u.value),c.terminate();break}case"validate.reject":c.removeEventListener("error",f),c.removeEventListener("message",h),a(u.reason),c.terminate()}};if(c.addEventListener("error",f),c.addEventListener("message",h),c.postMessage({id:"init",url:_e.GetBabylonScriptURL(this.Configuration.url)}),ArrayBuffer.isView(e)){let d=e.slice();c.postMessage({id:"validate",data:d,rootUrl:t,fileName:i},[d.buffer])}else c.postMessage({id:"validate",data:e,rootUrl:t,fileName:i})}):(this._LoadScriptPromise||(this._LoadScriptPromise=_e.LoadBabylonScriptAsync(this.Configuration.url)),this._LoadScriptPromise.then(()=>ND(e,t,i,r)))}};Jm.Configuration={url:`${_e._DefaultCdnUrl}/gltf_validator.js`};Jm._LastResults=null});var Tc,Vg,FX=C(()=>{Tc="Z2xURg",Vg={name:"gltf",extensions:{".gltf":{isBinary:!1,mimeType:"model/gltf+json"},".glb":{isBinary:!0,mimeType:"model/gltf-binary"}},canDirectLoad(n){return n.indexOf("asset")!==-1&&n.indexOf("version")!==-1||n.startsWith("data:base64,"+Tc)||n.startsWith("data:;base64,"+Tc)||n.startsWith("data:application/octet-stream;base64,"+Tc)||n.startsWith("data:model/gltf-binary;base64,"+Tc)}}});function BX(n,e,t){try{return Promise.resolve(new Uint8Array(n,e,t))}catch(i){return Promise.reject(i)}}function Ece(n,e,t){try{if(e<0||e>=n.byteLength)throw new RangeError("Offset is out of range.");if(e+t>n.byteLength)throw new RangeError("Length is out of range.");return Promise.resolve(new Uint8Array(n.buffer,n.byteOffset+e,t))}catch(i){return Promise.reject(i)}}var ep,ld,rs,cR,Sce,wD,Kf,FD=C(()=>{di();Ii();$m();Ug();Pt();NX();wX();FX();Wl();U_();(function(n){n[n.AUTO=0]="AUTO",n[n.FORCE_RIGHT_HANDED=1]="FORCE_RIGHT_HANDED"})(ep||(ep={}));(function(n){n[n.NONE=0]="NONE",n[n.FIRST=1]="FIRST",n[n.ALL=2]="ALL"})(ld||(ld={}));(function(n){n[n.LOADING=0]="LOADING",n[n.READY=1]="READY",n[n.COMPLETE=2]="COMPLETE"})(rs||(rs={}));cR=class{constructor(){this.alwaysComputeBoundingBox=!1,this.alwaysComputeSkeletonRootNode=!1,this.animationStartMode=ld.FIRST,this.compileMaterials=!1,this.compileShadowGenerators=!1,this.coordinateSystemMode=ep.AUTO,this.createInstances=!0,this.loadAllMaterials=!1,this.loadMorphTargets=!0,this.loadNodeAnimations=!0,this.loadOnlyMaterials=!1,this.loadSkins=!0,this.skipMaterials=!1,this.targetFps=60,this.transparencyAsCoverage=!1,this.useClipPlane=!1,this.useGltfTextureNames=!1,this.useRangeRequests=!1,this.useSRGBBuffers=!0,this.validate=!1,this.useOpenPBR=!1,this.dontUseTransmissionHelper=!1}},Sce=new cR,wD=class extends cR{constructor(){super(...arguments),this.extensionOptions={},this.preprocessUrlAsync=e=>Promise.resolve(e)}copyFrom(e){var t,i,r,s,a,o,l,c,f,h,d,u,m,p,_,g,v,x,A,S,E,R,I,y,M,D;e&&(this.alwaysComputeBoundingBox=(t=e.alwaysComputeBoundingBox)!=null?t:this.alwaysComputeBoundingBox,this.alwaysComputeSkeletonRootNode=(i=e.alwaysComputeSkeletonRootNode)!=null?i:this.alwaysComputeSkeletonRootNode,this.animationStartMode=(r=e.animationStartMode)!=null?r:this.animationStartMode,this.capturePerformanceCounters=(s=e.capturePerformanceCounters)!=null?s:this.capturePerformanceCounters,this.compileMaterials=(a=e.compileMaterials)!=null?a:this.compileMaterials,this.compileShadowGenerators=(o=e.compileShadowGenerators)!=null?o:this.compileShadowGenerators,this.coordinateSystemMode=(l=e.coordinateSystemMode)!=null?l:this.coordinateSystemMode,this.createInstances=(c=e.createInstances)!=null?c:this.createInstances,this.customRootNode=e.customRootNode,this.extensionOptions=(f=e.extensionOptions)!=null?f:this.extensionOptions,this.loadAllMaterials=(h=e.loadAllMaterials)!=null?h:this.loadAllMaterials,this.loadMorphTargets=(d=e.loadMorphTargets)!=null?d:this.loadMorphTargets,this.loadNodeAnimations=(u=e.loadNodeAnimations)!=null?u:this.loadNodeAnimations,this.loadOnlyMaterials=(m=e.loadOnlyMaterials)!=null?m:this.loadOnlyMaterials,this.loadSkins=(p=e.loadSkins)!=null?p:this.loadSkins,this.loggingEnabled=(_=e.loggingEnabled)!=null?_:this.loggingEnabled,this.onCameraLoaded=e.onCameraLoaded,this.onMaterialLoaded=e.onMaterialLoaded,this.onMeshLoaded=e.onMeshLoaded,this.onParsed=e.onParsed,this.onSkinLoaded=e.onSkinLoaded,this.onTextureLoaded=e.onTextureLoaded,this.onValidated=e.onValidated,this.preprocessUrlAsync=(g=e.preprocessUrlAsync)!=null?g:this.preprocessUrlAsync,this.skipMaterials=(v=e.skipMaterials)!=null?v:this.skipMaterials,this.targetFps=(x=e.targetFps)!=null?x:this.targetFps,this.transparencyAsCoverage=(A=e.transparencyAsCoverage)!=null?A:this.transparencyAsCoverage,this.useClipPlane=(S=e.useClipPlane)!=null?S:this.useClipPlane,this.useGltfTextureNames=(E=e.useGltfTextureNames)!=null?E:this.useGltfTextureNames,this.useOpenPBR=(R=e.useOpenPBR)!=null?R:this.useOpenPBR,this.useRangeRequests=(I=e.useRangeRequests)!=null?I:this.useRangeRequests,this.useSRGBBuffers=(y=e.useSRGBBuffers)!=null?y:this.useSRGBBuffers,this.validate=(M=e.validate)!=null?M:this.validate,this.dontUseTransmissionHelper=(D=e.dontUseTransmissionHelper)!=null?D:this.dontUseTransmissionHelper)}},Kf=class n extends wD{constructor(e){super(),this.onParsedObservable=new ie,this.onMeshLoadedObservable=new ie,this.onSkinLoadedObservable=new ie,this.onTextureLoadedObservable=new ie,this.onMaterialLoadedObservable=new ie,this.onCameraLoadedObservable=new ie,this.onCompleteObservable=new ie,this.onErrorObservable=new ie,this.onDisposeObservable=new ie,this.onExtensionLoadedObservable=new ie,this.onValidatedObservable=new ie,this._loader=null,this._state=null,this._requests=new Array,this.name=Vg.name,this.extensions=Vg.extensions,this.onLoaderStateChangedObservable=new ie,this._logIndentLevel=0,this._loggingEnabled=!1,this._log=this._logDisabled,this._capturePerformanceCounters=!1,this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled,this.copyFrom(Object.assign({...Sce},e))}set onParsed(e){this._onParsedObserver&&this.onParsedObservable.remove(this._onParsedObserver),e&&(this._onParsedObserver=this.onParsedObservable.add(e))}set onMeshLoaded(e){this._onMeshLoadedObserver&&this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver),e&&(this._onMeshLoadedObserver=this.onMeshLoadedObservable.add(e))}set onSkinLoaded(e){this._onSkinLoadedObserver&&this.onSkinLoadedObservable.remove(this._onSkinLoadedObserver),e&&(this._onSkinLoadedObserver=this.onSkinLoadedObservable.add(t=>e(t.node,t.skinnedNode)))}set onTextureLoaded(e){this._onTextureLoadedObserver&&this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver),e&&(this._onTextureLoadedObserver=this.onTextureLoadedObservable.add(e))}set onMaterialLoaded(e){this._onMaterialLoadedObserver&&this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver),e&&(this._onMaterialLoadedObserver=this.onMaterialLoadedObservable.add(e))}set onCameraLoaded(e){this._onCameraLoadedObserver&&this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver),e&&(this._onCameraLoadedObserver=this.onCameraLoadedObservable.add(e))}set onComplete(e){this._onCompleteObserver&&this.onCompleteObservable.remove(this._onCompleteObserver),this._onCompleteObserver=this.onCompleteObservable.add(e)}set onError(e){this._onErrorObserver&&this.onErrorObservable.remove(this._onErrorObserver),this._onErrorObserver=this.onErrorObservable.add(e)}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set onExtensionLoaded(e){this._onExtensionLoadedObserver&&this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver),this._onExtensionLoadedObserver=this.onExtensionLoadedObservable.add(e)}get loggingEnabled(){return this._loggingEnabled}set loggingEnabled(e){this._loggingEnabled!==e&&(this._loggingEnabled=e,this._loggingEnabled?this._log=this._logEnabled:this._log=this._logDisabled)}get capturePerformanceCounters(){return this._capturePerformanceCounters}set capturePerformanceCounters(e){this._capturePerformanceCounters!==e&&(this._capturePerformanceCounters=e,this._capturePerformanceCounters?(this._startPerformanceCounter=this._startPerformanceCounterEnabled,this._endPerformanceCounter=this._endPerformanceCounterEnabled):(this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled))}set onValidated(e){this._onValidatedObserver&&this.onValidatedObservable.remove(this._onValidatedObserver),this._onValidatedObserver=this.onValidatedObservable.add(e)}dispose(){this._loader&&(this._loader.dispose(),this._loader=null);for(let e of this._requests)e.abort();this._requests.length=0,delete this._progressCallback,this.preprocessUrlAsync=e=>Promise.resolve(e),this.onMeshLoadedObservable.clear(),this.onSkinLoadedObservable.clear(),this.onTextureLoadedObservable.clear(),this.onMaterialLoadedObservable.clear(),this.onCameraLoadedObservable.clear(),this.onCompleteObservable.clear(),this.onExtensionLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(void 0),this.onDisposeObservable.clear()}loadFile(e,t,i,r,s,a,o,l){if(ArrayBuffer.isView(t))return this._loadBinary(e,t,i,r,o,l),null;this._progressCallback=s;let c=t.name||_e.GetFilename(t);if(a){if(this.useRangeRequests){this.validate&&te.Warn("glTF validation is not supported when range requests are enabled");let f={abort:()=>{},onCompleteObservable:new ie},h={readAsync:(d,u)=>new Promise((m,p)=>{this._loadFile(e,t,_=>{m(new Uint8Array(_))},!0,_=>{p(_)},_=>{_.setRequestHeader("Range",`bytes=${d}-${d+u-1}`)})}),byteLength:0};return this._unpackBinaryAsync(new od(h)).then(d=>{f.onCompleteObservable.notifyObservers(f),r(d)},o?d=>o(void 0,d):void 0),f}return this._loadFile(e,t,f=>{this._validate(e,new Uint8Array(f,0,f.byteLength),i,c),this._unpackBinaryAsync(new od({readAsync:(h,d)=>BX(f,h,d),byteLength:f.byteLength})).then(h=>{r(h)},o?h=>o(void 0,h):void 0)},!0,o)}else return this._loadFile(e,t,f=>{try{this._validate(e,f,i,c),r({json:this._parseJson(f)})}catch(h){o&&o()}},!1,o)}_loadBinary(e,t,i,r,s,a){this._validate(e,new Uint8Array(t.buffer,t.byteOffset,t.byteLength),i,a),this._unpackBinaryAsync(new od({readAsync:(o,l)=>Ece(t,o,l),byteLength:t.byteLength})).then(o=>{r(o)},s?o=>s(void 0,o):void 0)}importMeshAsync(e,t,i,r,s,a){return Promise.resolve().then(()=>(this.onParsedObservable.notifyObservers(i),this.onParsedObservable.clear(),this._log(`Loading ${a||""}`),this._loader=this._getLoader(i),this._loader.importMeshAsync(e,t,null,i,r,s,a)))}loadAsync(e,t,i,r,s){return Promise.resolve().then(()=>(this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${s||""}`),this._loader=this._getLoader(t),this._loader.loadAsync(e,t,i,r,s)))}loadAssetContainerAsync(e,t,i,r,s){return Promise.resolve().then(()=>{this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${s||""}`),this._loader=this._getLoader(t);let a=new ul(e),o=[];this.onMaterialLoadedObservable.add(h=>{o.push(h)});let l=[];this.onTextureLoadedObservable.add(h=>{l.push(h)});let c=[];this.onCameraLoadedObservable.add(h=>{c.push(h)});let f=[];return this.onMeshLoadedObservable.add(h=>{h.morphTargetManager&&f.push(h.morphTargetManager)}),this._loader.importMeshAsync(null,e,a,t,i,r,s).then(h=>(Array.prototype.push.apply(a.geometries,h.geometries),Array.prototype.push.apply(a.meshes,h.meshes),Array.prototype.push.apply(a.particleSystems,h.particleSystems),Array.prototype.push.apply(a.skeletons,h.skeletons),Array.prototype.push.apply(a.animationGroups,h.animationGroups),Array.prototype.push.apply(a.materials,o),Array.prototype.push.apply(a.textures,l),Array.prototype.push.apply(a.lights,h.lights),Array.prototype.push.apply(a.transformNodes,h.transformNodes),Array.prototype.push.apply(a.cameras,c),Array.prototype.push.apply(a.morphTargetManagers,f),a))})}canDirectLoad(e){return Vg.canDirectLoad(e)}directLoad(e,t){if(t.startsWith("base64,"+Tc)||t.startsWith(";base64,"+Tc)||t.startsWith("application/octet-stream;base64,"+Tc)||t.startsWith("model/gltf-binary;base64,"+Tc)){let i=hf(t);return this._validate(e,new Uint8Array(i,0,i.byteLength)),this._unpackBinaryAsync(new od({readAsync:(r,s)=>BX(i,r,s),byteLength:i.byteLength}))}return this._validate(e,t),Promise.resolve({json:this._parseJson(t)})}createPlugin(e){return new n(e[Vg.name])}get loaderState(){return this._state}whenCompleteAsync(){return new Promise((e,t)=>{this.onCompleteObservable.addOnce(()=>{e()}),this.onErrorObservable.addOnce(i=>{t(i)})})}_setState(e){this._state!==e&&(this._state=e,this.onLoaderStateChangedObservable.notifyObservers(this._state),this._log(rs[this._state]))}_loadFile(e,t,i,r,s,a){let o=e._loadFile(t,i,l=>{this._onProgress(l,o)},!0,r,s,a);return o.onCompleteObservable.add(()=>{o._lengthComputable=!0,o._total=o._loaded}),this._requests.push(o),o}_onProgress(e,t){if(!this._progressCallback)return;t._lengthComputable=e.lengthComputable,t._loaded=e.loaded,t._total=e.total;let i=!0,r=0,s=0;for(let a of this._requests){if(a._lengthComputable===void 0||a._loaded===void 0||a._total===void 0)return;i=i&&a._lengthComputable,r+=a._loaded,s+=a._total}this._progressCallback({lengthComputable:i,loaded:r,total:i?s:0})}_validate(e,t,i="",r=""){this.validate&&(this._startPerformanceCounter("Validate JSON"),Jm.ValidateAsync(t,i,r,s=>this.preprocessUrlAsync(i+s).then(a=>e._loadFileAsync(a,void 0,!0,!0).then(o=>new Uint8Array(o,0,o.byteLength)))).then(s=>{this._endPerformanceCounter("Validate JSON"),this.onValidatedObservable.notifyObservers(s),this.onValidatedObservable.clear()},s=>{this._endPerformanceCounter("Validate JSON"),_e.Warn(`Failed to validate: ${s.message}`),this.onValidatedObservable.clear()}))}_getLoader(e){let t=e.json.asset||{};this._log(`Asset version: ${t.version}`),t.minVersion&&this._log(`Asset minimum version: ${t.minVersion}`),t.generator&&this._log(`Asset generator: ${t.generator}`);let i=n._parseVersion(t.version);if(!i)throw new Error("Invalid version: "+t.version);if(t.minVersion!==void 0){let a=n._parseVersion(t.minVersion);if(!a)throw new Error("Invalid minimum version: "+t.minVersion);if(n._compareVersion(a,{major:2,minor:0})>0)throw new Error("Incompatible minimum version: "+t.minVersion)}let s={1:n._CreateGLTF1Loader,2:n._CreateGLTF2Loader}[i.major];if(!s)throw new Error("Unsupported version: "+t.version);return s(this)}_parseJson(e){this._startPerformanceCounter("Parse JSON"),this._log(`JSON length: ${e.length}`);let t=JSON.parse(e);return this._endPerformanceCounter("Parse JSON"),t}_unpackBinaryAsync(e){return this._startPerformanceCounter("Unpack Binary"),e.loadAsync(20).then(()=>{let t={Magic:1179937895},i=e.readUint32();if(i!==t.Magic)throw new Ts("Unexpected magic: "+i,Ea.GLTFLoaderUnexpectedMagicError);let r=e.readUint32();this.loggingEnabled&&this._log(`Binary version: ${r}`);let s=e.readUint32();!this.useRangeRequests&&s!==e.buffer.byteLength&&te.Warn(`Length in header does not match actual data length: ${s} != ${e.buffer.byteLength}`);let a;switch(r){case 1:{a=this._unpackBinaryV1Async(e,s);break}case 2:{a=this._unpackBinaryV2Async(e,s);break}default:throw new Error("Unsupported version: "+r)}return this._endPerformanceCounter("Unpack Binary"),a})}_unpackBinaryV1Async(e,t){let i={JSON:0},r=e.readUint32(),s=e.readUint32();if(s!==i.JSON)throw new Error(`Unexpected content format: ${s}`);let a=t-e.byteOffset,o={json:this._parseJson(e.readString(r)),bin:null};if(a!==0){let l=e.byteOffset;o.bin={readAsync:(c,f)=>e.buffer.readAsync(l+c,f),byteLength:a}}return Promise.resolve(o)}_unpackBinaryV2Async(e,t){let i={JSON:1313821514,BIN:5130562},r=e.readUint32();if(e.readUint32()!==i.JSON)throw new Error("First chunk format is not JSON");return e.byteOffset+r===t?e.loadAsync(r).then(()=>({json:this._parseJson(e.readString(r)),bin:null})):e.loadAsync(r+8).then(()=>{let a={json:this._parseJson(e.readString(r)),bin:null},o=()=>{let l=e.readUint32();switch(e.readUint32()){case i.JSON:throw new Error("Unexpected JSON chunk");case i.BIN:{let f=e.byteOffset;a.bin={readAsync:(h,d)=>e.buffer.readAsync(f+h,d),byteLength:l},e.skipBytes(l);break}default:{e.skipBytes(l);break}}return e.byteOffset!==t?e.loadAsync(8).then(o):Promise.resolve(a)};return o()})}static _parseVersion(e){if(e==="1.0"||e==="1.0.1")return{major:1,minor:0};let t=(e+"").match(/^(\d+)\.(\d+)/);return t?{major:parseInt(t[1]),minor:parseInt(t[2])}:null}static _compareVersion(e,t){return e.major>t.major?1:e.majort.minor?1:e.minor{fR=class{get resolve(){return this._resolve}get reject(){return this._reject}constructor(){this.promise=new Promise((e,t)=>{this._resolve=e,this._reject=t})}}});var zn,VX=C(()=>{Gt();Vt();fl();lA();Ge();Ii();zn=class{constructor(){this.keysUp=[38],this.keysUpward=[33],this.keysDown=[40],this.keysDownward=[34],this.keysLeft=[37],this.keysRight=[39],this.rotationSpeed=.5,this.keysRotateLeft=[],this.keysRotateRight=[],this.keysRotateUp=[],this.keysRotateDown=[],this._keys=new Array}attachControl(e){e=_e.BackCompatCameraNoPreventDefault(arguments),!this._onCanvasBlurObserver&&(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add(()=>{this._keys.length=0}),this._onKeyboardObserver=this._scene.onKeyboardObservable.add(t=>{let i=t.event;if(!i.metaKey){if(t.type===lo.KEYDOWN)(this.keysUp.indexOf(i.keyCode)!==-1||this.keysDown.indexOf(i.keyCode)!==-1||this.keysLeft.indexOf(i.keyCode)!==-1||this.keysRight.indexOf(i.keyCode)!==-1||this.keysUpward.indexOf(i.keyCode)!==-1||this.keysDownward.indexOf(i.keyCode)!==-1||this.keysRotateLeft.indexOf(i.keyCode)!==-1||this.keysRotateRight.indexOf(i.keyCode)!==-1||this.keysRotateUp.indexOf(i.keyCode)!==-1||this.keysRotateDown.indexOf(i.keyCode)!==-1)&&(this._keys.indexOf(i.keyCode)===-1&&this._keys.push(i.keyCode),e||i.preventDefault());else if(this.keysUp.indexOf(i.keyCode)!==-1||this.keysDown.indexOf(i.keyCode)!==-1||this.keysLeft.indexOf(i.keyCode)!==-1||this.keysRight.indexOf(i.keyCode)!==-1||this.keysUpward.indexOf(i.keyCode)!==-1||this.keysDownward.indexOf(i.keyCode)!==-1||this.keysRotateLeft.indexOf(i.keyCode)!==-1||this.keysRotateRight.indexOf(i.keyCode)!==-1||this.keysRotateUp.indexOf(i.keyCode)!==-1||this.keysRotateDown.indexOf(i.keyCode)!==-1){let r=this._keys.indexOf(i.keyCode);r>=0&&this._keys.splice(r,1),e||i.preventDefault()}}}))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){if(this._onKeyboardObserver){let e=this.camera;for(let t=0;t{Gt();di();Vt();fl();oo();Ii();cd=class{constructor(e=!0){this.touchEnabled=e,this.buttons=[0,1,2],this.angularSensibility=2e3,this._previousPosition=null,this.onPointerMovedObservable=new ie,this._allowCameraRotation=!0,this._currentActiveButton=-1,this._activePointerId=-1}attachControl(e){e=_e.BackCompatCameraNoPreventDefault(arguments);let t=this.camera.getEngine(),i=t.getInputElement();this._pointerInput||(this._pointerInput=r=>{let s=r.event,a=s.pointerType==="touch";if(!this.touchEnabled&&a||r.type!==st.POINTERMOVE&&this.buttons.indexOf(s.button)===-1)return;let o=s.target;if(r.type===st.POINTERDOWN){if(a&&this._activePointerId!==-1||!a&&this._currentActiveButton!==-1)return;this._activePointerId=s.pointerId;try{o==null||o.setPointerCapture(s.pointerId)}catch(l){}this._currentActiveButton===-1&&(this._currentActiveButton=s.button),this._previousPosition={x:s.clientX,y:s.clientY},e||(s.preventDefault(),i&&i.focus()),t.isPointerLock&&this._onMouseMove&&this._onMouseMove(r.event)}else if(r.type===st.POINTERUP){if(a&&this._activePointerId!==s.pointerId||!a&&this._currentActiveButton!==s.button)return;try{o==null||o.releasePointerCapture(s.pointerId)}catch(l){}this._currentActiveButton=-1,this._previousPosition=null,e||s.preventDefault(),this._activePointerId=-1}else if(r.type===st.POINTERMOVE&&(this._activePointerId===s.pointerId||!a)){if(t.isPointerLock&&this._onMouseMove)this._onMouseMove(r.event);else if(this._previousPosition){let l=this.camera._calculateHandednessMultiplier(),c=(s.clientX-this._previousPosition.x)*l,f=(s.clientY-this._previousPosition.y)*l;this._allowCameraRotation&&(this.camera.cameraRotation.y+=c/this.angularSensibility,this.camera.cameraRotation.x+=f/this.angularSensibility),this.onPointerMovedObservable.notifyObservers({offsetX:c,offsetY:f}),this._previousPosition={x:s.clientX,y:s.clientY},e||s.preventDefault()}}}),this._onMouseMove=r=>{if(!t.isPointerLock)return;let s=this.camera._calculateHandednessMultiplier();this.camera.cameraRotation.y+=r.movementX*s/this.angularSensibility,this.camera.cameraRotation.x+=r.movementY*s/this.angularSensibility,this._previousPosition=null,e||r.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,st.POINTERDOWN|st.POINTERUP|st.POINTERMOVE),i&&(this._contextMenuBind=r=>this.onContextMenu(r),i.addEventListener("contextmenu",this._contextMenuBind,!1))}onContextMenu(e){e.preventDefault()}detachControl(){if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._contextMenuBind){let t=this.camera.getEngine().getInputElement();t&&t.removeEventListener("contextmenu",this._contextMenuBind)}this.onPointerMovedObservable&&this.onPointerMovedObservable.clear(),this._observer=null,this._onMouseMove=null,this._previousPosition=null}this._activePointerId=-1,this._currentActiveButton=-1}getClassName(){return"FreeCameraMouseInput"}getSimpleName(){return"mouse"}};P([w()],cd.prototype,"buttons",void 0);P([w()],cd.prototype,"angularSensibility",void 0);Gn.FreeCameraMouseInput=cd});var fd,kX=C(()=>{Gt();Vt();di();oo();cA();Ii();fd=class{constructor(){this.wheelPrecisionX=3,this.wheelPrecisionY=3,this.wheelPrecisionZ=3,this.onChangedObservable=new ie,this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0,this._ffMultiplier=12,this._normalize=120}attachControl(e){e=_e.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==st.POINTERWHEEL)return;let i=t.event,r=i.deltaMode===co.DOM_DELTA_LINE?this._ffMultiplier:1;this._wheelDeltaX+=this.wheelPrecisionX*r*i.deltaX/this._normalize,this._wheelDeltaY-=this.wheelPrecisionY*r*i.deltaY/this._normalize,this._wheelDeltaZ+=this.wheelPrecisionZ*r*i.deltaZ/this._normalize,i.preventDefault&&(e||i.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,st.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null),this.onChangedObservable&&this.onChangedObservable.clear()}checkInputs(){this.onChangedObservable.notifyObservers({wheelDeltaX:this._wheelDeltaX,wheelDeltaY:this._wheelDeltaY,wheelDeltaZ:this._wheelDeltaZ}),this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0}getClassName(){return"BaseCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}};P([w()],fd.prototype,"wheelPrecisionX",void 0);P([w()],fd.prototype,"wheelPrecisionY",void 0);P([w()],fd.prototype,"wheelPrecisionZ",void 0)});var Li,ys,WX=C(()=>{Gt();Vt();fl();kX();Ge();(function(n){n[n.MoveRelative=0]="MoveRelative",n[n.RotateRelative=1]="RotateRelative",n[n.MoveScene=2]="MoveScene"})(Li||(Li={}));ys=class extends fd{constructor(){super(...arguments),this._moveRelative=b.Zero(),this._rotateRelative=b.Zero(),this._moveScene=b.Zero(),this._wheelXAction=Li.MoveRelative,this._wheelXActionCoordinate=0,this._wheelYAction=Li.MoveRelative,this._wheelYActionCoordinate=2,this._wheelZAction=null,this._wheelZActionCoordinate=null}getClassName(){return"FreeCameraMouseWheelInput"}set wheelXMoveRelative(e){e===null&&this._wheelXAction!==Li.MoveRelative||(this._wheelXAction=Li.MoveRelative,this._wheelXActionCoordinate=e)}get wheelXMoveRelative(){return this._wheelXAction!==Li.MoveRelative?null:this._wheelXActionCoordinate}set wheelYMoveRelative(e){e===null&&this._wheelYAction!==Li.MoveRelative||(this._wheelYAction=Li.MoveRelative,this._wheelYActionCoordinate=e)}get wheelYMoveRelative(){return this._wheelYAction!==Li.MoveRelative?null:this._wheelYActionCoordinate}set wheelZMoveRelative(e){e===null&&this._wheelZAction!==Li.MoveRelative||(this._wheelZAction=Li.MoveRelative,this._wheelZActionCoordinate=e)}get wheelZMoveRelative(){return this._wheelZAction!==Li.MoveRelative?null:this._wheelZActionCoordinate}set wheelXRotateRelative(e){e===null&&this._wheelXAction!==Li.RotateRelative||(this._wheelXAction=Li.RotateRelative,this._wheelXActionCoordinate=e)}get wheelXRotateRelative(){return this._wheelXAction!==Li.RotateRelative?null:this._wheelXActionCoordinate}set wheelYRotateRelative(e){e===null&&this._wheelYAction!==Li.RotateRelative||(this._wheelYAction=Li.RotateRelative,this._wheelYActionCoordinate=e)}get wheelYRotateRelative(){return this._wheelYAction!==Li.RotateRelative?null:this._wheelYActionCoordinate}set wheelZRotateRelative(e){e===null&&this._wheelZAction!==Li.RotateRelative||(this._wheelZAction=Li.RotateRelative,this._wheelZActionCoordinate=e)}get wheelZRotateRelative(){return this._wheelZAction!==Li.RotateRelative?null:this._wheelZActionCoordinate}set wheelXMoveScene(e){e===null&&this._wheelXAction!==Li.MoveScene||(this._wheelXAction=Li.MoveScene,this._wheelXActionCoordinate=e)}get wheelXMoveScene(){return this._wheelXAction!==Li.MoveScene?null:this._wheelXActionCoordinate}set wheelYMoveScene(e){e===null&&this._wheelYAction!==Li.MoveScene||(this._wheelYAction=Li.MoveScene,this._wheelYActionCoordinate=e)}get wheelYMoveScene(){return this._wheelYAction!==Li.MoveScene?null:this._wheelYActionCoordinate}set wheelZMoveScene(e){e===null&&this._wheelZAction!==Li.MoveScene||(this._wheelZAction=Li.MoveScene,this._wheelZActionCoordinate=e)}get wheelZMoveScene(){return this._wheelZAction!==Li.MoveScene?null:this._wheelZActionCoordinate}checkInputs(){if(this._wheelDeltaX===0&&this._wheelDeltaY===0&&this._wheelDeltaZ==0)return;this._moveRelative.setAll(0),this._rotateRelative.setAll(0),this._moveScene.setAll(0),this._updateCamera(),this.camera.getScene().useRightHandedSystem&&(this._moveRelative.z*=-1);let e=K.Zero();this.camera.getViewMatrix().invertToRef(e);let t=b.Zero();b.TransformNormalToRef(this._moveRelative,e,t),this.camera.cameraRotation.x+=this._rotateRelative.x/200,this.camera.cameraRotation.y+=this._rotateRelative.y/200,this.camera.cameraDirection.addInPlace(t),this.camera.cameraDirection.addInPlace(this._moveScene),super.checkInputs()}_updateCamera(){this._updateCameraProperty(this._wheelDeltaX,this._wheelXAction,this._wheelXActionCoordinate),this._updateCameraProperty(this._wheelDeltaY,this._wheelYAction,this._wheelYActionCoordinate),this._updateCameraProperty(this._wheelDeltaZ,this._wheelZAction,this._wheelZActionCoordinate)}_updateCameraProperty(e,t,i){if(e===0||t===null||i===null)return;let r=null;switch(t){case Li.MoveRelative:r=this._moveRelative;break;case Li.RotateRelative:r=this._rotateRelative;break;case Li.MoveScene:r=this._moveScene;break}switch(i){case 0:r.set(e,0,0);break;case 1:r.set(0,e,0);break;case 2:r.set(0,0,e);break}}};P([w()],ys.prototype,"wheelXMoveRelative",null);P([w()],ys.prototype,"wheelYMoveRelative",null);P([w()],ys.prototype,"wheelZMoveRelative",null);P([w()],ys.prototype,"wheelXRotateRelative",null);P([w()],ys.prototype,"wheelYRotateRelative",null);P([w()],ys.prototype,"wheelZRotateRelative",null);P([w()],ys.prototype,"wheelXMoveScene",null);P([w()],ys.prototype,"wheelYMoveScene",null);P([w()],ys.prototype,"wheelZMoveScene",null);Gn.FreeCameraMouseWheelInput=ys});var hd,HX=C(()=>{Gt();Vt();fl();oo();Ge();Ii();hd=class{constructor(e=!1){this.allowMouse=e,this.touchAngularSensibility=2e5,this.touchMoveSensibility=250,this.singleFingerRotate=!1,this._offsetX=null,this._offsetY=null,this._pointerPressed=new Array,this._isSafari=_e.IsSafari()}attachControl(e){e=_e.BackCompatCameraNoPreventDefault(arguments);let t=null;if(this._pointerInput===void 0&&(this._onLostFocus=()=>{this._offsetX=null,this._offsetY=null},this._pointerInput=i=>{let r=i.event,s=r.pointerType==="mouse"||this._isSafari&&typeof r.pointerType=="undefined";if(!(!this.allowMouse&&s)){if(i.type===st.POINTERDOWN){if(e||r.preventDefault(),this._pointerPressed.push(r.pointerId),this._pointerPressed.length!==1)return;t={x:r.clientX,y:r.clientY}}else if(i.type===st.POINTERUP){e||r.preventDefault();let a=this._pointerPressed.indexOf(r.pointerId);if(a===-1||(this._pointerPressed.splice(a,1),a!=0))return;t=null,this._offsetX=null,this._offsetY=null}else if(i.type===st.POINTERMOVE){if(e||r.preventDefault(),!t||this._pointerPressed.indexOf(r.pointerId)!=0)return;this._offsetX=r.clientX-t.x,this._offsetY=-(r.clientY-t.y)}}}),this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,st.POINTERDOWN|st.POINTERUP|st.POINTERMOVE),this._onLostFocus){let r=this.camera.getEngine().getInputElement();r&&r.addEventListener("blur",this._onLostFocus)}}detachControl(){if(this._pointerInput){if(this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null),this._onLostFocus){let t=this.camera.getEngine().getInputElement();t&&t.removeEventListener("blur",this._onLostFocus),this._onLostFocus=null}this._pointerPressed.length=0,this._offsetX=null,this._offsetY=null}}checkInputs(){if(this._offsetX===null||this._offsetY===null||this._offsetX===0&&this._offsetY===0)return;let e=this.camera,t=e._calculateHandednessMultiplier();if(e.cameraRotation.y=this._offsetX*t/this.touchAngularSensibility,this.singleFingerRotate&&this._pointerPressed.length===1||!this.singleFingerRotate&&this._pointerPressed.length>1)e.cameraRotation.x=-(this._offsetY*t)/this.touchAngularSensibility;else{let r=e._computeLocalCameraSpeed(),s=$.Vector3[0];s.copyFromFloats(0,0,this.touchMoveSensibility!==0?r*this._offsetY/this.touchMoveSensibility:0),K.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),b.TransformCoordinatesToRef(s,e._cameraRotationMatrix,s),e.cameraDirection.addInPlace(s)}}getClassName(){return"FreeCameraTouchInput"}getSimpleName(){return"touch"}};P([w()],hd.prototype,"touchAngularSensibility",void 0);P([w()],hd.prototype,"touchMoveSensibility",void 0);Gn.FreeCameraTouchInput=hd});var hR,zX=C(()=>{fl();VX();GX();WX();HX();hR=class extends Um{constructor(e){super(e),this._mouseInput=null,this._mouseWheelInput=null}addKeyboard(){return this.add(new zn),this}addMouse(e=!0){return this._mouseInput||(this._mouseInput=new cd(e),this.add(this._mouseInput)),this}removeMouse(){return this._mouseInput&&this.remove(this._mouseInput),this}addMouseWheel(){return this._mouseWheelInput||(this._mouseWheelInput=new ys,this.add(this._mouseWheelInput)),this}removeMouseWheel(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this}addTouch(){return this.add(new hd),this}clear(){super.clear(),this._mouseInput=null}}});var Ac,XX=C(()=>{Gt();Vt();Ge();wy();zX();Ii();Hi();wr();Ac=class extends bs{get angularSensibility(){let e=this.inputs.attached.mouse;return e?e.angularSensibility:0}set angularSensibility(e){let t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)}get keysUp(){let e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){let t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysUpward(){let e=this.inputs.attached.keyboard;return e?e.keysUpward:[]}set keysUpward(e){let t=this.inputs.attached.keyboard;t&&(t.keysUpward=e)}get keysDown(){let e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){let t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysDownward(){let e=this.inputs.attached.keyboard;return e?e.keysDownward:[]}set keysDownward(e){let t=this.inputs.attached.keyboard;t&&(t.keysDownward=e)}get keysLeft(){let e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){let t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){let e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){let t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}get keysRotateLeft(){let e=this.inputs.attached.keyboard;return e?e.keysRotateLeft:[]}set keysRotateLeft(e){let t=this.inputs.attached.keyboard;t&&(t.keysRotateLeft=e)}get keysRotateRight(){let e=this.inputs.attached.keyboard;return e?e.keysRotateRight:[]}set keysRotateRight(e){let t=this.inputs.attached.keyboard;t&&(t.keysRotateRight=e)}get keysRotateUp(){let e=this.inputs.attached.keyboard;return e?e.keysRotateUp:[]}set keysRotateUp(e){let t=this.inputs.attached.keyboard;t&&(t.keysRotateUp=e)}get keysRotateDown(){let e=this.inputs.attached.keyboard;return e?e.keysRotateDown:[]}set keysRotateDown(e){let t=this.inputs.attached.keyboard;t&&(t.keysRotateDown=e)}constructor(e,t,i,r=!0){super(e,t,i,r),this.ellipsoid=new b(.5,1,.5),this.ellipsoidOffset=new b(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this._needMoveForGravity=!1,this._oldPosition=b.Zero(),this._diffPosition=b.Zero(),this._newPosition=b.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(s,a,o=null)=>{this._newPosition.copyFrom(a),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>Me.CollisionsEpsilon&&(this.position.addToRef(this._diffPosition,this._deferredPositionUpdate),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate),this.onCollide&&o&&this.onCollide(o))},this.inputs=new hR(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=_e.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new b(0,0,0),this.cameraRotation=new we(0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;this.parent?t=b.TransformCoordinates(this.position,this.parent.getWorldMatrix()):t=this.position,t.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);let i=this.getScene().collisionCoordinator;this._collider||(this._collider=i.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let r=e;this.applyGravity&&(r=e.add(this.getScene().gravity)),i.getNewPosition(this._oldPosition,r,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=b.Zero(),this._transformedDirection=b.Zero()),this.inputs.checkInputs(),super._checkInputs()}set needMoveForGravity(e){this._needMoveForGravity=e}get needMoveForGravity(){return this._needMoveForGravity}_decideIfNeedsToMove(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):super._updatePosition()}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FreeCamera"}};P([Hr()],Ac.prototype,"ellipsoid",void 0);P([Hr()],Ac.prototype,"ellipsoidOffset",void 0);P([w()],Ac.prototype,"checkCollisions",void 0);P([w()],Ac.prototype,"applyGravity",void 0);Ft("BABYLON.FreeCamera",Ac)});var wa,dR=C(()=>{Ge();Zo();js();wa=class n extends _i{get _matrix(){return this._compose(),this._localMatrix}set _matrix(e){e.updateFlag===this._localMatrix.updateFlag&&!this._needToCompose||(this._needToCompose=!1,this._localMatrix.copyFrom(e),this._markAsDirtyAndDecompose())}constructor(e,t,i=null,r=null,s=null,a=null,o=null){var l;super(e,t.getScene(),!1),this.name=e,this.children=[],this.animations=[],this._index=null,this._scalingDeterminant=1,this._needToDecompose=!0,this._needToCompose=!1,this._linkedTransformNode=null,this._waitingTransformNodeId=null,this._waitingTransformNodeUniqueId=null,this._skeleton=t,this._localMatrix=(l=r==null?void 0:r.clone())!=null?l:K.Identity(),this._restMatrix=s!=null?s:this._localMatrix.clone(),this._bindMatrix=a!=null?a:this._localMatrix.clone(),this._index=o,this._absoluteMatrix=new K,this._absoluteBindMatrix=new K,this._absoluteInverseBindMatrix=new K,this._finalMatrix=new K,t.bones.push(this),this.setParent(i,!1),this._updateAbsoluteBindMatrices()}getClassName(){return"Bone"}getSkeleton(){return this._skeleton}get parent(){return this._parentNode}getParent(){return this.parent}getChildren(){return this.children}getIndex(){return this._index===null?this.getSkeleton().bones.indexOf(this):this._index}set parent(e){this.setParent(e)}setParent(e,t=!0){if(this.parent!==e){if(this.parent){let i=this.parent.children.indexOf(this);i!==-1&&this.parent.children.splice(i,1)}this._parentNode=e,this.parent&&this.parent.children.push(this),t&&this._updateAbsoluteBindMatrices(),this.markAsDirty()}}getLocalMatrix(){return this._compose(),this._localMatrix}getBindMatrix(){return this._bindMatrix}getBaseMatrix(){return this.getBindMatrix()}getRestMatrix(){return this._restMatrix}getRestPose(){return this.getRestMatrix()}setRestMatrix(e){this._restMatrix.copyFrom(e)}setRestPose(e){this.setRestMatrix(e)}getBindPose(){return this.getBindMatrix()}setBindMatrix(e){this.updateMatrix(e)}setBindPose(e){this.setBindMatrix(e)}getFinalMatrix(){return this._finalMatrix}getWorldMatrix(){return this.getFinalMatrix()}returnToRest(){var e;if(this._linkedTransformNode){let t=$.Vector3[0],i=$.Quaternion[0],r=$.Vector3[1];this.getRestMatrix().decompose(t,i,r),this._linkedTransformNode.position.copyFrom(r),this._linkedTransformNode.rotationQuaternion=(e=this._linkedTransformNode.rotationQuaternion)!=null?e:Xe.Identity(),this._linkedTransformNode.rotationQuaternion.copyFrom(i),this._linkedTransformNode.scaling.copyFrom(t)}else this._matrix=this._restMatrix}getAbsoluteInverseBindMatrix(){return this._absoluteInverseBindMatrix}getInvertedAbsoluteTransform(){return this.getAbsoluteInverseBindMatrix()}getAbsoluteMatrix(){return this._skeleton.computeAbsoluteMatrices(),this._absoluteMatrix}getAbsoluteTransform(){return this.getAbsoluteMatrix()}linkTransformNode(e){this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode--,this._linkedTransformNode=e,this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode++}getTransformNode(){return this._linkedTransformNode}get position(){return this._decompose(),this._localPosition}set position(e){this._decompose(),this._localPosition.copyFrom(e),this._markAsDirtyAndCompose()}get rotation(){return this.getRotation()}set rotation(e){this.setRotation(e)}get rotationQuaternion(){return this._decompose(),this._localRotation}set rotationQuaternion(e){this.setRotationQuaternion(e)}get scaling(){return this.getScale()}set scaling(e){this.setScale(e)}get animationPropertiesOverride(){return this._skeleton.animationPropertiesOverride}_decompose(){this._needToDecompose&&(this._needToDecompose=!1,this._localScaling||(this._localScaling=b.Zero(),this._localRotation=Xe.Zero(),this._localPosition=b.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))}_compose(){if(this._needToCompose){if(!this._localScaling){this._needToCompose=!1;return}this._needToCompose=!1,K.ComposeToRef(this._localScaling,this._localRotation,this._localPosition,this._localMatrix)}}updateMatrix(e,t=!0,i=!0){this._bindMatrix.copyFrom(e),t&&this._updateAbsoluteBindMatrices(),i?this._matrix=e:this.markAsDirty()}_updateAbsoluteBindMatrices(e,t=!0){if(e||(e=this._bindMatrix),this.parent?e.multiplyToRef(this.parent._absoluteBindMatrix,this._absoluteBindMatrix):this._absoluteBindMatrix.copyFrom(e),this._absoluteBindMatrix.invertToRef(this._absoluteInverseBindMatrix),t)for(let i=0;i{Fr();Gg=class n extends ge{constructor(e,t,i,r,s,a=!0,o=!1,l=3,c=0,f,h,d,u){super(null,s,!a,o,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,f),this.format=r,this._engine&&(!this._engine._caps.textureFloatLinearFiltering&&c===1&&(l=1),!this._engine._caps.textureHalfFloatLinearFiltering&&c===2&&(l=1),this._texture=this._engine.createRawTexture(e,t,i,r,a,o,l,null,c,f!=null?f:0,h!=null?h:!1,u),this.wrapU=ge.CLAMP_ADDRESSMODE,this.wrapV=ge.CLAMP_ADDRESSMODE,this._waitingForData=!!d&&!e)}update(e){this.updateMipLevel(e,0)}updateMipLevel(e,t){this._getEngine().updateRawTexture(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type,this._texture._useSRGBBuffer,t),this._waitingForData=!1}clone(){if(!this._texture)return super.clone();let e=new n(null,this.getSize().width,this.getSize().height,this.format,this.getScene(),this._texture.generateMipMaps,this._invertY,this.samplingMode,this._texture.type,this._texture._creationFlags,this._useSRGBBuffer);return e._texture=this._texture,this._texture.incrementReferences(),e}isReady(){return super.isReady()&&!this._waitingForData}static CreateLuminanceTexture(e,t,i,r,s=!0,a=!1,o=3){return new n(e,t,i,1,r,s,a,o)}static CreateLuminanceAlphaTexture(e,t,i,r,s=!0,a=!1,o=3){return new n(e,t,i,2,r,s,a,o)}static CreateAlphaTexture(e,t,i,r,s=!0,a=!1,o=3){return new n(e,t,i,0,r,s,a,o)}static CreateRGBTexture(e,t,i,r,s=!0,a=!1,o=3,l=0,c=0,f=!1){return new n(e,t,i,4,r,s,a,o,l,c,f)}static CreateRGBATexture(e,t,i,r,s=!0,a=!1,o=3,l=0,c=0,f=!1,h=!1){return new n(e,t,i,5,r,s,a,o,l,c,f,h)}static CreateRGBAStorageTexture(e,t,i,r,s=!0,a=!1,o=3,l=0,c=!1){return new n(e,t,i,5,r,s,a,o,l,1,c)}static CreateRTexture(e,t,i,r,s=!0,a=!1,o=ge.TRILINEAR_SAMPLINGMODE,l=1){return new n(e,t,i,6,r,s,a,o,l)}static CreateRStorageTexture(e,t,i,r,s=!0,a=!1,o=ge.TRILINEAR_SAMPLINGMODE,l=1){return new n(e,t,i,6,r,s,a,o,l,1)}}});var uR,KX=C(()=>{dR();di();Ge();YX();If();My();Di();Pt();W_();uR=class n{get useTextureToStoreBoneMatrices(){return this._useTextureToStoreBoneMatrices}set useTextureToStoreBoneMatrices(e){this._useTextureToStoreBoneMatrices=e,this._markAsDirty()}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}get isUsingTextureForMatrices(){return this.useTextureToStoreBoneMatrices&&this._canUseTextureForBones}get uniqueId(){return this._uniqueId}constructor(e,t,i){this.name=e,this.id=t,this.bones=[],this.needInitialSkinMatrix=!1,this._isDirty=!0,this._meshesWithPoseMatrix=new Array,this._identity=K.Identity(),this._currentRenderId=-1,this._textureWidth=0,this._textureHeight=1,this._ranges={},this._absoluteTransformIsDirty=!0,this._canUseTextureForBones=!1,this._uniqueId=0,this._numBonesWithLinkedTransformNode=0,this._hasWaitingData=null,this._parentContainer=null,this.doNotSerialize=!1,this._useTextureToStoreBoneMatrices=!0,this._animationPropertiesOverride=null,this.onBeforeComputeObservable=new ie,this.metadata=null,this.bones=[],this._scene=i||Oe.LastCreatedScene,this._uniqueId=this._scene.getUniqueId(),this._scene.addSkeleton(this),this._isDirty=!0;let r=this._scene.getEngine().getCaps();this._canUseTextureForBones=r.textureFloat&&r.maxVertexTextureImageUnits>0}getClassName(){return"Skeleton"}getChildren(){return this.bones.filter(e=>!e.getParent())}getTransformMatrices(e){if(this.needInitialSkinMatrix){if(!e)throw new Error("getTransformMatrices: When using the needInitialSkinMatrix flag, a mesh must be provided");return e._bonesTransformMatrices||this.prepare(!0),e._bonesTransformMatrices}return(!this._transformMatrices||this._isDirty)&&this.prepare(!this._transformMatrices),this._transformMatrices}getTransformMatrixTexture(e){return this.needInitialSkinMatrix&&e._transformMatrixTexture?e._transformMatrixTexture:this._transformMatrixTexture}getScene(){return this._scene}toString(e){let t=`Name: ${this.name}, nBones: ${this.bones.length}`;if(t+=`, nAnimationRanges: ${this._ranges?Object.keys(this._ranges).length:"none"}`,e){t+=", Ranges: {";let i=!0;for(let r in this._ranges)i&&(t+=", ",i=!1),t+=r;t+="}"}return t}getBoneIndexByName(e){for(let t=0,i=this.bones.length;t-1&&this._meshesWithPoseMatrix.splice(t,1)}_computeTransformMatrices(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(let i=0;i0){for(let r of this.bones)if(r._linkedTransformNode){let s=r._linkedTransformNode;r.position=s.position,s.rotationQuaternion?r.rotationQuaternion=s.rotationQuaternion:r.rotation=s.rotation,r.scaling=s.scaling}}let t=null;if(this.needInitialSkinMatrix)for(let r of this._meshesWithPoseMatrix){let s=r.getPoseMatrix(),a=this._isDirty;if(t===null&&(t=this._computeTextureSize()),(!r._bonesTransformMatrices||r._bonesTransformMatrices.length!==t)&&(r._bonesTransformMatrices=new Float32Array(t),a=!0),!!a){if(this._synchronizedWithMesh!==r){this._synchronizedWithMesh=r;for(let o of this.bones)o.getParent()||(o.getBindMatrix().multiplyToRef(s,$.Matrix[1]),o._updateAbsoluteBindMatrices($.Matrix[1]));if(this.isUsingTextureForMatrices){let o=(i=r._transformMatrixTexture)==null?void 0:i.getSize(),l=o?o.width*o.height*4:0;(!r._transformMatrixTexture||l!==t)&&(r._transformMatrixTexture&&r._transformMatrixTexture.dispose(),r._transformMatrixTexture=Gg.CreateRGBATexture(r._bonesTransformMatrices,this._textureWidth,this._textureHeight,this._scene,!1,!1,1,1))}}this._computeTransformMatrices(r._bonesTransformMatrices,s),this.isUsingTextureForMatrices&&r._transformMatrixTexture&&r._transformMatrixTexture.update(r._bonesTransformMatrices)}}else{if(!this._isDirty)return;t===null&&(t=this._computeTextureSize()),(!this._transformMatrices||this._transformMatrices.length!==t)&&(this._transformMatrices=new Float32Array(t),this.isUsingTextureForMatrices&&(this._transformMatrixTexture&&this._transformMatrixTexture.dispose(),this._transformMatrixTexture=Gg.CreateRGBATexture(this._transformMatrices,this._textureWidth,this._textureHeight,this._scene,!1,!1,1,1))),this._computeTransformMatrices(this._transformMatrices,null),this.isUsingTextureForMatrices&&this._transformMatrixTexture&&this._transformMatrixTexture.update(this._transformMatrices)}this._isDirty=!1}getAnimatables(){if(!this._animatables||this._animatables.length!==this.bones.length){this._animatables=[];for(let e=0;e-1&&this._parentContainer.skeletons.splice(e,1),this._parentContainer=null}this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null)}serialize(){var t,i;let e={};e.name=this.name,e.id=this.id,e.uniqueId=this.uniqueId,this.dimensionsAtRest&&(e.dimensionsAtRest=this.dimensionsAtRest.asArray()),e.bones=[],e.needInitialSkinMatrix=this.needInitialSkinMatrix,this.metadata&&(e.metadata=this.metadata);for(let r=0;r0&&(o.animation=s.animations[0].serialize()),e.ranges=[];for(let l in this._ranges){let c=this._ranges[l];if(!c)continue;let f={};f.name=l,f.from=c.from,f.to=c.to,e.ranges.push(f)}}return e}static Parse(e,t){let i=new n(e.name,e.id,t);e.dimensionsAtRest&&(i.dimensionsAtRest=b.FromArray(e.dimensionsAtRest)),i.needInitialSkinMatrix=e.needInitialSkinMatrix,e.metadata&&(i.metadata=e.metadata);let r;for(r=0;r-1&&(o=i.bones[s.parentBoneIndex]);let l=s.rest?K.FromArray(s.rest):null,c=new wa(s.name,i,o,K.FromArray(s.matrix),l,null,a);s.id!==void 0&&s.id!==null&&(c.id=s.id),s.length&&(c.length=s.length),s.metadata&&(c.metadata=s.metadata),s.animation&&c.animations.push(ht.Parse(s.animation)),s.linkedTransformNodeId!==void 0&&s.linkedTransformNodeId!==null&&(i._hasWaitingData=!0,c._waitingTransformNodeId=s.linkedTransformNodeId),s.linkedTransformNodeUniqueId!==void 0&&s.linkedTransformNodeUniqueId!==null&&(i._hasWaitingData=!0,c._waitingTransformNodeUniqueId=s.linkedTransformNodeUniqueId)}if(e.ranges)for(r=0;r0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e}sortBones(){let e=[],t=new Array(this.bones.length);for(let i=0;i{Gt();di();Di();ki();Vt();Tr();Hi();jf=class n{get influence(){return this._influence}set influence(e){if(this._influence===e)return;let t=this._influence;this._influence=e,this.onInfluenceChanged.hasObservers()&&this.onInfluenceChanged.notifyObservers(t===0||e===0)}get animationPropertiesOverride(){return!this._animationPropertiesOverride&&this._scene?this._scene.animationPropertiesOverride:this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}constructor(e,t=0,i=null,r=null){this.name=e,this.animations=[],this._positions=null,this._normals=null,this._tangents=null,this._uvs=null,this._uv2s=null,this._colors=null,this._uniqueId=0,this.onInfluenceChanged=new ie,this._onDataLayoutChanged=new ie,this.morphTargetManager=null,this._animationPropertiesOverride=null,this.id=e,this.morphTargetManager=r,this._scene=i||Oe.LastCreatedScene,this.influence=t,this._scene&&(this._uniqueId=this._scene.getUniqueId())}get uniqueId(){return this._uniqueId}get hasPositions(){return!!this._positions}get hasNormals(){return!!this._normals}get hasTangents(){return!!this._tangents}get hasUVs(){return!!this._uvs}get hasUV2s(){return!!this._uv2s}get hasColors(){return!!this._colors}get vertexCount(){return this._positions?this._positions.length/3:this._normals?this._normals.length/3:this._tangents?this._tangents.length/3:this._uvs?this._uvs.length/2:this._uv2s?this._uv2s.length/2:this._colors?this._colors.length/4:0}setPositions(e){let t=this.hasPositions;this._positions=e,t!==this.hasPositions&&this._onDataLayoutChanged.notifyObservers(void 0)}getPositions(){return this._positions}setNormals(e){let t=this.hasNormals;this._normals=e,t!==this.hasNormals&&this._onDataLayoutChanged.notifyObservers(void 0)}getNormals(){return this._normals}setTangents(e){let t=this.hasTangents;this._tangents=e,t!==this.hasTangents&&this._onDataLayoutChanged.notifyObservers(void 0)}getTangents(){return this._tangents}setUVs(e){let t=this.hasUVs;this._uvs=e,t!==this.hasUVs&&this._onDataLayoutChanged.notifyObservers(void 0)}getUVs(){return this._uvs}setUV2s(e){let t=this.hasUV2s;this._uv2s=e,t!==this.hasUV2s&&this._onDataLayoutChanged.notifyObservers(void 0)}getUV2s(){return this._uv2s}setColors(e){let t=this.hasColors;this._colors=e,t!==this.hasColors&&this._onDataLayoutChanged.notifyObservers(void 0)}getColors(){return this._colors}clone(){let e=it.Clone(()=>new n(this.name,this.influence,this._scene,this.morphTargetManager),this);return e._positions=this._positions,e._normals=this._normals,e._tangents=this._tangents,e._uvs=this._uvs,e._uv2s=this._uv2s,e._colors=this._colors,e}serialize(){let e={};return e.name=this.name,e.influence=this.influence,this.id!=null&&(e.id=this.id),e.uniqueId=this.uniqueId,e.positions=Array.prototype.slice.call(this.getPositions()),this.hasNormals&&(e.normals=Array.prototype.slice.call(this.getNormals())),this.hasTangents&&(e.tangents=Array.prototype.slice.call(this.getTangents())),this.hasUVs&&(e.uvs=Array.prototype.slice.call(this.getUVs())),this.hasUV2s&&(e.uv2s=Array.prototype.slice.call(this.getUV2s())),this.hasColors&&(e.colors=Array.prototype.slice.call(this.getColors())),it.AppendSerializedAnimations(this,e),e}getClassName(){return"MorphTarget"}static Parse(e,t,i=null){let r=new n(e.name,e.influence,t,i);if(r.setPositions(e.positions),e.id!=null&&(r.id=e.id),e.normals&&r.setNormals(e.normals),e.tangents&&r.setTangents(e.tangents),e.uvs&&r.setUVs(e.uvs),e.uv2s&&r.setUV2s(e.uv2s),e.colors&&r.setColors(e.colors),e.animations){for(let s=0;s{Fr();mR=class n extends ge{get depth(){return this._depth}constructor(e,t,i,r,s,a,o=!0,l=!1,c=ge.TRILINEAR_SAMPLINGMODE,f=0,h,d){super(null,a,!o,l),this.format=s,this._texture=a.getEngine().createRawTexture2DArray(e,t,i,r,s,o,l,c,null,f,h!=null?h:0,d),this._depth=r,this.is2DArray=!0}update(e){this.updateMipLevel(e,0)}updateMipLevel(e,t){this._texture&&this._getEngine().updateRawTexture2DArray(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type,t)}static CreateRGBATexture(e,t,i,r,s,a=!0,o=!1,l=3,c=0){return new n(e,t,i,r,5,s,a,o,l,c)}}});var dd,qX=C(()=>{so();Pt();Di();BD();jX();dd=class n{set areUpdatesFrozen(e){e?this._blockCounter++:(this._blockCounter--,this._blockCounter<=0&&(this._blockCounter=0,this._syncActiveTargets(this._forceUpdateWhenUnfrozen),this._forceUpdateWhenUnfrozen=!1))}get areUpdatesFrozen(){return this._blockCounter>0}constructor(e=null,t){if(this.meshName=t,this._targets=new Array,this._targetInfluenceChangedObservers=new Array,this._targetDataLayoutChangedObservers=new Array,this._activeTargets=new Bi(16),this._supportsPositions=!1,this._supportsNormals=!1,this._supportsTangents=!1,this._supportsUVs=!1,this._supportsUV2s=!1,this._supportsColors=!1,this._vertexCount=0,this._uniqueId=0,this._tempInfluences=new Array,this._canUseTextureForTargets=!1,this._blockCounter=0,this._mustSynchronize=!0,this._forceUpdateWhenUnfrozen=!1,this._textureVertexStride=0,this._textureWidth=0,this._textureHeight=1,this._parentContainer=null,this.optimizeInfluencers=!0,this.enablePositionMorphing=!0,this.enableNormalMorphing=!0,this.enableTangentMorphing=!0,this.enableUVMorphing=!0,this.enableUV2Morphing=!0,this.enableColorMorphing=!0,this._numMaxInfluencers=0,this._useTextureToStoreTargets=!0,this.metadata=null,this._influencesAreDirty=!1,this._needUpdateInfluences=!1,e||(e=Oe.LastCreatedScene),this._scene=e,this._scene){this._scene.addMorphTargetManager(this),this._uniqueId=this._scene.getUniqueId();let i=this._scene.getEngine().getCaps();this._canUseTextureForTargets=i.canUseGLVertexID&&i.textureFloat&&i.maxVertexTextureImageUnits>0&&i.texture2DArrayMaxLayerCount>1}}get numMaxInfluencers(){return n.ConstantTargetCountForTextureMode>0&&this.isUsingTextureForTargets?n.ConstantTargetCountForTextureMode:this._numMaxInfluencers}set numMaxInfluencers(e){this._numMaxInfluencers!==e&&(this._numMaxInfluencers=e,this._mustSynchronize=!0,this._syncActiveTargets())}get uniqueId(){return this._uniqueId}get vertexCount(){return this._vertexCount}get supportsPositions(){return this._supportsPositions&&this.enablePositionMorphing}get supportsNormals(){return this._supportsNormals&&this.enableNormalMorphing}get supportsTangents(){return this._supportsTangents&&this.enableTangentMorphing}get supportsUVs(){return this._supportsUVs&&this.enableUVMorphing}get supportsUV2s(){return this._supportsUV2s&&this.enableUV2Morphing}get supportsColors(){return this._supportsColors&&this.enableColorMorphing}get hasPositions(){return this._supportsPositions}get hasNormals(){return this._supportsNormals}get hasTangents(){return this._supportsTangents}get hasUVs(){return this._supportsUVs}get hasUV2s(){return this._supportsUV2s}get hasColors(){return this._supportsColors}get numTargets(){return this._targets.length}get numInfluencers(){return this._influencesAreDirty&&this._syncActiveTargets(),this._activeTargets.length}get influences(){return this._influencesAreDirty&&this._syncActiveTargets(),this._influences}get useTextureToStoreTargets(){return this._useTextureToStoreTargets}set useTextureToStoreTargets(e){this._useTextureToStoreTargets!==e&&(this._useTextureToStoreTargets=e,this._mustSynchronize=!0,this._syncActiveTargets())}get isUsingTextureForTargets(){var e;return n.EnableTextureStorage&&this.useTextureToStoreTargets&&this._canUseTextureForTargets&&!((e=this._scene)!=null&&e.getEngine().getCaps().disableMorphTargetTexture)}getActiveTarget(e){return this._influencesAreDirty&&this._syncActiveTargets(),this._activeTargets.data[e]}getTarget(e){return this._targets[e]}getTargetByName(e){for(let t of this._targets)if(t.name===e)return t;return null}addTarget(e){this._targets.push(e),this._targetInfluenceChangedObservers.push(e.onInfluenceChanged.add(t=>{this.areUpdatesFrozen&&t&&(this._forceUpdateWhenUnfrozen=!0),this._influencesAreDirty=!0,this._needUpdateInfluences=this._needUpdateInfluences||t})),this._targetDataLayoutChangedObservers.push(e._onDataLayoutChanged.add(()=>{this._mustSynchronize=!0,this._syncActiveTargets()})),this._mustSynchronize=!0,this._syncActiveTargets()}removeTarget(e){let t=this._targets.indexOf(e);t>=0&&(this._targets.splice(t,1),e.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(t,1)[0]),e._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(t,1)[0]),this._mustSynchronize=!0,this._syncActiveTargets()),this._scene&&this._scene.stopAnimation(e)}_bind(e){this._influencesAreDirty&&this._syncActiveTargets(),e.setFloat3("morphTargetTextureInfo",this._textureVertexStride,this._textureWidth,this._textureHeight),e.setFloatArray("morphTargetTextureIndices",this._morphTargetTextureIndices),e.setTexture("morphTargets",this._targetStoreTexture),e.setFloat("morphTargetCount",this.numInfluencers)}clone(){let e=new n(this._scene);e.areUpdatesFrozen=!0;for(let t of this._targets)e.addTarget(t.clone());return e.areUpdatesFrozen=!1,e.enablePositionMorphing=this.enablePositionMorphing,e.enableNormalMorphing=this.enableNormalMorphing,e.enableTangentMorphing=this.enableTangentMorphing,e.enableUVMorphing=this.enableUVMorphing,e.enableUV2Morphing=this.enableUV2Morphing,e.enableColorMorphing=this.enableColorMorphing,e.metadata=this.metadata,e}serialize(){let e={};e.id=this.uniqueId,e.meshName=this.meshName,e.targets=[];for(let t of this._targets)e.targets.push(t.serialize());return this.metadata&&(e.metadata=this.metadata),e}_syncActiveTargets(e=!1){if(this.areUpdatesFrozen)return;e=e||this._needUpdateInfluences,this._needUpdateInfluences=!1,this._influencesAreDirty=!1;let t=!!this._targetStoreTexture,i=this.isUsingTextureForTargets;(this._mustSynchronize||t!==i)&&(this._mustSynchronize=!1,this.synchronize());let r=0;this._activeTargets.reset(),(!this._morphTargetTextureIndices||this._morphTargetTextureIndices.length!==this._targets.length)&&(this._morphTargetTextureIndices=new Float32Array(this._targets.length));let s=-1;for(let a of this._targets)if(s++,!(a.influence===0&&this.optimizeInfluencers)){if(this._activeTargets.length>=n.MaxActiveMorphTargetsInVertexAttributeMode&&!this.isUsingTextureForTargets)break;this._activeTargets.push(a),this._morphTargetTextureIndices[r]=s,this._tempInfluences[r++]=a.influence}this._morphTargetTextureIndices.length!==r&&(this._morphTargetTextureIndices=this._morphTargetTextureIndices.slice(0,r)),(!this._influences||this._influences.length!==r)&&(this._influences=new Float32Array(r));for(let a=0;ae.getCaps().texture2DArrayMaxLayerCount&&(this.useTextureToStoreTargets=!1);for(let i of this._targets){this._supportsPositions=this._supportsPositions&&i.hasPositions,this._supportsNormals=this._supportsNormals&&i.hasNormals,this._supportsTangents=this._supportsTangents&&i.hasTangents,this._supportsUVs=this._supportsUVs&&i.hasUVs,this._supportsUV2s=this._supportsUV2s&&i.hasUV2s,this._supportsColors=this._supportsColors&&i.hasColors;let r=i.vertexCount;if(this._vertexCount===0)this._vertexCount=r;else if(this._vertexCount!==r){te.Error(`Incompatible target. Targets must all have the same vertices count. Current vertex count: ${this._vertexCount}, vertex count for target "${i.name}": ${r}`);return}}if(this.isUsingTextureForTargets){this._textureVertexStride=0,this._supportsPositions&&this._textureVertexStride++,this._supportsNormals&&this._textureVertexStride++,this._supportsTangents&&this._textureVertexStride++,this._supportsUVs&&this._textureVertexStride++,this._supportsUV2s&&this._textureVertexStride++,this._supportsColors&&this._textureVertexStride++,this._textureWidth=this._vertexCount*this._textureVertexStride||1,this._textureHeight=1;let i=e.getCaps().maxTextureSize;this._textureWidth>i&&(this._textureHeight=Math.ceil(this._textureWidth/i),this._textureWidth=i);let r=this._targets.length,s=new Float32Array(r*this._textureWidth*this._textureHeight*4),a;for(let o=0;o-1&&this._parentContainer.morphTargetManagers.splice(e,1),this._parentContainer=null}for(let e of this._targets)this._scene.stopAnimation(e)}}static Parse(e,t){let i=new n(t);for(let r of e.targets)i.addTarget(jf.Parse(r,t,i));return e.metadata&&(i.metadata=e.metadata),i}};dd.EnableTextureStorage=!0;dd.MaxActiveMorphTargetsInVertexAttributeMode=8;dd.ConstantTargetCountForTextureMode=0});function pR(n,e,t){kg(n)&&te.Warn(`Extension with the name '${n}' already exists`),UD.set(n,{isGLTFExtension:e,factory:t})}function kg(n){return UD.delete(n)}var UD,ZX,VD=C(()=>{Pt();UD=new Map,ZX=UD});var W,GD=C(()=>{W=class{};W.AUTOSAMPLERSUFFIX="Sampler";W.DISABLEUA="#define DISABLE_UNIFORMITY_ANALYSIS";W.ALPHA_DISABLE=0;W.ALPHA_ADD=1;W.ALPHA_COMBINE=2;W.ALPHA_SUBTRACT=3;W.ALPHA_MULTIPLY=4;W.ALPHA_MAXIMIZED=5;W.ALPHA_ONEONE=6;W.ALPHA_PREMULTIPLIED=7;W.ALPHA_PREMULTIPLIED_PORTERDUFF=8;W.ALPHA_INTERPOLATE=9;W.ALPHA_SCREENMODE=10;W.ALPHA_ONEONE_ONEONE=11;W.ALPHA_ALPHATOCOLOR=12;W.ALPHA_REVERSEONEMINUS=13;W.ALPHA_SRC_DSTONEMINUSSRCALPHA=14;W.ALPHA_ONEONE_ONEZERO=15;W.ALPHA_EXCLUSION=16;W.ALPHA_LAYER_ACCUMULATE=17;W.ALPHA_MIN=18;W.ALPHA_MAX=19;W.ALPHA_DUAL_SRC0_ADD_SRC1xDST=20;W.ALPHA_EQUATION_ADD=0;W.ALPHA_EQUATION_SUBSTRACT=1;W.ALPHA_EQUATION_REVERSE_SUBTRACT=2;W.ALPHA_EQUATION_MAX=3;W.ALPHA_EQUATION_MIN=4;W.ALPHA_EQUATION_DARKEN=5;W.DELAYLOADSTATE_NONE=0;W.DELAYLOADSTATE_LOADED=1;W.DELAYLOADSTATE_LOADING=2;W.DELAYLOADSTATE_NOTLOADED=4;W.NEVER=512;W.ALWAYS=519;W.LESS=513;W.EQUAL=514;W.LEQUAL=515;W.GREATER=516;W.GEQUAL=518;W.NOTEQUAL=517;W.KEEP=7680;W.ZERO=0;W.REPLACE=7681;W.INCR=7682;W.DECR=7683;W.INVERT=5386;W.INCR_WRAP=34055;W.DECR_WRAP=34056;W.TEXTURE_CLAMP_ADDRESSMODE=0;W.TEXTURE_WRAP_ADDRESSMODE=1;W.TEXTURE_MIRROR_ADDRESSMODE=2;W.TEXTURE_CREATIONFLAG_STORAGE=1;W.TEXTUREFORMAT_ALPHA=0;W.TEXTUREFORMAT_LUMINANCE=1;W.TEXTUREFORMAT_LUMINANCE_ALPHA=2;W.TEXTUREFORMAT_RGB=4;W.TEXTUREFORMAT_RGBA=5;W.TEXTUREFORMAT_RED=6;W.TEXTUREFORMAT_R=6;W.TEXTUREFORMAT_R16_UNORM=33322;W.TEXTUREFORMAT_RG16_UNORM=33324;W.TEXTUREFORMAT_RGB16_UNORM=32852;W.TEXTUREFORMAT_RGBA16_UNORM=32859;W.TEXTUREFORMAT_R16_SNORM=36760;W.TEXTUREFORMAT_RG16_SNORM=36761;W.TEXTUREFORMAT_RGB16_SNORM=36762;W.TEXTUREFORMAT_RGBA16_SNORM=36763;W.TEXTUREFORMAT_RG=7;W.TEXTUREFORMAT_RED_INTEGER=8;W.TEXTUREFORMAT_R_INTEGER=8;W.TEXTUREFORMAT_RG_INTEGER=9;W.TEXTUREFORMAT_RGB_INTEGER=10;W.TEXTUREFORMAT_RGBA_INTEGER=11;W.TEXTUREFORMAT_BGRA=12;W.TEXTUREFORMAT_DEPTH24_STENCIL8=13;W.TEXTUREFORMAT_DEPTH32_FLOAT=14;W.TEXTUREFORMAT_DEPTH16=15;W.TEXTUREFORMAT_DEPTH24=16;W.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8=17;W.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8=18;W.TEXTUREFORMAT_STENCIL8=19;W.TEXTUREFORMAT_UNDEFINED=4294967295;W.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM=36492;W.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM=36493;W.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT=36495;W.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT=36494;W.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5=33779;W.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919;W.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3=33778;W.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918;W.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1=33777;W.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1=33776;W.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917;W.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT=35916;W.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4=37808;W.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_5x4=37809;W.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_5x5=37810;W.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_6x5=37811;W.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_6x6=37812;W.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_8x5=37813;W.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_8x6=37814;W.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_8x8=37815;W.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_10x5=37816;W.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_10x6=37817;W.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_10x8=37818;W.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_10x10=37819;W.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_12x10=37820;W.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_12x12=37821;W.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=37840;W.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR=37841;W.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR=37842;W.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR=37843;W.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR=37844;W.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR=37845;W.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR=37846;W.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR=37847;W.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR=37848;W.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR=37849;W.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR=37850;W.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR=37851;W.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR=37852;W.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR=37853;W.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL=36196;W.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2=37492;W.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2=37493;W.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=37494;W.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=37495;W.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC=37496;W.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=37497;W.TEXTURETYPE_UNSIGNED_BYTE=0;W.TEXTURETYPE_UNSIGNED_INT=0;W.TEXTURETYPE_FLOAT=1;W.TEXTURETYPE_HALF_FLOAT=2;W.TEXTURETYPE_BYTE=3;W.TEXTURETYPE_SHORT=4;W.TEXTURETYPE_UNSIGNED_SHORT=5;W.TEXTURETYPE_INT=6;W.TEXTURETYPE_UNSIGNED_INTEGER=7;W.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8;W.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9;W.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10;W.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11;W.TEXTURETYPE_UNSIGNED_INT_24_8=12;W.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13;W.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14;W.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15;W.TEXTURETYPE_UNDEFINED=16;W.TEXTURE_2D=3553;W.TEXTURE_2D_ARRAY=35866;W.TEXTURE_CUBE_MAP=34067;W.TEXTURE_CUBE_MAP_ARRAY=3735928559;W.TEXTURE_3D=32879;W.TEXTURE_NEAREST_SAMPLINGMODE=1;W.TEXTURE_NEAREST_NEAREST=1;W.TEXTURE_BILINEAR_SAMPLINGMODE=2;W.TEXTURE_LINEAR_LINEAR=2;W.TEXTURE_TRILINEAR_SAMPLINGMODE=3;W.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3;W.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4;W.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5;W.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6;W.TEXTURE_NEAREST_LINEAR=7;W.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8;W.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9;W.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10;W.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11;W.TEXTURE_LINEAR_NEAREST=12;W.TEXTURE_EXPLICIT_MODE=0;W.TEXTURE_SPHERICAL_MODE=1;W.TEXTURE_PLANAR_MODE=2;W.TEXTURE_CUBIC_MODE=3;W.TEXTURE_PROJECTION_MODE=4;W.TEXTURE_SKYBOX_MODE=5;W.TEXTURE_INVCUBIC_MODE=6;W.TEXTURE_EQUIRECTANGULAR_MODE=7;W.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8;W.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9;W.TEXTURE_FILTERING_QUALITY_OFFLINE=4096;W.TEXTURE_FILTERING_QUALITY_HIGH=64;W.TEXTURE_FILTERING_QUALITY_MEDIUM=16;W.TEXTURE_FILTERING_QUALITY_LOW=8;W.SCALEMODE_FLOOR=1;W.SCALEMODE_NEAREST=2;W.SCALEMODE_CEILING=3;W.MATERIAL_TextureDirtyFlag=1;W.MATERIAL_LightDirtyFlag=2;W.MATERIAL_FresnelDirtyFlag=4;W.MATERIAL_AttributesDirtyFlag=8;W.MATERIAL_MiscDirtyFlag=16;W.MATERIAL_PrePassDirtyFlag=32;W.MATERIAL_ImageProcessingDirtyFlag=64;W.MATERIAL_AllDirtyFlag=127;W.MATERIAL_TriangleFillMode=0;W.MATERIAL_WireFrameFillMode=1;W.MATERIAL_PointFillMode=2;W.MATERIAL_PointListDrawMode=3;W.MATERIAL_LineListDrawMode=4;W.MATERIAL_LineLoopDrawMode=5;W.MATERIAL_LineStripDrawMode=6;W.MATERIAL_TriangleStripDrawMode=7;W.MATERIAL_TriangleFanDrawMode=8;W.MATERIAL_ClockWiseSideOrientation=0;W.MATERIAL_CounterClockWiseSideOrientation=1;W.MATERIAL_DIFFUSE_MODEL_E_OREN_NAYAR=0;W.MATERIAL_DIFFUSE_MODEL_BURLEY=1;W.MATERIAL_DIFFUSE_MODEL_LAMBERT=2;W.MATERIAL_DIFFUSE_MODEL_LEGACY=3;W.MATERIAL_DIELECTRIC_SPECULAR_MODEL_GLTF=0;W.MATERIAL_DIELECTRIC_SPECULAR_MODEL_OPENPBR=1;W.MATERIAL_CONDUCTOR_SPECULAR_MODEL_GLTF=0;W.MATERIAL_CONDUCTOR_SPECULAR_MODEL_OPENPBR=1;W.ACTION_NothingTrigger=0;W.ACTION_OnPickTrigger=1;W.ACTION_OnLeftPickTrigger=2;W.ACTION_OnRightPickTrigger=3;W.ACTION_OnCenterPickTrigger=4;W.ACTION_OnPickDownTrigger=5;W.ACTION_OnDoublePickTrigger=6;W.ACTION_OnPickUpTrigger=7;W.ACTION_OnPickOutTrigger=16;W.ACTION_OnLongPressTrigger=8;W.ACTION_OnPointerOverTrigger=9;W.ACTION_OnPointerOutTrigger=10;W.ACTION_OnEveryFrameTrigger=11;W.ACTION_OnIntersectionEnterTrigger=12;W.ACTION_OnIntersectionExitTrigger=13;W.ACTION_OnKeyDownTrigger=14;W.ACTION_OnKeyUpTrigger=15;W.PARTICLES_BILLBOARDMODE_Y=2;W.PARTICLES_BILLBOARDMODE_ALL=7;W.PARTICLES_BILLBOARDMODE_STRETCHED=8;W.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL=9;W.MESHES_CULLINGSTRATEGY_STANDARD=0;W.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1;W.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2;W.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3;W.SCENELOADER_NO_LOGGING=0;W.SCENELOADER_MINIMAL_LOGGING=1;W.SCENELOADER_SUMMARY_LOGGING=2;W.SCENELOADER_DETAILED_LOGGING=3;W.PREPASS_IRRADIANCE_LEGACY_TEXTURE_TYPE=0;W.PREPASS_POSITION_TEXTURE_TYPE=1;W.PREPASS_VELOCITY_TEXTURE_TYPE=2;W.PREPASS_REFLECTIVITY_TEXTURE_TYPE=3;W.PREPASS_COLOR_TEXTURE_TYPE=4;W.PREPASS_DEPTH_TEXTURE_TYPE=5;W.PREPASS_NORMAL_TEXTURE_TYPE=6;W.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE=7;W.PREPASS_WORLD_NORMAL_TEXTURE_TYPE=8;W.PREPASS_LOCAL_POSITION_TEXTURE_TYPE=9;W.PREPASS_SCREENSPACE_DEPTH_TEXTURE_TYPE=10;W.PREPASS_VELOCITY_LINEAR_TEXTURE_TYPE=11;W.PREPASS_ALBEDO_TEXTURE_TYPE=12;W.PREPASS_NORMALIZED_VIEW_DEPTH_TEXTURE_TYPE=13;W.PREPASS_IRRADIANCE_TEXTURE_TYPE=14;W.BUFFER_CREATIONFLAG_READ=1;W.BUFFER_CREATIONFLAG_WRITE=2;W.BUFFER_CREATIONFLAG_READWRITE=3;W.BUFFER_CREATIONFLAG_UNIFORM=4;W.BUFFER_CREATIONFLAG_VERTEX=8;W.BUFFER_CREATIONFLAG_INDEX=16;W.BUFFER_CREATIONFLAG_STORAGE=32;W.BUFFER_CREATIONFLAG_INDIRECT=64;W.RENDERPASS_MAIN=0;W.INPUT_ALT_KEY=18;W.INPUT_CTRL_KEY=17;W.INPUT_META_KEY1=91;W.INPUT_META_KEY2=92;W.INPUT_META_KEY3=93;W.INPUT_SHIFT_KEY=16;W.SNAPSHOTRENDERING_STANDARD=0;W.SNAPSHOTRENDERING_FAST=1;W.PERSPECTIVE_CAMERA=0;W.ORTHOGRAPHIC_CAMERA=1;W.FOVMODE_VERTICAL_FIXED=0;W.FOVMODE_HORIZONTAL_FIXED=1;W.RIG_MODE_NONE=0;W.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10;W.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11;W.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12;W.RIG_MODE_STEREOSCOPIC_OVERUNDER=13;W.RIG_MODE_STEREOSCOPIC_INTERLACED=14;W.RIG_MODE_VR=20;W.RIG_MODE_CUSTOM=22;W.MAX_SUPPORTED_UV_SETS=6;W.GL_ALPHA_EQUATION_ADD=32774;W.GL_ALPHA_EQUATION_MIN=32775;W.GL_ALPHA_EQUATION_MAX=32776;W.GL_ALPHA_EQUATION_SUBTRACT=32778;W.GL_ALPHA_EQUATION_REVERSE_SUBTRACT=32779;W.GL_ALPHA_FUNCTION_SRC=768;W.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR=769;W.GL_ALPHA_FUNCTION_SRC_ALPHA=770;W.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA=771;W.GL_ALPHA_FUNCTION_DST_ALPHA=772;W.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA=773;W.GL_ALPHA_FUNCTION_DST_COLOR=774;W.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR=775;W.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED=776;W.GL_ALPHA_FUNCTION_CONSTANT_COLOR=32769;W.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR=32770;W.GL_ALPHA_FUNCTION_CONSTANT_ALPHA=32771;W.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA=32772;W.GL_ALPHA_FUNCTION_SRC1_COLOR=35065;W.GL_ALPHA_FUNCTION_ONE_MINUS_SRC1_COLOR=35066;W.GL_ALPHA_FUNCTION_SRC1_ALPHA=34185;W.GL_ALPHA_FUNCTION_ONE_MINUS_SRC1_ALPHA=35067;W.SnippetUrl="https://snippet.babylonjs.com";W.FOGMODE_NONE=0;W.FOGMODE_EXP=1;W.FOGMODE_EXP2=2;W.FOGMODE_LINEAR=3;W.BYTE=5120;W.UNSIGNED_BYTE=5121;W.SHORT=5122;W.UNSIGNED_SHORT=5123;W.INT=5124;W.UNSIGNED_INT=5125;W.FLOAT=5126;W.PositionKind="position";W.NormalKind="normal";W.TangentKind="tangent";W.UVKind="uv";W.UV2Kind="uv2";W.UV3Kind="uv3";W.UV4Kind="uv4";W.UV5Kind="uv5";W.UV6Kind="uv6";W.ColorKind="color";W.ColorInstanceKind="instanceColor";W.MatricesIndicesKind="matricesIndices";W.MatricesWeightsKind="matricesWeights";W.MatricesIndicesExtraKind="matricesIndicesExtra";W.MatricesWeightsExtraKind="matricesWeightsExtra";W.ANIMATIONTYPE_FLOAT=0;W.ANIMATIONTYPE_VECTOR3=1;W.ANIMATIONTYPE_QUATERNION=2;W.ANIMATIONTYPE_MATRIX=3;W.ANIMATIONTYPE_COLOR3=4;W.ANIMATIONTYPE_COLOR4=7;W.ANIMATIONTYPE_VECTOR2=5;W.ANIMATIONTYPE_SIZE=6;W.ShadowMinZ=0;W.ShadowMaxZ=1e4;W.OUTLINELAYER_SAMPLING_TRIDIRECTIONAL=0;W.OUTLINELAYER_SAMPLING_OCTADIRECTIONAL=1});var pKe,QX=C(()=>{pKe=[{regex:new RegExp("^/nodes/\\d+/extensions/")}]});function qf(n,e,t,i){let r=at(n,e);return i?r[t][i]:r[t]}function at(n,e,t){var i,r,s;return(s=(r=n._data)==null?void 0:r[(i=t==null?void 0:t.fillMode)!=null?i:W.MATERIAL_TriangleFillMode])==null?void 0:s.babylonMaterial}function nn(n,e){return{offset:{componentsCount:2,type:"Vector2",get:(t,i,r)=>{let s=qf(t,r,n,e);return new we(s==null?void 0:s.uOffset,s==null?void 0:s.vOffset)},getTarget:at,set:(t,i,r,s)=>{let a=qf(i,s,n,e);a.uOffset=t.x,a.vOffset=t.y},getPropertyName:[()=>`${n}${e?"."+e:""}.uOffset`,()=>`${n}${e?"."+e:""}.vOffset`]},rotation:{type:"number",get:(t,i,r)=>{var s;return(s=qf(t,r,n,e))==null?void 0:s.wAng},getTarget:at,set:(t,i,r,s)=>qf(i,s,n,e).wAng=t,getPropertyName:[()=>`${n}${e?"."+e:""}.wAng`]},scale:{componentsCount:2,type:"Vector2",get:(t,i,r)=>{let s=qf(t,r,n,e);return new we(s==null?void 0:s.uScale,s==null?void 0:s.vScale)},getTarget:at,set:(t,i,r,s)=>{let a=qf(i,s,n,e);a.uScale=t.x,a.vScale=t.y},getPropertyName:[()=>`${n}${e?"."+e:""}.uScale`,()=>`${n}${e?"."+e:""}.vScale`]}}}function Wg(n){let e=n.split("/").map(i=>i.replace(/{}/g,"__array__")),t=$X;for(let i of e)i&&(t=t[i]);if(t&&t.type&&t.get)return t}function Hg(n,e){let t=n.split("/").map(r=>r.replace(/{}/g,"__array__")),i=$X;for(let r of t)r&&(i=i[r]);i&&i.type&&i.get&&(i.interpolation=e)}var Tce,Ace,xce,Rce,bce,Ice,$X,kD=C(()=>{Ge();GD();zt();Fy();QX();Tce={length:{type:"number",get:n=>n.length,getTarget:n=>n.map(e=>e._babylonTransformNode),getPropertyName:[()=>"length"]},__array__:{__target__:!0,translation:{type:"Vector3",get:n=>{var e;return(e=n._babylonTransformNode)==null?void 0:e.position},set:(n,e)=>{var t;return(t=e._babylonTransformNode)==null?void 0:t.position.copyFrom(n)},getTarget:n=>n._babylonTransformNode,getPropertyName:[()=>"position"]},rotation:{type:"Quaternion",get:n=>{var e;return(e=n._babylonTransformNode)==null?void 0:e.rotationQuaternion},set:(n,e)=>{var t,i;return(i=(t=e._babylonTransformNode)==null?void 0:t.rotationQuaternion)==null?void 0:i.copyFrom(n)},getTarget:n=>n._babylonTransformNode,getPropertyName:[()=>"rotationQuaternion"]},scale:{type:"Vector3",get:n=>{var e;return(e=n._babylonTransformNode)==null?void 0:e.scaling},set:(n,e)=>{var t;return(t=e._babylonTransformNode)==null?void 0:t.scaling.copyFrom(n)},getTarget:n=>n._babylonTransformNode,getPropertyName:[()=>"scaling"]},weights:{length:{type:"number",get:n=>n._numMorphTargets,getTarget:n=>n._babylonTransformNode,getPropertyName:[()=>"influence"]},__array__:{__target__:!0,type:"number",get:(n,e)=>{var t,i;return e!==void 0?(i=(t=n._primitiveBabylonMeshes)==null?void 0:t[0].morphTargetManager)==null?void 0:i.getTarget(e).influence:void 0},getTarget:n=>n._babylonTransformNode,getPropertyName:[()=>"influence"]},type:"number[]",get:(n,e)=>[0],getTarget:n=>n._babylonTransformNode,getPropertyName:[()=>"influence"]},matrix:{type:"Matrix",get:n=>{var e,t,i;return K.Compose((e=n._babylonTransformNode)==null?void 0:e.scaling,(t=n._babylonTransformNode)==null?void 0:t.rotationQuaternion,(i=n._babylonTransformNode)==null?void 0:i.position)},getTarget:n=>n._babylonTransformNode,isReadOnly:!0},globalMatrix:{type:"Matrix",get:n=>{var r,s,a,o,l,c,f;let e=K.Identity(),t=n.parent;for(;t&&t.parent;)t=t.parent;let i=((r=n._babylonTransformNode)==null?void 0:r.position._isDirty)||((a=(s=n._babylonTransformNode)==null?void 0:s.rotationQuaternion)==null?void 0:a._isDirty)||((o=n._babylonTransformNode)==null?void 0:o.scaling._isDirty);if(t){let h=(l=t._babylonTransformNode)==null?void 0:l.computeWorldMatrix(!0).invert();h&&((f=(c=n._babylonTransformNode)==null?void 0:c.computeWorldMatrix(i))==null||f.multiplyToRef(h,e))}else n._babylonTransformNode&&e.copyFrom(n._babylonTransformNode.computeWorldMatrix(i));return e},getTarget:n=>n._babylonTransformNode,isReadOnly:!0},extensions:{EXT_lights_ies:{multiplier:{type:"number",get:n=>{var e,t;return(t=(e=n._babylonTransformNode)==null?void 0:e.getChildren(i=>i instanceof Ur,!0)[0])==null?void 0:t.intensity},getTarget:n=>{var e;return(e=n._babylonTransformNode)==null?void 0:e.getChildren(t=>t instanceof Ur,!0)[0]},set:(n,e)=>{if(e._babylonTransformNode){let t=e._babylonTransformNode.getChildren(i=>i instanceof Ur,!0)[0];t&&(t.intensity=n)}}},color:{type:"Color3",get:n=>{var e,t;return(t=(e=n._babylonTransformNode)==null?void 0:e.getChildren(i=>i instanceof Ur,!0)[0])==null?void 0:t.diffuse},getTarget:n=>{var e;return(e=n._babylonTransformNode)==null?void 0:e.getChildren(t=>t instanceof Ur,!0)[0]},set:(n,e)=>{if(e._babylonTransformNode){let t=e._babylonTransformNode.getChildren(i=>i instanceof Ur,!0)[0];t&&(t.diffuse=n)}}}},KHR_node_visibility:{visible:{type:"boolean",get:n=>n._primitiveBabylonMeshes?n._primitiveBabylonMeshes[0].isVisible:!1,getTarget:()=>{},set:(n,e)=>{e._primitiveBabylonMeshes&&e._primitiveBabylonMeshes.forEach(t=>t.isVisible=n)}}}}}},Ace={length:{type:"number",get:n=>n.length,getTarget:n=>n.map(e=>e._babylonAnimationGroup),getPropertyName:[()=>"length"]},__array__:{}},xce={length:{type:"number",get:n=>n.length,getTarget:n=>n.map(e=>{var t;return(t=e.primitives[0]._instanceData)==null?void 0:t.babylonSourceMesh}),getPropertyName:[()=>"length"]},__array__:{}},Rce={__array__:{__target__:!0,orthographic:{xmag:{componentsCount:2,type:"Vector2",get:n=>{var e,t,i,r;return new we((t=(e=n._babylonCamera)==null?void 0:e.orthoLeft)!=null?t:0,(r=(i=n._babylonCamera)==null?void 0:i.orthoRight)!=null?r:0)},set:(n,e)=>{e._babylonCamera&&(e._babylonCamera.orthoLeft=n.x,e._babylonCamera.orthoRight=n.y)},getTarget:n=>n,getPropertyName:[()=>"orthoLeft",()=>"orthoRight"]},ymag:{componentsCount:2,type:"Vector2",get:n=>{var e,t,i,r;return new we((t=(e=n._babylonCamera)==null?void 0:e.orthoBottom)!=null?t:0,(r=(i=n._babylonCamera)==null?void 0:i.orthoTop)!=null?r:0)},set:(n,e)=>{e._babylonCamera&&(e._babylonCamera.orthoBottom=n.x,e._babylonCamera.orthoTop=n.y)},getTarget:n=>n,getPropertyName:[()=>"orthoBottom",()=>"orthoTop"]},zfar:{type:"number",get:n=>{var e;return(e=n._babylonCamera)==null?void 0:e.maxZ},set:(n,e)=>{e._babylonCamera&&(e._babylonCamera.maxZ=n)},getTarget:n=>n,getPropertyName:[()=>"maxZ"]},znear:{type:"number",get:n=>{var e;return(e=n._babylonCamera)==null?void 0:e.minZ},set:(n,e)=>{e._babylonCamera&&(e._babylonCamera.minZ=n)},getTarget:n=>n,getPropertyName:[()=>"minZ"]}},perspective:{aspectRatio:{type:"number",get:n=>{var e;return(e=n._babylonCamera)==null?void 0:e.getEngine().getAspectRatio(n._babylonCamera)},getTarget:n=>n,getPropertyName:[()=>"aspectRatio"],isReadOnly:!0},yfov:{type:"number",get:n=>{var e;return(e=n._babylonCamera)==null?void 0:e.fov},set:(n,e)=>{e._babylonCamera&&(e._babylonCamera.fov=n)},getTarget:n=>n,getPropertyName:[()=>"fov"]},zfar:{type:"number",get:n=>{var e;return(e=n._babylonCamera)==null?void 0:e.maxZ},set:(n,e)=>{e._babylonCamera&&(e._babylonCamera.maxZ=n)},getTarget:n=>n,getPropertyName:[()=>"maxZ"]},znear:{type:"number",get:n=>{var e;return(e=n._babylonCamera)==null?void 0:e.minZ},set:(n,e)=>{e._babylonCamera&&(e._babylonCamera.minZ=n)},getTarget:n=>n,getPropertyName:[()=>"minZ"]}}}},bce={__array__:{__target__:!0,emissiveFactor:{type:"Color3",get:(n,e,t)=>at(n,e,t).emissiveColor,set:(n,e,t,i)=>at(e,t,i).emissiveColor.copyFrom(n),getTarget:(n,e,t)=>at(n,e,t),getPropertyName:[()=>"emissiveColor"]},emissiveTexture:{extensions:{KHR_texture_transform:nn("emissiveTexture")}},normalTexture:{scale:{type:"number",get:(n,e,t)=>{var i;return(i=qf(n,t,"bumpTexture"))==null?void 0:i.level},set:(n,e,t,i)=>{let r=qf(e,i,"bumpTexture");r&&(r.level=n)},getTarget:(n,e,t)=>at(n,e,t),getPropertyName:[()=>"level"]},extensions:{KHR_texture_transform:nn("bumpTexture")}},occlusionTexture:{strength:{type:"number",get:(n,e,t)=>at(n,e,t).ambientTextureStrength,set:(n,e,t,i)=>{let r=at(e,t,i);r&&(r.ambientTextureStrength=n)},getTarget:(n,e,t)=>at(n,e,t),getPropertyName:[()=>"ambientTextureStrength"]},extensions:{KHR_texture_transform:nn("ambientTexture")}},pbrMetallicRoughness:{baseColorFactor:{type:"Color4",get:(n,e,t)=>{let i=at(n,e,t);return lt.FromColor3(i.albedoColor,i.alpha)},set:(n,e,t,i)=>{let r=at(e,t,i);r.albedoColor.set(n.r,n.g,n.b),r.alpha=n.a},getTarget:(n,e,t)=>at(n,e,t),getPropertyName:[()=>"albedoColor",()=>"alpha"]},baseColorTexture:{extensions:{KHR_texture_transform:nn("albedoTexture")}},metallicFactor:{type:"number",get:(n,e,t)=>at(n,e,t).metallic,set:(n,e,t,i)=>{let r=at(e,t,i);r&&(r.metallic=n)},getTarget:(n,e,t)=>at(n,e,t),getPropertyName:[()=>"metallic"]},roughnessFactor:{type:"number",get:(n,e,t)=>at(n,e,t).roughness,set:(n,e,t,i)=>{let r=at(e,t,i);r&&(r.roughness=n)},getTarget:(n,e,t)=>at(n,e,t),getPropertyName:[()=>"roughness"]},metallicRoughnessTexture:{extensions:{KHR_texture_transform:nn("metallicTexture")}}},extensions:{KHR_materials_anisotropy:{anisotropyStrength:{type:"number",get:(n,e,t)=>at(n,e,t).anisotropy.intensity,set:(n,e,t,i)=>{at(e,t,i).anisotropy.intensity=n},getTarget:(n,e,t)=>at(n,e,t),getPropertyName:[()=>"anisotropy.intensity"]},anisotropyRotation:{type:"number",get:(n,e,t)=>at(n,e,t).anisotropy.angle,set:(n,e,t,i)=>{at(e,t,i).anisotropy.angle=n},getTarget:(n,e,t)=>at(n,e,t),getPropertyName:[()=>"anisotropy.angle"]},anisotropyTexture:{extensions:{KHR_texture_transform:nn("anisotropy","texture")}}},KHR_materials_clearcoat:{clearcoatFactor:{type:"number",get:(n,e,t)=>at(n,e,t).clearCoat.intensity,set:(n,e,t,i)=>{at(e,t,i).clearCoat.intensity=n},getTarget:(n,e,t)=>at(n,e,t),getPropertyName:[()=>"clearCoat.intensity"]},clearcoatRoughnessFactor:{type:"number",get:(n,e,t)=>at(n,e,t).clearCoat.roughness,set:(n,e,t,i)=>{at(e,t,i).clearCoat.roughness=n},getTarget:(n,e,t)=>at(n,e,t),getPropertyName:[()=>"clearCoat.roughness"]},clearcoatTexture:{extensions:{KHR_texture_transform:nn("clearCoat","texture")}},clearcoatNormalTexture:{scale:{type:"number",get:(n,e,t)=>{var i;return(i=at(n,e,t).clearCoat.bumpTexture)==null?void 0:i.level},getTarget:at,set:(n,e,t,i)=>at(e,t,i).clearCoat.bumpTexture.level=n},extensions:{KHR_texture_transform:nn("clearCoat","bumpTexture")}},clearcoatRoughnessTexture:{extensions:{KHR_texture_transform:nn("clearCoat","textureRoughness")}}},KHR_materials_dispersion:{dispersion:{type:"number",get:(n,e,t)=>at(n,e,t).subSurface.dispersion,getTarget:at,set:(n,e,t,i)=>at(e,t,i).subSurface.dispersion=n}},KHR_materials_emissive_strength:{emissiveStrength:{type:"number",get:(n,e,t)=>at(n,e,t).emissiveIntensity,getTarget:at,set:(n,e,t,i)=>at(e,t,i).emissiveIntensity=n}},KHR_materials_ior:{ior:{type:"number",get:(n,e,t)=>at(n,e,t).indexOfRefraction,getTarget:at,set:(n,e,t,i)=>at(e,t,i).indexOfRefraction=n}},KHR_materials_iridescence:{iridescenceFactor:{type:"number",get:(n,e,t)=>at(n,e,t).iridescence.intensity,getTarget:at,set:(n,e,t,i)=>at(e,t,i).iridescence.intensity=n},iridescenceIor:{type:"number",get:(n,e,t)=>at(n,e,t).iridescence.indexOfRefraction,getTarget:at,set:(n,e,t,i)=>at(e,t,i).iridescence.indexOfRefraction=n},iridescenceTexture:{extensions:{KHR_texture_transform:nn("iridescence","texture")}},iridescenceThicknessMaximum:{type:"number",get:(n,e,t)=>at(n,e,t).iridescence.maximumThickness,getTarget:at,set:(n,e,t,i)=>at(e,t,i).iridescence.maximumThickness=n},iridescenceThicknessMinimum:{type:"number",get:(n,e,t)=>at(n,e,t).iridescence.minimumThickness,getTarget:at,set:(n,e,t,i)=>at(e,t,i).iridescence.minimumThickness=n},iridescenceThicknessTexture:{extensions:{KHR_texture_transform:nn("iridescence","thicknessTexture")}}},KHR_materials_sheen:{sheenColorFactor:{type:"Color3",get:(n,e,t)=>at(n,e,t).sheen.color,getTarget:at,set:(n,e,t,i)=>at(e,t,i).sheen.color.copyFrom(n)},sheenColorTexture:{extensions:{KHR_texture_transform:nn("sheen","texture")}},sheenRoughnessFactor:{type:"number",get:(n,e,t)=>at(n,e,t).sheen.intensity,getTarget:at,set:(n,e,t,i)=>at(e,t,i).sheen.intensity=n},sheenRoughnessTexture:{extensions:{KHR_texture_transform:nn("sheen","thicknessTexture")}}},KHR_materials_specular:{specularFactor:{type:"number",get:(n,e,t)=>at(n,e,t).metallicF0Factor,getTarget:at,set:(n,e,t,i)=>at(e,t,i).metallicF0Factor=n,getPropertyName:[()=>"metallicF0Factor"]},specularColorFactor:{type:"Color3",get:(n,e,t)=>at(n,e,t).metallicReflectanceColor,getTarget:at,set:(n,e,t,i)=>at(e,t,i).metallicReflectanceColor.copyFrom(n),getPropertyName:[()=>"metallicReflectanceColor"]},specularTexture:{extensions:{KHR_texture_transform:nn("metallicReflectanceTexture")}},specularColorTexture:{extensions:{KHR_texture_transform:nn("reflectanceTexture")}}},KHR_materials_transmission:{transmissionFactor:{type:"number",get:(n,e,t)=>at(n,e,t).subSurface.refractionIntensity,getTarget:at,set:(n,e,t,i)=>at(e,t,i).subSurface.refractionIntensity=n,getPropertyName:[()=>"subSurface.refractionIntensity"]},transmissionTexture:{extensions:{KHR_texture_transform:nn("subSurface","refractionIntensityTexture")}}},KHR_materials_diffuse_transmission:{diffuseTransmissionFactor:{type:"number",get:(n,e,t)=>at(n,e,t).subSurface.translucencyIntensity,getTarget:at,set:(n,e,t,i)=>at(e,t,i).subSurface.translucencyIntensity=n},diffuseTransmissionTexture:{extensions:{KHR_texture_transform:nn("subSurface","translucencyIntensityTexture")}},diffuseTransmissionColorFactor:{type:"Color3",get:(n,e,t)=>at(n,e,t).subSurface.translucencyColor,getTarget:at,set:(n,e,t,i)=>{var r;return n&&((r=at(e,t,i).subSurface.translucencyColor)==null?void 0:r.copyFrom(n))}},diffuseTransmissionColorTexture:{extensions:{KHR_texture_transform:nn("subSurface","translucencyColorTexture")}}},KHR_materials_volume:{attenuationColor:{type:"Color3",get:(n,e,t)=>at(n,e,t).subSurface.tintColor,getTarget:at,set:(n,e,t,i)=>at(e,t,i).subSurface.tintColor.copyFrom(n)},attenuationDistance:{type:"number",get:(n,e,t)=>at(n,e,t).subSurface.tintColorAtDistance,getTarget:at,set:(n,e,t,i)=>at(e,t,i).subSurface.tintColorAtDistance=n},thicknessFactor:{type:"number",get:(n,e,t)=>at(n,e,t).subSurface.maximumThickness,getTarget:at,set:(n,e,t,i)=>at(e,t,i).subSurface.maximumThickness=n},thicknessTexture:{extensions:{KHR_texture_transform:nn("subSurface","thicknessTexture")}}}}}},Ice={KHR_lights_punctual:{lights:{length:{type:"number",get:n=>n.length,getTarget:n=>n.map(e=>e._babylonLight),getPropertyName:[n=>"length"]},__array__:{__target__:!0,color:{type:"Color3",get:n=>{var e;return(e=n._babylonLight)==null?void 0:e.diffuse},set:(n,e)=>{var t;return(t=e._babylonLight)==null?void 0:t.diffuse.copyFrom(n)},getTarget:n=>n._babylonLight,getPropertyName:[n=>"diffuse"]},intensity:{type:"number",get:n=>{var e;return(e=n._babylonLight)==null?void 0:e.intensity},set:(n,e)=>e._babylonLight?e._babylonLight.intensity=n:void 0,getTarget:n=>n._babylonLight,getPropertyName:[n=>"intensity"]},range:{type:"number",get:n=>{var e;return(e=n._babylonLight)==null?void 0:e.range},set:(n,e)=>e._babylonLight?e._babylonLight.range=n:void 0,getTarget:n=>n._babylonLight,getPropertyName:[n=>"range"]},spot:{innerConeAngle:{type:"number",get:n=>{var e;return(e=n._babylonLight)==null?void 0:e.innerAngle},set:(n,e)=>e._babylonLight?e._babylonLight.innerAngle=n:void 0,getTarget:n=>n._babylonLight,getPropertyName:[n=>"innerConeAngle"]},outerConeAngle:{type:"number",get:n=>{var e;return(e=n._babylonLight)==null?void 0:e.angle},set:(n,e)=>e._babylonLight?e._babylonLight.angle=n:void 0,getTarget:n=>n._babylonLight,getPropertyName:[n=>"outerConeAngle"]}}}}},EXT_lights_area:{lights:{length:{type:"number",get:n=>n.length,getTarget:n=>n.map(e=>e._babylonLight),getPropertyName:[n=>"length"]},__array__:{__target__:!0,color:{type:"Color3",get:n=>{var e;return(e=n._babylonLight)==null?void 0:e.diffuse},set:(n,e)=>{var t;return(t=e._babylonLight)==null?void 0:t.diffuse.copyFrom(n)},getTarget:n=>n._babylonLight,getPropertyName:[n=>"diffuse"]},intensity:{type:"number",get:n=>{var e;return(e=n._babylonLight)==null?void 0:e.intensity},set:(n,e)=>e._babylonLight?e._babylonLight.intensity=n:void 0,getTarget:n=>n._babylonLight,getPropertyName:[n=>"intensity"]},size:{type:"number",get:n=>{var e;return(e=n._babylonLight)==null?void 0:e.height},set:(n,e)=>e._babylonLight?e._babylonLight.height=n:void 0,getTarget:n=>n._babylonLight,getPropertyName:[n=>"size"]},rect:{aspect:{type:"number",get:n=>{var e,t;return((e=n._babylonLight)==null?void 0:e.width)/((t=n._babylonLight)==null?void 0:t.height)},set:(n,e)=>e._babylonLight?e._babylonLight.width=n*e._babylonLight.height:void 0,getTarget:n=>n._babylonLight,getPropertyName:[n=>"aspect"]}}}}},EXT_lights_ies:{lights:{length:{type:"number",get:n=>n.length,getTarget:n=>n.map(e=>e._babylonLight),getPropertyName:[n=>"length"]}}},EXT_lights_image_based:{lights:{length:{type:"number",get:n=>n.length,getTarget:n=>n.map(e=>e._babylonTexture),getPropertyName:[n=>"length"]},__array__:{__target__:!0,intensity:{type:"number",get:n=>{var e;return(e=n._babylonTexture)==null?void 0:e.level},set:(n,e)=>{e._babylonTexture&&(e._babylonTexture.level=n)},getTarget:n=>n._babylonTexture},rotation:{type:"Quaternion",get:n=>{var e;return n._babylonTexture&&Xe.FromRotationMatrix((e=n._babylonTexture)==null?void 0:e.getReflectionTextureMatrix())},set:(n,e)=>{var t;e._babylonTexture&&((t=e._babylonTexture.getScene())!=null&&t.useRightHandedSystem||(n=Xe.Inverse(n)),K.FromQuaternionToRef(n,e._babylonTexture.getReflectionTextureMatrix()))},getTarget:n=>n._babylonTexture}}}}};$X={cameras:Rce,nodes:Tce,materials:bce,extensions:Ice,animations:Ace,meshes:xce}});function WD(...n){let e=t=>!!t&&typeof t=="object";return n.reduce((t,i)=>{let r=Object.keys(i);for(let s of r){let a=t[s],o=i[s];Array.isArray(a)&&Array.isArray(o)?t[s]=a.concat(...o):e(a)&&e(o)?t[s]=WD(a,o):t[s]=o}return t},{})}var JX=C(()=>{});var zg,e5=C(()=>{zg=class{constructor(e){this._factory=e}get value(){return this._factory&&(this._value=this._factory(),this._factory=void 0),this._value}}});var _R,t5=C(()=>{Ge();If();_R=class{get currentFrame(){return this._currentFrame}get weight(){return this._weight}get currentValue(){return this._currentValue}get targetPath(){return this._targetPath}get target(){return this._currentActiveTarget}get isAdditive(){return this._host&&this._host.isAdditive}constructor(e,t,i,r){if(this._events=new Array,this._currentFrame=0,this._originalValue=new Array,this._originalBlendValue=null,this._offsetsCache={},this._highLimitsCache={},this._stopped=!1,this._blendingFactor=0,this._currentValue=null,this._currentActiveTarget=null,this._directTarget=null,this._targetPath="",this._weight=1,this._absoluteFrameOffset=0,this._previousElapsedTime=0,this._yoyoDirection=1,this._previousAbsoluteFrame=0,this._targetIsArray=!1,this._coreRuntimeAnimation=null,this._animation=t,this._target=e,this._scene=i,this._host=r,this._activeTargets=[],t._runtimeAnimations.push(this),this._animationState={key:0,repeatCount:0,loopMode:this._getCorrectLoopMode()},this._animation.dataType===ht.ANIMATIONTYPE_MATRIX&&(this._animationState.workValue=K.Zero()),this._keys=this._animation.getKeys(),this._minFrame=this._keys[0].frame,this._maxFrame=this._keys[this._keys.length-1].frame,this._minFrame!==0){let a={frame:0,value:this._keys[0].value};this._keys.splice(0,0,a)}if(this._target instanceof Array){let a=0;for(let o of this._target)this._preparePath(o,a),this._getOriginalValues(a),a++;this._targetIsArray=!0}else this._preparePath(this._target),this._getOriginalValues(),this._targetIsArray=!1,this._directTarget=this._activeTargets[0];let s=t.getEvents();if(s&&s.length>0)for(let a of s)this._events.push(a._clone());this._enableBlending=e&&e.animationPropertiesOverride?e.animationPropertiesOverride.enableBlending:this._animation.enableBlending}_preparePath(e,t=0){let i=this._animation.targetPropertyPath;if(i.length>1){let r=e;for(let s=0;s-1&&this._animation.runtimeAnimations.splice(e,1)}setValue(e,t){if(this._targetIsArray){for(let i=0;ii[i.length-1].frame&&(e=i[i.length-1].frame);let r=this._events;if(r.length)for(let a=0;athis._maxFrame)&&(t=this._minFrame),(ithis._maxFrame)&&(i=this._maxFrame),d=i-t;let m,p=e*(o.framePerSecond*s)/1e3+this._absoluteFrameOffset,_=0,g=!1,v=r&&this._animationState.loopMode===ht.ANIMATIONLOOPMODE_YOYO;if(v){let x=(p-t)/d,A=Math.sin(x*Math.PI);p=Math.abs(A)*d+t;let E=A>=0?1:-1;this._yoyoDirection!==E&&(g=!0),this._yoyoDirection=E}if(this._previousElapsedTime=e,this._previousAbsoluteFrame=p,!r&&i>=t&&(p>=d&&s>0||p<=0&&s<0))c=!1,_=o.evaluate(i);else if(!r&&t>=i&&(p<=d&&s<0||p>=0&&s>0))c=!1,_=o.evaluate(t);else if(this._animationState.loopMode!==ht.ANIMATIONLOOPMODE_CYCLE){let x=i.toString()+t.toString();if(!this._offsetsCache[x]){this._animationState.repeatCount=0,this._animationState.loopMode=ht.ANIMATIONLOOPMODE_CYCLE;let A=o._interpolate(t,this._animationState),S=o._interpolate(i,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),o.dataType){case ht.ANIMATIONTYPE_FLOAT:this._offsetsCache[x]=S-A;break;case ht.ANIMATIONTYPE_QUATERNION:this._offsetsCache[x]=S.subtract(A);break;case ht.ANIMATIONTYPE_VECTOR3:this._offsetsCache[x]=S.subtract(A);break;case ht.ANIMATIONTYPE_VECTOR2:this._offsetsCache[x]=S.subtract(A);break;case ht.ANIMATIONTYPE_SIZE:this._offsetsCache[x]=S.subtract(A);break;case ht.ANIMATIONTYPE_COLOR3:this._offsetsCache[x]=S.subtract(A);break;default:break}this._highLimitsCache[x]=S}_=this._highLimitsCache[x],m=this._offsetsCache[x]}if(m===void 0)switch(o.dataType){case ht.ANIMATIONTYPE_FLOAT:m=0;break;case ht.ANIMATIONTYPE_QUATERNION:m=Cy;break;case ht.ANIMATIONTYPE_VECTOR3:m=yy;break;case ht.ANIMATIONTYPE_VECTOR2:m=Py;break;case ht.ANIMATIONTYPE_SIZE:m=Dy;break;case ht.ANIMATIONTYPE_COLOR3:m=Ly;break;case ht.ANIMATIONTYPE_COLOR4:m=Oy;break}if(this._host&&this._host.syncRoot){let x=this._host.syncRoot,A=(x.masterFrame-x.fromFrame)/(x.toFrame-x.fromFrame);f=t+d*A}else p>0&&t>i||p<0&&t0&&this.currentFrame>f||s<0&&this.currentFrame0?0:o.getKeys().length-1}this._currentFrame=f,this._animationState.repeatCount=d===0?0:p/d>>0,this._animationState.highLimitValue=_,this._animationState.offsetValue=m}let u=o._interpolate(f,this._animationState);if(this.setValue(u,a),h.length){for(let m=0;m=0&&f>=h[m].frame&&h[m].frame>=t||d<0&&f<=h[m].frame&&h[m].frame<=t){let p=h[m];p.isDone||(p.onlyOnce&&(h.splice(m,1),m--),p.isDone=!0,p.action(f))}}return c||(this._stopped=!0),c}}});function Mce(n){if(n.totalWeight===0&&n.totalAdditiveWeight===0)return n.originalValue;let e=1,t=$.Vector3[0],i=$.Vector3[1],r=$.Quaternion[0],s=0,a=n.animations[0],o=n.originalValue,l,c=!1;if(n.totalWeight<1)l=1-n.totalWeight,o.decompose(i,r,t);else{if(s=1,e=n.totalWeight,l=a.weight/e,l==1)if(n.totalAdditiveWeight)c=!0;else return a.currentValue;a.currentValue.decompose(i,r,t)}if(!c){i.scaleInPlace(l),t.scaleInPlace(l),r.scaleInPlace(l);for(let h=s;h0?l:-l,r),u.scaleAndAddToRef(l,t)}r.normalize()}for(let h=0;h0)r.copyFrom(i);else if(n.animations.length===1){if(Xe.SlerpToRef(i,t.currentValue,Math.min(1,n.totalWeight),r),n.totalAdditiveWeight===0)return r}else if(n.animations.length>1){let s=1,a,o;if(n.totalWeight<1){let c=1-n.totalWeight;a=[],o=[],a.push(i),o.push(c)}else{if(n.animations.length===2&&(Xe.SlerpToRef(n.animations[0].currentValue,n.animations[1].currentValue,n.animations[1].weight/n.totalWeight,e),n.totalAdditiveWeight===0))return e;a=[],o=[],s=n.totalWeight}for(let c=0;c=l&&v.frame<=c&&(s?(A=v.value.clone(),m?(x=A.getTranslation(),A.setTranslation(x.scaleInPlace(p))):_&&a?(x=A.getTranslation(),A.setTranslation(x.multiplyInPlace(a))):A=v.value):A=v.value,g.push({frame:v.frame+r,value:A}));return this.animations[0].createRange(i,l+r,c+r),!0}),n&&(n.prototype._animate=function(t){if(!this.animationsEnabled)return;let i=pr.Now;if(!this._animationTimeLast){if(this._pendingData.length>0)return;this._animationTimeLast=i}this.deltaTime=t!==void 0?t:this.useConstantAnimationDeltaTime?16:(i-this._animationTimeLast)*this.animationTimeScale,this._animationTimeLast=i;let r=this._activeAnimatables;if(r.length===0)return;this._animationTime+=this.deltaTime;let s=this._animationTime;for(let a=0;at.playOrder-i.playOrder)},n.prototype.beginWeightedAnimation=function(t,i,r,s=1,a,o=1,l,c,f,h,d=!1){let u=this.beginAnimation(t,i,r,a,o,l,c,!1,f,h,d);return u.weight=s,u},n.prototype.beginAnimation=function(t,i,r,s,a=1,o,l,c=!0,f,h,d=!1){if(a<0){let m=i;i=r,r=m,a=-a}i>r&&(a=-a),c&&this.stopAnimation(t,void 0,f),l||(l=new Xg(this,t,i,r,s,a,o,void 0,h,d));let u=f?f(t):!0;if(t.animations&&u&&l.appendAnimations(t,t.animations),t.getAnimatables){let m=t.getAnimatables();for(let p=0;ps&&(o=-o),new Xg(this,t,r,s,a,o,l,i,c,f)},n.prototype.beginDirectHierarchyAnimation=function(t,i,r,s,a,o,l,c,f,h=!1){let d=t.getDescendants(i),u=[];u.push(this.beginDirectAnimation(t,r,s,a,o,l,c,f,h));for(let m of d)u.push(this.beginDirectAnimation(m,r,s,a,o,l,c,f,h));return u},n.prototype.getAnimatableByTarget=function(t){for(let i=0;i{di();t5();If();wl();Ge();Xg=class n{get syncRoot(){return this._syncRoot}get masterFrame(){return this._runtimeAnimations.length===0?0:this._runtimeAnimations[0].currentFrame}get weight(){return this._weight}set weight(e){if(e===-1){this._weight=-1;return}this._weight=Math.min(Math.max(e,0),1)}get speedRatio(){return this._speedRatio}set speedRatio(e){for(let t=0;t-1&&(this._scene._activeAnimatables.splice(t,1),this._scene._activeAnimatables.push(this))}return this}getAnimations(){return this._runtimeAnimations}appendAnimations(e,t){for(let i=0;i{this.onAnimationLoopObservable.notifyObservers(this),this.onAnimationLoop&&this.onAnimationLoop()},this._runtimeAnimations.push(s)}}getAnimationByTargetProperty(e){let t=this._runtimeAnimations;for(let i=0;i-1){let a=this._runtimeAnimations;for(let o=a.length-1;o>=0;o--){let l=a[o];e&&l.animation.name!=e||t&&!t(l.target)||(l.dispose(),a.splice(o,1))}a.length==0&&(i||this._scene._activeAnimatables.splice(s,1),r||this._raiseOnAnimationEnd())}}else{let s=this._scene._activeAnimatables.indexOf(this);if(s>-1){i||this._scene._activeAnimatables.splice(s,1);let a=this._runtimeAnimations;for(let o=0;o{this.onAnimationEndObservable.add(()=>{e(this)},void 0,void 0,this,!0)})}_animate(e){if(this._paused)return this.animationStarted=!1,this._pausedDelay===null&&(this._pausedDelay=e),!0;if(this._localDelayOffset===null?(this._localDelayOffset=e,this._pausedDelay=null):this._pausedDelay!==null&&(this._localDelayOffset+=e-this._pausedDelay,this._pausedDelay=null),this._manualJumpDelay!==null&&(this._localDelayOffset+=this.speedRatio<0?-this._manualJumpDelay:this._manualJumpDelay,this._manualJumpDelay=null,this._frameToSyncFromJump=null),this._goToFrame=null,!n.ProcessPausedAnimatables&&this._weight===0&&this._previousWeight===0)return!0;this._previousWeight=this._weight;let t=!1,i=this._runtimeAnimations,r;for(r=0;r{dR();HD();As();HD();i5(Jt,wa)});var n5={};tt(n5,{AnimationGroup:()=>zD,TargetedAnimation:()=>gR});var gR,zD,s5=C(()=>{If();di();Di();df();r5();pA();gR=class{getClassName(){return"TargetedAnimation"}constructor(e){this.parent=e,this.uniqueId=Ql.UniqueId}serialize(){let e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e.targetUniqueId=this.target.uniqueId,e}},zD=class n{get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this.syncWithMask(!0))}syncWithMask(e=!1){if(!this.mask&&!e){this._numActiveAnimatables=this._targetedAnimations.length;return}this._numActiveAnimatables=0;for(let t=0;t0)){for(let t=0;ta&&(a=l.to);let o=new n(e[0].name+"_merged",e[0]._scene,r);for(let l of e){i&&l.normalize(s,a);for(let c of l.targetedAnimations)o.addTargetedAnimation(c.animation,c.target);t&&l.dispose()}return o}getScene(){return this._scene}constructor(e,t=null,i=-1,r=0){this.name=e,this._targetedAnimations=new Array,this._animatables=new Array,this._from=Number.MAX_VALUE,this._to=-Number.MAX_VALUE,this._speedRatio=1,this._loopAnimation=!1,this._isAdditive=!1,this._weight=-1,this._playOrder=0,this._enableBlending=null,this._blendingSpeed=null,this._numActiveAnimatables=0,this._shouldStart=!0,this._parentContainer=null,this.onAnimationEndObservable=new ie,this.onAnimationLoopObservable=new ie,this.onAnimationGroupLoopObservable=new ie,this.onAnimationGroupEndObservable=new ie,this.onAnimationGroupPauseObservable=new ie,this.onAnimationGroupPlayObservable=new ie,this.metadata=null,this._mask=null,this._animationLoopFlags=[],this._scene=t||Oe.LastCreatedScene,this._weight=i,this._playOrder=r,this.uniqueId=this._scene.getUniqueId(),this._scene.addAnimationGroup(this)}addTargetedAnimation(e,t){let i=new gR(this);i.animation=e,i.target=t;let r=e.getKeys();return this._from>r[0].frame&&(this._from=r[0].frame),this._to-1;t--)this._targetedAnimations[t].animation===e&&this._targetedAnimations.splice(t,1)}normalize(e=null,t=null){e==null&&(e=this._from),t==null&&(t=this._to);for(let i=0;ie){let l={frame:e,value:a.value,inTangent:a.inTangent,outTangent:a.outTangent,interpolation:a.interpolation};s.splice(0,0,l)}if(o.frame{this.onAnimationLoopObservable.notifyObservers(t),!this._animationLoopFlags[i]&&(this._animationLoopFlags[i]=!0,this._animationLoopCount++,this._animationLoopCount===this._numActiveAnimatables&&(this.onAnimationGroupLoopObservable.notifyObservers(this),this._animationLoopCount=0,this._animationLoopFlags.length=0))}}start(e=!1,t=1,i,r,s){if(this._isStarted||this._targetedAnimations.length===0)return this;this._loopAnimation=e,this._shouldStart=!1,this._animationLoopCount=0,this._animationLoopFlags.length=0;for(let a=0;a{this.onAnimationEndObservable.notifyObservers(o),this._checkAnimationGroupEnded(l)},this._processLoop(l,o,a),this._animatables.push(l)}return this.syncWithMask(),this._scene.sortActiveAnimatables(),this._speedRatio=t,this._isStarted=!0,this._isPaused=!1,this.onAnimationGroupPlayObservable.notifyObservers(this),this}pause(){if(!this._isStarted)return this;this._isPaused=!0;for(let e=0;e0?this._scene._activeAnimatables[i++]=s:e&&this._checkAnimationGroupEnded(s,e)}return this._scene._activeAnimatables.length=i,this._isStarted=!1,this}setWeightForAllAnimatables(e){for(let t=0;t-1&&this._parentContainer.animationGroups.splice(e,1),this._parentContainer=null}this.onAnimationEndObservable.clear(),this.onAnimationGroupEndObservable.clear(),this.onAnimationGroupPauseObservable.clear(),this.onAnimationGroupPlayObservable.clear(),this.onAnimationLoopObservable.clear(),this.onAnimationGroupLoopObservable.clear()}_checkAnimationGroupEnded(e,t=!1){let i=this._animatables.indexOf(e);i>-1&&this._animatables.splice(i,1),this._animatables.length===this._targetedAnimations.length-this._numActiveAnimatables&&(this._isStarted=!1,t||this.onAnimationGroupEndObservable.notifyObservers(this),this._animatables.length=0)}clone(e,t,i=!1,r=!1){let s=new n(e||this.name,this._scene,this._weight,this._playOrder);s._from=this.from,s._to=this.to,s._speedRatio=this.speedRatio,s._loopAnimation=this.loopAnimation,s._isAdditive=this.isAdditive,s._enableBlending=this.enableBlending,s._blendingSpeed=this.blendingSpeed,s.metadata=this.metadata,s.mask=this.mask;for(let a of this._targetedAnimations)s.addTargetedAnimation(i?a.animation.clone(r):a.animation,t?t(a.target):a.target);return s}serialize(){let e={};e.name=this.name,e.from=this.from,e.to=this.to,e.speedRatio=this.speedRatio,e.loopAnimation=this.loopAnimation,e.isAdditive=this.isAdditive,e.weight=this.weight,e.playOrder=this.playOrder,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,e.targetedAnimations=[];for(let t=0;tp[0].frame&&(c=p[0].frame),f=t&&p<=i||s&&_.frame>=t&&_.frame<=i){let g={frame:_.frame,value:_.value.clone?_.value.clone():_.value,inTangent:_.inTangent,outTangent:_.outTangent,interpolation:_.interpolation,lockedTangent:_.lockedTangent};m===Number.MAX_VALUE&&(m=g.frame),g.frame-=m,u.push(g)}}if(u.length===0){l.splice(c,1),c--;continue}a>u[0].frame&&(a=u[0].frame),oYg,TransformNodeAnimationPropertyInfo:()=>tp,WeightAnimationPropertyInfo:()=>vR,getQuaternion:()=>a5,getVector3:()=>XD,getWeights:()=>o5});function XD(n,e,t,i){return b.FromArray(e,t).scaleInPlace(i)}function a5(n,e,t,i){return Xe.FromArray(e,t).scaleInPlace(i)}function o5(n,e,t,i){let r=new Array(n._numMorphTargets);for(let s=0;s{If();Ge();kD();Yg=class{constructor(e,t,i,r){this.type=e,this.name=t,this.getValue=i,this.getStride=r}_buildAnimation(e,t,i){let r=new ht(e,this.name,t,this.type);return r.setKeys(i,!0),r}},tp=class extends Yg{buildAnimations(e,t,i,r){let s=[];return s.push({babylonAnimatable:e._babylonTransformNode,babylonAnimation:this._buildAnimation(t,i,r)}),s}},vR=class extends Yg{buildAnimations(e,t,i,r){let s=[];if(e._numMorphTargets)for(let a=0;a({frame:l.frame,inTangent:l.inTangent?l.inTangent[a]:void 0,value:l.value[a],outTangent:l.outTangent?l.outTangent[a]:void 0,interpolation:l.interpolation})),!0),e._primitiveBabylonMeshes){for(let l of e._primitiveBabylonMeshes)if(l.morphTargetManager){let c=l.morphTargetManager.getTarget(a),f=o.clone();c.animations.push(f),s.push({babylonAnimatable:c,babylonAnimation:f})}}}return s}};Hg("/nodes/{}/translation",[new tp(ht.ANIMATIONTYPE_VECTOR3,"position",XD,()=>3)]);Hg("/nodes/{}/rotation",[new tp(ht.ANIMATIONTYPE_QUATERNION,"rotationQuaternion",a5,()=>4)]);Hg("/nodes/{}/scale",[new tp(ht.ANIMATIONTYPE_VECTOR3,"scaling",XD,()=>3)]);Hg("/nodes/{}/weights",[new vR(ht.ANIMATIONTYPE_FLOAT,"influence",o5,n=>n._numMorphTargets)])});var Pce,Dce,Lce,Oce,YD,ER,KD,f5,SR=C(()=>{Fr();OC();Pce="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR42u29yY5tWXIlZnbuiSaTbZFUkZRKrCKhElASQA0EoQABgn6hJvoXzfUP+gP9hWb6Bg00IgRoQJaKqUxmZmTEe8/v0uB2u7Fm2T7HIyIrnz88uPvt3f2a2WrMbOvf/u3PvvzP/sUf/N6//i8vf/lv/3v5H//d//Sb//Uq/5u8yf8hV/m/5Cp/L1f5hVzlG7nKJ7mKyJuIXN/hPwqXI/g++zq6rPI5u8z+WqfLre+zy7PrVv9L8brsMiGvk8XLmM/sdfHXal4e3ad6GXPdyu2ij8u/+uv/5cuf/OSLfdtEfvUr+dnf/d0X//t3H/7bf/hP//N/928h/0Yg/4VA/kogfyGQP5Wr/IFAvhbIlwK5CGQTPP+9z5uPeePJSW+yo2+s/GtN30Rnv1E+f5zxof9R/lSXv/nr//mrr3+i+5dfyX7ZZQP07Tffys//8R/l/9TtX7790T/7r/8G8pdy+/8XAvnnAvkzgfwzgfyxQP5AIL8vkJ8K5KsmMVzu1U7p5PA5AXxOAJ8TwPf7sX/51ZeXfcemqnp9w/W77/S7X/6T/vzf/7383RWCX3/z05/9i3/13/0PX//eX/2FyP8tIv+PiPy9iPy/IvIzEfm5iPxCRH4lIt/c/393//9BRD6KyKf7f488fP74/PH544dJAF9cLl98IZfLBZtuqterXr/7Dt9982v95S9+Lv+gF/3i7Spv/8lf/vnf/vGf/dF/JfKnIvLnIvLvReQ/NEngn0TklyLy6/v/34jIt00iGJOBlxAsdvv54/PH5493SQCXy9t2ueh2ueimKorrFbjq9eNH+fDtb+TXv/ol/vHyhX4Fxfbx7euPf/Lnf/PfiPyeiPyhiPxxkwB+fk8AvxzQgJcIrGTwFsiAEXH4/PH54/PHUgLY7whgu2C7bLqpQgHB2xvePn6SDx8+6G9+84384vKF/IPu8iVU9Y/+7C/+jWxffiHytYj8VER+X0T+oEEBvxqQwCMJeIngo5EI3goIwVMIPn98/vj8ESaAbbtu2ybbvl8u2ybbdtluSECA65u8ffqIDx8+6G++/VZ/efkV/sO261dQXP7wT/7kX8vl8qXIFyLylbySwe/dE0CLAr65B/9vGn0gQwRMMqgmhM/J4fPH548eAezbZd/lsm3YtssNAYiqiogAAkCvb5/k46cP8u2HD/rrb7+R/2/b9Wu9yJe//8d/9Ney6S5yEZFdRL68/38khG/uKOCnAwoYkcCoEXwkEgGDDq7CeQfyOTl8/vhd1QCum26ybZtu2yabbrKpQvXue1yvuF6v+vbpTT5+/CDffviAX1++1V9sO77WXb/66R/+4V/dgkbllQi+aBLBV/dE8LWRALwkYCWCNyMZXElkwLTMeMkga/P4/PH547ccAVwuctkvdxSw6bbdtYDbTfSZBN7e8PHTR/3u4wf55vKd/nL7DX6mu3791U9//5+/gkNFZGuSgZUQvnKowKgLWLTAQgRtEniTuEfwaELw0MJvf3LQzynud+53uG+X6y3gN9kul+2y6XVT1U27JCDAFVc8ksAn/e7jR/nN5YP+avtWfq6Xy9f7Vz/9w1dgRYngiyYhfNkkgzYBWHTg44AEMmqQUYQKOmDaiCIa8TmsfmzB+DnZDQjgcpGLbti2y3bZHjRAdRMVvb/dcYU8kcDbPQlsH/CrbddfbF98+RPZfvLFnAQeieCRDC5DMvju/vmD4JkEvjRQgKULeGggowdHkAHTYxihg89vu88I5UeGAPSOAFTlrgPopiqbKPSmCKreUoAAkCcSePukHz590m8vH+WbD9/JP335k6/+tA86KxFchv8jMvhiogE4JQm8XhfKqOAqx5qRPyeGzx8/cgSwbXcUoLJtim27C4Oi93+4v6VxQwKAvl2v+Hj9pB8+fZJvt4/yzfbF9lPdv/wJnsE2BogmyeCRED40tGFvksIXiSbgiYSRRpDNDZ6BDI6ghM+J4fPHeyKAO+zX7cb9t4tedMMNAQju5V+f1uAtBSiu1zsduMrHy5t8ePsk3376KN98sX/xE5FPAnm7/782o0DiUINXMkCXCB7/P94/e87AWUmARQWVvgMuKej9t1RLBp+Tw+ePgwngsutFFdu26WXbbl+rSvdfbnqAiuA23QcBgCugV1zl7e1NPm5v+LC96XfbJ/1W9y++fgXjA3bDYXV+MuhRwSPwL3JLMFYC+HS/LU8HYrGwIhwyNOF12SvgM4SgztdifP85MXz+KGsA2C6X7aJ6bXSAOwrY5OYIqGy3d5uq4P5GhABXuV6veLvRAf10fZMPb2/y3b7vX7+g+9v98/WOBq7GG7RNAlYy+Dgkhhb+Xxp0sE8IAC4SGAP/TbgVJK/PoJPBnAiwPKxsXfbbnRg+i3s/JAK4Q/4b9NfLtomBAqCickMBjy7BuywAUVyv8na94tMjCVzf9KNcLl/0SeA6oAEYb1i9g+FtSALb/bKL8/+t+wxXFMyswqiHoK4ToIgKqslgpg1qUC0QoYbvJZg/B/q5v4szHmPX7YEAsD0CX25OwEUVm9xag1+agKg+nxQArnKjAtDr9U0+Xd/k4/UqH7bL5YsewrcBBiMJZPRAp6TwQgWfjM9vgRbgUYGL8AvLWH2gqhesCokeUmCSwPsnhs8fP2YNYMO2XeSmAWxy2VQaXeDmDIhApf33rD4PTUCuV+DtCn27XuXT5ir8VmCJ2G5BpBM8/r/dEcJb8/0lEQMtJHA5TAlqNuLRhJChhEpSqFabH3di+G1AGj+W1/dyAR4IYJNNnuLf6+tWC9CHHiAtFhAIFLjK2/Uqn65X+SS67aK+3QeTDoy/IG2ogQ7fb/dAtz5vBgrYGqrwNtCHsVfgIvwK07OTQBURVNCBFpKCOjqCHn5L/67TgTN+fpySAC56nwSUi256kXsSuFGAVyLoUIDo8/Pz7fdoErr/v17lk162HbgHvFpIYDfoAJJfW4sGPjkU4VNAF8ZEcLmLhdc7kljdY1y1Dq9yLiI4IiRqcLujb138KIPn80ejATwRwIbtBvn1cqv+2J78/5EI5N4cJA8qIPcmwRsKAHDF9WYP6mV7VmrgLuTpxYTcMEW0LAmoQxFsuvAI8tv/a/C5fV2ZMMiKg++FCM7RDPRu8ebWY7VG6VJi+Bzk35MI2LsAckMAgwvQ0gC5DQjd3ABg2HQLAPpEAlZ1Bu7VV7MGHDFRAbo3VKsTbAY9sPWC/uvx86gBbDK3D1eEQS8pbAeSgSwmhepnJb6uBv/o/PzHLzxWA/X7TH77De5j6AGQi6o0CUGfCOD2X7cXAlCFQABtEsGLDtxuOyQB2UTQBKZe5GUPXgkUYCUAbZJRhBDeuq8xBf+bgwbehDm+BFQi2IJksOocvA8ysIMfxluVcRsY/eB3JzH8GFDAXQO48X/dcIf9jyDHptIigDsFkEe066tBSETQUYF7ElDdYEBytN4+rk9UcBPfrKaZqFHWcw3i4J8/X4ev2//bSXqAhwTay6OEIPLD2Ipt8OtAGzxkwLw9WVFRjTc/qC6H3+YK/b1oAA0KuOizHfieCLaHHiAb5NYTIC9EMEbZrVEQt1xwhVy1UfBh8PUOquMizwaap3tQXfY5B//tea/NZdfhsvbz+PURQTDSGWB87VX/7WSd4KxjUqrIgE0IUkoKGnhIvwvawpGf6eECXJ7tv4qbA7DJgwpsKthEmmYgfaAAffYF3HLxo0vwNjJ0SwRWMG4db4eh1gPNm18vQ+us/0eGmxDemu/fnM/X4evq/8342ksGHgLY5LyT/zg0wM8lcMjgGFXwqIOVFJBQw99eCvF9oZL9Mfl3QwAvIXDsBRC9R+fz8x0FPBLB0xJEpwUobrfAkARgIAF41h3wQgP6QAmX5E/7eI43IxGwwf/moIkRyWRJQIPgt9CA9b39nzt4bYUWjAlCjWDPgv8IEjgLJfzuaAsrv9VdVG4OwOXW/fdoA35qAdL0BDwvf6AAUVHd8LIEu94A3K+Q+2YxaB84MOH62P//qoo38fCRDERE2zf0JfmDa+MieElAjcDPKz+mRKCOtdgGtXaBjgNJ4H2owSpNeAW/rRH4CaHSpMwnBYYycjgSJwfie9CR6mPu20Uv8kABF206AvXlBMiIBPSlB9wjBW1fwEuSb94296VCqgMaGCt/G1BbExi3IG+r3a3J6P48Gv/J0YmEYoiGY7V/SxwFCwGoE/xa0AJ0CEiV9QPCJb1OJ5F1VTjEY2/MO9AEJvj1BJTQpqLfTlGwjABuzT962e4IoKnyrdh3+/6mzDVJ4PHOxj0JqGKoy20+wBMN6D1gLWi9NQHfVP5MEEPzjGYy8BMAOnTAJgEr8HUIejRo5xrA5xkR5AngmiSHs+zDDAmMgWzTg55GSJEmHE8IvWPAoYTfhWak/Wn/bQ0CGLSAjv83SUEfKp5q24LXuQICpzrjrgWoza8xVE00CQCORdhMJuTUT/rjuls0gO4Iby8BIEgK6gS7BsGuTtDrScH/fR68biUHNVGBnxjeNyHEvQe/ve3LZQqgG3rof6cEclsNflG9J4KtaQ8WHcVBHS1BtHE4QP9OBMS98mpbKTeDW7dJwRsnHpMBTFJpV4I+b0kY/NqInVFSyBLANbnMSgBM8F+Fqfxq/h657/Up+GaBnwV9hRqc9bZ/vA6vu+T9E8KPJWns94UfTeCj2QXwCHS9dNL8Xf3Ho/rfewSeFODGDV69AU0y6NFAE1DP3qK++rdB7/1HRxf86gT376zOr99T/h/ioBiXWQkgQgVeIrCC/WomhDmQK+hASI2ARQZKooHMLdCJwGEBBXC3+uERwg+VOHZ9ioAt9H80AI06wGgJ3nQA3BoCut6AhxYwgcPOFnxuFnrphk+NIKIGrWPQtgz3b0i7Y6D5rs1GKqTop0nQX52vmQC4BkjA+r4a7Kx9WLENGeegkhSETBCrNXIMdi/444Rw1n6E96ry7OPuj8UfLxtQ78NA2iSBbg7gIiIbdDLsb5agPhLC3RkYKv8NDbS2YGsatNRAG2oQwf9ZIOydgy1MAzBkAw8UwEEIDzSAqdPQ6za0PkeJAMH3Z0wXniUSZoHvBXU2mcjQgv56TedIKglCpIoQfgwCIjOytd8WgN0bfxoR8Fn9Gx0Aj5Zgq0lIZbsH/ibSJoFnS+C98g9ooHEELI3gliy25yONIiE6pb0NfBlyNEYyENoodkKwgl6I6s8kARgJ4ZoEfuYWHLEJa0LhSBXm7kImGeSfVdoJ1DO2G7WXsehAptupSOoyrCSF904k+6vt98X/ZcM98Hsd4JYIXhQAIg3/f9AAUYhsLQKAtkHVBnzjCKhOoYl2ym+iBtvzDzQ2DLXJ4PUmbJHAVnBQX4jkxfvHhNDqAdHXGQJgv0aSDGItgOseHIU+K9hXnIJzkoGlEKzNHagTdJ6VWEUH4iCKH4fd2AwDPaYBm4Wgng4gQ9V/CoGiuNmD04AQtNGMGzSAAQ2I2pzfogY9LRh7BrbOh4+D30sAencljFu2CUFrwY8UAWRfWwGvVOVfbx2uIILM0pwDv082dUTw8hYs8L+uIWiHGpWgClnAa1lMPJogovvvbePPs/q3Xr++kgCsfgB5oQF9WYKPJqEn6G+OE3i5AqouF59FQOmahQC8rlPLj38kg1c2f30vw+XaoIX24/pMGIgSBoZqoH3wo0sIIGlA9PWcCPrAtpPB8eBf6x1o6cHra+2+tpIFP4PgBfxZtZUJfo4qxELT948D9ucK8Mt9+ccjIQw6QJcEbrD/1g340ATuDgDkFfx6twSf1f9xvuBECYxq/7ythQQGm+5JDx6Brw4CkMGT3wgscCUoQ4sU2t6DR2ciBjTgtcpenQoZVX9NuL4Owc+dVaDursYVkVALX+shjSBKBuvCYDUZjE5BdNkxdHAUBexyHwB6NP7Iyw7sxUDViwge1t+mz8B/LAvVx/c3PeBBCToB8IUGOgqA3iV4yUg6UAOxaUFHDx6CYS8SorMOue0CCJGAf5YfRhoAI+A1CvwxqNkAY5yAIx2EQmkFfeWOXi+nEdSQQA0ZHMEItiagJArQxDXIrj8nCfQi4HZPAttrIahso9oPQ/2/JwV5JQU8zw+7I4D7/sBn4EO6rjw0FR+i3Z9fHtahzsFvJgM0X+tmVH5vaYiNDGAigewAz+gyNLThnjCURQFR1b9d3lZvnVqmj9mEPDKIUIC4KCCjBXywS4N+otp/Hk3QVthOkwEKlV9PQwXjT7s/zwF4Qf9toAAzFdjuaEB6S7D1//U5FIQu2MevO0rQQH8ZmoXE6B/IkgE60XCjVoq8gt2iCG0S8L5GdxkM1cGsfsCMArSCAnrr7dzAZxCEEpepvB8tqHJ/q+bmJGGts/AcAXFOMMeTwC7Pw0B6CtCtA2vWgonqBQJFSwH0JQK29OB2kvgj2HHXAoyeAIsCQO0kMNECAhFMqCBf8mElAkyBbX1tJQP2RJ/ha0gpAfS9l+/5n00CkrQpq0MZbOdAuxmMvHswog62jZj7BnYQe19b14kxNq2D/ehX/p68HEcF+x3yP7z/V/A/q/5DA3i5A/dzA5pdgbKp3v3/wQF4Bb70WkCTHGRAA6+KL0bFl6FJaFw0ImZwm6igSwbbwPn9RMBWf3sN2JgA/BVh/Rg0kQBgePf6HglAHLFQwqQQOwDjbdVxNZjR4iM6Qa3WxwvNxh0JFb3g/WzFQQS8b/ttKcDWoABtUMAd8j9hf0MB2uDXhzX4CHj03L9DBU3Qjz0C0l4mLSLQPicOOwZoVCB6P6dA7nDbGkVuxcNr8PU2JQO4wX5trEqmccZaHU4q8oCDFOpzAnOwqyMIMktNNNAHouDGxO37DgArQZzlmp/14W1QlqHTMaIIx7SCx0+5yza7AKJ3IXBrNAHVDcMZAU/BT/vgv/ULPOA+XiLggAREDF2g0ci6xNDRglegd7P7TWWH5oJfayliEg7bScQRBVgI4Ookg/F6rvpLWP29swREqA3CaG8/FpKqS8DTAV4TiBqIqtxfzaQRLys5I0XEFIFrPbZRQb+16Fgi2LvJv8EFUPW1gGfQv1T/F/d/HBnccP7rAwnIIyHI4ArgWeGbU4eHy6Tx/EeTZIb5bo/BsMBjmjBE08f/RB0PHYBd9eVRAGY7cHRwiBf8WeCPHY1bgBTa9xKTELzEkQX9CPtl0gJiqsAmCT7I8xbjivh3JGFI+D2nBcSJQJ8agDX+O9iBL7UfG4bzAkcaICrbtYHz1ycSmGmAjJfL3CMgT3tQpmrfB7gxSzC1DnvdhQMieG47u75+kTouKNkM8c/+vq/Q7ZYjO/hhVvRq8F/9gGfhP8aqE9EIdR6LTwJ1h0BItyDqB8iFwuNqASscRnYioxOg9ApvnYA35f8e9Ohbfe8J4rknoFkO0lmA2gmAG0YK0DkB4ieEjiLoMD8wBzom27ANZkzIoU8EMHk/uo1mzeVoEoRWKn8L/62EYAX/lsB7D/LXg74uAMr9oGivJ0CNJCGD6i9DhZdQF+gtOp4S+NODRzsDVbhdgv4BqTMNyIL9SCKwL9/FGPp5oQKxIf8A/UX6r231H7YIqLML0Ae2GtrADOvRQH5b/MPE9dt9BGLNG8jVTAQvIaK5TtvvvWQgDvyXIClUA78S9Nfg7VtIBlO7cbsEYkQDMot+ygQ7QwmOawTHnAM2XUSnJvPIYRYMmYPS+sv3J+cfP3d04JYIXsF/EwMbBKB9Q9AY+BiSwFj9mzrSXmcJhFPVHySTbgHJCPvRQ/z7G/SVUETsg0ZF+i3CRoCjhf7y1A9mOiDD7TwdwEoEXjLwAv+avLE2B7Jnb+OqDpBoAchoQJskxKnss0vu7Q2YhcDv4ySeLOg9GsCKiUIihP7yfW7zbTsBh0TQfN0iAWn9f72Z56/Ax9P7j5OAH/Qvv3/QxKfk0DgDuP+R3USg3bzBC7bO/QT9Eeh9QvDPG7glBQzJwK740lAFFgFk8P88CqDGAa223YckWYhr+c0BPdwetl2ocnsfzePAWcVnnAIp6gDVhDLyfV4nqFEDPxHsbWD3k4BDkN+pARqKMLYBPzYEvxp9xmCHQQdgWH/9EtH2TIFpu3AH/cdGydv1j0TQbRrq+D/mLcX3ZACZ15bF378CG0My6Kq/zoGOQwhASDFwFbxyNGBuSxbCEhQ/uEPe/6gAERWQObCVVfjPpQX+rexxYhYFxIkgpgX7Y/vPs+Pvxf9vwt8kAs7i32t3QCP+3SPaTwIytQXP38u0PESm+YER+o9B3vr8mETAUfDrEkPI80ck0FZ0dXh9U+HRbhey0cAc2H7A4y4egoD6y8JfkBiigLdFP8v2W00E8deT2IeAKujZ/QAVKpAtKI20gLWksHedfgPcb+0+NEHefd9vB9rayi8h7J91gBbaw20MsnWAF5xHkyDUCOoXp+yrOwwxcKj0aL6fFppaaKDv6OpHR5sgx5BAlK/+fYhuP1D196o8e7lFBaKqv5YIMnFQpd0FGVR35RJCnCDaABaXBtgbiSwtICMtalKC+1JQ6bx/PLcDPQL91QFodQNKpwOgF/9eqcBxBBqRcKAAVk+ArQOMx1RYGgB6naDhlK+uQQwJYx4meQbxtNnYQwMjt/d4f3M9ZE4UOld1LAh99fbfzOxiEkKFCkTJIUIMUeVnJ/9sDt8/e1NEJOi9oVHDGYhgnSLss9DX2IAqw1zALUncKcDr0FB5NP+0cBQNrEezDiyiADPkt9qGpwoPdL0AGPx/NOKeyf3b9WJNdfcFv6bKd2cLMJVfJ6Y3B6wB9WFUfWWEwKMfGiQL+3bz9XGQz2EHKhF41GCtZyDi/gUCsNhYoAr3UNJ58YidHKqnMb/6AB5J4N73/4L+t7mAkeeP3P+1LNSB/l0SkMEd8DcEuUlguEw6t2AU/PCE/q++Akw6QFf1u6SBrj1ZnnhG50AfkoGIdf7gJv1KcSfgzWWkQ9U33Z3tHXYASKJ9e/YhU90rvD+q9Ej69/wxYJVs506Eg/r3DkMDzEdDBRGgcZay49XihLA30P+l8N+hf1f57/0AoxbQbwYaan/rBMirE9Dk+sBzTkC8JNDEUlv5McB8PP19Y01Gayep+hC/2zvQ/2HGLAurowsNGlA1cnqGGzeH5weiYLZm7h3QQC4O2tXdhvMMk1ZS5ebpgI8eMrPvPGkwaxayk8Yc6PMOBPEdC1XZ+2UfbfOPtxLMQQAG9BcZFoF0gp/RKjxe7+oAw9T7ZPWhgedodgz0gf5KBtrtIZhQAZpAV1Bi36w6t98qVfH7hqGI318lLCjLCUFlxRHwqYEH9a2qb4XjWvDT7kBwfbZA5P0+PNuRuW1yf4yNQH3zzwv6b70QOJ0G9OT/dhoYRUGT15uQH/71MjQLtQlxfDuiCXrtM+SkA+icQdH6sU/xz7Ze7FlubV4TpoTQ2osdpaEjtqADmEU7OkBEFoLeC3IWFFeswJXKXzkboNL+wzcFHU8hTGKIboO7CLi1/P+5F+gydQhuvRbwEgxvtACmANikhLTbj0gCYk8KdlYgmj+4Ymaod7TwahwadICuX0Cm2fE5iNHPK0x/CDV66Kyg1MnqjNFBnhBoLQCgUULfaVe5nq/6EQWY67bXCszUb+7232fVPz51iGB12owK9peyP1T4raMFF/OEYJP792mgXYfZ04GHMAhBkCSmSj+dKqRPgVFGHbpLEGMiGFeQWfSgrY52VxaeDUPSNJI0P7NoisG729HHl78z6hxfs9rV3m4JjgM/lsui2qmThjCfDFSb+I9vwUqG5wwL55U7C+6ot8B+7N2o6r3q37T9trfpjgmTvv7PSQATLLeRAOZhIJHBQfDQQJPBdUwEbVW3+L08EcEE/9G4ANrCeWcnPKRHDupbNynMx5AA9IRYLmrc/YLSiD5EaEBS/s/TgnU9ILcH19n+CpHwegLejx7Mn/d25fdN+e9U/1vgb7bqf08MOtf8EXxaoh+GY8L6gDfhvs4i6HQ7seYI2sv1GchdMsBIG3xlvxcCRzdgCPTn+6q/TW00VE8Q9FaFv+R2VlOM1vm/hhjhDCdgNflVKME5B47I9xT8z0YgPAJ8myb/LqHy36j/Mwqw9AALxuO1JVjiuQAYLcFzIhiEPe05fk8tRjGw7yWQbsfuLAT2VqOId1osnr0F49VM8INACPHDoBz4B5mqqSnUgyh3ArjXxfQH5BbgUS8gP7aU+w0zHD9GGD0CGHf+P1p/DeivlhU4BbxR9a2kYFR58YaDZCUR2P0DMmgED2eg77puegy6PgDphEB0CwlG/i9d+/Hs34pBEQrBn0W51mqGnJAk3ACCHeiqkQ1XFQA5AlKH7Lk8yJKWY3/nym14h2C3JvxeMwD9ZVMz0BPMi1n1RbKl1cYhIVblF3G0ATsRiCMUvoK9//OgcwYMoe+ZKOLlC6/Xk50br9NFz9fanqA8UIYSpCwlBO4kHc4WLLBfBHVaKwKgLQjmP4Un61Vq+3s7Bsyi0WztmLjJwJwFeE0I2vD/1Q6MVwefxfUf32skCPbCnxQqf+QMPEUDHZ7vGeyj020JgkPXXwsldA7SYR1RE3h94NvNtugswcgxXEkIcBPCGZ1rmrgDC0A4K88nm2fn/eTnpQtWyZfybRoK8Dro4zYDIMGsf7saTBzvX0SMbkAD6o9CYbsfMK38cJKD9l2FJt9/VGs0h5Gib33pxMKWNsigFUh3G2un+/N1WUglI/EEx8fq27vUNnwsiOoKecL7kQS8VnWAGCFUgn6dBtQhv40CmIYggwK0uwDHRGAuBXVdfwzHUjZzATLMAoyJ4FmBhzaWBlrHld9CCWpPHRqofBqMReMGTJ78q9rDes1Tv7/0m0v0AFHXNR6P6g30SHivin7V1BOhh3iWPwvps/yE836L2XiwnUT8x2iHgfqhnwn667QHEE8oLQjEvtEW7GYBZDrDVkwNIO4G5GiBDf9fGoFM6n+vbEtzXwP6u9AduaWnGYSLAlVdl/AU+ikrSeEIKgwdaZ4AACAASURBVKj4/wtgHcHtdO2nWKcBkPfxcvnNQvsj2Me9f02r76T8q0IBn9OLKfz1HX8yVXQYGoAB/2UeBQ5/5kCL6+H/OGGoRnLSwdd3oH8r7KkGTbgIxEwVWvnF8KOpHnyzfF9Jod5Px+IF1h8owyitDw/XEgRb5bPqbt1uvn7qBIQ16vtS/u+DP3cR7CH0WWJgd5mTJKYgNzoGjQrfvu99NDBC+bnyW1x/qhTatv2OaMKgJWPvv5kwnMgxHYGFRtJW8VMl3uP+MgoqSZyWFKr7+KIDw1d6+IiOgZI4+d5iYL3imzbgyO+tph9t2oSBxOM3ugHtPoFZ1LM0hF4kXNEBssvVgPdjdXZWK7uKvyS3q1Xb1WQwtVDqSUggq+Vw3t56JA2cz7PXOwGNW1ecwxPhfe3QEUsDsFaAz8jg0nf+iZMAHNg/XSazDuC18Iq1HBRrOsAQ8NLB+16g614jmuSgs3bROxE55D+WDDQNA4ivdMJ9M1b309UqknaDU8ObV9/PwmMPATvTMAxpABLBzugUtV9bLdhNDQA+7B9tQJ06/7QNDHGSwtgZOCIA47InIoDdROQGtt0U1HI3GaoUnCnC/rzBMQJteN17+VaAzYNA7e+PFqHQUyXPUYB7iQYa5ZFjq1Zqpx8Uqu/XT7+6BWC1Xaj0GlBIwMoHu7UzcI/6/Acb8KIq+hzmGWmAYnADrIpvKP7TZeLaf0LAeQkGgebbq9FToI44p654F47tekKkI0L5PQNZPsDwPBpy/ni+wKMN76Vav4+2cFZFf8+JwAraMt0DFB7beA/u4Zz/a+RXx0M/ct4/jwaNAS8G17eSwmta0Fhx0VRxJkHMivso+onMXr+YwdWKbgioy1jp4x4AzIKg5lEA7wvHEYCRmdx11TAuT6lDLVl4KvXkAET9P4RT8H2u+lg9EPQIpw+/NpJ7RwE8HaDv/Mu4f3OdNkq/EfAiEiOANjEALvcWL9gfFV4NZbgbQc6qPky4Pm35QZxtH1f4j+P/jXuaYPcWwIEH/fmEPBoAO4m4LGxV3txOQqDU+dXgey+UwSzuqP++uImO/u/6ogCb7wTc1n61sL+vZi87rxnrNas+giTg6QLzaUCjIp6JfhwtGI7AjBBB9JjDY4ePYVR6ZPgN4owVv6Q2N5hhVHwNeYrM+w6dN6K1sMHZm/Ce7bHe3dzKr1xw1w4JrSQMZtgnoQHlr18fzunAszD4qurNUg/TDqzx/lfCaO6t4tACMUQ6P6htWjDPC1hCoZ8kpODzJ70MUR9AODcgwyqyPhmE+wfHYB/hvSqt6qeXUShhXH+d9SR8DzrDaZZdpSp/HxqLMQuATgDU/qDPRgOIeT8cvz/h/XC6BtE7ACLOWPE0KIS4UUjmZaJ2grBphiWgT41BUVWZfP3AnEIT6OrfoF122l2rMycBoU5i/OXoUZ4/aglsXwLzHNU++FVF3qikOj5HXm2PBitT1WuvJRAB+6O//W0/PY8vQH5IrAsMs/WuVmAdHBrQgrbOxJShXwRSsu08h8JMBpo0+aDTALwV4tbswgzHrftG/dJKIAQb5h9KCssWIMeto+GYqG12/HWGjx8kzqNJaa0noMWOr2KwW01AMwJoNvhMQda2/RKQP/3ecABM3g9uD6BY68Ntz9+nDOMb5iV+hIE+dP/Zs/wwJhJ9mgBnohBuStABUXjugF3hkXF9ZZJAjefKdHZCc389LoStKvIl7QIEb1d9RyciQgFDI9Cjyccc/23Aam7/PZJBhgDgin5CtQvbCzX8ip9YgIFtOAt+w0owp/hOiCWgEGbVHuYjRigPGR/YOnEoqPDoV5z5YqB3mRq2ox5ICmSSgAP1Ne+XV2NE+/vuFbCTRADxtS70VRBCjgBk2OyDUQiUgfl77b7DwaHm2rAZ7osRSOOUoHgKfNBSLI767+oDYrfwZvqChSpGfj3pFwZFsCJg2jeIQQBUiyI4WgD68ww4qO8khuWkkIuDrxWv2nv+UTBpJYiPd0KemTA8qqFiuUF1jWS3BoG6pADJq751JqBI0wvAVPyMQvjcX1zbELltKK+zBiXRFiRxG+b7q3M9xuLdzR8g0gCGNzSM5gNYfqGO9CBT8OHct6oB3KsSDBisUnwsFuISQaRHxDSv0vptt2oeLHMERfRn/FG/Cx01EpgIQG8LP+/i37PKw53xn6sYCM4/JwSRrCnIeB1ZkLsawDhaPKv/njU3wnZ/dBdGE8+YTHSG8+ofGgIjsC19YnwdM/KAnTSsqj6ig7uGgIPw3nYFzhhIIvriAxFP9CQd4HSlnzgxONIdrE7A8ZDPx9fjib8ifgegNIliRgdx95+E1T7+3nQVNNhEzDgGA3T2rEDLduwtPpuuouPcs8swwXFjdTaMKt+jA5gUAQPcf95KJQxYU0cYxEDvsBSmYuukp7AwnqniC9Afa5z8vboI68ImT0t26CvwBzSggkj447r9IojvCn7U92J/Hw0QSdwZKNNjxPCfSxRqnATkdwpOwh88oc4J8KTSm/wdbZjrc+4iFP8YO0/5JJDCfaijK5xVXevqfg6zGRrQf83chvX4aRfAE//6vv5+6490U4ADdO7QgM/5bcHP/n4OtCQhBEFeDWSvos8DPq8/IwzLzjpa8/U6MMSkBklDm8e0mn3QIY7XG1Om8wzN48y7HwhOK3P0/ZwUQHHv4psbdoVeb9VlAjChBCdtDDpOKTh9ZfcagOYq31RFjN4/gwBYzp8lAwYNwBELhZoxECeZxMlAzWGdCRV0fQWGHo8+8Kx+AAxnCIzowAxy9KvNepWfsfp4RR9kUrD88CPVTuXRybhqqTHcnxEGndsgub1Gdug8yz9fHt3Hpl57x/mfCOC29FOSQ7/noAZR5W3Ob24UMpuPYAYiQrQgk1gnFoUIKr4vKFpV15pHUJO3Y5rfH3UFHU4bGkU+NKJ9f2hJyOMxDBDpjAgwiYqvk5TqNl9EH2Arb6fA3yaA4cBtPWewhkEcIQJBlGzYp6zRmr1v+e3Fv27xpzvyI44NGDkCIi7CGNV9Dw0M8NtHC2vUwHINumCGNG8erxOwtQINsW88Tlwdoc+F85nI559ngEDpt2F/Uu3hiXYrkN/pBFS26hYDAkFgErMK67y9mGBA3L5ore5izf8b3n805MOq/t7XU4WHv1DUF/5gugCSOAIW/59uMwl6CHWAib8bvfxWl9/rBGEMTTwDfG+ezEYG4yk6FvRPuPwE+wvc39IRjENWM+/cm5b0W4Pf4WuKUnw/vD6eDbB1ETs5vl77Dhnm/51g6wPWwQAqxnivgQaeS3gy/u/1H4hpTPrIgHAN0mSgXUX13YP5PMIuQAfBr/f70cdeE+QoCX3i8nFMLcAjInBoAIYqt1LhC1WdtvmSab28AYffaeivCB+ohdYQgfUa/WS4ToMsNLHLc9nnvPZLwn1/EefPVf+U/xvnCVSEQEkEQEnEQJO7S7RvYDxNeNYKrG7DKMhtsQ8cMmhgPKKKj+F7CiHYFR5KIIPxOmg5IVAtu3ACQSPh7CzUQOgAej5CWEkIe3vgxz0ROGO//qYfz/dnLT+ZxDr4QW0eNCJBorCFOVC312Ec2TiY5Bk0cAaQmiA1VH1MOwDHQ0kHdEDDf+2UTWhS4Z8diQMicLx8MLBfverLcP/jQzF0P8EJj5+NGK9RCz755S6F/f1+X/gxeP+Wsedv+vF8/54aSPJYFjIQd624MDz/UDLQnr8HU3ztKHRf8Qeno1vyAQJBaLcMtTV3cvgP56COCqd/QP9xLgBkH4BxO13n4hNUDtACC6G1S3zqooZ6Ba4lp/zcAFb7iERKQwQcF39IFJjdXECGADw0IE4gg674pYAnk4HoHPx54tD5daO5vxrugSkMjgiiqc7TVKAT6AT8R4ckbHEQCYR/IZBxJgA+XZjsR7vaoRpIxWqeqfXuGC2CxwudicwePEB1kNkaZCuwyF0DuKv/4sz9mzP/Qxdg3BDkBTMC8Q+loD6UGBzx0Kz6eAX/KArOQTlPHFoI4vVtf4rNuLrca9edRn4xBP7k8w+9AgZCgBfEUZWfEs8iFNZ3UO7TqmkjCO/rWdgco/yIqHcQWaC2EGTzgz5y/iXQAvyx3riyxxV/JeBriaGB9OrTA5g9/eokM+37GszqfA/UZk9iW5UnCtBqBl3XoNN6Ag/+zy6A5evPAp+TIFDn15gQw9rjrOzFX0s2JBVAxa/nP1a6AsNWYGjPNGPLTQgBsNUFvOA3Ht9o/rGDN0tWOCcxJGp+f7++kkP7PxcGv1+GjkaLt/fawpwwerQxBJNW4b+PJsYEgiAYYdEAGIlDNaAbRkIgK3ut0jKByp+8yz23X6GttmBmjwDvChgiYLP5V/zhH6/110sGcKo5CkggCngxnIPoPja0j2B+1BRkiYJiviaLJqghDI63G2nAgAxMCuDdnoD0wIQm+urMB3VuAwbBrFGgGgnhAFqg9+ujKsLxB3qGCQNEEtPinIQlAj4WgIw7/iXc9V/x/yUWFs2KH504bAh4aYWf4TrTLGTy9YbftyLeVOWNfYNyt/ji29mQnqMAltU3ioTtbX343yv/1u0YPUBz6zB702tQucnX0gWaFh6DgPdmhXaapGotw0SFz1qDiTMdd8h45HfcqCPRUhA3+NmKz1l9teCPaMd4urGaewRitNBDdahR5c3AfQmDCFT9vmtQEwqAYXX4XI2n23Z9B/Yb1FL+LWox6wHGbZSo6FR1LzyG+3hriSZvWT6jfXhl2cmQZJDrAbuYAqAHo1GA/EOgD8eGcU7A8eDvH4fQBuAhBL/Zp/vamPTrRENDGLTV/7E1WEPLDlP/PwzU4YhusIMUgfIPAr6Dhv5R4y2r8ldFwiFoYHnmr8TAHbhRQSZOctH598ZYhqt6wP7q/ouqe77RJxvzFYaji/z4vna4v5cUMDXqDAJ5ytktqtBDckyjvJg04hl16LB0xFfyMfD77PZjErGQRRjYIfSvoAXntks0ok8MsUC4KARWnYPlJBeIgLeFrUgDOHYCag0/XNAbWgRwQuLAsaQwIhC1g7+jCNKuT38JfnYSyTi+QQEwwHeT4/dWHYxJPxfOj5oAnRQqgU3YgGZSOaDyK3n/qkDYBKptzR3oD6B4fyRKjp2AzSl80YR/3P+/1vBjX18Jbu+YsrMRgbqPP8zrDLTAaupphfeZtyPs9BPztpLSBZjowF3woYRwBwOWaqbev15b7X4RWsiqYiY6ZkFEIoUwUA2OrkeEQE8HYNyD/rl3m88jCGgO/nPW3xy8x4Q/HBcM1dYg5q8N+B/SBSYhtD0EY1PRGLDoKIBHF3yLz4H/gSYQJRETgqeB2d4vC8L2NVnQn4PoVJJAcP0inahAfdXVI8CFszjRagCTtRdV7Sr895NBpRKXIT64RMFw/iw5eChhEvmmyUIH+k+Qu3cLzOAN6ILlFvgWnx3YWFDz0f38ze9GlfP6UQ3ojEY0gtqRIEbA5/WgQFhsEuIeL75uTzvqHktAWfj/OD6sQXssROcGiRgFn0QVkld7OznMDT7CJKzhMIqxW9B+LCOQdH4uyxIcE49VTSeLj0wKjzcp2oDXQA8YoDEGBLMW0BJw+eAxXejPV/IXd59/tp5rVyYXDw5BlRetSpQAcvgfOwVM8ObzBq/AQ2wX4lwkQV3vNhYFfn2LFgaoDU1ogqsfqGkJYmrj9Tr22KQwBLzbLuzDeA9yzyJjVRfwegWq0H+FThDPA6ZhZwX2M2Kh4waovCzAWJTzD/qY00c+6PM8coz08VNqglzx54LfHuTJK7z2rwX35ABLg1DzsZ7Qv7l/f2yXDlbf4C/irg0MJ0aCuD0wP74MrxfdFlX7tq+vtRdCpvt599EG9Yz3V+P+Oj/n4zLruZHcJ7oMt/MNp9eD6HEeFb6/TMfbWo85Pb79HJo8t3371/PuIAZqMvjPC34nVV6ZB4hEuA7AzA5cfU0y2n6ux89D/35/n2/vWY5Bf0qwf3tPLISO1Tap9qzFB6eap/beqI94NCCbGwgqOItY3CGl446CaQ8i2Q9g0AvmgJOnBoAA0gu17tsKtKS7D4udgCYERy2QIceCX/P7mBW+g/7D9S6Mn50CS0eAoQPDcBjopIA5+EcxEjLweRjXq0UbLIjcBxsGx2IZvlf0ATjz/6qypAmY7bhrk4ahsIis6ccXKHdueAfUgk+RWPCLh42c6zEeKyJpRTdRAOqBbl/Wq/uT+q+Fx3FoTIuCzc6+hN8j4veGjuAnhSE5gKnco3A3XwYlq2sq+lmP4yEOpqEoG0M+mGDYuYT0pKCFHgLHKt3T7T9p8GcWH+n1UwGa8X6kQt2x4CeqPexegT6o/Z4Cr313PHdgrsS2ZReLfpKIf+IMFnmVmwxQ9AhithYT73+p2s+JIVfrjwiHnpAZrSsr9CMstQXP1+1+510N/q8E/YoekMN9OMFvi5LvkRDsy9rgFCOoPdpgaQIWBZjf5KCSQszZJ1ivTvLokpen6tsJAVND0NFqb6GUGg2Im4Dyx9Pn7/0dm4pADAslJzTv+dKNrAPQ0wyySm7bj1RQgbAXsRa4R+mBJzpaQmHLmy0BLoL+Nh2ZRca8uUc6P37k97n451fvTieAE8BdZ2ItqFEK6oOJIYPsiU4woo140Oh+H/UC++gatHYcOFT+2y3AYvD1rM/fpxdUcsAi70c0OxAEP45X/hymE9XeoC0zfYhbcqfbhs09HpwnKMDR6g0mmYyKth/UcLl9ITGQ8N1S6s+gA1HvQCc2pluPvN2Br8SyZyfyxPP/VhCi1L1HWX2CQCuAE8TIq/sBYdANZmTIwqq0sb0HIzhhugBeUpBZLFyA8y+EErsBUYDZHYN9QAAooQwOws+uQlhdESSSqk5Qsh8LSYI6LDS1AbmOvLlRBqQIeITvM36+TP63VfE5hFClCTr9zEyVFwS3STQBy66DMHB+PJWIrfgGnYBx2dTboPa2X49GaBVlePA7CFx4iaGi4ns0aLVjMGvtPTDtmO4XEE8E5Kb/8qYai+NHl60LgAICcUCoJPVeiYG6Pxw/X9VFNVbFn9FNPzXoIRDTyzcpREYB5Fm1EQQn3KRi9wKApR8Tz48SwxnV3qM0q7ZhpdKvr0zfY+gO4oQf+EGPFYW/Xf5hwWsUgxiBbShGoGIx+D2eH1h2EeR3UQMH4zMaUKr4033nzkSkfQADelFbLOQCalxdxvN8mInhPas9bxtGJw29Fx3Y8429MAS0fL33Oeo7qFZeiToCC3B/VSNYuU0fgDnkhxGgMFdxiYEY7MYel+OHPH30IMeVFK1C79l+QdXVpFqHlMAXEf3EYDyfkkGdNvJ8f3RAXU0jpgM7jMNA5yCrtfzOicKG/M9bgEkEjqqPPDEcDfqVwGZv6zcO9avDfOhf4OmLFd9OLBHHdxp51HvOBlnAoQksYjASA1xnIhPsapTCPjbsGB2YevpPpgM73EYeSYIftgPgte6CWesVBB9QEgfnWYMgoeC8ql69bWoRIqYHvSIv/u26bj/jdqZ9KSGk74JRo6QS9PuTiSHm6Z62kLUGH0UO4rwWrhtRETkR4iKRdI8giJ2D2nUCMjsA0TXiVDb98NAf/rCMlajA9wesWHZrAe1dlwRyVI2jx4KkyUHSx7YDe6YD4tOC6XW01puEdAJwaEJzf1uATHi6ZlSCpBQscsh6C1xRcWEG4bCFeKcAVhVlDu54JQIkTT21hptIT/Afk0kMcS9BKfjBJozcDXCrtgbWXxbMAw3INQIxtQJPAGwXmYaBbYh4SCsuKwLOAQ5awKskCMmRg8P3xwlBfbosQaDqyZqBkyQe1CLQACoTgN4qbyHsPwkTiF2pYaj6MAXBmUosQHnUEYCsBL3MW39SNKMJ5PfoBsT33DVJCEbFnBCMOkHfvj6Xq8uw+dgRIhGgAiUqf5QgKDFyhe8nnYrlqn9sG1GoAfirubygX4H+8IM1CmQrMFAJ5ExzKIp54nPoVU2Auh6eBShDlTV4u5c4HE/fVvjFrsII0Ik6QX+Iq68jB19ziLoKC27FYe0gC+j1RSS+BgB7AvAM3m8HLdy5fV60C8RMVuhD1ieQB32MCCq0QPJuvuw5IHF/geMKwOPdpmsxBwVEfGEOgeincJqNmuSFIPhPq/xM81CWIIi+gCFBqDX3QPYd2OcCRo6GZBoA3AM+00aesAOQ7/2Pe/vBCXoguD4OBD1WfPwClzcui12AuH+gC0gEwW72KfjBCQRBr05D0IQc7N8PzOCMehPWK384MPVDJQim7yDdoiRTItzzFV/ZOX9sYFetP0fsQzb6O7wOoFjxk89YoQXv+BmSN+yYHYO+BsDRAXHhuJXsEFbdIEGZQWUkNVNzGA9NZUVBIQL7jASR0AclE4Pb7JN3BO72mG92+o8UG3nybj+mASh0FsLKn9GPxDrEcS2Au35BzHO1BksriIJdpqWjKR1wlpR4fN977rZqI+XbYjYDgVDpcYQalOYKMiuQbB3G6Pu/HlMbi9a0EMkksXtjvvXTfgMKAEZRN/i/O7yD8Da2S2Bdh3ICWfp8yuMkYl5a4df4vVWt4UF0yyqEnaT6swYyWB8/j111Y1ERS9oB0SLMtBGDEBD1PEHwtdjUEAHnqmoHU4wCDAoAS+lHwtu9eQLUAgmxVvAuMB9cELMV3m8EUtcBYYI9nkNIEEJYrQeUHfnzzRyC39j8CgSkir/E0P2odnAmAqDnDIhqrtV9BDNS2POjv/0pwKr6z1h/PMz3uf9ykFYq9TtoAXSwpz0HljdvBCVAPY6t7osv6gFhMpkX13rcfXQMIpuTsfTibkfOPRAC2meLRipI4mDPwMD5x+v3+Ey+qEfACwoUEkKQSMZxYJDz9R68PyP43yvo2aYf881rNQbZgRU/jp80QnW/hdXqJxMvCFxXQSNHpE8QiF4XI+wFfQcw7VL2Md7RRajsKgh2D+6SLAKPF356+/7yXYBTUgFy/38StUjFHweD+iiHh8/LV/i/TSvGk4L5x7F6AsIKbgb4C0YjgdGRIToGUx7cgS3JKP8pRcgak95BJGQbjaJdBYQ1qHYnYHL8F45QgHx2gLMQ2cDxBD/4SeR0LSDi5XzPQNjM4ySE/HGG6g+ugltLNSARn281BPtNO72eJLjdX4ITSEgpQvJYFEUg24f1qAYQNQdxx6Q/RcB85j9f+03zf2QV33IDPHegNgPABTfqFR8cZK9TA7/ll0EQbUUHW8Gr1d+MSadia+LRHwhunv87yWoJ3h/pRDwJAbDNQQFd2P2mH4kP/wDT/ZeN3CK3+ZjvgVpw4r20AMafb58j4N1UMknuj6iCx883PU9g2VHVH5JX2eEcPghSgRBCKPzK0Q3fknwPN0Hk0CyC0zBkz//7duEetgFjVtypASDI4CsknYJgYDhqsBxxy29+eyxrAZX75EEf8f+CkOcijMDDHx4ASYGGu8WHgPwpHJc0qOG8FgFTuVk0cRZVePFwHEIUEu8xSHoL5qWg4I7/HgOKXe2dcnu2SSdCGIDTA+AcxY1zYL6Q6AAFu+/1GvjKPSe"+"EoJV3NiM4Dz9C6oWkEav+NWjPWXNOIkKgNTi2I8LeBgaZHJxqrC4oNXoB9pzzMws/OW3ghSyQJgjbygOVEDhoj4nHLld8HPD6UUMFVLIgKrTL7cFoBRLQgEdXIseZ2/HhFPKbk4d5tYWwwR0nIFQSD2P5gQhs6meVfB+Bkyz2fOIvX/zxqsSODuAGIOLtPNnmIPCrv6Kqvgz3q4tCwNl9lWYfnsdHj2HTgQw5IBHwULmfSu1jEV3gDFSxTBmqSEVqiYK2IkWcRiAkwV/cyW9YhqHXDw9dkNQAcO6HFNJT7oChfrPUYc3KY17zAd+evAwF2w5SCKLV4EuCEKsKfjBVWHu9Q9Arh4CoBqEMWYBsNX7YgKP/69uC3M7/mOOz232QT+ox4iCyJGEFP4oBHd+GVvXBwX35nqp7qeIbV6L6tdZub3ueJ+gBIKgC6S5gOQFxDoGr+Bv2nzqbknd7ph/EmXzO0o+kZdc/wqvQkAOUffVMzKtYgx5Vob1/+HAfCdzHSiXHenX35/2JTr3KZ9Ruj2lYiMhLIFoNyMq9hFroeYMTE0bSLbhb4l3YlFPa6hMd2jk8dmrDgdQCnC4/+ANFlYTB6ATlx2GDGXP1rvL+SnWHw+cJes5/rRWt4H2pw9GklD4uSMpwasIQiaYR92gIyFX5S8dtRZt/nCAH48VXW3hRE/HKOsGquj8EM85Q9cfeAV4XwNGAlmIFIwPYrfLKuxV476RRetzcdeAsRSZhiHizCKEIOHn3EMOWy5X4uIJnXX6sFiBFLaBm/THOQAkVJK9j6TKwiSDTBWpwHkSPQJX7U959uAkoaTUuug6oQCBz1Zlxm0OJSIoIw04M+7zCGuYiznCfHww9AN6Ir+HXA7lfn2oBSJ2FOOh8SzINfmcAyITq8JX/sOMPx6A9LeYtVfwgCBZhdu25OB9/XmWWNPUEPD5dUuJ68wd1AqD2+w1PI9KxE9BW5t3z/igdYGWiL7L+wPv9jgVY8f0ZcbCKCuLAHN+c5wa69Zpr0J9t2KnpAGzyiAIPiFalJ8/xXrrA6Y+/8NoDnWCPNwFJzf5DpVkHte8hx76P+HU1+HEytEeSEIzAsu5r6wPJGu6oLz8VrKofXLce+ywIHhNa/Dmw8LrptWXZ4NKZm4pr/QQ7Qk8ehMrPtAF7PQCD309QgRgRZMKgAbFREAfBBXNalbHA9cEHMo4IgIUuPjjBWEUFEQpYTkhVO43eRiynJw9Jjj8TOUIlJExK+0wA4gWgQvcFBHAc7P4/u78/Ff4CC5ATB3P3oUwFClYgcALcxzp/B9Ez4DUV8RjBbsCBrMH4dLNwIDaCGhA6o3pXksdBvYBsktrXDgNJKAFy1Z+ZGIy5NXgXoBT8a3ZgVSPIUAMV6DjLxhsV8wX4n4ibbONObHNyCr8Z4FinNFjg8ziiF5zSV8A99u7Zdf5OisvVaAAAG3VJREFU/kIPAJLWX3hUIFD6o7MD4WkHIMXBk4IftSrPNBJVk0OoC7ice8HGS8XBKDoz/YFBLaQi392lGpCMJfhD9xVkx5Xbj73P9V4m1j0v73x9FjDDPlYvATkgFAVWcdNvJBamliOjAwRV0EpeRymAe717kMYRyy/j5FwFBX0fP7Dyx8gq8wn2ZXi8GfGYR+lFcGJSxa3Y84WgzBHetlU4cvKY44Ps4iP9fsgsPGEhQTAcHqwwGCj61SoPexKwasXFqtxq8qhD9SixoBBYcJEDNzmIoi3J7QkoJActVHocTVpPBCDhElAvMDK1PT/Sq3DwB/ygmyB9GNhYDH4so4Foy48kkPtZfZEv1PQTxYpyX0EI3Bu+/5krcN8fgwVdwWu2JNVNWAk+PcOOPMNdGFyAZ5Aj6gicgzNfwuHZg0HrLxBWfjSRl88fVCo/apX/IBrIvf65ZxtEoK9Bec4KZIPLe76osQns46NwW0pUPCPAyMc4A/KXOwZzFLGbAqD5xhhbgBcWfoJBAlarcCSQgdQJ+Movnih4gjZQTw51rz588y/ZgxVUEAQ8soCfX8OR26JwujCLGFAMsOjnwGrlPuQw9D/PPv8BYVR7pG/eeFtQpsLzR2KFI8SwKj9KlX++HeLOPuSBKrKeHBi7L4b+Kx184+ptAp4Trcscv69oARVYzWgaK01H1X0K3zNSmARKtxXYHvwJuT+8gLGGWgpHcWOmBeljFB2Ckg6wiAYOqfxEK3GMCAj6kIiTWdCBCXhkjUKMgJcLk271N9uLSbtvvK0S69OXAvoA5z94VsFubbmZvx4QAnXgBnJxENyQjy38wef81uPhxMpPJIQzr5ckuUTKe0wZyN57iFTWga8GvCwlh5UqvYgmaNV9XSxEVWs40kkosFwA70RgNOu8mLZfR6wDiwRa35y7j08NksqPQhcfkRBK/J8R75Iz+9C8gJpqzwiIeZII3QnYOkJWbVEI5jNuA+o2BwK82ifwnpSgHwaC+GNAdmW2VXfC+vPu6wR6lBj84C9WfvivZyUhZMJlJhjSukDlFJ3g4AvGJfC1iEpQJ/CaEd7G9wds7p71+odruKrHip/C7RdsxeVjzIxhoNkFGOW/+sk/YVAGtltfzZAIfzix8gcHhZCXpcGN2u69qWqD9OlRFAy7x2fQBhHUiETB+DocqvArYt98f+AEAXApsEmEcNLC0t2uPHCqPQIXwHYDfI4/9+8LMpchqr5HK39MJSrBXwnutNqjovjHFdq+fcHLp7YLR4mGgduW5hFpAXUoL4cTTuW5HJSkB5PC0S7A+8c+837DyoM1J9iv/po/o3BunlDqPjOSO/YbLFd+FGy9sxKFeT8b+nLNPrkAyD53FtT27yUS32yqUaEGTMBiASGcZ0FmK8nWxbvjC1q6WQC4VdWdAcBY8eFoAzIrC0b7Wt8wlPcIdE1FhUWeKU1Igv8Q/0dl4k/NnYSxdlDon8diUDeuQB4c8XVzcahRgyyZmNC+LAgeCfSVALde8/t1DCYawNoePGT83wlOpFUdOZKwxn89OsMEf0X8CxJCBN/dwKbFwkSMgx0ACJJDJD4iC1JEYh6XcEqVHpx4+J4I4UiAl26r5x64sttvSlAn3LBuQCz6edU8C+J5epBrC4YP52EFDgHrCw1B0eU9bOaTgh3wmYvQV3Oqqcf53XnVNXUBELX1xtSgFrirlII5d3HFulxBCNEfZx0h7K2f34XwdHpuYQcguN189Ow/nPXclaUcqMH5leCXjKOjbv3F0a7i2ZaRHmBe5zwnhA9S736ZC8AH8LHkg/T5znYgmES1dtuzGo92qwHIquiWX+4KgVLd8utv9Ml1BQNhEJW/FOgweiTguCUoQHkEwYhjfQIgm8eAzPKzHqAG5xGiiPyxeGRRaYetUpDVpHVC1T9bHGyaknb/TQTnuG7rDYwYCUT7/cMjtILzA+Go/FPw581F/mWeTkDuBsBCAK8ki+A29nMzPn4Rzjv6QV7xWW4fzQFUxb9jQQ1qc28kMi4mDl1NBr4usIsz5ltZqNm7AeJXfuTHd7nioLEyPBISU+8/tP1AC4Il/n+YGmjg2NiBRdl6yCw//zG5ph7bqaBuz8B4VMU/TqSsNPbwCeZA1cdxyG9SgKzRZPL+GXFOiH1/SFZ9wX8M3zUgvH8a4rMBjZj/h1W9MrwTiN6MlsCKiI4gycBzgV/xUaQGjGDHwHiYi0VIzeEAasCpNuL76AC7BIEl7i4AIxnAfoMxk35eJbZ68wWEUChs8IPz/EEE9BkUoNA4RCWSLJkY1h0Y/dG9bVCtUVPe7QRhtStXG4nOECDfUxc4Uw/Ik8JkA9o9+a83IrfHH11EdFUWc4phNgVFWkPsIHBnCvCCYBSgqEN9qtoXuwHhByYoJJA7BxIkkRwpDGgAHo+vQ3ZGOwCFJCJKUAx4MBpFZWvReeLgtBBkDDQu2OJxXa7SE/P4ZiUPHABjY1DsFIhPAaygWewiXK72hHjow/k8gCL6gKES8qcDZ7A+EhYlWCPGCX1wXIwzkQEKt8cP6iqkC0FEhFj/ZYtvXCtwuBLcDT5wXN+9H6ZEIkTwV/x/s78fXFX3siWHEKrC3tw7EFZ31Ll7ttknQyEMGgAqCaVe1bGk8r8nFWCQQR0h7CY0dsU/mIeIuA1AGCo02Q0YVXxub36sG1Qgfo0CBBUXxap+ECFEycQVyViBEBFPt14TK9rZHB9EwMG7DPXOv0OVHkdtx7OSCXfb3av4CFZGTwQBwT7/hKPHE4PzpJ4L4+FM9r1n8B+B+9R9I4Fu9brYUZgCunZWNxdQgIs8mASBQ4F8hJpEiaf4GPihk8FdAxin/kybjZjTj+mAQy6ihZ9whDvHAWB6BKrBXQr+5SBfqPaINwiz12UIwoTmbPACZY/fshBBBKNlW8ZCHwH/cVKSOZMm4Mxk4OwE9JeB+EFkn1IzcPQoiSB4vGgNeJSoik1A7m0TCmE/HrggB+/1M12C1Z18ACGoIeH1pH2IhAqFWgBq+kDFEWAvA3X8tpW0cnSD5WAOriOHhnYraF1eLTkS8P/QsHUBdtMPnOrMaANJE9AZiaKWII5Ue/8PTHn/UcCSTgIF2xN4zdmAQYIAKeBFl6FiO0aKfq5jcImHfPwTxcEdRmD3LcFoAva1Hdjm9UgGggI9YOoPkOBYLsT8HlG3nucMDGkOOJ8CkNOELdSO7D5qqAeJYBb2GpABgRi2gxLITgrOQ9C937HgB+0i7MeRx3gfPWCXLtgbLJAu/gCFBPzRX8eADJqCvA3FViC/BlOQC4LZyrBq8BdQAOUKoKjqR7v7EFfVFMojPgEoSlJesNIePyLHwW9NRgq7E6HvUN8A0yj0wyWDHRZ3J2A1jHdMyu3hCGwSDwdRir7h9VP7AKLgPoMCgKziOFLtrUm8aIFHlgxYfz8WBYUU55iAXauo+evJaIK/NTgRJM9sUcZRzcCnMdNKMJc7usnAyrpxHYkTRHK+n1HxS01LheAHqRWwKIDqLvQC0+PupHZgBawfVGsiniTVHwZHRqbUI/D4Cd+ftgyLAR1ehkIiqaKFw7MJEwUIuK5zsu4svoFYCFKgBJZACBuppOId2RDkPZas8H9kULcA9a0KTCQDGtpnzT+RMJiOGseHl4BQ1C29AWUXIIf/OIwwqoNEK3SCuA7FRiBrE9B4/PcrGJ1OQNj83F4Xbol/TgVHfMiIZLAdcaVkgh8sLrd+liNQH/FqsNTfj15m1J0X+ffZuq/gTY7QnvIfJz6UzBJLs83ItQpt3RfZz5iuGfNPajpngUm0R8DoA5jDlzsOTAwZjzsC3Jjxg7H914PjlcskGdghgx9HG4OOQH34uwQyzz61/0qiYNQjXxECuWYbGM/DrjtPH/Mw/K+gBLLSA+cEfPr4MroArzcDuybbr8Zc72i2UnzeHnTgzD4Ug78SzIvCoARVOQxaFFR3TzWnkkHUVFShEuqKxZnKz4p4YYcf8ZhYhuu8wFgSHcuuwCJagI4bgchJQK/qe9c/RT6nGcg6KGREJpb+MI0EY/b0jcsni3AJBeCQNsBOFVYoApcM2Aom4VFgIRdHpeIG8D3YaxBD+qCiQ+rBOSVnci8hzkAG1t/pgHA4uwDzmu8xFKkkkIqCfkIRs204r/hiDgutoAAcowBMZ9+KS0CcXVBOHCvJw2jMQSJyeoeExF2DuTuRcuWAo9sefyUQ6/oBaIjPtiRH1KvQKvygAHb171d+vc4GRMDPoxN/kL5pwlVh1mBQ1quQJAJ5j0TgOAis+h8d3mnC8xTKE34+8sDNjyVXE6nFMN+H39TQDmocHScENvN74LoGScGU4f7g6IG3n3C3qnG6JBS+Z5tHOOzRYQx+u7MZmAl0OSsRLAS/VIKfRAWU92+12aaVPksGDBWQuCMvgNy2M2Mt8EwqbjosZAec5xLEAmXmcFTHiOWARWglpNpjdEtBQRxJJU5VL5/7F1X86XntXgUK4q+KggsUoIIK8oA+kgy4+zLaACqQGTVOX6MBWdehL6BxHn+tlyBMDGAqufd7WOX5WTJwKYDfXJJP2GXDPk7Tj5Ed7BOG7DMFaBRAJgI/+H2Ngeb2SKb0zkoGlQBHkefDr7xMA5HZeJPtKIzyApI9gmnPgf1c3mulfhe0gFekDCdNFnrOwi4Gs6eTACNjB+Uegcgojog4V25P8bctRYY6RL8AJklE9ACFAGZdBEahd4d4CmghFhbzcwaXYH5qTlS6DY+KfNH5Avzjo2JJ0poDkSCMxLn73H/eB+ifvgvyIFCWAji7BWC8hd0qj0FziMdrS70BlVbgamIgcmotGZDNPwm0L9l5iHv7WRoAFx57ScFS2r2iwot8oKu8l+TOCOg2mZ2nFdjTgOFQENzKkJ8OjEnsE8f6AzyXwT6MNF3RDRnuj0Lwo6wTlBMDIyqaz6G+RiLJMg/KUrQV/rh9uH0tWduwoxmky0kSMQ+rnXxZsGadgnxfgk1pCnsIsGYltvfdzTOBIclIsN8MLAGcz5gBwj94AE8DuC9Molip/JGwB57nRyJiyD3pyk6q5ij+3TzRLohcqyqCEQBTepF15+WVmW8SEr5jMUUkx3oMIsrH3ndwAQganKzyMpOJNxMQooGBYwcByw7axIhgPRGEr6GSGJhkAELoQ1YRg+dPeD5IIRDIqq5PA2Jh0Rq0YcS8XBi0ghGRFpCtWTdum5+yLOsQf2EuYY8AfnbQZDgCjHxBSKwTGpt8QCIDVH3/4H5OwEvldhliINwAFLsEyyIfGKV+vm3eEehVqKTdNxtDiPoLHCRiuwTJxCECxMDqDjTvZ63KaPKvRgV2i/F3ohm88V8LN8hgJcXD5pVGIPPNn9EBqSQC0I4AMxBUcQNCkarkFgSn/oCs9GCVep4eUG5BRAOcQOCWlGSc3If0IFqRfURQGRrKewPKEJ9sLnIowKCcw+f48N6UHjqYtgInaCCkBbPSj8VEkCr2g8U43wY1xX/BNkwreQrzg+oaJghOCGTU8RBxuIp6VFOGoEXgEsBLIgV6gBgxoLSI5CgiYNT+GBHsU01GthrceiMUtv9KgAYktgVNeGrBbtiOQVi9x8WjiAW7UNUnm4Vet7WtsFgDCDYEwQ/EVL1PnQf/xCDLTowTh4c4HPRDoQaiwhKIAae4B7xgCBydI/CDPOrevK0FR4p6w3VfoXgQiB3T1N8Y1PCD0X19JqcHGfzB5WkQE4p/kdeXBcEVUXEIFqSij82lMyrWq/7c+LFHA7z5/dwOHHg8s/Y8C2CmhbmALtare+4UWLfb25BmXABKABTniC8gRAP2yvDAiUAsElnrxFzITQa/sAFecAOY7zPV/8jMQHSbWAiUPGkQNABhw85xrSCv+mMSzFR8+7mjw01A8f4F8S/td4jnDHYxpT8/OEyV3gz2+GTfdAeAszswfJNGlQhEIjB0Bls0BKn4Iw7WKu9f1gmSagmvqleEwJwnZwjO7npz1HdCJ1hS/mlBcRXyF3i/M7NxqJFoeH27z7nnJaBmpUZKHsTbGUc1ALEoIGsGYl9ixS50gjAT/VhB8IzvGTrBVfWEz1MzAkRFTtecW731VdjNQPukVdhdn0Y8d/a7WYH6i/TBPBzUFwAlHwtGHOQISrgb1AMUgDETTA3+THAdeRJhg59V/Ektofa9I8wxVICkC7QQSAd2O3cftzPzdMK6aA4iZI4ILfYRbb9RgqICt2AxVnYZ4kkBvHOBxT/zN9ybHx/f5Ql2fkGCX6ANm6F8WCfqAS+Eq5AGcHJd2IFHagTMHAAj+mWBnDXuc81CjhsAi5dL2K8QCYI1aJ/PJtSSxEFXASv7C2I3ZB9/a0j/7nDn/j1pHsz9Jr8fNpxPBUAUUYD4wz5GBlmyAiORjtAIGDFwzSUwqiNZ1d1tPiB7/Q9VeI9KeJU16/knkEeQJEALjY4rkp74fCZiMDSA/PgvT/aT2gYgp5E/P29AKBQAo6TRth5T4VesQFb0i4K7RA2MZpgyFXCEQHCOixuYMPgy2L7+45ezSSKt2oUkURlpXkEMOLSiXPuDQZjk63N5bmzOSxQdLHX7AhwUEA0BAeQPJIQzkAuFlOK/GtyLdiGDKEBdllQ7YouxV2Xdwza9So4Kp5Z0yAgUhTlJgFzSFrznIHYIwKcCu2/L3LsCg6UI1b1/CA+ApIV5/32HqOIjdQusE4azip5Wc1b0q/QGIAlaWEJbXP3r/L+AEipw/+BtkQVY9fIM2i/ZhgVEgJO6DZ1ksVtlYdoQAPhVO0oKmYBmnAYco4DRCRB3TwCziptaE0auER9/VzRqKNOEYINOQg2m1l9GpGNQAhh1v6UmxNQh2M4+LmlUzll0OTjYQOaGlZAEMCrdhmBphaMBwBADrSQQc3//He8KgFETT7p6BHnjj2X9EXsDjrgBS6ihoAmcSQVYmE4JgYWFpp1waAQRoqDzxDhU+HxSnZHz/9JEY6Y5MJA+cwoWrt99+U3Mc/9g/NQTFaigAEtwB1yBzwzucZSX7RZEILhR1d5GDCsBLVUdIQvsldZfEJt5i/MHx2hGJZFkVVyK242iFeh58oBUFqIQbkfp2DV2X0CkAYgv1sU+P+I/HmBu8nErugdRnUWhfp+A/ddlbEH3uQlBsNobUEMHasK1HOYn8BEEvCUaiuigXRIKj+sGOPA4KAWz9/s7WxcgB4+a6/fI2osEwv4yOENAiPf+wQhbc/5f0gGisWuQaRFmGoIqguARWsBQgTTocDLMT5OJUQnhqdCEig+/EShKSEgTVV0MBMnz04BcshPnLk/+OaV0/dwKzB4QUt1NB6uTDfGOP+cNm9mEsBAFiM7AQh9AKVEU75vy68jeOxrUC4mDEuYO0oLqoSdHaEF2eXYYSm0V+oEOwpLmYFOF3Z4CmAeBTIGueiIw2xoKPzDBJVBXQ5g5O8/twwA+QguIjJt3+g0NQEcDfUXgO5gsqlTBLkQLdl86K3CWneitQ8sg/5oWAUJP2C3V3RoEyji5n4b9lB4t9pz2CA+cAFn1Z9I/uzYsU/ELtEBOCHYQQqGcFejV+yeuRJX31zsKV5IGjway9z6PLDxKwNEPsBuOEiqw57jGgOtZ1Y++T50AuMFl7hPIbhskiOwsATtRoc7rS7dXrpcgrMCGJca6ELJo+Y0be0BW5ZKGcFz4y8W9BduwcDnK9iO5fagsKpp9ANnvDPxeP8THNyIVFo1AMas8Qk5v2Ytm0LCCYAXqn+wQsPTBh/5Bcnne14Os3uCQt28vsK1WUESJFviBgAW//3u9PLxusXchcCR2WsNzv/ImvgZzzkUByDUAIrjTvmSHAowpJBQE4SUlxMxnARlQbIqkArVAJ6pBBvELCCKlkyCDAP45BYfEPfcUpfMch3Vn4bheYK4E66BxAxHSVd5INgEPgU/NBCDfNQ8Ho1CoINAPQAW/QT8OCIZlNFCB84XhoDChFByHGjx35v9BLgyhmojqHYb5QYXnuAecvua0hZe6BV9f7v4ibvgvamrmAc1TmaEir0LQ9h97eYAYVoM/nWA60i8Q3Ifezha9BqaaL3zvqd6IAuwwLSCCuCLuJWch4h30giPtyiAphKEBcCu9BV5wwzkMxID8rhMwdwMhcSFgrBT3RUTQboAUg3+p+Qe1IGarOioVnazmefV3lHpwA0AcLWCahUiXwePHWJsP+GH1gnp/we5KfOhJAbsj0H/BIEb04TbrTPsAyb2LLu93KwfCvn5PLAwrOXAa72eEQRo1CNdw5IprsAZ3hApy9zlcITG2vpCihsRSYxNS+J4vdBZ6B52eqRcQ/QXmSjAWSfa/5GA5qEg4iJFtm624AqXLrSA2gx8p1Mdqcghv41S0lSp/xAYs9gakQc4Ie2RTUYwYgt748mV+FU1Xgp14eW3XYZ6cdqGTNHwHICTwEeTPl0jEZwIgP9gDEaogeg5IHWCF+1eoAhvEKPB/EAeTRsM/pSAP5wjWEUMM1/NJRhwJbpJSgK7S7zF3EOsI5jBQBK9DV80Z8Y0COzvmWzJXgDl40KEC6cqvqgi4OB5cpgLFYK/1CvDiItXqC6/S87wfAUfPtxqfGNzlYaOjlf1IsHPPvffHgDAoEeEST4ZLZUd/RSo91/BjXY5ggWgQ4In3fyj4mUqPrInHOCLKO3wUwRsfyXpt1nEIRLrqcWeTuk7bigsbid1zD4iDRQtnIdQsyIXnFCn1I9D7ADgxEhOvR5AJosoUbu1FkJyYCi9OhQERoIx+4AX/YqUXQhtYEwKN4Cy1HntLMmtaAQpqfrT/UCoLSxeswjA5UWPPi0mjajUWxMTdVusNvt/ChMdmILK5IRMFu90BMEzFYHdg2GAgeYVHMMJIBTA7EFTx/5fpgTFXz9w/en0ZjD8kCDoKPNGwlB01BmoWQbh+AxR689mBponGJOr9OwmMu3dtJ/ylW1Tik4ElUPmR9RqII+pVhD9ychABMQ51gOIZg+/G+5mGIzLB1JJC5WhzYjhJ7IWmLDpA8jzsAafUPkB2WnFBF4iSxkq1ty7f25rv/+EQLOxs2oUdTSA9HIR9swdBlCcFe9owPC3XWDDC0ISVzsEVbSCF/sWdA5Fu4HJqankp2SeQCYYrImNalfmhpVxYrGkUS4LeSUjg8dD7+D7w/ybIfy7vlB9/HJ978zr7/45Qgajzj+4EjIK/ULHPRAOlKr/aG0AFcqCyu0GcW45Igh6JMJmhA49/U+cEssHNJhtXDC1MOya3j/sAiAGcrEtqtgjBD6wEzSDc7D8o6C8rIqAZyPk+NQoNLAZ1hR64Yl1FBY648smUYKnSg1Xwk/0DyRyArByMUobyByhCcPnOaPyoegREFS4jNfYAw+IHCjdC1J2WDZBke/OyN85J24WiXwDYPoJyYuCD238ulvuzwt6KgHf0shWKsqCFFGjB/w8HU8eeTED9wAAAAABJRU5ErkJggg==",Dce="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAF9UlEQVR4nGWVy64eVxGF16X27u7/HMcyuZGYAINwmTBigngBXoc34El4B0ZMGDJjFCExQUIKiRKZYBITHdvn/L1rF4P+c+yEUqmH9WmtrrWLkdB4C1/91h/9yn947D8+8CfdlBeGGAMtqwNd6K7VWAJrw9qwLtw2nDaernh6wKuHPD3S1Vs6vaPT97W9r/Wx1seKUWj7Uzz6vX79T//wF/Gbx/7rw/jsFB/39nlrX7q99LKrp5bJZXAtrqW1uJIncbNOXafBU+o0tZW28got0AJ3KACsE4OfYvmzfvDMb/+4//Td9snD9rfr9vHWnyz9361/1fpNLLde0mt5pTZ7a9pCm32SrqQTfZI3aqNXHAwvcAB4BPwnk/oMEcqX8eaz1t9cHjxs7133f5z6p2v/Ylme9eWmLbexjlhnrPBirz3WxWv30rw0L/Yi96PpDrcDcPMEfq+qvQCfsFF1blcv2js3vb2xLNd9O/XT1p8u/Vlfnvd+25bResXC6BFLj2WJpUdv7uEe0exGByPoOAC//BH+cgNqUjfkU4mOEetde+O2vf+y8br71Nva+9q/XpYXvZ97z9ardUXrra3RerQWrUU4myLk4AzYiADwJ+NRQ41i7MSNEBIcM5YR1+f21rnlXcPWtbVYW1/a7dL21mZvbK211lv01lpEtIi0MxTmFGzMAABAN6gF1CTPxI1gkXa5Z5xGPNrbfo6xB/bQubW9nXvkHtXDPfqIJd2bI+1mpZjmNK17QFuxDzhBJued8Fy0KLvcp7fpNzJuM3JE7daIWGKMqAylW0bLiHQ0e1ppTXEK8Qrwkzv8fUIua6oG553wQpRIme7lbfpBxm3GnoEMZ+wZlYGMlu6pNh1pT3nqALCEugCeAB2ohKqYk9hZd4JFS5ThDm/lB9N305nGtKfnNKZiqk23qZhySZOcYhHFewXfI54UMCBDOYlU3TMkSaYWaCtdwXu5yprOKUxrqk9FyUWXNKXiBfCNgucGboGAUBwUJzFYO3G+MCwFtdAn6K6UZZSyXCXBAUVdGCoS5IVxAcQNujAHKCiLLHJqDtWZh1GHV0Et8EYNqOABTUhglKJoyKBBgSwCBC6Ajz7Azz+GiJbwhFTkZCXnEM6EJcuHDmmlztCkBE2IkMGAAhQoSCBBvgYA0G6xN4DgLE5IU5iqZA1hJ8zDqCY2qktJHfEnZSpIk6bE++kEXwHUEBMCmBBBFzE5UzNZuyBRshlSSF0aEg6MaDHIgyFCPAqvA/YdIjTgQ3WBLNZkpWoQPnRIUljdGiIkHd9jumgeO0ESEI97cNTPJj6Z4ISOZh1JUSVLwiAs7pRp02aTypRUhwIzjvhfPCKF1wH/BTqwA5pQlnYyipgs6dDBQVncZatZaZUlsUxZYVq0jyfm8kNeBzz/Gu0ETrjABAURAoTJOVVJpDAoM3ZOc5olfmMK42CYMrRTAr6tIK6QiSA84VtIIEosslSTNYUkUxyS5aEDQ6tMmQ7YDMOmjziYx8E56oPEl8DdDgM2/BLeIJVw9CRSTClZg97ZrDl0BF6m49V0GTIZQL4CvNuxFj47w4ASmqUkAalYU+DBoIbK8hAG506aZTLonWFG0IMa1AAHXlegW9wFGuAJG97hhFkqiuCxUZyqSSWR5GCZHKxB7nSwDcZADHiACQ4eJ/Oot9+BvsaLQD2Hby9RUEEs1cUlcdKpmWKSQ2VyqAY56J0RiEEPOqHxXYv2W4yJuANWxBkBOKEGFcwyjlhMYdLJSjLJpA8FAxqMwXZRQA0wgdQ94Hcf4nqDFnQhBDcY5YJUIqSSpnxpRqone6ol+2Af7Il2MJJxnN/8lgIA8yWQUKItaBMRsGEdDIrQoYNTnGSyBqdZQSY16IEYaANOOKn/A+htXH+OdgLOiB1BBOEGCz5ejmO6JpGEeexVJTmohJNORqIlnVDyO4CvvsT2AGm0BVEHo0IMHeEooeQipzDFY5eSNcigLgwoGYlIKHF/ky9Z+xD/WrCfoQUuRCGAKBhlwIBRQvmSuykkMYHkqx7EAPK+/wdqEbWmfB0bfwAAAABJRU5ErkJggg==",Lce="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAABGSklEQVR42u3cx4tb6brvcf0DmmpUoxrUoAY1KCgwFAZjME1jjGmMTWNs2tjY2MY2DjjinHPOOeec3dXOOeecU2VlaSksSc/9aq1X0pJKqmD3Dn3upvnCSe197v38nlfS2fscW1x+kbCMloAsFY/skEY5KbVySb7JXfkoT+WtvJGX8ol/67s8lDr+o065KW65Jl7+q/zyF3/nWTpJx+gQ/7H94pPd/Oe38yduEZds4E9dK/Wykj95GX/OYvkq8/kz58h7mcmfP41/hMnyTCbIIxkn9/nv5raMlOsyTK7IELkgg6RKBshp6ScnpI8ckd5yQHrJHvmd/3578I/QjX+E32SNdOEfobMskV9lAf+vmiOdZIZ0lKnSQSZKe/7kSv7kdjKchkoFf2q59Ke+UsafWCY9pZQ/rZQ/rUS6Umcp5k8q5k8p5k8p4k8p4k8o4u928Hc7+Dsd/F1mpWLn7zArVhWpHOlsRvYC/Yf++t8A/j8fQCxrADvTA/j6vwH8/zGAaOzX/w3g/+cBaJEuEkqMMQbg/t8A2jiA8n/+AHzB7qLFx8K2zBhAA5Q16QE8+98A/q8PwOXvLYHYePEllsO666cGcPR/A/jnDaDRN0C80Ynija8QV2K3GsBlywDe5h3AVYAvAv0X4IUH4P7fAP7bB9DgGyau0BRx6yvFGd8j9YlTUp24LF+g/gDKGwbwAqwnwD1o5QD2/VcPYMT/BmD9q94/Thq0GeKMrpbG2B6pi5+S78kBJAoNoDFrAFU/PICP/+UD6PL/xwDqAlOlNjBH6sMQ6XulJnZavsWvyGcG8D7BABJvsgZwxxiAK2sAZ9ID8P/gAF78QwbQ/v/eAGqDc6Tav1BqtA1SE90v1fpp+Rq7Ip/id+UdA3jNAJ4nPsnjRGYAN0C9whe8C+kB+BmAP2sAu/jPNx1AjRrAlzwDeNqKARz/3wD+7r+qtSXy1QdLcJN8Dx+Qb9Ez8kW/Ih9id+Vt/Jm8sgzgfqL5ARwxBuBjAN70ADbznSE5gDWMJzWARekBvGsygLFy738D+Hf+9T20Sj77VsuXwFb5oh2SL5Gz8lG/Ku8ZwJvYM3kZfyPP4h/lUeIbA6iV24lGuZ5IDcALjQ8aP4+zOYCD/Pt70wNwqQE0WAbwLWcAr/MM4FbOAP78Bw+g6L97AN/CG+Sjb6N89O+Qj9oR+Rg+J++jV+Wtfk9eMYAXsTfyhAE8jH+TuwzgVqLBGMDlhFvOJ7zyZyI5AB8D8EHjyxrAtjYN4EnWAEYYA7j8XzCAXwoMoOJvHsB/aARfwtvkvS/ZHnkfOCbvtCp5G74mb6L35KX+TJ4xgMexj/IgOYB4rdyMN8i1hFMuGQPwyDlGcJoRHE+YAzgA/l7jn1VwqwE0WgZQLUuNAXxmAB+MAcyQVxClBvCQAdxtxQD25x1A1x8ewB9tGEAljO3+7wzgU2SPvPPvlje+A/LGf0LeBP+S16Fr8jJyT55Hn8kT/Y080j/K/dhXuROvYQD1cjWeHIBL/lIDOEXH6TAdoD0JcwBbGcAmBrCeL4Br+AWQO4DZ/MQ0B/C8mQGczxnA4YIDaM0LUNmqAfz2LxmA/b9xAB8iB+VN4IC88h2Rl/5T8jJwXl5o1+V56L48jTyTx9HX8kD/IHf1r3IrViPXY/VyJd4oF+IuqYq75SzYJ0E/ZgzAI/tpD6/DDgaylZdiE9efHMBqYwDfGcBXBvBJ5uUMYJIxgAeWAVyzDODcv2gAA35oAEV5BpAZwT9sAO+iR+VV4Ii88B2X576z8tx/QZ4Fb8gT7b48Dj+Vh5HXcj/6Qe7oX+SmXi3XYnVyOdbAAJwMwCVnGMHJuEeOAn/IGICbAbiMAWzhC+NGvjOs49fD6kSNrFADWGgM4L0awEs1gMeWAdxUA7jUxgGs+Le8AP+nBvAmelJeBE/IM99peeqrkif+S/I4cFMeMYAHoadyP/xK7kTey63oF7muf5creq1c4hU4H2uUczGXnGYEJxjBETpE+4DfbQzAqQZQzwBqZVWiWlbwS2JJ4ossTHxUA3ijBvDMGMB4YwB3ZFTeAZz6FwzA+gL0+jcN4L/sl8BL/Yw8004Df04e+87LI98Veei/JQ+CD+Se9lTuhF7JrfB7uRH5JNei3+SyXiMX9Hqp0hvkbMwppxjBcTrCEA7SXtrF67Ad/C1c/wauf60awHJjAJ8ZwAeZm3gnsxJvZHrihUxNpAZwvxUDOKQGsJsBbP+bB/A7df/JAfzD/mcBz3WuXvtTHvmr5IHvotz3XZN7DOBu4IHcCT6VW9oruRF6J9fCn+RK5KtcjFbL+Wid/MkITuuNcpIRHKPDjGA/8HtoJ98RtvFrYTNfGDeAv5bnf2XiOwP4KosTn2SBMYC3DOCVMYApiacyKfFIxifuy5hEcgA3YLrKAC7KYPlLBjKA/nKSARzLM4DNagCr/4UD6PRvGsB/YARPda5eOy8PAhfknu+y3PVdlzu+O3LL/0BuBp7Kde2lXNPeyZXQR7kU/irnI9+lKlojZxnBKV6B44zgCB3iI2E/7aEd4G8Ff1O8Tjbw03FNvFpW8jNyGc//Yp7/BYn3lgE8ZwBPZKIxgHsM4LaMSlyXEYkrMjTBABJVDOCsMYC+lgH0VAPo/hMDqGhxAJ1bOYCyf+4AHuuX+Ky/yMVfAv6q3PLdlJsM4Ib/oVxnANeCL+WK9lYuaR/kQuiLVIW/yblItZyO1spJRnCMl+AwQzhAe2kXXxB38B1hC18WN4K/HvzV8e8M4KssjX+WRfGPMp/nfw7P/8zES5mWHsADGZe4ywBuGQMYbgzggjmAxBnpn2AAiaPSJ5EcwD4GsAuubWoA6/83gB/964F+Re6Grsjt4FW56b8uN3y35LrvrlzzPZQr/qdyOfBSLgbfyHntvVRpn+Rc6KucCX+Xk5EaOR6plSOM4FC0XvYzhD20U6+TbeBvidXKBn42rot9l1Vc/4r4FwbwiQF8kHnxtzI7/lpmxl8wgGcyOfE4awAjE9cYwGXLAE4zgBMM4AgDOCi9E3ulZ4IBJBhAYpN0S6QGsByyxX/bAEqyBtDxJwbwX/xL4J5+TW6Hr8nN4HW57r8B/G254rsnl32P5BIDuOB/IecDb6Qq+F7OaR/ljPZFToW+yXFGcJQRHGYEB3gN9tJufiHsoK18UdzET8YN4K+JfZOVsa+yPPZJlsQ+yML4OwbwhgG8khnx5zI1/lQmxx/JhPh9BnBHRiduqgFcYgDnGcCfWQP4Iz2AndkDSKySLgkGkGAAifnyS2K2GsCUv2UAxQUH8A//HwbdiV2Xm2HwtRtyNXAL/DtyyXdfLjCA876n8hcDqAq8lnOBd3Im+EFO8QqcYATHGMFhRnAwXC37GcIe2sl3g+18SdwC/kZ+Mq7Xv8lq/SsD+CzLYh9lcey9LIi9lbmx1zIr/lKmx58xgCcyKf6QAdyTsfHbMjp+Q0bGrxoDGMIABiXOqQEcVwM4wAD2qAFsVQNYl38ACQaQYAAJBpBgAIm2DKDrDwzg7/gp+G8ewc3YTbkevilXtZs897flov8u+PfBfyRVDOCc74Wc9b+S04G3cpJX4ETwoxzTPssR7ascYgT7+U6whyHs4svhDtoa/S6b+Lm4Afi1+hdZpX+WFfpHWap/kEWxdzI/9kbmxF7JzNgLmR57KlPijxnAAxkfv8sAbjEAvgDGr8iw+EUZEv9LBsX5CZjgJ6AxgMMMgF8AxgB2SA9jABuNAXRt7QASDCDBABIMIMEAEgwgwQAShQbQ+n9VUNP/WcA/4HvA9RhXH7nFl7xbciFwR84zgCrfA/mTAZzzPZEzvudy2v9STvrfyHFegaO8AkcYwSFGsJ+XYC/fCXbTDoawLfJNtvBTcSOtj36RNdFPshL85eAv0d/JQv2tzNNfyWzwZ8aeybTYE5kceyQTY/dlfOyOjInflFHxawzgMgO4wACqGMBZGRDnJ2D8mPSNH8oZwBY1gLUMYCUDWMYAFlkGML1tA0gwgAQDSDCARKEBFP7nA/6RA7jCAC5FbssFDfwg+P57wD8A/pGcZgAnGcAJ30s57n8tR/1v5XDgvRxiBPsZwV4+DvYwhJ38OthOW8JfZBNtiHyWtZFPsir6UVZEP8jS6DtZBP4C/bXM1V/KLP25zNCfylT9MQN4IBNid2Vc7LaMid2QUTGe/xif/3E+/+N/MoDTagD8AkgOIM4A4rulZ5wBxJMD2JBnAPPyDGAs+KPyDKBf4QEkGECCASQYQIIBJP5d/7OAf+MILvH/8Rcid+Sv0B35kwGcC9zn4h/IKQZwkgEc9z2TY3wMHPG9kkO8AgcZwX5GsJcR7GEEO/liuJ0hbAl9ks20IfxR1tHqyAdZGXkvyyPvZEn0rSyMvpZ50ZcyR+f69WcyHfwp+kOZpN+XCfodGcsQR/N9ZGTsCgO4KENjf8ngGJ//DKB//DgD4BdAnC+A8X0MgF8A8e3mAOIb5Lf4GukaTw5gqWUAsywDmNDGAXQrPIAEA0gwgAQDSDCABANIMIBEqZE9UaIqVhVZcqSzJf5LBnCep7cqeoefd3flrHaPz/r7PPcPuPpH4D+RowzgMK/AIV6BA3wX2M8I9vJ9YDcfBzv5TrCdIWzVPshm2hj6IOtpTei9rAy/kxW0NPJWFkVeywLw50ZfyOzoM5kRfSLT9EcyWX8gE/W7Ml6/LWP1GzKaXyQjYjz/sQsMoIoBnJWBsZPSP8bnf+wwA+ALYHwvA+ALYHwbA9icPYA4A4gvlF/jc+WXeGoAk/+GAfzSigGUtXEAagS5/bsHUMUAzkXv8tv+Lt/w78lJBnCcARxlAEd8j4F/KgcZwH5egX2MYA8j2M0IdjCC7bQ1+E4200btnayntbQq9FZW0rLwG1kSfiULIy9lXuSFzIk8k1ngT48+lqnRBzI5es+4/nH6TRmjX5dR+hUZoV+SYfp5GRLj+Y/x/BsD4PM/xvMf2y+9Y3z+x3YwgK0MgF8AcX4CxlczgBUMYEn2AOLTpGOcAcStAxje4gBK/5MDSGfL9K/86xwDOM0ATjGAEwzgePC+HAk8kMP+R+A/lgO8Avt5BfYygj2MYBcj2MEItvOdYEvgjWymjcE3sp7Wam9kNa2k5aFXsoQWhV/K/PBzmRt+JrMjT2RG5LFMizyUKdH7Mol/3PHRWzI2al7/SP2yDNe5fr1KhujnZJDOAHSe/9gRywB2mwOI8fzH+AIY4ydgfBUDWK4GsEANYGb2AOIMIM4A4gwgzgDihb4E9rAMoMvfMIDiHxxAzghy+7v+Os0ATgJxnAEcYwBHGMAhBnDQ/xD4R1z9Y+CfyG5GsJMR7GAE22gLvww2M4SNgVeyntYGX8lqWqm9kuXaS1lKi7UXsiD0XOaFnsmc8BOZGX4s08MPZWrkvkyO3JWJfPkcF+X6o9dkVJTrj15kAOcZwJ8yWD8jA/WT5gB0nn/9gPyh8/zHdjGA7WoAfAGMrZXfYiula4wBxBYbA/glPqd1A4gzgDgDiDOAOAOIM4A4A4gzgDgDiDOAeGoAnZoZQL7vAcXNvgI/PYC21NxfJ+N35Difw0cZwJHQPb7h35cDDGA/HwN7eQX2MIBdDGAHbWcEW2kLQ9jECDb4X8h6Wht4IatpZfCFLKelwefgP5eF2jOZrz2VOaHHMiv0SGaEHsi08H2Zwj/WJPAnRG7KuMh1GRO5ygAuMYALMizK9UfN6x+on5D++lHpqx9iAFy/vkd66Tulp87nf2yzGsAaYwBdYvwCiPEFMMZPwNgc6RSbwQCmMoBJDGA8AxhjGcCQtg0gzgDiDCDOAOK5A/iZL4L/xhEU6hgDOMIADnORB/kiuF+7L/sYwR5GsJtXYCevwA5GsI22MILNfCfYxAg20Hpa638uq2ll4LksDzyTpbQ4+EwWBp+A/0Tmao9ltvZIZoI/PQQ+/xiTwuCHwQ9fl7Hgj45clpGRCzI8wvVHuf7oGRkU5fqjxxkAz79+kOvfxwB2MwCef53Pf32TdNfXSzedz39jAEvVAPgFEJttDKBjjAHEGECMAcSSAxj59wwgzgDiDCBeYfZPHsARBnCIL2IHGcB+cPbyMbCHAeziy+AOXoHtvgdc/SPwH4H/WDbSBoawjtbQKlrpfyLLaWngiSymhYHHMj/4WOYGH4H/QGYyqun8uVO1uzI5dFsmhm7K+BD44WsyOnxFRoUvygjwh0W4/shZGRzh+qMnGMBR6Rfl+qP7jee/t87zr/P861sYAJ//Op//Op//Ol8AdT7/db4A6skB8AUwxi+AGD8BYxNpnDmA2EhpFxtGDCDGAGL9pTzGAGIMINaaAXTMGUBqBAwgXqZiAPF/0AAOxW/LAQawL3JH9jCA3SDtDN7jW/592ea/L1sZwRZGsMn3EPhHXP0jWUtrGMIqWknLaan/sSzmI2MhzQ88lLm8ILMZ0kyaEbwr07Q7MkW7JZO0mzJBuy7jQtdkTAj80CUZGT4vw8NVMjR8jgGclkERrj/C9Ue4/uhBcwBRnv/oDukZ3coAeP51nn+dz3+dz3+dz3+dz3+dL4A6XwB1BqAzAJ0B6AxAZwD6aKnUrQMY2HQAMQYQYwCx/AMoNgaQ7xXIMwCjYktFmbIG4PjPDmA/A9jH7/A9DGBX+I7sAGo7I9gWuMu3/Ht80bvP1d8H/z5X/wD8B7KaVjKIFbSMlvLvL6aFjGU+zeXvmc3fO4s/Y0bwjkwL3pYpwQz+eO2qjNWuyOgkfuiCjAhVybAQ+OEzMjh8UgaGjzOAI9Ivckj6RsCPcP2RXQyA649y/dGN0j3K8x9drQawjAEsYgDzGQBfAHW+AOp8AdT5AqjzBTA9gBHSTmcA+mCp0AeC38wAYgwgxgBi/BSMtXUApc0PIO5IZzOym/0nRrAnfkv26LdkV/S27OCzeXvojmxlBFuA2wTgBv9dvujdBf8eV3+fq78vK733ZQUt499eQotoIc3nv2Yu/7WzaZb/jswI3JZpgVsyJXBTJgevy8TgNRkfTOJfljHaRRmlga/9JcNDf8rQ0BkZEjolg0I8/eGj0j98WPqFuf7wPgawhwFw/ZFt8ntkMwPYwADWMgCe/yjPf5TP/yjPf5TnPzqb+AKo8/mvT1IDGEujmg5AZwA6A9AZgJ4aQPecAfxqDiDGAGIMIMYAYgwg1poBlLRtAAWzFe5nB7ArflN2MoAd/B7fFr4lW/iM3qzd5rf9HdkQuAP+Hb7o3eHq73L1Zsu9d2UpLaFF/PsLaL7vjsyl2b7b4N+SGTTNfxP8GzI5AH4giX9FxgUvyZhgEv+8jNSqZLj2pwzTzsoQ7bQMDnH9oWMyIMT1h7j+8H4GAH6Y6w9vZwBbGABf/iJcf4Rv/xGuP8LzH+H5j/L8R3n+ozz/0enEAKIMIDo+ZwBDCw9AZwA6A9AZgN6KAcQYQIwBxMpVDCBWavT3DqCFEfzMQHYwgO36TdnK7/EtDGBT6JZs4LN6A0/2Oq53DVe8yn8b+Ns8+be5+js8+Xdksfe2LKQFNM93C/xb4N+Smb6bMoOm+a/LFJrsvyYT/VdkQuCyjAuAH7ggo4PgB6tkRPCcgT80ia+dlEEaT792RPqD3y8Efmiv/BHazQC4/jCf/WGuP8z1h9dJtzDPf2QFA1jKAHj+Izz/EZ7/yExjAB2jU2iiOYAoXwCjDCA63DIAfgHo/ahP4QHoDEBnADoD0Ns4gFiJqlhVZCl3AI5/3QBaalv8hmzRb8jm6A3ZyO/yDXxDX89n9VpaHbwpq3i+V3LNy2kZwEtoMS303pT5NI/m0GzvDfCvy3Sa5rsmU2iy74qJ778k4/wXZWwSPwB+APzAORkePCNDg6dlSNDEH5jE18DXDkhfbZ/00bj+0E7pFeL6Q1x/aKP0CK1nAFx/mOsPc/3hJbRQOofnMQCe/wjPf4TP/wif/5EJDIDP/yif/9GR5gCifAGM8gsgah1A79YNQGcAOgPQGYDOAHQGoLd2AHlGoLIZ2bP7dw1gS/y6bNKvy4YoRa7LOn6br9FuyGpaGbwhK3jCl/tv8C3/BvA3ePJv8OTfAP+6zKU5NItmeq/JdJrmuwr+FfAvy0TfJZnguwj+BRnrPy+j/VUyyv+niR8AP3BKhgROyOAg+MEjMiB4iAFk8P/QdklvbYf00rh+jevXuP4Q1x/i+kMMIMSXvxDPf5jnP8zzH55FPP9hnv/IJHMAEZ7/CAOIjGAAw7IHEGUAUQYQZQDRnj8+AL1cxQD0UiO7/pMDyJvN7O8cwMb4NdmgX5P10WuyNnJN1vDbfBW/0VfybX0FX9yW8fm9hBbznC/kqhfQPJpLswGf5b0qM7xXwL8iU2mK95JMoonAj/ddkHG+8zLW95eM9iXxz8kI/1kZ7j8tw/wnTfzAMRkUAD8AfvCg9Avul75B8IMZ/J4a169x/RrXr62RbtpK+U1bzgC4/hDXH+L6Qzz/YZ7/8DTi+Q/z/Id5/iNjaJQxgHYRBhBhABF+Akb6Nx1AlAFEGUCUAUQZQJQBRFszgArLAMoyAzAqtlRklncAjtYPoFA/MoAN8auyLnZV1uhXZXXkqqwMX5UVoauynJ9qS/nGvoQWBa7yE+8qP/Gugn9F5tBsmgn4DO9lmQb4VJrivQj+BZlI473nZZz3L/CrwP9TRvnA952R4T6F7z8ug/3g+4/IwCR+4ID0C4Af2CN9ArsYAPjBbdIzCH4Q/CDXr/HNX1sFPp/9Gp/9Gtevcf2hucTzH+L5D3H9ockMgOsP8/yH+fwP8/yHef7DfP5HBmcGEOlLfP5HGECEAUR6GAMoif6WPYAoA4gygCgDiLZ1ACVNB2DkSGfT/6YBtKXUANbGr8ia2BVZpV+RlZErsiJ8RZaFrshSfqcvpkV8c18QuAL+ZX7iXQb/ksyimTQd9GmgTwV8Mk0CfQKN91aBXyVjvH/KaO85GeU9A/5p8E/KMN8JGeoD33fUxPcfkgF+8P3g+8H3gx/YIb0D26RXYIv0DGyS3wMbGMBa6R5cLd2CyetfxgC4fo3r17h+jevXZhLPf4jrD/H8h8YTz39otGUAQ4jnP8zzH2YAYQYQTg6gV2YAEQYQYQARBhApMIAoA4gygCgDiFaYNRlAaQsDyDMC3d60f+UIkq2OX5KVMdIvyfLoJVkaviRLQpdkkXZJFtJ8frbN49v7XJrNF7lZPO0zeNqn0zTQpwA+mSZy7RNAHw/6ONDH0GjgR3lPywjvKRnuBd97HPxj4B+RQb7DMtAHvu+A9Pftk74+he8H3w++H3y/wg+sk+4B8APgB3n6g1x/kG/+wQUMgOvXuH6N69f48qdx/RrPv8bzr/H8h3j+Q3z+h3j+Qzz/IQYQSg6A5z/M858cQJgBhHn+wwwg3M0ygM5SHGEAEQYQYQARBhApMIAoA4iWqcCP/k0DaJItu58dwMr4RVkRuyjL9IuyNHpRFkcuyqLQRVmgXZD5NDd4Qebw7X02zeSL3Ayaxuf6VD7Xp4A+CfSJNAH48aCP9Z4F/wz4p2Uk8COAH+49YeJ7j8pgL/jeQzLQe1AGePcb+P3A7+sD3we+D3wf+D7w/eD7wfevMfEDK2ipdA0sli4B8INcf5DrD3L9Qa5f4/o1rl/j+dd4/rXRxPVrXL/G86/x/Id4/kNcf4gBhBhAiOc/xC8A6wDCDCDchRhAOM8AIgwgwgAiDCDSzACiJapiS3/zAFpboQEsj1+QZbELskS/IIujF2Rh5IIsCJ+XeaHzMlc7L7P5zT6LZgb+kun+v/h9XwV+Fd/y/5RJNBH0JPw44MeCPoZGeU7JSM9JGeE5IcM9x2WY55gM8RwB/7DCP2Die/dKPy/43l3Sx7tD/vBuk97eLQxgEwPYIL/71ksP3xoGsEq6+cH38/T7efoDPP2B+TRHfg3wzT/A9QenEtcf5PqDPP9Bnn+N69e4fo3r14aYA9AYgMYANJ7/0B9qADz/IQYQ4gtgiAGEcgYQZgBhBhBmAOE8AzBiAJEyVakaQYEBpHOks/07RpCvpfHzsjh2Xhbp52VB9LzMj/wl88J/yZzQXzJbq5KZNCNYJdP57T6Vn3BT+CY/mS90k2iC7yz4Z8A/beCP5tpHAT8S+BHADwd+GPBDPIdlsOeQDPIclIGe/TLAs0/6e/ZIP89u6evZKX08Fnwv+F7wvQrfB76P6/cpfP8iAt/P0++fbeD/EuCbf4DrD0wirj/I9Qd5/oMMIMgAguYAKjSef43nX+tnDkBjABrPv8YAtB6WAfD8hxhAiAGEGEAoZwBhBhBmAGEGEC4wALJHSlTFZs0NIJ29af/KASyOV8nCWJUs0KtkXrRK5kaqZE64SmaF/gT/T5mhnZNpwXMyld/uUwJnZZL/DD/xzoB/mp95SfhTXP1J8E+Afxz84+Cb8EMN/EPgHwT/gMLfq/B3gb8D/O3yh2er9PaA7wHfo/C94HvB9ybxl9MS6eoD38fT75tn4P/q5+n38/T7uX4/1+/n+gPjCPwA+AGe/wDPf5DnP8j1B7n+INcfTA6A51/rrQbwuzkAjQFoXL/GALScAYQ6SVGIAYQYQChnAEYMIFymKjAAoyJLjjwjsLciW3Y/M4CF8T9lfuxPmaefkznRczI7ck5mhc/JjNA5ma6dlWk0JXhGJgdOyySayG/48f5T/L4/yU+8k+CfAP84X/aOAX+Uqz+i8A8p/AMyyL1fBrr3yQD3Hunv3i393Dulrxt8N/hu8N0WfM866eEB32Pid/OC7+Vz3wu+18Tv7OPp9/H0+7h+H9fvM/E7+nn6/Tz9fj77/Ul8rj/A9Qd4/gNcf2CAGgDXH2QAQQYQtA6A67cOQGMAGvga15/GVwMIMYAQAwhVmOUOgOzhElWxWZMBqBGobEb27FozgNZUaADz4udkbuyszNHPyqzoWZkZOSMzwmdkeui0TNVOyxSaHDwlEwOnZELgJPgnZZz/BPjHZYzPhB/Jl7sRfLkbzlM/DHQT/4AMBn4Q8AOBN/F3gb9D4W8Dfwv4m6WXe6P0dIPvBt9t4nf3gO8B3wO+hy99ngUMAHwv+F7wveB7k/g8/T6efh9Pv4/r93H9fq7fD76f6/dz/X6uPzDQGEB5gOsPMIDAH2oAPP9BBhDk+oMMIJgaQBL/18wANAagga+1V+UMIMQAQmWqUqMmAzAqyslhlh5AnhHkzWYW/cnmxk/L7NhpmaWflpnR0zI9clqmhU/J1NAp8E/KJJoYPCkTgidkfOA4+MD7j8lofseP4ufcSOBH8OVuOOjDeOqHAj+Ep34w8IPcexX+bvB3Sj8X+K7t0se1Vf5wge/aJL1cG8BfD/5aA7+HG3w3+G7w3SZ+V89CBsDnvofPfQ9Pv4en38vT7+Xp93L9Xp5+L9fv4/p9XL+P6/cNJ67fz/X7uX4/A/Bz/f4kPtcfAD/A9QcYQKCHZQDgB7n+IAMIMoBgMwPQGIBWoWIAWs4AQiWqYksFBkC2dPbsmhtAS7U0gNnxUzIzdkpm6KdkevSkTIuclCnhkzI5dEIm0UTtuIwPAh88JmMDx8A/KqP9R0x8fseP4Fv9MK8F3pMfvh/wfV3bwN8C/mbwN5r4LvBd4LtW00rp7loB/jLw+cx3g+8G3w2+ey4pfM90At8DvoenP4nvHUtcv5fr944w8X1cv4/r94Hv4/n39zMH4Of6/QzA35N+NwcQYAABrj/AAAI5AwgygCADCDKAYAq/wACMSo3sWolZ1giKcnKks4UKDCBvNrPITzYzflJmxIDXT8jU6AmZEjkuk8PHZSJNCB2T8doxGacdlbHBIzImALz/sIz0Aw/+cN9B8A/w+34/+PvA38uXvT3g7wZ/F/g71NVvM67exN9kwV8H/ppsfBf4riW0SLq6ePZdFnw3+G7w3eC7JzMAnn4PT7+Hp98DvmcUA+D6vVy/F3wv1+8dpAbA9fsYgK8PMQBfL2MApckB+MH3c/1+BuBXAwgwgAADCDCAAAMIWAYQrFQxgGCFWXMDMCpWFWWXOwAje/7yDaClWhrA9PhxmRY7LlN14PVjMil6TCZGjsqE8FEZHzoiYzXgtcMyOnhIRgUOgX9QRvgPgL9fhtFQ7z4Zwu/5wcAP4mfdQOAHAG/ibwN/a/rq/wC+N/C9uPqeXL2Jv0rhL8+DP4/Ad4Hvmkngu5L4Uwh89wQC383T7+Hp94Dv4fo9XL8HfA/X7wXfy/V7wfdy/d4kfm9zAD7wfVy/jwH4UgMA3w++H3w/+H4T3xhAgAEEGEAA/EA7I3MA5aoyVamRPZhvALkjcKSzpbMXHkE6W3bhH2xq/JhMiR0F/6hM0o/IxOgRGR85IuPCh2Vs6BD4h2Q0jQoelJGBA+Dvl+H+JP4+GerbA/4eGezdDf4ufubtUPjbwd8K/hbwN6ur36Dw10lPJ/hOrt650qi7M4m/FPjFOfhzmuK7wHeB7wLfNd7A7+AG3831u8F3D6OhBn47D9fvAd/D9XuS+H3MAXjB9/L8exmAt4eBX+oD38f1+xiAjwH4LAPwg+/voMoZQIABBMpVZWbWAaQrttSKARSquRE0V6EBTIkfkUkx4MGfoB+W8dFDMi5ySMaGwQ8dBP+AjNT2y4gg8IF9Msy/V4b6gQd/sA94r4I38LeDv5Vv+lsU/qb01fd2rpdewPd0rgF/lcJfAf4y6eYE3wm+c6F0dYLvBN8JvhN8Zwb/l1x8F/gunn4X+C7wXcNNfDfX7wbfzfW7+zOAfuYAPOB7uH4PA/AofC/X7+X6vQzAywC8DMCrBuBjAD4G4GMAPvB97c0B+BmAH3wjBuAvN0sNIFBqZA+UWMoZQDpHOluwFQPIyta0UBubFD8kE2OHwD8k42ls9KCMiRyQ0eH9Miq038TX9snw4F4ZFthj4vt3g79TBvl2yEBvEh94zzYD3sTfDP5G8JNXn4RfR2vAXw3+SoW/XOHz5DsXKfz5FvxZJr4TfCf4TvCd4Dsn5sEfaeK7ePpd4Lu4flcSf4AxgHI3+G6u380A3En8nuYAPAzAwwA84HvA9yh8L/he8L2dVJYB+CpV4PsqzFID8JepwDcqMUsNIF2RJUfTERjZm9aaAbQm6wAmxA/K+NhBGacfkLH6fhkT3S+jI+CH98nI0F7w98hwGhbcLUMDu8DfKYP9OxT+dhng3QY+8NSX3/R9+U3fB3gTf526+tW0SuGbV9+dq+/WyNU3gt+4QLo2gt84l8BvBL9xBmXjd0riO8F3gu8E3wm+cyQDMPErXUMVPtfvAt/F9bu4fhf4riR+b3MAbvDd4LvBd3P9bssAPAzAwwA8DMCj8I0YgJcBeCtVDMCrBuArV5WpwPdZBmBUbKnILDUAS7Z0drNgc9my+5ExjI/vl3Gx/Sa+vk9GR/fKqAjwYeBDwGvAa8AHd8qQwA4T379dBvq2gb9F+nuT+En4TdLHvUHhrwd/bfrqewL/u+XquzcuUfgLFf48hT87G78R/EbwG8FvBL9xPPGlr3EMAxht4jt5+p3gO8F3gu9M4g+04PdVAwDfBb6L63cxABcDcCUHAL4bfDf47s5GxW4G4FYD8IDv6aBiAB7wPe0yAzAqV5Wp1AB8Jari7FIDMHJkZUuVGkCz2ZqOoLnyDWBcfJ+Mie2V0Trw+h4ZGd0jIyK7ZXh4twwL7QIfeA34IPAB4P1bZYB/iwzwJfE3Sz/vJunr2Wjg/+FeD/468NfwZS9z9b9z9T0M+KUKf5HCn6/w5yj8mQp/msKfrPAnZOM3gt8IfiP4jeA3JvGHGPjtnOA7uX4n+E7wneA7uX5nHnwX1+9iAC4G4GIALvBdCt/dScUA3OC726vMATiMwPeUq8pUpeYAjEpUxZl8RTk5skoPwG8vnHUALdXSKMbE98jo2B4TX98tI6K7ZHhkpwwL75ChoR3gb5fB2jYZFNwqAwNbDPz+/s3S37cJ/I3gc/Ue4N3rjKvvDXwvftr1VPC/c/U9LFffTV29ic/VN4DfMEs6N4DfMJ3AbwC/AfwG8BvAbwC/gWe/AfwGK/5wE78R/EauvxH8RvAbuf5G8BtT+L3NATgZgJMBOMF38s3facW3DMDFAFzguzoaFbkYgEvhG4HvrlCVqywDILtRicoyAG9RTg6z1ADS2ZuWdxC2pgXa0Oj4bhkV2wX+Lhmh75Th0R0yLAJ+eLsMCW0Df6sM0rbIwCD4AeD9wPuA922Qvt714K+TPzzAu9cY8L34Td/Tlbn6Hs7k1S82rr6b5eq7NiTxZyv8GRb8KQp/Yn78BvAbwG8Av2Eogd8AfgP4DeA3JPG5fmMAfxD4jeA3gt8IfiPX32gOoCQ5ACcDcILvBN8JvvMXMzWANL5RpYoBuCpU5WbJARiVGtndJZmSA0hXlJMjMwKypbNn8jWXLZO/DaUGMDK+U0bEdshwHXgaGgU+Anx4qwwObTHxtc0yILhJ+gc2Sj//BgO/j2+d9PGuBX8N+Fy9e6XC5+pdyw34HnzD7+40r76b5eq7GlefxJ9pwZ+ajV8Pfj349eDXg18Pfj349SMYQC7+oAx+A/gN4Ddw/Q3gN4DfAH6DBb+R628EvxH8RvAbOxsVN6YGAL6zo1GRkwE426vAd7bLPwBXmarUyO6yDMBdbKkou+QALNnS2c28LWXLHkFL5Q5hRBz82Hbwt8lQGhIFPgJ8GPjQZvA3yQBto/QPbpB+AfD9wPuA966h1dLbs8rAT8L3BP531zKFvxj8RQp/PvjzFL559Sa+efW/1oNfD349T359Cn+cBX9UBr8e/Hrw68GvB7+ez/168OvBrwe/Hvx68Ot5+uutAwDfiAE0cP0NDKCBATQwgAaF3/iLigE0gt/YQQV+Y6UZA3AYge8sV5VlDcCeGkC6YktFZukROLKypbNnRtBcyQG0pkKDGB7fJsNiW8HfIkNocBT8CPBh4EPAaxtM/OB66RtYK338wPtWg78KfK6eerqXg78MfOBdSwz47vyu7+Y0r/63JDxf9LpannwDvz6Jn4SfbMEf3zJ+Hfh14Ncl8Qem8Sss+OVJ/Hrw68Gv5/rrwa8Hv57rrwe/Hvx6E98YQAMDaAC/AfyGjkZFDeA3tDczBtDOyNFYoSo3Sw7AqNTIblSSKd8A0jmysqVKDqCljBHYWq65YQyLb5GhsST+ZhlMg6KbZGBkowwIAx8CXlsP/joTPwC8H3jfSuntTeKvMPB/dy8Ffwn4XL0rib8AfPPqM/iz0k++iT/Vgm9evYFfB34d+HWjCfw68OvAr+Pbfl0Ofh34deDXgV8Hfh34deDXgV8Hfh34deDXgV8Hfp0VXw2gHvx68Ot/UTGAevDrO5gZA6hUtTNyNFSo1AAay1SlRnajkkzOYktFORUYgMvefOkh2JqvpXEMjW+WIbFN4G+SQfpGGRjdIAMi4IeBDwGvrZW+wTXgrwIfeOrlWyG9vFy9Z5nCXww+8K6FGXznXPCB5+ediW/Cd1ZP/q/qyU/j14034DvWjcnBH94Uvxb8WvBrwa8Fvxb8WvBrwa8FvzaDX2bFp5I6BlAHfh34dVx/HfhG4NeBX9fRqKguOYD2qkoV+PUVqnJzAA1llkqN7A0lmRqLcyrKLjkAS7Z09kzNjsFWOHcrGhLfKINjG8HfIANpQHS99I+sk35h4EPAa6ulTxD8QBIfeN9yWiY9vcB7uHp3Eh94F/Cu+eDPU/jANwLPb/sMvgn/q3ryDfy6JP64PPhcfS34teDXgl8Lfm0r8WvBrwW/FnwjBlDLAGrBrwW/FvzazkbFteDXgl/bySyFbwR+XaWqnZGjzjIAozJVqZHdqMTMGEFxTkXZNTrS2bKyZ3I2l83M9YMNjm+QQbEk/noZoK+T/tG14K8BH3htFa2UP4LgB8D3A+9bCv4S8IH3LGIAKfx5BLxzDqXwZ4BvXn02/kQyrz4bf5R0qOXqa5viV6bwa/jCVwN+Dfg14NeAXwN+TW8Cv6aniqe/Bvwa8GvArwG/BvyaLioGUAN+zS9mxgA6GhXVgl/bXlWpAr9WDcCoXFWmKjWyG5WYGUMotlTUtAZHOltW9kyNzWUzc7ay3AEMiq+XgbF14K+V/voa6RdZLX3DwIeAT+JrK6R3kKsPgO8H37dYfvcC71kI/gLw51vwgXfOAn9mDr4J/6u6+mz8McTV1xbArwG/Bvyaga3A79UCftcc/NQAOqnAr+mgAr+mUtXOyFFboSpXlVkqNbIblWRGUFdsqahp9Y50tqzsmRqay2bW2MpyBzEwvlYGxNaAv1r6RVdJ38hK6RMGPrQC/OXSW1smvYLAB5YwAPB94HsXMID50t1twndzcfUuhe8EvnE6mVffFN+E76SuvmNtHvyaYWn4yppB2fjV4Ff3JfCrwa/ubVRWDX41+NU8/dXgV4NfDX71b0Yl1eBXg1/d2ai4Gvxq8Ks7qbj+auCN2qsqzZL4RhWqclWZqtTIblRilhxBbXFORU2rc6SzZWXPVN9ctkwNrcw6iAHx1dI/tkr66SulbxT8CPDh5QxgGfhLpZcGfHAxA1gkv/u5eh9X7wXfA77bhP/NlYSfmQcf+IZJ4JtX3zy+Cd++ZmhT/Grwq1vA/w7+d/C/g/8d/O/dVOB/B/87+N87q8D//osK/O8djYq+d1BZ8KvbGTmqK1TllspUpUZ2o5LMCGqKcyrKCfjaTLas7NnVFcqWXX0rS42hfxz8GPgMoE8U/AhXHwY/lMH/PbAQfK7eB7x3HvhzTXy3wnfNAB945zTwgW/k6hX+L03wzSe/o4LvYLn6LPxq8KtN/HZW/O/gfwf/e2+jsu/N4H8D/xv437qowP8G/rdfVJ1UOfhGlSrwjSpU5aoyS6VG9u8lZtWpii0V5clhjkBlS2dvWm2hbE2ra2XJIfSLgx9bIX10rj4KfGQpA1givUJcvcbVB8EPgO8H3we+d4508wDvngX+TBPfZeJ3dqbwufoG4BsUfL159Xnxa3Lwq/Pgfwf/ewH8b+B/A/8b+N/A/9ZNVQj/1yb4xd+AN2qvqlS1M3J8q1CVWypTlRrZjUrMjCEU51SUJ4c5ApUtnT1/+YZRY8tfbSvrG18ufWLL5A8d+OgSBrBYeoUXSc8Q8NoCBjBfegSA989lAOB7wfeA755pwHd1cfVJeOcU8Ln6xjz49T+I/z0P/jfwvyXh8+HTV/C/gv+1qwr8r+B/Bd4I/K+dVB2Nir52UIH/tVLVzsjxtcJSuarMUqmR3agkM4JvxTkV5clhxhBsWdmbL2sYtsLVtKI+cfBj4OvgR8GPgB8GPwS+Bn4Q/MAcBjBbuvmA985kAFy9W+G7FL5T4Tcq/AYFX6/g+YnXUcF3sDz57S3wlQY8fc/B/wb+tzz4X8H/Cv7X7ioTvzSF/wX8L51V4H/5RQX+l45GRV86qNqrKlXtjBxfKlTllspUpUZ2oxJzAOmKcyrKyZGV7Zs1e8ulB2FrueZG8kcc+NhiBrBIekUXSs8I8OH5DGCe9NC4+iD4AfD9VnwTvosLeNdk8E34XxuT8OPz49e1Al/Bp/G/5cH/miwP/hfwv4D/JQnfEr4awGfgjdqrKlXtjByfKyyVq8oslRrZjUrMERgV51SUJ0dWtmRfU9lb3zdb68s3jj/i4MfA18GPgh8BP6zwNfCDs8AH3jeDAXD1HvDdOfhOhd+Yg1//I/hJ+Bz8r+Cn4RX+F/C/dFdZ8D8nA/9zZxX4n4H/lKyTqqNR0SfwP7VXVaraGTmMKlTlqjJLpUZ2o5KcinMqyu5zMkdWNmtf7G3IZva1jaVG0Tu+UHrFFkhPHfjoPAYwV3qEgddmE/gB8P3g+8D3gu8B353En0TAOycQ8I3jwAe+YQz4wNeb8B3rTPgOtcNaid83g/81g1+ewv9i4pel8D+D/xn8JPynZOB/6qwC36gA/sdk7VWVqnZGjo8VqnJLZZZKjexGJZaK81TUtE+OrGzp7K3rcypb0760oV5x8GPzGQD4UfAj4IcUfhD8wHQGME26+oD3TgGfq3crfJcFv7EAfp3CrzXh2xs/8fLgW66+Cf6XJHwO/meF/wn8T3nwPwJvBP7HTqqORia8Bf9DpaqdkeNDhaVyVZmlUiO7UUlOxTkV5cmR6SPoWdnbGIiffrDkWHrGwY+Br4MfBT4yiwHMlG4aVx8EPwC+H3wf+J48+E4LfoPCr28O34QviG/A5+L/bvYZ/CT8p2Q5+B+7qEz8kjS+GsCHjirgjdqrcvDfJ6tQlVsqs1RqZDcqyak4p6I8ObKypfqQzN7GbE372IZ6xufK77E50kMHPwp+GPwQ+Br4QfAD4PvB94LvmcgAgHeNJ+CdY8EHvnE0+MA3jGwVfuonXrP4Xyz4nxX+pxz8j0n4HPwPvxoVf/hFlYP/Pll7VaWldkZp/HfllsoslRrZjUpyKs6pqECOrGxZ2TO9b022lvvQTL/HwY/NZgDgR8EPgx8CXwM/OIUBTOb6uXov+B7w3QrfBb5T4Tem8EcQ8HXDaKiJX6vwa3Lx++XB750f/1MKv5vZxxz8D8ny4L/vpAL/fQ7+u2SVqnZGjncVlhT+2zJLpensRiWWivNUlCdHVrYm2Qv3Ll+2Hys1jh5x8GPg6+BHpzOAaQxgqnTVwA+C7wffB743D77Tgt+Qiw987eBm8NWXva8W/C8WfAM+B/9jBr/0Q1cFb8F/D/77X1QW/Hd87r/roLLgv03WzsjxtsJSuSXg36QqNbIbleRUnFNRgRxZ2bKy/0A2s7c/WI/4TOkemyHddPAj4IfBD4GvgR8A3w++D3wP+G6F77LgN1rw63PxB6XxK1vE75WD3yOD/9GC/yEH/31nAz4L/10nVUcV8G+TtVdl4xe9YQBvKlTllpriO16Db1Riqbhpr4oK5MjKlpW9cK8LZWu5N83UPT6DAYCvgx8BPwx+CHxtEgMA3w++F3wP8O4x4APvGsUARmbwGyz4dQq/NolvwjfF75Mf/3MO/kcL/gcL/vsuKgv+u19UCv9tR5UF/02ySlW7dAb861TlZq/Kcio1shuV5FSc3ctkRXlyZGVrkr2N2bJ79QN1j4MfA1+fygDADyv8IPgB4P3jGAD4HvDdFnwn8I3DwR9m4tfnwa9J4vc3/gkdA/975vO+IufLnoH/KQ/+Bwv++xz8d78apfHfdlJZ8N90UPAK/3WqdkaOVxWWyi0p+JfJSo3sRiU5FWf3IllRgRxZ2bKy/0C2H8s6mm5x8GPg6+BHwA+Dr02QzsHxDAB8H/heC77Lgt8IfMPQDH5dK/C/tYD/sRX473Lw31rw33RUWfBftzfRX6VqZ5SGf5ms3FKZJfBfmNmNSnIqzu55sqI8OZpky8r+A9l+vm5x8GPg65MZAPgh8DXwg+AHxjIA8L2jGYCJ38kFvtOKD3z94Ax+rcKvSeL3y4Pfuxn87k3x31vw31nw3/6q4BX+mxz81x1M+FftLfD0sp2RiW7Bf5GqzJIF/3mykpyKm/asqECOrGxNsv9Atp/vtzj4MfCjE6VLBPwQ+Br4QfD94PvA94DvVvgu8J3gN4LfkMIfZNQEv7pvC/i/N8VPX70FPw3f2YA3U/hvLPivkwH/qoOCV72sVJn4RS8YwIsKlQX/eVlOpUYG/rOSPBVn97SoQKA/yc6Wlf0Hs/18v8XB17n86AQGAH4IfA38IPh+8L3ge8B358FvAL/egl+bB//7D+C/z4P/Ngf/jQU/Cf8qmQX/ZSqF/6JdujT+82TllkB/lqo0nf2ZGsBTa4A/ya0of48dWdmaZG97j5LZfr6u8UkMAPwo+JFxDAB8DfwA+H7wveB7FL4LfCf4jUMYgMKvB77Ogl+Twu+Tg9+rbfjvCuC/seC/7qTgTfzilx0s8PSiUqXwn7dT6Kpn5ZYs+E9L09mfJCvJSYE/tlaUv0eOJtmaZM/fw+aytb0Heeoa5+nXwY+CHwE/NIYBgB8A3w++F3y3wneB7wS/EfyGHPxaC361Bf/bT+C/teC/seAb8Bb8lxb8F6kU/vN26Uz0VBb8p2VmT5KVpjPwH5fkSaE/slaUv4eOrGzJHlizt637qWx/T13iE9QAwA+DHwJfG8UAwPeNYADgu4cxgBz8BuDrga+z4NdY8L9b8L/+BP4bC/7rXxS8wn9pwX9hwX9eqVL4z9pZ4OlpudmTcoVu6XFpOvtjNYBH1izoD1MVmT3IzdEk2/3c7M13r1C27O7+YF3i4OtcfxT8MPgh8IPgB8D3ge8B3w2+C3wn+I0mfvsUfh34tRb86gx+hRX/S/Zv/Dbhv87Bf2nBf5HEVwN4bsF/VmnAmyXR6UmFQrfgP7YG/CMzu5FCf5gK7Ae5WcDv5+bI7h7gWQF5t43dSWX7e+oSB1/n+o0BgK+BHwTfD74PfI/Cd4HvBL8R/IYB6vot+DU5+N9y8D9n45dZ8d8p/LcK/00O/qs8+C8s+M8t+M8s+E+TpeAV/mNrCv5RWRrewH9YaoI/yA3w+7lZwO9Zuutoks3aHYcFs4Vu58tmdusn6xwHXwc/yvUbAwA/CL4ffC/4HhO/gwt8J/iNwBsD6M8AwK818c3rB/+7Bf+riV+ehd8tD34XKW0J/6XCf2HBf67wn7XPwD+tNOGfJFPwj1Mp+EflCl0FuNED4I0U+H1rFvR7qZLQBQI4N1uq26ksoLda2c1kth/vRk6d4+Dr4EfBD3P9xgDA9w9lAOC7W8Cv7aOu34L/LQ/+pzz47wvgv6ZXzeA/z4P/VPWkXboMfIVCt+A/VD0oM+CN7oNvZIG/V2Ji381XEjpfgN+2dAvsJllBW9ENawrv+k90TfVrfDQDAD8Kfhh8jetXA+igBtBeDaDSGAD49eDX5eBXg/89B//LT+K/VPgv8uA/U/hpeAv+Ywv+Iwv+w3ILuup+aToD/55Cv5vKAn7HmsK+rbplzZHpJth5y0Wl663omj2D15quttCvcfD1kQwA/PBwBgB+AHwf+F7w3eC7uH4n+I3gN4BfD35dH2MAFTU5+N/A/6rwP1vwP7YevyQf/nMTv/hZDv4TC/5jhf+oItNDBf+g3IKeSuHfA/5uqQWd7qSyoN9W3Spq2s1UjuxugJ3qeqpCsM10NZUF70obulwgcwDgR8APga/x9AfA9/H0exS+C3yniV+ZD7+6lxpAHvxP/wL8p+0t8JVp+KJHyVLwFRb48hz4MgPdcdcsjX8npzR4blZw1Y0iA9voeiabtWupCuGqrjRXHsRLbehiTr/ER6YH0DEEvgZ+AHwf+B4LfiP4DX0t1w9+TR78rz3Mf+Wugd89g/8h81Ov9F0L+C8U/vOOaXgD/2kO/uNKC7zCT8I/qMjA3y+3oKvuZvAdd0ot4KpbJdngN61Zwem6NQV/LVMa/WqqFoAvW7qUr2YwL7Sh86pf4uDrXH9kmGUAgxgA+J4BDAB8Zz9jAO2MAYBfB34t+DW9jAGUfwf/2++W6+9uefpbif8yH37HbPwn7S3wOfhp+AoLvMpAT2Wip7LfLrWgW/Bv5nSjOA84XUtlgb9qZruSpxaBVRctXbDWDGZz/ZWnKmMA4OvgR8APgR/k+v1cv5cBuLl+NYB2jbn4vbPxv6Wuv7vl6c/+Z/XMp/9n8Ntn8NPw9MCCnwVfboEvy4J3JOFvlWbQb1pLgdP1VLngqqsqcHOzXVZdStVaZEvnrbWAWtWK/sypkzEA8CNDGAD4QfD94HvBd4Pv4vqd4DeAXw9+XW/L9YP/PQf/cw7+hxz8t23Af9rBAq/wHxXAv1+RA2/Bv6O6bcI7blnwrfA3SnLQ6VqqXHBrgF9WXTKzWbuYqjXIlv6yVGVvPeq5FjprqVN8WHoAHYwBgO/n6feC7wbfBX4j+A1/WAYAfg346QGA/7W7un6F/zEXv0vr8J+1At+AV/j3LaXhyzPoBnyZgZ7KfrM0B52ul+RBVzUBp8uqS47sLlrAL1hrBXRVgf5M1QbYZGdyOp2nTnHwda4/An6I61cDqPRYrl8NoKI+P37m+rsZA8jCf9/F8rmf/YWvJI3fqQl+cSvwi9LwFRl4K74Bb8G/aZaGv24pC1x1pbgp+iVrJrjRhUwG+HlrhS66APS5fP0AbqpTOZ20ZA4A/Ahf/DTwg1y/D3yPun4n+I3J6we/rpcxgHJjAOB/72G5/m6W6++qBtCl6Ze+tuI/UvgPKxU83W9n4hvwFvw75TnwZVnwjhvgJ8uCT2VFV13Og35RdaEoC91+3iyN/pelghddAPus6oyl1uCebKYTOR1XdYwPSQ+gfXIAAfB94HvAd4HvBL+ht3n9xgDAr8mDb1x/U/yCn/vN4T9uI/4dVRZ8WRa843oSvjQHna6WZMNfVl0qLoBuwT9v6S8zW1VOzWGfzYN9Ok+tQc6Hm69jOXWMg69z/WHwtQF5B1BhDAD8OoWvrr/sW3fL9Vs+9z90UQNoBf7zVuLfV6XhKzLwufg3y7Lg0/i58FdKsuEvWcqHfj5VNrq9yswEV51L1VZs1UlrbUC24h7N6UiesgcAfgB8H/hu8F1cfyP4DeDX98xcfzXX/727GkDy+n+zXH8e/Dd5vvQ1we/QFP9BK/Bv061yC3xZFryBf63Ucu0p+JKca0/BFxdAp79UVY7sssBVZx0/iK06oTpubz3ykQIdtnQop45x8HXwwwMyA/BmBlCRGkDy+mvBr+lhuX7wv/xmDCD99BsDsPwrePN97reE/7AZ/DsVGfi8+GUZ/GtmTeFLsuEvpuCLm0FPZYIbncuURj+j+mHsnFoL3RxyqoOWDqg6pAfQnwGAH+jLAMB3c/1O8BvN6y+v+90cQPr6u6UHkPzf0W96/Zl/Tj/7S19T/OKW8IEvysW/pcqCL8uCd1wtbQp/qSTn2i2dL86Gr7L0Z1ETdPtZswy6pULgzWKrjqqO2NsOnQ852f4CdYgPZAADjAFUJgfg5/q94LvAd4Lf2DMzgOT1V4OfGoBx/V3VALpYrj/zr+BN47/M81v/ieVzPx/+vVbgp+HLMvAp/CbwqrzwxXmuXcGfS5VBtwNuP52LrmoNeF7snA7b2wZdCHmfpb2W9qgBtI9y/WHwNa7f3yd7AA3g1yevv4cxgLLq1PX/Zrn+LvmffuP6O2U//Xnx27eMf7vCAt8MPvCOK0n80jzwJU3RDfjiZtDpbFEWujUTPKd86C2BH1YdspaD3dJFF0LO125Vh/gAYwCVagDt/OB7wHeB7+T6G35Xz39yAMnr75YeQPL/KldmAJ0LX39z3/gftbd84au04LdrHf61six4A/9yDr4BX1IAvrh5+DNFTeFBt2eBq447mqK3CZwOqg7YC2Pnu+jmkJPtsrTTUodYcgDgh7n+YJ/sAfD8lxsDAL+2u3n9xgCS19/V+L/MVfDpV9ef/fRn8ItbgV+UDz/r6pviO5L4TeBLCsAXq8/23GtX8KeLmqCnykZXNXflrQKn/al+EDsf9I4Cbaf2sf7mAEJqAL7eDAB8F9ffCH59D3MAyeuvBv/7b5br75K+fuN/T/+d+b+2ZV5/HvxnzXzps+LfycG/mcIvz8a/WpYF77hU2hTeip8Fr2py7Sl4OlXUBN7eBF111NE69ILgqn2qtmDvbAF7u6Vtqq2qzADAD/5hDKDCbQ6gPDWA5PXXdDMHkLz+r10tA8jz9L9Ofe7n/LN7hb70tQX/Whvwz6vywhdnw5/OgT9ZlIVuP54pG52OOLLRm7vyguCqPfafu+xcaCv2ljy1j4Ef7WsZAPhurt8JfmOP7AEkr/+bwv+s8Ft7/blP/8NWPPst4St4Az8vfEkB+OIW4IvywtuboKsKoee78rzglnbb8193a7C3toC9WbXJUmYA4Ae5fusAGpLPP/i13SzPf3IAXTLX/yEH/3Whpz/P5376d34ufkUG/3oO/pV8+KUt46fhi5uHP1GUDX9M1QRddcjxc+i7VbtUhcCbe8Zbi71RtcFS+xj4Ua4/OYAAA/AmBwC+s0fOANT1pwfQ2RhA9vV3Utdv+RdzNvnWn/Ol767l6W8rPvCOC6V54EsKwNPp4mbg6XhRBv6o6ohZNrqqNeh7WkKnHal+4Lpbi51qvaXKrAGA7+X6XakBgF8Hfs1vlgF0ST//qf/TbCXvLNf/Kv/T3+LnfnP4V/9m/ILwRRn4I5aaoKvaim4Fz0JXWdHbct2twV5naa1qjU3+HwuefjlXE4+yAAAAAElFTkSuQmCC",Oce=0,YD=(n,e,t,i)=>{if(!n[t]){let r=n.useDelayedTextureLoading;n.useDelayedTextureLoading=!1;let s=n._blockEntityCollection;n._blockEntityCollection=!1;let a=ge.CreateFromBase64String(e,i+Oce++,n,!0,!1,ge.BILINEAR_SAMPLINGMODE);n._blockEntityCollection=s;let o=n.getEngine().getLoadedTexturesCache(),l=o.indexOf(a.getInternalTexture());l!==-1&&o.splice(l,1),a.isRGBD=!0,a.wrapU=ge.CLAMP_ADDRESSMODE,a.wrapV=ge.CLAMP_ADDRESSMODE,n[t]=a,n.useDelayedTextureLoading=r,lm.ExpandRGBDTexture(a);let c=n.getEngine().onContextRestoredObservable.add(()=>{a.isRGBD=!0;let f=n.onBeforeRenderObservable.add(()=>{a.isReady()&&(n.onBeforeRenderObservable.remove(f),lm.ExpandRGBDTexture(a))})});n.onDisposeObservable.add(()=>{n.getEngine().onContextRestoredObservable.remove(c)})}return n[t]},ER=n=>YD(n,Pce,"environmentBRDFTexture","EnvironmentBRDFTexture"),KD=n=>YD(n,Dce,"environmentFuzzBRDFTexture","EnvironmentFuzzBRDFTexture"),f5=n=>YD(n,Lce,"openPBREnvironmentBRDFTexture","OpenPBREnvironmentBRDFTexture")});function h5(n){return class extends n{constructor(){super(...arguments),this.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.INVERTCUBICMAP=!1,this.USESPHERICALFROMREFLECTIONMAP=!1,this.USEIRRADIANCEMAP=!1,this.USE_IRRADIANCE_DOMINANT_DIRECTION=!1,this.USESPHERICALINVERTEX=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1}}}var d5=C(()=>{});var jD=C(()=>{vs();Pt();Zn();bt.prototype.restoreSingleAttachment=function(){let n=this._gl;this.bindAttachments([n.BACK])};bt.prototype.restoreSingleAttachmentForRenderTarget=function(){let n=this._gl;this.bindAttachments([n.COLOR_ATTACHMENT0])};bt.prototype.buildTextureLayout=function(n,e=!1){let t=this._gl,i=[];if(e)i.push(t.BACK);else for(let r=0;r1&&(e.depthTextureFormat===13||e.depthTextureFormat===17||e.depthTextureFormat===16||e.depthTextureFormat===14||e.depthTextureFormat===18)&&(o=e.depthTextureFormat)),o===void 0&&(o=s?13:14);let M=this._gl,D=this._currentFramebuffer,O=M.createFramebuffer();this._bindUnboundFramebuffer(O);let V=(X=n.width)!=null?X:n,N=(Y=n.height)!=null?Y:n,F=[],U=[],G=this.webGLVersion>1&&(o===13||o===17||o===18);y.label=(ue=e==null?void 0:e.label)!=null?ue:"MultiRenderTargetWrapper",y._framebuffer=O,y._generateDepthBuffer=a||r,y._generateStencilBuffer=a?G:s,y._depthStencilBuffer=this._setupFramebufferDepthAttachments(y._generateStencilBuffer,y._generateDepthBuffer,V,N,1,o),y._attachments=U;for(let ae=0;ae1||this.isWebGPU);let St=this.webGLVersion>1,Ye=M[St?"COLOR_ATTACHMENT"+ae:"COLOR_ATTACHMENT"+ae+"_WEBGL"];if(U.push(Ye),he===-1||I)continue;let je=new Pi(this,6);F[ae]=je,M.activeTexture(M["TEXTURE"+ae]),M.bindTexture(he,je._hardwareTexture.underlyingResource),M.texParameteri(he,M.TEXTURE_MAG_FILTER,ze.mag),M.texParameteri(he,M.TEXTURE_MIN_FILTER,ze.min),M.texParameteri(he,M.TEXTURE_WRAP_S,M.CLAMP_TO_EDGE),M.texParameteri(he,M.TEXTURE_WRAP_T,M.CLAMP_TO_EDGE);let $t=this._getRGBABufferInternalSizedFormat(re,De,de),Lt=this._getInternalFormat(De),xi=this._getWebGLTextureType(re);if(St&&(he===35866||he===32879))he===35866?je.is2DArray=!0:je.is3D=!0,je.baseDepth=je.depth=Ie,M.texImage3D(he,0,$t,V,N,Ie,0,Lt,xi,null);else if(he===34067){for(let oe=0;oe<6;oe++)M.texImage2D(M.TEXTURE_CUBE_MAP_POSITIVE_X+oe,0,$t,V,N,0,Lt,xi,null);je.isCube=!0}else M.texImage2D(M.TEXTURE_2D,0,$t,V,N,0,Lt,xi,null);i&&M.generateMipmap(he),this._bindTextureDirectly(he,null),je.baseWidth=V,je.baseHeight=N,je.width=V,je.height=N,je.isReady=!0,je.samples=1,je.generateMipMaps=i,je.samplingMode=me,je.type=re,je._useSRGBBuffer=de,je.format=De,je.label=(Be=R[ae])!=null?Be:y.label+"-Texture"+ae,this._internalTexturesCache.push(je)}if(a&&this._caps.depthTextureExtension&&!I){let ae=new Pi(this,14),me=5,re=M.DEPTH_COMPONENT16,de=M.DEPTH_COMPONENT,De=M.UNSIGNED_SHORT,he=M.DEPTH_ATTACHMENT;this.webGLVersion<2?re=M.DEPTH_COMPONENT:o===14?(me=1,De=M.FLOAT,re=M.DEPTH_COMPONENT32F):o===18?(me=0,De=M.FLOAT_32_UNSIGNED_INT_24_8_REV,re=M.DEPTH32F_STENCIL8,de=M.DEPTH_STENCIL,he=M.DEPTH_STENCIL_ATTACHMENT):o===16?(me=0,De=M.UNSIGNED_INT,re=M.DEPTH_COMPONENT24,he=M.DEPTH_ATTACHMENT):(o===13||o===17)&&(me=12,De=M.UNSIGNED_INT_24_8,re=M.DEPTH24_STENCIL8,de=M.DEPTH_STENCIL,he=M.DEPTH_STENCIL_ATTACHMENT),this._bindTextureDirectly(M.TEXTURE_2D,ae,!0),M.texParameteri(M.TEXTURE_2D,M.TEXTURE_MAG_FILTER,M.NEAREST),M.texParameteri(M.TEXTURE_2D,M.TEXTURE_MIN_FILTER,M.NEAREST),M.texParameteri(M.TEXTURE_2D,M.TEXTURE_WRAP_S,M.CLAMP_TO_EDGE),M.texParameteri(M.TEXTURE_2D,M.TEXTURE_WRAP_T,M.CLAMP_TO_EDGE),M.texImage2D(M.TEXTURE_2D,0,re,V,N,0,de,De,null),M.framebufferTexture2D(M.FRAMEBUFFER,he,M.TEXTURE_2D,ae._hardwareTexture.underlyingResource,0),this._bindTextureDirectly(M.TEXTURE_2D,null),y._depthStencilTexture=ae,y._depthStencilTextureWithStencil=G,ae.baseWidth=V,ae.baseHeight=N,ae.width=V,ae.height=N,ae.isReady=!0,ae.samples=1,ae.generateMipMaps=i,ae.samplingMode=1,ae.format=o,ae.type=me,ae.label=y.label+"-DepthStencil",F[l]=ae,this._internalTexturesCache.push(ae)}if(y.setTextures(F),t&&M.drawBuffers(U),this._bindUnboundFramebuffer(D),y.setLayerAndFaceIndices(S,A),this.resetTextureCache(),!I)this.updateMultipleRenderTargetTextureSampleCount(y,c,t);else if(c>1){let ae=M.createFramebuffer();if(!ae)throw new Error("Unable to create multi sampled framebuffer");y._samples=c,y._MSAAFramebuffer=ae,l>0&&t&&(this._bindUnboundFramebuffer(ae),M.drawBuffers(U),this._bindUnboundFramebuffer(D))}return y};bt.prototype.updateMultipleRenderTargetTextureSampleCount=function(n,e,t=!0){if(this.webGLVersion<2||!n)return 1;if(n.samples===e)return e;let i=this._gl;e=Math.min(e,this.getCaps().maxMSAASamples),n._depthStencilBuffer&&(i.deleteRenderbuffer(n._depthStencilBuffer),n._depthStencilBuffer=null),n._MSAAFramebuffer&&(i.deleteFramebuffer(n._MSAAFramebuffer),n._MSAAFramebuffer=null);let r=n._attachments.length;for(let a=0;a1&&typeof i.renderbufferStorageMultisample=="function"){let a=i.createFramebuffer();if(!a)throw new Error("Unable to create multi sampled framebuffer");n._MSAAFramebuffer=a,this._bindUnboundFramebuffer(a);let o=[];for(let l=0;l1?"COLOR_ATTACHMENT"+l:"COLOR_ATTACHMENT"+l+"_WEBGL"],d=this._createRenderBuffer(c.width,c.height,e,-1,this._getRGBABufferInternalSizedFormat(c.type,c.format,c._useSRGBBuffer),h);if(!d)throw new Error("Unable to create multi sampled framebuffer");f.addMSAARenderBuffer(d),c.samples=e,o.push(h)}t&&i.drawBuffers(o)}else this._bindUnboundFramebuffer(n._framebuffer);let s=n._depthStencilTexture?n._depthStencilTexture.format:void 0;return n._depthStencilBuffer=this._setupFramebufferDepthAttachments(n._generateStencilBuffer,n._generateDepthBuffer,n.width,n.height,e,s),this._bindUnboundFramebuffer(null),n._samples=e,e};bt.prototype.generateMipMapsMultiFramebuffer=function(n){let e=n,t=this._gl;if(e.isMulti)for(let i=0;i1?"COLOR_ATTACHMENT"+a:"COLOR_ATTACHMENT"+a+"_WEBGL"],t.readBuffer(r[a]),t.drawBuffers(r),t.blitFramebuffer(0,0,o.width,o.height,0,0,o.width,o.height,i,t.NEAREST)}for(let a=0;a1?"COLOR_ATTACHMENT"+a:"COLOR_ATTACHMENT"+a+"_WEBGL"];t.drawBuffers(r),t.bindFramebuffer(this._gl.FRAMEBUFFER,e._MSAAFramebuffer)}});var TR,u5=C(()=>{Fr();_f();jD();TR=class extends Br{get isSupported(){var e,t;return(t=(e=this._engine)==null?void 0:e.getCaps().drawBuffersExtension)!=null?t:!1}get textures(){return this._textures}get count(){return this._count}get depthTexture(){return this._textures[this._textures.length-1]}set wrapU(e){if(this._textures)for(let t=0;t0&&(this._createInternalTextures(),this._createTextures(a))}_initTypes(e,t,i,r,s,a,o,l,c,f){for(let h=0;h{this.onAfterRenderObservable.notifyObservers(t)})}dispose(e=!1){this._releaseTextures(),e?this._texture=null:this.releaseInternalTextures(),super.dispose()}releaseInternalTextures(){var t,i;let e=(t=this._renderTarget)==null?void 0:t.textures;if(e){for(let r=e.length-1;r>=0;r--)this._textures[r]._texture=null;(i=this._renderTarget)==null||i.dispose(),this._renderTarget=null}}}});var m5,Nce,p5=C(()=>{k();m5="mrtFragmentDeclaration",Nce=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) layout(location=0) out vec4 glFragData[{X}]; #endif -`;T.IncludesShadersStore[m5]||(T.IncludesShadersStore[m5]=Nce)});var _5,wce,TR=C(()=>{W();_5="pbrFragmentReflectionDeclaration",wce=`#ifdef REFLECTION +`;T.IncludesShadersStore[m5]||(T.IncludesShadersStore[m5]=Nce)});var _5,wce,AR=C(()=>{k();_5="pbrFragmentReflectionDeclaration",wce=`#ifdef REFLECTION #ifdef REFLECTIONMAP_3D #define sampleReflection(s,c) textureCube(s,c) uniform samplerCube reflectionSampler; @@ -10753,12 +10753,12 @@ varying vec3 vDirectionW; #endif #endif #endif -`;T.IncludesShadersStore[_5]||(T.IncludesShadersStore[_5]=wce)});var g5,Fce,qD=C(()=>{W();g5="sceneFragmentDeclaration",Fce=`uniform mat4 viewProjection; +`;T.IncludesShadersStore[_5]||(T.IncludesShadersStore[_5]=wce)});var g5,Fce,qD=C(()=>{k();g5="sceneFragmentDeclaration",Fce=`uniform mat4 viewProjection; #ifdef MULTIVIEW uniform mat4 viewProjectionR; #endif uniform mat4 view;uniform mat4 projection;uniform vec4 vEyePosition;uniform mat4 inverseProjection; -`;T.IncludesShadersStore[g5]||(T.IncludesShadersStore[g5]=Fce)});var v5,Bce,rp=C(()=>{W();v5="pbrBRDFFunctions",Bce=`#define FRESNEL_MAXIMUM_ON_ROUGH 0.25 +`;T.IncludesShadersStore[g5]||(T.IncludesShadersStore[g5]=Fce)});var v5,Bce,ip=C(()=>{k();v5="pbrBRDFFunctions",Bce=`#define FRESNEL_MAXIMUM_ON_ROUGH 0.25 #define BRDF_DIFFUSE_MODEL_EON 0 #define BRDF_DIFFUSE_MODEL_BURLEY 1 #define BRDF_DIFFUSE_MODEL_LAMBERT 2 @@ -10931,7 +10931,7 @@ vec3 transmittanceBRDF_Burley(const vec3 tintColor,const vec3 diffusionDistance, float computeWrappedDiffuseNdotL(float NdotL,float w) {float t=1.0+w;float invt2=1.0/square(t);return saturate((NdotL+w)*invt2);} #endif #endif -`;T.IncludesShadersStore[v5]||(T.IncludesShadersStore[v5]=Bce)});var E5,Uce,ZD=C(()=>{W();E5="openpbrDielectricReflectance",Uce=`struct ReflectanceParams +`;T.IncludesShadersStore[v5]||(T.IncludesShadersStore[v5]=Bce)});var E5,Uce,ZD=C(()=>{k();E5="openpbrDielectricReflectance",Uce=`struct ReflectanceParams {float F0;float F90;vec3 coloredF0;vec3 coloredF90;}; #define pbr_inline ReflectanceParams dielectricReflectance( @@ -10949,7 +10949,7 @@ float maxF0=max(specularColor.r,max(specularColor.g,specularColor.b));outParams. outParams.F0=mix(dielectricF0_NoSpec,dielectricF0,specularWeight); #endif outParams.F90=mix(f90Scale_NoSpec,f90Scale,specularWeight);outParams.coloredF0=mix(vec3(dielectricF0_NoSpec),vec3(dielectricF0),specularWeight)*specularColor.rgb;outParams.coloredF90=mix(dielectricColorF90_NoSpec,dielectricColorF90,specularWeight);return outParams;} -`;T.IncludesShadersStore[E5]||(T.IncludesShadersStore[E5]=Uce)});var S5,Vce,AR=C(()=>{W();S5="pbrIBLFunctions",Vce=`#if defined(REFLECTION) || defined(SS_REFRACTION) +`;T.IncludesShadersStore[E5]||(T.IncludesShadersStore[E5]=Uce)});var S5,Vce,xR=C(()=>{k();S5="pbrIBLFunctions",Vce=`#if defined(REFLECTION) || defined(SS_REFRACTION) float getLodFromAlphaG(float cubeMapDimensionPixels,float microsurfaceAverageSlope) {float microsurfaceAverageSlopeTexels=cubeMapDimensionPixels*microsurfaceAverageSlope;float lod=log2(microsurfaceAverageSlopeTexels);return lod;} float getLinearLodFromRoughness(float cubeMapDimensionPixels,float roughness) {float lod=log2(cubeMapDimensionPixels)*roughness;return lod;} #endif @@ -10963,7 +10963,7 @@ float environmentHorizonOcclusion(vec3 view,vec3 normal,vec3 geometricNormal) {v #define UNPACK_LOD(x) (1.0-x)*255.0 float getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {float microsurfaceAverageSlope=alphaG;microsurfaceAverageSlope*=sqrt(abs(NdotV));return getLodFromAlphaG(cubeMapDimensionPixels,microsurfaceAverageSlope);} #endif -`;T.IncludesShadersStore[S5]||(T.IncludesShadersStore[S5]=Vce)});var T5,Gce,QD=C(()=>{W();T5="openpbrGeometryInfo",Gce=`struct geometryInfoOutParams +`;T.IncludesShadersStore[S5]||(T.IncludesShadersStore[S5]=Vce)});var T5,Gce,QD=C(()=>{k();T5="openpbrGeometryInfo",Gce=`struct geometryInfoOutParams {float NdotV;float NdotVUnclamped;vec3 environmentBrdf;float horizonOcclusion;};struct geometryInfoAnisoOutParams {float NdotV;float NdotVUnclamped;vec3 environmentBrdf;float horizonOcclusion;float anisotropy;vec3 anisotropicTangent;vec3 anisotropicBitangent;mat3 TBN;}; #define pbr_inline @@ -10992,7 +10992,7 @@ geometryInfoAnisoOutParams geometryInfoAniso( in vec3 normalW,in vec3 viewDirectionW,in float roughness,in vec3 geometricNormalW ,in vec3 vAnisotropy,in mat3 TBN ) -{geometryInfoOutParams geoInfo=geometryInfo(normalW,viewDirectionW,roughness,geometricNormalW);geometryInfoAnisoOutParams outParams;outParams.NdotV=geoInfo.NdotV;outParams.NdotVUnclamped=geoInfo.NdotVUnclamped;outParams.environmentBrdf=geoInfo.environmentBrdf;outParams.horizonOcclusion=geoInfo.horizonOcclusion;outParams.anisotropy=vAnisotropy.b;vec3 anisotropyDirection=vec3(vAnisotropy.xy,0.);mat3 anisoTBN=mat3(normalize(TBN[0]),normalize(TBN[1]),normalize(TBN[2]));outParams.anisotropicTangent=normalize(anisoTBN*anisotropyDirection);outParams.anisotropicBitangent=normalize(cross(anisoTBN[2],outParams.anisotropicTangent));outParams.TBN=TBN;return outParams;}`;T.IncludesShadersStore[T5]||(T.IncludesShadersStore[T5]=Gce)});var A5,kce,$D=C(()=>{W();A5="openpbrIblFunctions",kce=`#ifdef REFLECTION +{geometryInfoOutParams geoInfo=geometryInfo(normalW,viewDirectionW,roughness,geometricNormalW);geometryInfoAnisoOutParams outParams;outParams.NdotV=geoInfo.NdotV;outParams.NdotVUnclamped=geoInfo.NdotVUnclamped;outParams.environmentBrdf=geoInfo.environmentBrdf;outParams.horizonOcclusion=geoInfo.horizonOcclusion;outParams.anisotropy=vAnisotropy.b;vec3 anisotropyDirection=vec3(vAnisotropy.xy,0.);mat3 anisoTBN=mat3(normalize(TBN[0]),normalize(TBN[1]),normalize(TBN[2]));outParams.anisotropicTangent=normalize(anisoTBN*anisotropyDirection);outParams.anisotropicBitangent=normalize(cross(anisoTBN[2],outParams.anisotropicTangent));outParams.TBN=TBN;return outParams;}`;T.IncludesShadersStore[T5]||(T.IncludesShadersStore[T5]=Gce)});var A5,kce,$D=C(()=>{k();A5="openpbrIblFunctions",kce=`#ifdef REFLECTION vec3 sampleIrradiance( in vec3 surfaceNormal #if defined(NORMAL) && defined(USESPHERICALINVERTEX) @@ -11214,7 +11214,7 @@ return getReflectanceFromBRDFLookup(reflectance.coloredF0,reflectance.coloredF90 #endif } #endif -`;T.IncludesShadersStore[A5]||(T.IncludesShadersStore[A5]=kce)});var x5,Wce,JD=C(()=>{W();x5="openpbrSubsurfaceLayerData",Wce=`float subsurface_weight=vSubsurfaceWeight;vec3 subsurface_color=vSubsurfaceColor.rgb;float subsurface_radius=vSubsurfaceRadius;vec3 subsurface_radius_scale=vSubsurfaceRadiusScale;float subsurface_scatter_anisotropy=clamp(vSubsurfaceScatterAnisotropy,-0.9999,0.9999); +`;T.IncludesShadersStore[A5]||(T.IncludesShadersStore[A5]=kce)});var x5,Wce,JD=C(()=>{k();x5="openpbrSubsurfaceLayerData",Wce=`float subsurface_weight=vSubsurfaceWeight;vec3 subsurface_color=vSubsurfaceColor.rgb;float subsurface_radius=vSubsurfaceRadius;vec3 subsurface_radius_scale=vSubsurfaceRadiusScale;float subsurface_scatter_anisotropy=clamp(vSubsurfaceScatterAnisotropy,-0.9999,0.9999); #ifdef SUBSURFACE_WEIGHT vec4 subsurfaceWeightFromTexture=texture2D(subsurfaceWeightSampler,vSubsurfaceWeightUV+uvOffset); #endif @@ -11238,7 +11238,7 @@ subsurface_color*=vSubsurfaceColorInfos.y; #ifdef SUBSURFACE_RADIUS_SCALE subsurface_radius_scale*=subsurfaceRadiusScaleFromTexture.rgb; #endif -`;T.IncludesShadersStore[x5]||(T.IncludesShadersStore[x5]=Wce)});var R5,Hce,eL=C(()=>{W();R5="openpbrTransmissionLayerData",Hce=`float transmission_weight=vTransmissionWeight;vec3 transmission_color=vTransmissionColor.rgb;float transmission_depth=vTransmissionDepth;vec3 transmission_scatter=vTransmissionScatter.rgb;float transmission_scatter_anisotropy=clamp(vTransmissionScatterAnisotropy,-0.9999,0.9999);float transmission_dispersion_scale=vTransmissionDispersionScale;float transmission_dispersion_abbe_number=vTransmissionDispersionAbbeNumber; +`;T.IncludesShadersStore[x5]||(T.IncludesShadersStore[x5]=Wce)});var R5,Hce,eL=C(()=>{k();R5="openpbrTransmissionLayerData",Hce=`float transmission_weight=vTransmissionWeight;vec3 transmission_color=vTransmissionColor.rgb;float transmission_depth=vTransmissionDepth;vec3 transmission_scatter=vTransmissionScatter.rgb;float transmission_scatter_anisotropy=clamp(vTransmissionScatterAnisotropy,-0.9999,0.9999);float transmission_dispersion_scale=vTransmissionDispersionScale;float transmission_dispersion_abbe_number=vTransmissionDispersionAbbeNumber; #ifdef TRANSMISSION_WEIGHT vec4 transmissionWeightFromTexture=texture2D(transmissionWeightSampler,vTransmissionWeightUV+uvOffset); #endif @@ -11274,7 +11274,7 @@ transmission_scatter*=transmissionScatterFromTexture.rgb; #ifdef TRANSMISSION_DISPERSION_SCALE transmission_dispersion_scale*=transmissionDispersionScaleFromTexture.r; #endif -`;T.IncludesShadersStore[R5]||(T.IncludesShadersStore[R5]=Hce)});var I5={};tt(I5,{geometryPixelShader:()=>zce});var tL,b5,zce,iL=C(()=>{W();Ec();p5();Hx();zx();ya();TR();qD();rd();rp();ZD();AR();wg();QD();$D();sd();Sc();Xx();JD();eL();tL="geometryPixelShader",b5=`#extension GL_EXT_draw_buffers : require +`;T.IncludesShadersStore[R5]||(T.IncludesShadersStore[R5]=Hce)});var I5={};tt(I5,{geometryPixelShader:()=>zce});var tL,b5,zce,iL=C(()=>{k();vc();p5();zx();Xx();Ca();AR();qD();rd();ip();ZD();xR();wg();QD();$D();sd();Ec();Yx();JD();eL();tL="geometryPixelShader",b5=`#extension GL_EXT_draw_buffers : require #if defined(BUMP) || !defined(NORMAL) #extension GL_OES_standard_derivatives : enable #endif @@ -11512,8 +11512,8 @@ irradiance_alpha=min(subsurface_weight+transmission_weight,1.0); gl_FragData[IRRADIANCE_INDEX]=vec4(irradiance,irradiance_alpha); #endif } -`;T.ShadersStore[tL]||(T.ShadersStore[tL]=b5);zce={name:tL,shader:b5}});var M5,Xce,C5=C(()=>{W();M5="geometryVertexDeclaration",Xce="uniform mat4 viewProjection;uniform mat4 view;";T.IncludesShadersStore[M5]||(T.IncludesShadersStore[M5]=Xce)});var y5,Yce,P5=C(()=>{W();rd();y5="geometryUboDeclaration",Yce=`#include -`;T.IncludesShadersStore[y5]||(T.IncludesShadersStore[y5]=Yce)});var D5,Kce,np=C(()=>{W();D5="harmonicsFunctions",Kce=`#ifdef USESPHERICALFROMREFLECTIONMAP +`;T.ShadersStore[tL]||(T.ShadersStore[tL]=b5);zce={name:tL,shader:b5}});var M5,Xce,C5=C(()=>{k();M5="geometryVertexDeclaration",Xce="uniform mat4 viewProjection;uniform mat4 view;";T.IncludesShadersStore[M5]||(T.IncludesShadersStore[M5]=Xce)});var y5,Yce,P5=C(()=>{k();rd();y5="geometryUboDeclaration",Yce=`#include +`;T.IncludesShadersStore[y5]||(T.IncludesShadersStore[y5]=Yce)});var D5,Kce,rp=C(()=>{k();D5="harmonicsFunctions",Kce=`#ifdef USESPHERICALFROMREFLECTIONMAP #ifdef SPHERICAL_HARMONICS vec3 computeEnvironmentIrradiance(vec3 normal) {return vSphericalL00 + vSphericalL1_1*(normal.y) @@ -11528,7 +11528,7 @@ vec3 computeEnvironmentIrradiance(vec3 normal) {return vSphericalL00 vec3 computeEnvironmentIrradiance(vec3 normal) {float Nx=normal.x;float Ny=normal.y;float Nz=normal.z;vec3 C1=vSphericalZZ.rgb;vec3 Cx=vSphericalX.rgb;vec3 Cy=vSphericalY.rgb;vec3 Cz=vSphericalZ.rgb;vec3 Cxx_zz=vSphericalXX_ZZ.rgb;vec3 Cyy_zz=vSphericalYY_ZZ.rgb;vec3 Cxy=vSphericalXY.rgb;vec3 Cyz=vSphericalYZ.rgb;vec3 Czx=vSphericalZX.rgb;vec3 a1=Cyy_zz*Ny+Cy;vec3 a2=Cyz*Nz+a1;vec3 b1=Czx*Nz+Cx;vec3 b2=Cxy*Ny+b1;vec3 b3=Cxx_zz*Nx+b2;vec3 t1=Cz *Nz+C1;vec3 t2=a2 *Ny+t1;vec3 t3=b3 *Nx+t2;return t3;} #endif #endif -`;T.IncludesShadersStore[D5]||(T.IncludesShadersStore[D5]=Kce)});var O5={};tt(O5,{geometryVertexShader:()=>jce});var rL,L5,jce,nL=C(()=>{W();dc();uc();Wf();Hf();Ff();C5();P5();mc();np();zf();Xf();pc();_c();gc();vc();Lx();rL="geometryVertexShader",L5=`precision highp float; +`;T.IncludesShadersStore[D5]||(T.IncludesShadersStore[D5]=Kce)});var O5={};tt(O5,{geometryVertexShader:()=>jce});var rL,L5,jce,nL=C(()=>{k();hc();dc();kf();Wf();wf();C5();P5();uc();rp();Hf();zf();mc();pc();_c();gc();Ox();rL="geometryVertexShader",L5=`precision highp float; #include #include #include @@ -11740,7 +11740,7 @@ vEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector)*vReflectio #endif #endif } -`;T.ShadersStore[rL]||(T.ShadersStore[rL]=L5);jce={name:rL,shader:L5}});var N5,qce,sp=C(()=>{W();N5="harmonicsFunctions",qce=`#ifdef USESPHERICALFROMREFLECTIONMAP +`;T.ShadersStore[rL]||(T.ShadersStore[rL]=L5);jce={name:rL,shader:L5}});var N5,qce,np=C(()=>{k();N5="harmonicsFunctions",qce=`#ifdef USESPHERICALFROMREFLECTIONMAP #ifdef SPHERICAL_HARMONICS fn computeEnvironmentIrradiance(normal: vec3f)->vec3f {return uniforms.vSphericalL00 + uniforms.vSphericalL1_1*(normal.y) @@ -11755,7 +11755,7 @@ fn computeEnvironmentIrradiance(normal: vec3f)->vec3f {return uniforms.vSpherica fn computeEnvironmentIrradiance(normal: vec3f)->vec3f {var Nx: f32=normal.x;var Ny: f32=normal.y;var Nz: f32=normal.z;var C1: vec3f=uniforms.vSphericalZZ.rgb;var Cx: vec3f=uniforms.vSphericalX.rgb;var Cy: vec3f=uniforms.vSphericalY.rgb;var Cz: vec3f=uniforms.vSphericalZ.rgb;var Cxx_zz: vec3f=uniforms.vSphericalXX_ZZ.rgb;var Cyy_zz: vec3f=uniforms.vSphericalYY_ZZ.rgb;var Cxy: vec3f=uniforms.vSphericalXY.rgb;var Cyz: vec3f=uniforms.vSphericalYZ.rgb;var Czx: vec3f=uniforms.vSphericalZX.rgb;var a1: vec3f=Cyy_zz*Ny+Cy;var a2: vec3f=Cyz*Nz+a1;var b1: vec3f=Czx*Nz+Cx;var b2: vec3f=Cxy*Ny+b1;var b3: vec3f=Cxx_zz*Nx+b2;var t1: vec3f=Cz *Nz+C1;var t2: vec3f=a2 *Ny+t1;var t3: vec3f=b3 *Nx+t2;return t3;} #endif #endif -`;T.IncludesShadersStoreWGSL[N5]||(T.IncludesShadersStoreWGSL[N5]=qce)});var F5={};tt(F5,{geometryVertexShaderWGSL:()=>Zce});var sL,w5,Zce,B5=C(()=>{W();rc();nc();Uf();Vf();wf();ed();sc();sp();Gf();kf();ac();oc();lc();cc();lx();sL="geometryVertexShader",w5=`#include +`;T.IncludesShadersStoreWGSL[N5]||(T.IncludesShadersStoreWGSL[N5]=qce)});var F5={};tt(F5,{geometryVertexShaderWGSL:()=>Zce});var sL,w5,Zce,B5=C(()=>{k();ic();rc();Bf();Uf();Nf();ed();nc();np();Vf();Gf();sc();ac();oc();lc();cx();sL="geometryVertexShader",w5=`#include #include #include #include[0..maxSimultaneousMorphTargets] @@ -11966,7 +11966,7 @@ vertexOutputs.vEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVect #endif #endif } -`;T.ShadersStoreWGSL[sL]||(T.ShadersStoreWGSL[sL]=w5);Zce={name:sL,shader:w5}});var U5,Qce,xR=C(()=>{W();U5="pbrFragmentReflectionDeclaration",Qce=`#ifdef REFLECTION +`;T.ShadersStoreWGSL[sL]||(T.ShadersStoreWGSL[sL]=w5);Zce={name:sL,shader:w5}});var U5,Qce,RR=C(()=>{k();U5="pbrFragmentReflectionDeclaration",Qce=`#ifdef REFLECTION #ifdef REFLECTIONMAP_3D var reflectionSamplerSampler: sampler;var reflectionSampler: texture_cube; #ifdef LODBASEDMICROSFURACE @@ -11994,7 +11994,7 @@ varying vDirectionW: vec3f; #endif #endif #endif -`;T.IncludesShadersStoreWGSL[U5]||(T.IncludesShadersStoreWGSL[U5]=Qce)});var V5,$ce,ap=C(()=>{W();V5="pbrBRDFFunctions",$ce=`#define FRESNEL_MAXIMUM_ON_ROUGH 0.25 +`;T.IncludesShadersStoreWGSL[U5]||(T.IncludesShadersStoreWGSL[U5]=Qce)});var V5,$ce,sp=C(()=>{k();V5="pbrBRDFFunctions",$ce=`#define FRESNEL_MAXIMUM_ON_ROUGH 0.25 #define BRDF_DIFFUSE_MODEL_EON 0 #define BRDF_DIFFUSE_MODEL_BURLEY 1 #define BRDF_DIFFUSE_MODEL_LAMBERT 2 @@ -12166,7 +12166,7 @@ fn transmittanceBRDF_Burley(tintColor: vec3f,diffusionDistance: vec3f,thickness: fn computeWrappedDiffuseNdotL(NdotL: f32,w: f32)->f32 {var t: f32=1.0+w;var invt2: f32=1.0/(t*t);return saturate((NdotL+w)*invt2);} #endif #endif -`;T.IncludesShadersStoreWGSL[V5]||(T.IncludesShadersStoreWGSL[V5]=$ce)});var G5,Jce,aL=C(()=>{W();G5="openpbrDielectricReflectance",Jce=`struct ReflectanceParams +`;T.IncludesShadersStoreWGSL[V5]||(T.IncludesShadersStoreWGSL[V5]=$ce)});var G5,Jce,aL=C(()=>{k();G5="openpbrDielectricReflectance",Jce=`struct ReflectanceParams {F0: f32, F90: f32, coloredF0: vec3f, @@ -12188,7 +12188,7 @@ let dielectricColorF90: vec3f=specularColor.rgb*vec3f(f90Scale)*specularWeight; let dielectricColorF90: vec3f=vec3f(f90Scale)*specularWeight; #endif outParams.coloredF90=dielectricColorF90;return outParams;} -`;T.IncludesShadersStoreWGSL[G5]||(T.IncludesShadersStoreWGSL[G5]=Jce)});var k5,efe,RR=C(()=>{W();k5="pbrIBLFunctions",efe=`#if defined(REFLECTION) || defined(SS_REFRACTION) +`;T.IncludesShadersStoreWGSL[G5]||(T.IncludesShadersStoreWGSL[G5]=Jce)});var k5,efe,bR=C(()=>{k();k5="pbrIBLFunctions",efe=`#if defined(REFLECTION) || defined(SS_REFRACTION) fn getLodFromAlphaG(cubeMapDimensionPixels: f32,microsurfaceAverageSlope: f32)->f32 {var microsurfaceAverageSlopeTexels: f32=cubeMapDimensionPixels*microsurfaceAverageSlope;var lod: f32=log2(microsurfaceAverageSlopeTexels);return lod;} fn getLinearLodFromRoughness(cubeMapDimensionPixels: f32,roughness: f32)->f32 {var lod: f32=log2(cubeMapDimensionPixels)*roughness;return lod;} #endif @@ -12202,7 +12202,7 @@ fn environmentHorizonOcclusion(view: vec3f,normal: vec3f,geometricNormal: vec3f) fn UNPACK_LOD(x: f32)->f32 {return (1.0-x)*255.0;} fn getLodFromAlphaGNdotV(cubeMapDimensionPixels: f32,alphaG: f32,NdotV: f32)->f32 {var microsurfaceAverageSlope: f32=alphaG;microsurfaceAverageSlope*=sqrt(abs(NdotV));return getLodFromAlphaG(cubeMapDimensionPixels,microsurfaceAverageSlope);} #endif -`;T.IncludesShadersStoreWGSL[k5]||(T.IncludesShadersStoreWGSL[k5]=efe)});var W5,tfe,oL=C(()=>{W();W5="openpbrGeometryInfo",tfe=`struct geometryInfoOutParams +`;T.IncludesShadersStoreWGSL[k5]||(T.IncludesShadersStoreWGSL[k5]=efe)});var W5,tfe,oL=C(()=>{k();W5="openpbrGeometryInfo",tfe=`struct geometryInfoOutParams {NdotV: f32, NdotVUnclamped: f32, environmentBrdf: vec3f, @@ -12239,7 +12239,7 @@ normalW: vec3f,viewDirectionW: vec3f,roughness: f32,geometricNormalW: vec3f ,vAnisotropy: vec3f,TBN: mat3x3 )->geometryInfoAnisoOutParams {let geoInfo: geometryInfoOutParams=geometryInfo(normalW,viewDirectionW,roughness,geometricNormalW);var outParams: geometryInfoAnisoOutParams;outParams.NdotV=geoInfo.NdotV;outParams.NdotVUnclamped=geoInfo.NdotVUnclamped;outParams.environmentBrdf=geoInfo.environmentBrdf;outParams.horizonOcclusion=geoInfo.horizonOcclusion;outParams.anisotropy=vAnisotropy.b;let anisotropyDirection: vec3f=vec3f(vAnisotropy.xy,0.);let anisoTBN: mat3x3=mat3x3(normalize(TBN[0]),normalize(TBN[1]),normalize(TBN[2]));outParams.anisotropicTangent=normalize(anisoTBN*anisotropyDirection);outParams.anisotropicBitangent=normalize(cross(anisoTBN[2],outParams.anisotropicTangent));outParams.TBN=TBN;return outParams;} -`;T.IncludesShadersStoreWGSL[W5]||(T.IncludesShadersStoreWGSL[W5]=tfe)});var H5,ife,lL=C(()=>{W();H5="openpbrIblFunctions",ife=`#ifdef REFLECTION +`;T.IncludesShadersStoreWGSL[W5]||(T.IncludesShadersStoreWGSL[W5]=tfe)});var H5,ife,lL=C(()=>{k();H5="openpbrIblFunctions",ife=`#ifdef REFLECTION fn sampleIrradiance( surfaceNormal: vec3f #if defined(NORMAL) && defined(USESPHERICALINVERTEX) @@ -12457,7 +12457,7 @@ return getReflectanceFromBRDFLookup(reflectance.coloredF0,reflectance.coloredF90 #endif } #endif -`;T.IncludesShadersStoreWGSL[H5]||(T.IncludesShadersStoreWGSL[H5]=ife)});var z5,rfe,cL=C(()=>{W();z5="openpbrSubsurfaceLayerData",rfe=`var subsurface_weight: f32=uniforms.vSubsurfaceWeight;var subsurface_color: vec3f=uniforms.vSubsurfaceColor.rgb;var subsurface_radius: f32=uniforms.vSubsurfaceRadius;var subsurface_radius_scale: vec3f=uniforms.vSubsurfaceRadiusScale;var subsurface_scatter_anisotropy: f32=clamp(uniforms.vSubsurfaceScatterAnisotropy,-0.9999f,0.9999f); +`;T.IncludesShadersStoreWGSL[H5]||(T.IncludesShadersStoreWGSL[H5]=ife)});var z5,rfe,cL=C(()=>{k();z5="openpbrSubsurfaceLayerData",rfe=`var subsurface_weight: f32=uniforms.vSubsurfaceWeight;var subsurface_color: vec3f=uniforms.vSubsurfaceColor.rgb;var subsurface_radius: f32=uniforms.vSubsurfaceRadius;var subsurface_radius_scale: vec3f=uniforms.vSubsurfaceRadiusScale;var subsurface_scatter_anisotropy: f32=clamp(uniforms.vSubsurfaceScatterAnisotropy,-0.9999f,0.9999f); #ifdef SUBSURFACE_WEIGHT let subsurfaceWeightFromTexture: vec4f=textureSample(subsurfaceWeightSampler,subsurfaceWeightSamplerSampler,fragmentInputs.vSubsurfaceWeightUV+uvOffset); #endif @@ -12481,7 +12481,7 @@ subsurface_color*=uniforms.vSubsurfaceColorInfos.y; #ifdef SUBSURFACE_RADIUS_SCALE subsurface_radius_scale*=subsurfaceRadiusScaleFromTexture.rgb; #endif -`;T.IncludesShadersStoreWGSL[z5]||(T.IncludesShadersStoreWGSL[z5]=rfe)});var X5,nfe,fL=C(()=>{W();X5="openpbrTransmissionLayerData",nfe=`var transmission_weight: f32=uniforms.vTransmissionWeight;var transmission_color: vec3f=uniforms.vTransmissionColor.rgb;var transmission_depth: f32=uniforms.vTransmissionDepth;var transmission_scatter: vec3f=uniforms.vTransmissionScatter.rgb;var transmission_scatter_anisotropy: f32=clamp(uniforms.vTransmissionScatterAnisotropy,-0.9999f,0.9999f);var transmission_dispersion_scale: f32=uniforms.vTransmissionDispersionScale;var transmission_dispersion_abbe_number: f32=uniforms.vTransmissionDispersionAbbeNumber; +`;T.IncludesShadersStoreWGSL[z5]||(T.IncludesShadersStoreWGSL[z5]=rfe)});var X5,nfe,fL=C(()=>{k();X5="openpbrTransmissionLayerData",nfe=`var transmission_weight: f32=uniforms.vTransmissionWeight;var transmission_color: vec3f=uniforms.vTransmissionColor.rgb;var transmission_depth: f32=uniforms.vTransmissionDepth;var transmission_scatter: vec3f=uniforms.vTransmissionScatter.rgb;var transmission_scatter_anisotropy: f32=clamp(uniforms.vTransmissionScatterAnisotropy,-0.9999f,0.9999f);var transmission_dispersion_scale: f32=uniforms.vTransmissionDispersionScale;var transmission_dispersion_abbe_number: f32=uniforms.vTransmissionDispersionAbbeNumber; #ifdef TRANSMISSION_WEIGHT let transmissionWeightFromTexture: vec4f=textureSample(transmissionWeightSampler,transmissionWeightSamplerSampler,fragmentInputs.vTransmissionWeightUV+uvOffset); #endif @@ -12517,7 +12517,7 @@ transmission_scatter*=transmissionScatterFromTexture.rgb; #ifdef TRANSMISSION_DISPERSION_SCALE transmission_dispersion_scale*=transmissionDispersionScaleFromTexture.r; #endif -`;T.IncludesShadersStoreWGSL[X5]||(T.IncludesShadersStoreWGSL[X5]=nfe)});var K5={};tt(K5,{geometryPixelShaderWGSL:()=>sfe});var hL,Y5,sfe,j5=C(()=>{W();fc();gx();vx();Ca();xR();ed();ap();aL();RR();Og();oL();lL();id();hc();Ex();cL();fL();hL="geometryPixelShader",Y5=`#ifdef BUMP +`;T.IncludesShadersStoreWGSL[X5]||(T.IncludesShadersStoreWGSL[X5]=nfe)});var K5={};tt(K5,{geometryPixelShaderWGSL:()=>sfe});var hL,Y5,sfe,j5=C(()=>{k();cc();vx();Ex();Ma();RR();ed();sp();aL();bR();Og();oL();lL();id();fc();Sx();cL();fL();hL="geometryPixelShader",Y5=`#ifdef BUMP varying vWorldView0: vec4f;varying vWorldView1: vec4f;varying vWorldView2: vec4f;varying vWorldView3: vec4f;varying vNormalW: vec3f; #else varying vNormalV: vec3f; @@ -12778,22 +12778,22 @@ fragmentOutputs.fragData6=fragData[6]; fragmentOutputs.fragData7=fragData[7]; #endif } -`;T.ShadersStoreWGSL[hL]||(T.ShadersStoreWGSL[hL]=Y5);sfe={name:hL,shader:Y5}});var q5,dL,ss,Z5=C(()=>{Ve();Gi();Fr();u5();zt();hn();Vn();iL();nL();Da();ol();Un();jD();q5=["diffuseSampler","bumpSampler","reflectivitySampler","albedoSampler","morphTargets","boneSampler","transmissionWeightSampler","subsurfaceWeightSampler","iblShadowSampler"],dL=["world","mBones","viewProjection","diffuseMatrix","view","previousWorld","previousViewProjection","mPreviousBones","bumpMatrix","reflectivityMatrix","albedoMatrix","reflectivityColor","albedoColor","reflectionMatrix","vTransmissionWeight","vSubsurfaceWeight","vEyePosition","vTransmissionScatterAnisotropy","vSubsurfaceScatterAnisotropy","shadowTextureSize","metallic","glossiness","vTangentSpaceParams","vBumpInfos","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices","boneTextureInfo"];bf(dL,q5,!0);wn(dL);ss=class n{get normalsAreUnsigned(){return this._normalsAreUnsigned}_linkPrePassRenderer(e){this._linkedWithPrePass=!0,this._prePassRenderer=e,this._multiRenderTarget&&(this._multiRenderTarget.onClearObservable.clear(),this._multiRenderTarget.onClearObservable.add(()=>{}))}_unlinkPrePassRenderer(){this._linkedWithPrePass=!1,this._createRenderTargets()}_resetLayout(){this._enableDepth=!0,this._enableNormal=!0,this._enablePosition=!1,this._enableReflectivity=!1,this._enableVelocity=!1,this._enableVelocityLinear=!1,this._enableScreenspaceDepth=!1,this._enableIrradiance=!1,this._attachmentsFromPrePass=[]}_forceTextureType(e,t){e===n.POSITION_TEXTURE_TYPE?(this._positionIndex=t,this._enablePosition=!0):e===n.VELOCITY_TEXTURE_TYPE?(this._velocityIndex=t,this._enableVelocity=!0):e===n.VELOCITY_LINEAR_TEXTURE_TYPE?(this._velocityLinearIndex=t,this._enableVelocityLinear=!0):e===n.REFLECTIVITY_TEXTURE_TYPE?(this._reflectivityIndex=t,this._enableReflectivity=!0):e===n.DEPTH_TEXTURE_TYPE?(this._depthIndex=t,this._enableDepth=!0):e===n.NORMAL_TEXTURE_TYPE?(this._normalIndex=t,this._enableNormal=!0):e===n.SCREENSPACE_DEPTH_TEXTURE_TYPE?(this._screenspaceDepthIndex=t,this._enableScreenspaceDepth=!0):e===n.IRRADIANCE_TEXTURE_TYPE&&(this._irradianceIndex=t,this._enableIrradiance=!0)}_setAttachments(e){this._attachmentsFromPrePass=e}_linkInternalTexture(e){this._multiRenderTarget.setInternalTexture(e,0,!1)}get renderList(){return this._multiRenderTarget.renderList}set renderList(e){this._multiRenderTarget.renderList=e}get isSupported(){return this._multiRenderTarget.isSupported}getTextureIndex(e){switch(e){case n.POSITION_TEXTURE_TYPE:return this._positionIndex;case n.VELOCITY_TEXTURE_TYPE:return this._velocityIndex;case n.VELOCITY_LINEAR_TEXTURE_TYPE:return this._velocityLinearIndex;case n.REFLECTIVITY_TEXTURE_TYPE:return this._reflectivityIndex;case n.DEPTH_TEXTURE_TYPE:return this._depthIndex;case n.NORMAL_TEXTURE_TYPE:return this._normalIndex;case n.SCREENSPACE_DEPTH_TEXTURE_TYPE:return this._screenspaceDepthIndex;case n.IRRADIANCE_TEXTURE_TYPE:return this._irradianceIndex;default:return-1}}get enableDepth(){return this._enableDepth}set enableDepth(e){this._enableDepth=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableNormal(){return this._enableNormal}set enableNormal(e){this._enableNormal=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enablePosition(){return this._enablePosition}set enablePosition(e){this._enablePosition=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableVelocity(){return this._enableVelocity}set enableVelocity(e){this._enableVelocity=e,e||(this._previousTransformationMatrices={}),this._linkedWithPrePass||(this.dispose(),this._createRenderTargets()),this._scene.needsPreviousWorldMatrices=e}get enableVelocityLinear(){return this._enableVelocityLinear}set enableVelocityLinear(e){this._enableVelocityLinear=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableReflectivity(){return this._enableReflectivity}set enableReflectivity(e){this._enableReflectivity=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableScreenspaceDepth(){return this._enableScreenspaceDepth}set enableScreenspaceDepth(e){this._enableScreenspaceDepth=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableIrradiance(){return this._enableIrradiance}set enableIrradiance(e){this._enableIrradiance=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get scene(){return this._scene}get ratio(){return typeof this._ratioOrDimensions=="object"?1:this._ratioOrDimensions}get shaderLanguage(){return this._shaderLanguage}constructor(e,t=1,i=15,r){this._previousTransformationMatrices={},this._previousBonesTransformationMatrices={},this.excludedSkinnedMeshesFromVelocity=[],this.renderTransparentMeshes=!0,this.generateNormalsInWorldSpace=!1,this._normalsAreUnsigned=!1,this._resizeObserver=null,this._enableDepth=!0,this._enableNormal=!0,this._enablePosition=!1,this._enableVelocity=!1,this._enableVelocityLinear=!1,this._enableReflectivity=!1,this._enableScreenspaceDepth=!1,this._enableIrradiance=!1,this._clearColor=new lt(0,0,0,0),this._clearDepthColor=new lt(0,0,0,1),this._positionIndex=-1,this._velocityIndex=-1,this._velocityLinearIndex=-1,this._reflectivityIndex=-1,this._depthIndex=-1,this._normalIndex=-1,this._screenspaceDepthIndex=-1,this._irradianceIndex=-1,this._linkedWithPrePass=!1,this.generateIrradianceWithScatterMask=!1,this.useSpecificClearForDepthTexture=!1,this._shaderLanguage=0,this._shadersLoaded=!1,this._scene=e,this._ratioOrDimensions=t,this._useUbo=e.getEngine().supportsUniformBuffers,this._depthFormat=i,this._textureTypesAndFormats=r||{},this._initShaderSourceAsync(),n._SceneComponentInitialization(this._scene),this._createRenderTargets()}async _initShaderSourceAsync(){this._scene.getEngine().isWebGPU&&!n.ForceGLSL?(this._shaderLanguage=1,await Promise.all([Promise.resolve().then(()=>(B5(),F5)),Promise.resolve().then(()=>(j5(),K5))])):await Promise.all([Promise.resolve().then(()=>(nL(),O5)),Promise.resolve().then(()=>(iL(),I5))]),this._shadersLoaded=!0}isReady(e,t){if(!this._shadersLoaded)return!1;let i=e.getMaterial();if(i&&i.disableDepthWrite)return!1;let r=[],s=[L.PositionKind],a=e.getMesh();a.isVerticesDataPresent(L.NormalKind)&&(r.push("#define HAS_NORMAL_ATTRIBUTE"),s.push(L.NormalKind));let l=!1,c=!1,f=!1;if(i){let _=!1;if(i.needAlphaTestingForMesh(a)&&i.getAlphaTestTexture()&&(r.push("#define ALPHATEST"),r.push(`#define ALPHATEST_UV${i.getAlphaTestTexture().coordinatesIndex+1}`),_=!0),(i.bumpTexture||i.normalTexture||i.geometryNormalTexture)&&le.BumpTextureEnabled){let g=i.bumpTexture||i.normalTexture||i.geometryNormalTexture;r.push("#define BUMP"),r.push(`#define BUMP_UV${g.coordinatesIndex+1}`),_=!0}if(this._enableReflectivity){let g=!1;if(i.getClassName()==="PBRMetallicRoughnessMaterial")i.metallicRoughnessTexture&&(r.push("#define ORMTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.metallicRoughnessTexture.coordinatesIndex+1}`),r.push("#define METALLICWORKFLOW"),_=!0,g=!0),i.metallic!=null&&(r.push("#define METALLIC"),r.push("#define METALLICWORKFLOW"),g=!0),i.roughness!=null&&(r.push("#define ROUGHNESS"),r.push("#define METALLICWORKFLOW"),g=!0),g&&(i.baseTexture&&(r.push("#define ALBEDOTEXTURE"),r.push(`#define ALBEDO_UV${i.baseTexture.coordinatesIndex+1}`),i.baseTexture.gammaSpace&&r.push("#define GAMMAALBEDO"),_=!0),i.baseColor&&r.push("#define ALBEDOCOLOR"));else if(i.getClassName()==="PBRSpecularGlossinessMaterial")i.specularGlossinessTexture?(r.push("#define SPECULARGLOSSINESSTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.specularGlossinessTexture.coordinatesIndex+1}`),_=!0,i.specularGlossinessTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE")):i.specularColor&&r.push("#define REFLECTIVITYCOLOR"),i.glossiness!=null&&r.push("#define GLOSSINESS");else if(i.getClassName()==="PBRMaterial")i.metallicTexture&&(r.push("#define ORMTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.metallicTexture.coordinatesIndex+1}`),r.push("#define METALLICWORKFLOW"),_=!0,g=!0),i.metallic!=null&&(r.push("#define METALLIC"),r.push("#define METALLICWORKFLOW"),g=!0),i.roughness!=null&&(r.push("#define ROUGHNESS"),r.push("#define METALLICWORKFLOW"),g=!0),g?(i.albedoTexture&&(r.push("#define ALBEDOTEXTURE"),r.push(`#define ALBEDO_UV${i.albedoTexture.coordinatesIndex+1}`),i.albedoTexture.gammaSpace&&r.push("#define GAMMAALBEDO"),_=!0),i.albedoColor&&r.push("#define ALBEDOCOLOR")):(i.reflectivityTexture?(r.push("#define SPECULARGLOSSINESSTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.reflectivityTexture.coordinatesIndex+1}`),i.reflectivityTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE"),_=!0):i.reflectivityColor&&r.push("#define REFLECTIVITYCOLOR"),i.microSurface!=null&&r.push("#define GLOSSINESS"));else if(i.getClassName()==="StandardMaterial")i.specularTexture&&(r.push("#define REFLECTIVITYTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.specularTexture.coordinatesIndex+1}`),i.specularTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE"),_=!0),i.specularColor&&r.push("#define REFLECTIVITYCOLOR");else if(i.getClassName()==="OpenPBRMaterial"){let v=i;r.push("#define METALLIC"),r.push("#define ROUGHNESS"),v._useRoughnessFromMetallicTextureGreen&&v.baseMetalnessTexture?(r.push("#define ORMTEXTURE"),r.push(`#define REFLECTIVITY_UV${v.baseMetalnessTexture.coordinatesIndex+1}`),_=!0):v.baseMetalnessTexture?(r.push("#define METALLIC_TEXTURE"),r.push(`#define METALLIC_UV${v.baseMetalnessTexture.coordinatesIndex+1}`),_=!0):v.specularRoughnessTexture&&(r.push("#define ROUGHNESS_TEXTURE"),r.push(`#define ROUGHNESS_UV${v.specularRoughnessTexture.coordinatesIndex+1}`),_=!0),v.baseColorTexture&&(r.push("#define ALBEDOTEXTURE"),r.push(`#define ALBEDO_UV${v.baseColorTexture.coordinatesIndex+1}`),v.baseColorTexture.gammaSpace&&r.push("#define GAMMAALBEDO"),_=!0),v.baseColor&&r.push("#define ALBEDOCOLOR")}}if(this._enableIrradiance&&this.generateIrradianceWithScatterMask&&(r.push("#define IRRADIANCE_SCATTER_MASK"),i.getClassName()==="OpenPBRMaterial")){let g=i;g.subsurfaceWeight>0&&g.subsurfaceWeightTexture&&(r.push("#define SUBSURFACE_WEIGHT"),r.push(`#define SUBSURFACEWEIGHT_UV${g.subsurfaceWeightTexture.coordinatesIndex+1}`),_=!0),g.transmissionWeight>0&&g.transmissionWeightTexture&&(r.push("#define TRANSMISSION_WEIGHT"),r.push(`#define TRANSMISSIONWEIGHT_UV${g.transmissionWeightTexture.coordinatesIndex+1}`),_=!0)}_&&(r.push("#define NEED_UV"),a.isVerticesDataPresent(L.UVKind)&&(s.push(L.UVKind),r.push("#define UV1"),l=!0),a.isVerticesDataPresent(L.UV2Kind)&&(s.push(L.UV2Kind),r.push("#define UV2"),c=!0))}if(this._enableDepth&&(r.push("#define DEPTH"),r.push("#define DEPTH_INDEX "+this._depthIndex)),this._enableNormal&&(r.push("#define NORMAL"),r.push("#define NORMAL_INDEX "+this._normalIndex)),this._enablePosition&&(r.push("#define POSITION"),r.push("#define POSITION_INDEX "+this._positionIndex)),this._enableVelocity&&(r.push("#define VELOCITY"),r.push("#define VELOCITY_INDEX "+this._velocityIndex),this.excludedSkinnedMeshesFromVelocity.indexOf(a)===-1&&r.push("#define BONES_VELOCITY_ENABLED")),this._enableVelocityLinear&&(r.push("#define VELOCITY_LINEAR"),r.push("#define VELOCITY_LINEAR_INDEX "+this._velocityLinearIndex),this.excludedSkinnedMeshesFromVelocity.indexOf(a)===-1&&r.push("#define BONES_VELOCITY_ENABLED")),this._enableReflectivity&&(r.push("#define REFLECTIVITY"),r.push("#define REFLECTIVITY_INDEX "+this._reflectivityIndex)),this._enableScreenspaceDepth&&this._screenspaceDepthIndex!==-1&&(r.push("#define SCREENSPACE_DEPTH_INDEX "+this._screenspaceDepthIndex),r.push("#define SCREENSPACE_DEPTH")),this._enableIrradiance&&this._irradianceIndex!==-1){r.push("#define IRRADIANCE_INDEX "+this._irradianceIndex),r.push("#define IRRADIANCE");let _=this._scene;if(_.environmentTexture){let g={},v=!1,x=0;(i.getClassName()==="OpenPBRMaterial"||i.getClassName()==="StandardMaterial"||i.getClassName()==="PBRMetallicRoughnessMaterial"||i.getClassName()==="PBRSpecularGlossinessMaterial"||i.getClassName()==="PBRMaterial")&&(v=!!i.realtimeFiltering,x=i.realtimeFilteringQuality||0),Rf(_,_.environmentTexture,g,v,x,!0);for(let S in g)g[S]&&r.push("#define "+S);g.USEIRRADIANCEMAP||r.push("#define SPHERICAL_HARMONICS");let A=_.postProcessRenderPipelineManager.supportedPipelines.find(S=>S.getClassName()==="IBLShadowsRenderPipeline");if(A){let S=A;S._getAccumulatedTexture()&&(r.push("#define IBL_SHADOW_TEXTURE"),S.coloredShadows&&r.push("#define COLORED_IBL_SHADOWS"))}}}this.generateNormalsInWorldSpace&&r.push("#define NORMAL_WORLDSPACE"),this._normalsAreUnsigned&&r.push("#define ENCODE_NORMAL"),a.useBones&&a.computeBonesUsingShaders&&a.skeleton?(s.push(L.MatricesIndicesKind),s.push(L.MatricesWeightsKind),a.numBoneInfluencers>4&&(s.push(L.MatricesIndicesExtraKind),s.push(L.MatricesWeightsExtraKind)),r.push("#define NUM_BONE_INFLUENCERS "+a.numBoneInfluencers),r.push("#define BONETEXTURE "+a.skeleton.isUsingTextureForMatrices),r.push("#define BonesPerMesh "+(a.skeleton.bones.length+1))):(r.push("#define NUM_BONE_INFLUENCERS 0"),r.push("#define BONETEXTURE false"),r.push("#define BonesPerMesh 0"));let h=a.morphTargetManager?ll(a.morphTargetManager,r,s,a,!0,!0,!1,l,c,f):0;t&&(r.push("#define INSTANCES"),mo(s,this._enableVelocity||this._enableVelocityLinear),e.getRenderingMesh().hasThinInstances&&r.push("#define THIN_INSTANCES")),this._linkedWithPrePass?r.push("#define SCENE_MRT_COUNT "+this._attachmentsFromPrePass.length):r.push("#define SCENE_MRT_COUNT "+this._multiRenderTarget.textures.length),al(i,this._scene,r);let d=this._scene.getEngine(),u=e._getDrawWrapper(void 0,!0),m=u.defines,p=r.join(` -`);return m!==p&&u.setEffect(d.createEffect("geometry",{attributes:s,uniformsNames:dL,samplers:q5,defines:p,onCompiled:null,fallbacks:null,onError:null,uniformBuffersNames:["Scene"],indexParameters:{buffersCount:this._multiRenderTarget.textures.length-1,maxSimultaneousMorphTargets:h},shaderLanguage:this.shaderLanguage},d),p),u.effect.isReady()}getGBuffer(){return this._multiRenderTarget}get samples(){return this._multiRenderTarget.samples}set samples(e){this._multiRenderTarget.samples=e}dispose(){var e,t;this._resizeObserver&&(this._scene.getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null),(e=this._multiRenderTarget)!=null&&e.renderTarget&&this.scene.getEngine()._currentRenderTarget===this._multiRenderTarget.renderTarget&&this.scene.getEngine().unBindFramebuffer((t=this._multiRenderTarget)==null?void 0:t.renderTarget),this.getGBuffer().dispose()}_assignRenderTargetIndices(){let e=[],t=[],i=0;return this._enableDepth&&(this._depthIndex=i,i++,e.push("gBuffer_Depth"),t.push(this._textureTypesAndFormats[n.DEPTH_TEXTURE_TYPE])),this._enableNormal&&(this._normalIndex=i,i++,e.push("gBuffer_Normal"),t.push(this._textureTypesAndFormats[n.NORMAL_TEXTURE_TYPE])),this._enablePosition&&(this._positionIndex=i,i++,e.push("gBuffer_Position"),t.push(this._textureTypesAndFormats[n.POSITION_TEXTURE_TYPE])),this._enableVelocity&&(this._velocityIndex=i,i++,e.push("gBuffer_Velocity"),t.push(this._textureTypesAndFormats[n.VELOCITY_TEXTURE_TYPE])),this._enableVelocityLinear&&(this._velocityLinearIndex=i,i++,e.push("gBuffer_VelocityLinear"),t.push(this._textureTypesAndFormats[n.VELOCITY_LINEAR_TEXTURE_TYPE])),this._enableReflectivity&&(this._reflectivityIndex=i,i++,e.push("gBuffer_Reflectivity"),t.push(this._textureTypesAndFormats[n.REFLECTIVITY_TEXTURE_TYPE])),this._enableScreenspaceDepth&&(this._screenspaceDepthIndex=i,i++,e.push("gBuffer_ScreenspaceDepth"),t.push(this._textureTypesAndFormats[n.SCREENSPACE_DEPTH_TEXTURE_TYPE])),this._enableIrradiance&&(this._irradianceIndex=i,i++,e.push("gBuffer_Irradiance"),t.push(this._textureTypesAndFormats[n.IRRADIANCE_TEXTURE_TYPE])),[i,e,t]}_createRenderTargets(){var g;let e=this._scene.getEngine(),[t,i,r]=this._assignRenderTargetIndices(),s=0;e._caps.textureFloat&&e._caps.textureFloatLinearFiltering?s=1:e._caps.textureHalfFloat&&e._caps.textureHalfFloatLinearFiltering&&(s=2);let a=this._ratioOrDimensions.width!==void 0?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions},o=[],l=[],c=[];for(let v of r)v?(o.push(v.textureType),l.push(v.textureFormat),c.push((g=v.samplingMode)!=null?g:2)):(o.push(s),l.push(5),c.push(2));if(this._normalsAreUnsigned=o[n.NORMAL_TEXTURE_TYPE]===11||o[n.NORMAL_TEXTURE_TYPE]===13,this._multiRenderTarget=new SR("gBuffer",a,t,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,types:o,formats:l,samplingModes:c,depthTextureFormat:this._depthFormat},i.concat("gBuffer_DepthBuffer")),!this.isSupported)return;this._multiRenderTarget.wrapU=_e.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=_e.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null;let f=[!0],h=[!1],d=[!0];for(let v=1;v{v.bindAttachments(this.useSpecificClearForDepthTexture?m:u),v.clear(this._clearColor,!0,!0,!0),this.useSpecificClearForDepthTexture&&(v.bindAttachments(p),v.clear(this._clearDepthColor,!0,!0,!0)),v.bindAttachments(u)}),this._resizeObserver=e.onResizeObservable.add(()=>{if(this._multiRenderTarget){let v=this._ratioOrDimensions.width!==void 0?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions};this._multiRenderTarget.resize(v)}});let _=v=>{let x=v.getRenderingMesh(),A=v.getEffectiveMesh(),S=this._scene,E=S.getEngine(),R=v.getMaterial();if(!R)return;if(A._internalAbstractMeshDataInfo._isActiveIntermediate=!1,(this._enableVelocity||this._enableVelocityLinear)&&!this._previousTransformationMatrices[A.uniqueId]&&(this._previousTransformationMatrices[A.uniqueId]={world:j.Identity(),viewProjection:S.getTransformMatrix()},x.skeleton)){let D=x.skeleton.getTransformMatrices(x);this._previousBonesTransformationMatrices[x.uniqueId]=this._copyBonesTransformationMatrices(D,new Float32Array(D.length))}let I=x._getInstancesRenderList(v._id,!!v.getReplacementMesh());if(I.mustReturn)return;let y=E.getCaps().instancedArrays&&(I.visibleInstances[v._id]!==null||x.hasThinInstances),M=A.getWorldMatrix();if(this.isReady(v,y)){let D=v._getDrawWrapper();if(!D)return;let O=D.effect;E.enableEffect(D),y||x._bind(v,O,R.fillMode),this._useUbo?(xf(O,this._scene.getSceneUniformBuffer()),this._scene.finalizeSceneUbo()):(O.setMatrix("viewProjection",S.getTransformMatrix()),O.setMatrix("view",S.getViewMatrix()),this._scene.bindEyePosition(O,"vEyePosition"));let V;if(!x._instanceDataStorage.isFrozen&&(R.backFaceCulling||R.sideOrientation!==null)){let F=A._getWorldMatrixDeterminant();V=R._getEffectiveOrientation(x),F<0&&(V=V===Ee.ClockWiseSideOrientation?Ee.CounterClockWiseSideOrientation:Ee.ClockWiseSideOrientation)}else V=x._effectiveSideOrientation;if(R._preBind(D,V),R.needAlphaTestingForMesh(A)){let F=R.getAlphaTestTexture();F&&(O.setTexture("diffuseSampler",F),O.setMatrix("diffuseMatrix",F.getTextureMatrix()))}if((R.bumpTexture||R.normalTexture||R.geometryNormalTexture)&&S.getEngine().getCaps().standardDerivatives&&le.BumpTextureEnabled){let F=R.bumpTexture||R.normalTexture||R.geometryNormalTexture;O.setFloat3("vBumpInfos",F.coordinatesIndex,1/F.level,R.parallaxScaleBias),O.setMatrix("bumpMatrix",F.getTextureMatrix()),O.setTexture("bumpSampler",F),O.setFloat2("vTangentSpaceParams",R.invertNormalMapX?-1:1,R.invertNormalMapY?-1:1)}if(this._enableReflectivity){if(R.getClassName()==="PBRMetallicRoughnessMaterial")R.metallicRoughnessTexture!==null&&(O.setTexture("reflectivitySampler",R.metallicRoughnessTexture),O.setMatrix("reflectivityMatrix",R.metallicRoughnessTexture.getTextureMatrix())),R.metallic!==null&&O.setFloat("metallic",R.metallic),R.roughness!==null&&O.setFloat("glossiness",1-R.roughness),R.baseTexture!==null&&(O.setTexture("albedoSampler",R.baseTexture),O.setMatrix("albedoMatrix",R.baseTexture.getTextureMatrix())),R.baseColor!==null&&O.setColor3("albedoColor",R.baseColor);else if(R.getClassName()==="PBRSpecularGlossinessMaterial")R.specularGlossinessTexture!==null?(O.setTexture("reflectivitySampler",R.specularGlossinessTexture),O.setMatrix("reflectivityMatrix",R.specularGlossinessTexture.getTextureMatrix())):R.specularColor!==null&&O.setColor3("reflectivityColor",R.specularColor),R.glossiness!==null&&O.setFloat("glossiness",R.glossiness);else if(R.getClassName()==="PBRMaterial")R.metallicTexture!==null&&(O.setTexture("reflectivitySampler",R.metallicTexture),O.setMatrix("reflectivityMatrix",R.metallicTexture.getTextureMatrix())),R.metallic!==null&&O.setFloat("metallic",R.metallic),R.roughness!==null&&O.setFloat("glossiness",1-R.roughness),R.roughness!==null||R.metallic!==null||R.metallicTexture!==null?(R.albedoTexture!==null&&(O.setTexture("albedoSampler",R.albedoTexture),O.setMatrix("albedoMatrix",R.albedoTexture.getTextureMatrix())),R.albedoColor!==null&&O.setColor3("albedoColor",R.albedoColor)):(R.reflectivityTexture!==null?(O.setTexture("reflectivitySampler",R.reflectivityTexture),O.setMatrix("reflectivityMatrix",R.reflectivityTexture.getTextureMatrix())):R.reflectivityColor!==null&&O.setColor3("reflectivityColor",R.reflectivityColor),R.microSurface!==null&&O.setFloat("glossiness",R.microSurface));else if(R.getClassName()==="StandardMaterial")R.specularTexture!==null&&(O.setTexture("reflectivitySampler",R.specularTexture),O.setMatrix("reflectivityMatrix",R.specularTexture.getTextureMatrix())),R.specularColor!==null&&O.setColor3("reflectivityColor",R.specularColor);else if(R.getClassName()==="OpenPBRMaterial"){let F=R;F._useRoughnessFromMetallicTextureGreen&&F.baseMetalnessTexture?(O.setTexture("reflectivitySampler",F.baseMetalnessTexture),O.setMatrix("reflectivityMatrix",F.baseMetalnessTexture.getTextureMatrix())):F.baseMetalnessTexture?(O.setTexture("metallicSampler",F.baseMetalnessTexture),O.setMatrix("metallicMatrix",F.baseMetalnessTexture.getTextureMatrix())):F.specularRoughnessTexture&&(O.setTexture("roughnessSampler",F.specularRoughnessTexture),O.setMatrix("roughnessMatrix",F.specularRoughnessTexture.getTextureMatrix())),O.setFloat("metallic",F.baseMetalness),O.setFloat("glossiness",1-F.specularRoughness),F.baseColorTexture!==null&&(O.setTexture("albedoSampler",F.baseColorTexture),O.setMatrix("albedoMatrix",F.baseColorTexture.getTextureMatrix())),F.baseColor!==null&&O.setColor3("albedoColor",F.baseColor)}}if(this._enableIrradiance&&S.environmentTexture){let F=S.environmentTexture,U=S.postProcessRenderPipelineManager.supportedPipelines.find(k=>k.getClassName()==="IBLShadowsRenderPipeline");if(U){let ee=U._getAccumulatedTexture();ee&&(O.setTexture("iblShadowSampler",ee),O.setFloat2("shadowTextureSize",ee.getSize().width,ee.getSize().height))}if(O.setMatrix("reflectionMatrix",F.getReflectionTextureMatrix()),O.setFloat2("vReflectionInfos",F.level*S.iblIntensity,0),O.setTexture("reflectionSampler",F),F.irradianceTexture&&(O.setTexture("irradianceSampler",F.irradianceTexture),F.irradianceTexture._dominantDirection&&O.setVector3("vReflectionDominantDirection",F.irradianceTexture._dominantDirection)),F.sphericalPolynomial){let k=F.sphericalPolynomial;if(k.preScaledHarmonics){let ee=k.preScaledHarmonics;O.setVector3("vSphericalL00",ee.l00),O.setVector3("vSphericalL1_1",ee.l1_1),O.setVector3("vSphericalL10",ee.l10),O.setVector3("vSphericalL11",ee.l11),O.setVector3("vSphericalL2_2",ee.l2_2),O.setVector3("vSphericalL2_1",ee.l2_1),O.setVector3("vSphericalL20",ee.l20),O.setVector3("vSphericalL21",ee.l21),O.setVector3("vSphericalL22",ee.l22)}else O.setFloat3("vSphericalX",k.x.x,k.x.y,k.x.z),O.setFloat3("vSphericalY",k.y.x,k.y.y,k.y.z),O.setFloat3("vSphericalZ",k.z.x,k.z.y,k.z.z),O.setFloat3("vSphericalXX_ZZ",k.xx.x-k.zz.x,k.xx.y-k.zz.y,k.xx.z-k.zz.z),O.setFloat3("vSphericalYY_ZZ",k.yy.x-k.zz.x,k.yy.y-k.zz.y,k.yy.z-k.zz.z),O.setFloat3("vSphericalZZ",k.zz.x,k.zz.y,k.zz.z),O.setFloat3("vSphericalXY",k.xy.x,k.xy.y,k.xy.z),O.setFloat3("vSphericalYZ",k.yz.x,k.yz.y,k.yz.z),O.setFloat3("vSphericalZX",k.zx.x,k.zx.y,k.zx.z)}if(this.generateIrradianceWithScatterMask&&R.getClassName()==="OpenPBRMaterial"){let k=R;O.setFloat("vSubsurfaceWeight",k.subsurfaceWeight),k.subsurfaceWeightTexture&&(O.setTexture("subsurfaceWeightSampler",k.subsurfaceWeightTexture),O.setMatrix("subsurfaceWeightMatrix",k.subsurfaceWeightTexture.getTextureMatrix())),O.setFloat("vTransmissionWeight",k.transmissionWeight),k.transmissionWeightTexture&&(O.setTexture("transmissionWeightSampler",k.transmissionWeightTexture),O.setMatrix("transmissionWeightMatrix",k.transmissionWeightTexture.getTextureMatrix())),O.setFloat("vTransmissionScatterAnisotropy",k.transmissionScatterAnisotropy),O.setFloat("vSubsurfaceScatterAnisotropy",k.subsurfaceScatterAnisotropy)}}if(Fn(O,R,this._scene),x.useBones&&x.computeBonesUsingShaders&&x.skeleton){let F=x.skeleton;if(F.isUsingTextureForMatrices&&O.getUniformIndex("boneTextureInfo")>-1){let U=F.getTransformMatrixTexture(x);O.setTexture("boneSampler",U),O.setFloat2("boneTextureInfo",F._textureWidth,F._textureHeight)}else O.setMatrices("mBones",x.skeleton.getTransformMatrices(x));(this._enableVelocity||this._enableVelocityLinear)&&O.setMatrices("mPreviousBones",this._previousBonesTransformationMatrices[x.uniqueId])}Bn(x,O),x.morphTargetManager&&x.morphTargetManager.isUsingTextureForTargets&&x.morphTargetManager._bind(O),(this._enableVelocity||this._enableVelocityLinear)&&(O.setMatrix("previousWorld",this._previousTransformationMatrices[A.uniqueId].world),O.setMatrix("previousViewProjection",this._previousTransformationMatrices[A.uniqueId].viewProjection)),y&&x.hasThinInstances&&O.setMatrix("world",M),x._processRendering(A,v,O,R.fillMode,I,y,(F,U)=>{F||O.setMatrix("world",U)})}(this._enableVelocity||this._enableVelocityLinear)&&(this._previousTransformationMatrices[A.uniqueId].world=M.clone(),this._previousTransformationMatrices[A.uniqueId].viewProjection=this._scene.getTransformMatrix().clone(),x.skeleton&&this._copyBonesTransformationMatrices(x.skeleton.getTransformMatrices(x),this._previousBonesTransformationMatrices[A.uniqueId]))};this._multiRenderTarget.customIsReadyFunction=(v,x,A)=>{if((A||x===0)&&v.subMeshes)for(let S=0;S{let E;if(this._linkedWithPrePass){if(!this._prePassRenderer.enabled)return;this._scene.getEngine().bindAttachments(this._attachmentsFromPrePass)}if(S.length){for(e.setColorWrite(!1),E=0;E{throw Ze("GeometryBufferRendererSceneComponent")}});var Q5,afe,uL=C(()=>{W();ed();Lg();Q5="openpbrUboDeclaration",afe=`uniform vTangentSpaceParams: vec2f;uniform vLightingIntensity: vec4f;uniform pointSize: f32;uniform vDebugMode: vec2f;uniform renderTargetSize: vec2f;uniform cameraInfo: vec4f;uniform backgroundRefractionMatrix: mat4x4f;uniform vBackgroundRefractionInfos: vec3f;uniform vReflectionInfos: vec2f;uniform reflectionMatrix: mat4x4f;uniform vReflectionMicrosurfaceInfos: vec3f;uniform vReflectionPosition: vec3f;uniform vReflectionSize: vec3f;uniform vReflectionFilteringInfo: vec2f;uniform vReflectionDominantDirection: vec3f;uniform vReflectionColor: vec3f;uniform vSphericalL00: vec3f;uniform vSphericalL1_1: vec3f;uniform vSphericalL10: vec3f;uniform vSphericalL11: vec3f;uniform vSphericalL2_2: vec3f;uniform vSphericalL2_1: vec3f;uniform vSphericalL20: vec3f;uniform vSphericalL21: vec3f;uniform vSphericalL22: vec3f;uniform vSphericalX: vec3f;uniform vSphericalY: vec3f;uniform vSphericalZ: vec3f;uniform vSphericalXX_ZZ: vec3f;uniform vSphericalYY_ZZ: vec3f;uniform vSphericalZZ: vec3f;uniform vSphericalXY: vec3f;uniform vSphericalYZ: vec3f;uniform vSphericalZX: vec3f;uniform vBaseWeight: f32;uniform vBaseColor: vec4f;uniform vBaseDiffuseRoughness: f32;uniform vReflectanceInfo: vec4f;uniform vSpecularColor: vec4f;uniform vSpecularAnisotropy: vec3f;uniform vTransmissionWeight : f32;uniform vTransmissionColor : vec3f;uniform vTransmissionDepth : f32;uniform vTransmissionScatter : vec3f;uniform vTransmissionScatterAnisotropy : f32;uniform vTransmissionDispersionScale : f32;uniform vTransmissionDispersionAbbeNumber : f32;uniform vSubsurfaceWeight: f32;uniform vSubsurfaceColor: vec3f;uniform vSubsurfaceRadius: f32;uniform vSubsurfaceRadiusScale: vec3f;uniform vSubsurfaceScatterAnisotropy: f32;uniform vCoatWeight: f32;uniform vCoatColor: vec3f;uniform vCoatRoughness: f32;uniform vCoatRoughnessAnisotropy: f32;uniform vCoatIor: f32;uniform vCoatDarkening : f32;uniform vFuzzWeight: f32;uniform vFuzzColor: vec3f;uniform vFuzzRoughness: f32;uniform vGeometryThinWalled: f32;uniform vGeometryCoatTangent: vec2f;uniform vGeometryThickness: f32;uniform vEmissionColor: vec3f;uniform vThinFilmWeight: f32;uniform vThinFilmThickness: vec2f;uniform vThinFilmIor: f32;uniform vBaseWeightInfos: vec2f;uniform baseWeightMatrix: mat4x4f;uniform vBaseColorInfos: vec2f;uniform baseColorMatrix: mat4x4f;uniform vBaseDiffuseRoughnessInfos: vec2f;uniform baseDiffuseRoughnessMatrix: mat4x4f;uniform vBaseMetalnessInfos: vec2f;uniform baseMetalnessMatrix: mat4x4f;uniform vSpecularWeightInfos: vec2f;uniform specularWeightMatrix: mat4x4f;uniform vSpecularColorInfos: vec2f;uniform specularColorMatrix: mat4x4f;uniform vSpecularRoughnessInfos: vec2f;uniform specularRoughnessMatrix: mat4x4f;uniform vSpecularRoughnessAnisotropyInfos: vec2f;uniform specularRoughnessAnisotropyMatrix: mat4x4f;uniform vTransmissionWeightInfos : vec2f;uniform transmissionWeightMatrix : mat4x4f;uniform vTransmissionColorInfos : vec2f;uniform transmissionColorMatrix : mat4x4f;uniform vTransmissionDepthInfos : vec2f;uniform transmissionDepthMatrix : mat4x4f;uniform vTransmissionScatterInfos : vec2f;uniform transmissionScatterMatrix : mat4x4f;uniform vTransmissionDispersionScaleInfos : vec2f;uniform transmissionDispersionScaleMatrix : mat4x4f;uniform vSubsurfaceWeightInfos: vec2f;uniform subsurfaceWeightMatrix: mat4x4f;uniform vSubsurfaceColorInfos: vec2f;uniform subsurfaceColorMatrix: mat4x4f;uniform vSubsurfaceRadiusScaleInfos: vec2f;uniform subsurfaceRadiusScaleMatrix: mat4x4f;uniform vCoatWeightInfos: vec2f;uniform coatWeightMatrix: mat4x4f;uniform vCoatColorInfos: vec2f;uniform coatColorMatrix: mat4x4f;uniform vCoatRoughnessInfos: vec2f;uniform coatRoughnessMatrix: mat4x4f;uniform vCoatRoughnessAnisotropyInfos: vec2f;uniform coatRoughnessAnisotropyMatrix: mat4x4f;uniform vCoatDarkeningInfos : vec2f;uniform coatDarkeningMatrix : mat4x4f;uniform vFuzzWeightInfos: vec2f;uniform fuzzWeightMatrix: mat4x4f;uniform vFuzzColorInfos: vec2f;uniform fuzzColorMatrix: mat4x4f;uniform vFuzzRoughnessInfos: vec2f;uniform fuzzRoughnessMatrix: mat4x4f;uniform vGeometryNormalInfos: vec2f;uniform geometryNormalMatrix: mat4x4f;uniform vGeometryTangentInfos: vec2f;uniform geometryTangentMatrix: mat4x4f;uniform vGeometryCoatNormalInfos: vec2f;uniform geometryCoatNormalMatrix: mat4x4f;uniform vGeometryCoatTangentInfos: vec2f;uniform geometryCoatTangentMatrix: mat4x4f;uniform vGeometryOpacityInfos: vec2f;uniform geometryOpacityMatrix: mat4x4f;uniform vGeometryThicknessInfos: vec2f;uniform geometryThicknessMatrix: mat4x4f;uniform vEmissionInfos: vec2f;uniform emissionMatrix: mat4x4f;uniform vThinFilmWeightInfos: vec2f;uniform thinFilmWeightMatrix: mat4x4f;uniform vThinFilmThicknessInfos: vec2f;uniform thinFilmThicknessMatrix: mat4x4f;uniform vAmbientOcclusionInfos: vec2f;uniform ambientOcclusionMatrix: mat4x4f; +`;T.ShadersStoreWGSL[hL]||(T.ShadersStoreWGSL[hL]=Y5);sfe={name:hL,shader:Y5}});var q5,dL,ns,Z5=C(()=>{Ge();ki();Fr();u5();zt();hn();Vn();iL();nL();Pa();ol();Un();jD();q5=["diffuseSampler","bumpSampler","reflectivitySampler","albedoSampler","morphTargets","boneSampler","transmissionWeightSampler","subsurfaceWeightSampler","iblShadowSampler"],dL=["world","mBones","viewProjection","diffuseMatrix","view","previousWorld","previousViewProjection","mPreviousBones","bumpMatrix","reflectivityMatrix","albedoMatrix","reflectivityColor","albedoColor","reflectionMatrix","vTransmissionWeight","vSubsurfaceWeight","vEyePosition","vTransmissionScatterAnisotropy","vSubsurfaceScatterAnisotropy","shadowTextureSize","metallic","glossiness","vTangentSpaceParams","vBumpInfos","morphTargetInfluences","morphTargetCount","morphTargetTextureInfo","morphTargetTextureIndices","boneTextureInfo"];Rf(dL,q5,!0);wn(dL);ns=class n{get normalsAreUnsigned(){return this._normalsAreUnsigned}_linkPrePassRenderer(e){this._linkedWithPrePass=!0,this._prePassRenderer=e,this._multiRenderTarget&&(this._multiRenderTarget.onClearObservable.clear(),this._multiRenderTarget.onClearObservable.add(()=>{}))}_unlinkPrePassRenderer(){this._linkedWithPrePass=!1,this._createRenderTargets()}_resetLayout(){this._enableDepth=!0,this._enableNormal=!0,this._enablePosition=!1,this._enableReflectivity=!1,this._enableVelocity=!1,this._enableVelocityLinear=!1,this._enableScreenspaceDepth=!1,this._enableIrradiance=!1,this._attachmentsFromPrePass=[]}_forceTextureType(e,t){e===n.POSITION_TEXTURE_TYPE?(this._positionIndex=t,this._enablePosition=!0):e===n.VELOCITY_TEXTURE_TYPE?(this._velocityIndex=t,this._enableVelocity=!0):e===n.VELOCITY_LINEAR_TEXTURE_TYPE?(this._velocityLinearIndex=t,this._enableVelocityLinear=!0):e===n.REFLECTIVITY_TEXTURE_TYPE?(this._reflectivityIndex=t,this._enableReflectivity=!0):e===n.DEPTH_TEXTURE_TYPE?(this._depthIndex=t,this._enableDepth=!0):e===n.NORMAL_TEXTURE_TYPE?(this._normalIndex=t,this._enableNormal=!0):e===n.SCREENSPACE_DEPTH_TEXTURE_TYPE?(this._screenspaceDepthIndex=t,this._enableScreenspaceDepth=!0):e===n.IRRADIANCE_TEXTURE_TYPE&&(this._irradianceIndex=t,this._enableIrradiance=!0)}_setAttachments(e){this._attachmentsFromPrePass=e}_linkInternalTexture(e){this._multiRenderTarget.setInternalTexture(e,0,!1)}get renderList(){return this._multiRenderTarget.renderList}set renderList(e){this._multiRenderTarget.renderList=e}get isSupported(){return this._multiRenderTarget.isSupported}getTextureIndex(e){switch(e){case n.POSITION_TEXTURE_TYPE:return this._positionIndex;case n.VELOCITY_TEXTURE_TYPE:return this._velocityIndex;case n.VELOCITY_LINEAR_TEXTURE_TYPE:return this._velocityLinearIndex;case n.REFLECTIVITY_TEXTURE_TYPE:return this._reflectivityIndex;case n.DEPTH_TEXTURE_TYPE:return this._depthIndex;case n.NORMAL_TEXTURE_TYPE:return this._normalIndex;case n.SCREENSPACE_DEPTH_TEXTURE_TYPE:return this._screenspaceDepthIndex;case n.IRRADIANCE_TEXTURE_TYPE:return this._irradianceIndex;default:return-1}}get enableDepth(){return this._enableDepth}set enableDepth(e){this._enableDepth=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableNormal(){return this._enableNormal}set enableNormal(e){this._enableNormal=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enablePosition(){return this._enablePosition}set enablePosition(e){this._enablePosition=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableVelocity(){return this._enableVelocity}set enableVelocity(e){this._enableVelocity=e,e||(this._previousTransformationMatrices={}),this._linkedWithPrePass||(this.dispose(),this._createRenderTargets()),this._scene.needsPreviousWorldMatrices=e}get enableVelocityLinear(){return this._enableVelocityLinear}set enableVelocityLinear(e){this._enableVelocityLinear=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableReflectivity(){return this._enableReflectivity}set enableReflectivity(e){this._enableReflectivity=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableScreenspaceDepth(){return this._enableScreenspaceDepth}set enableScreenspaceDepth(e){this._enableScreenspaceDepth=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableIrradiance(){return this._enableIrradiance}set enableIrradiance(e){this._enableIrradiance=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get scene(){return this._scene}get ratio(){return typeof this._ratioOrDimensions=="object"?1:this._ratioOrDimensions}get shaderLanguage(){return this._shaderLanguage}constructor(e,t=1,i=15,r){this._previousTransformationMatrices={},this._previousBonesTransformationMatrices={},this.excludedSkinnedMeshesFromVelocity=[],this.renderTransparentMeshes=!0,this.generateNormalsInWorldSpace=!1,this._normalsAreUnsigned=!1,this._resizeObserver=null,this._enableDepth=!0,this._enableNormal=!0,this._enablePosition=!1,this._enableVelocity=!1,this._enableVelocityLinear=!1,this._enableReflectivity=!1,this._enableScreenspaceDepth=!1,this._enableIrradiance=!1,this._clearColor=new lt(0,0,0,0),this._clearDepthColor=new lt(0,0,0,1),this._positionIndex=-1,this._velocityIndex=-1,this._velocityLinearIndex=-1,this._reflectivityIndex=-1,this._depthIndex=-1,this._normalIndex=-1,this._screenspaceDepthIndex=-1,this._irradianceIndex=-1,this._linkedWithPrePass=!1,this.generateIrradianceWithScatterMask=!1,this.useSpecificClearForDepthTexture=!1,this._shaderLanguage=0,this._shadersLoaded=!1,this._scene=e,this._ratioOrDimensions=t,this._useUbo=e.getEngine().supportsUniformBuffers,this._depthFormat=i,this._textureTypesAndFormats=r||{},this._initShaderSourceAsync(),n._SceneComponentInitialization(this._scene),this._createRenderTargets()}async _initShaderSourceAsync(){this._scene.getEngine().isWebGPU&&!n.ForceGLSL?(this._shaderLanguage=1,await Promise.all([Promise.resolve().then(()=>(B5(),F5)),Promise.resolve().then(()=>(j5(),K5))])):await Promise.all([Promise.resolve().then(()=>(nL(),O5)),Promise.resolve().then(()=>(iL(),I5))]),this._shadersLoaded=!0}isReady(e,t){if(!this._shadersLoaded)return!1;let i=e.getMaterial();if(i&&i.disableDepthWrite)return!1;let r=[],s=[L.PositionKind],a=e.getMesh();a.isVerticesDataPresent(L.NormalKind)&&(r.push("#define HAS_NORMAL_ATTRIBUTE"),s.push(L.NormalKind));let l=!1,c=!1,f=!1;if(i){let _=!1;if(i.needAlphaTestingForMesh(a)&&i.getAlphaTestTexture()&&(r.push("#define ALPHATEST"),r.push(`#define ALPHATEST_UV${i.getAlphaTestTexture().coordinatesIndex+1}`),_=!0),(i.bumpTexture||i.normalTexture||i.geometryNormalTexture)&&ce.BumpTextureEnabled){let g=i.bumpTexture||i.normalTexture||i.geometryNormalTexture;r.push("#define BUMP"),r.push(`#define BUMP_UV${g.coordinatesIndex+1}`),_=!0}if(this._enableReflectivity){let g=!1;if(i.getClassName()==="PBRMetallicRoughnessMaterial")i.metallicRoughnessTexture&&(r.push("#define ORMTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.metallicRoughnessTexture.coordinatesIndex+1}`),r.push("#define METALLICWORKFLOW"),_=!0,g=!0),i.metallic!=null&&(r.push("#define METALLIC"),r.push("#define METALLICWORKFLOW"),g=!0),i.roughness!=null&&(r.push("#define ROUGHNESS"),r.push("#define METALLICWORKFLOW"),g=!0),g&&(i.baseTexture&&(r.push("#define ALBEDOTEXTURE"),r.push(`#define ALBEDO_UV${i.baseTexture.coordinatesIndex+1}`),i.baseTexture.gammaSpace&&r.push("#define GAMMAALBEDO"),_=!0),i.baseColor&&r.push("#define ALBEDOCOLOR"));else if(i.getClassName()==="PBRSpecularGlossinessMaterial")i.specularGlossinessTexture?(r.push("#define SPECULARGLOSSINESSTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.specularGlossinessTexture.coordinatesIndex+1}`),_=!0,i.specularGlossinessTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE")):i.specularColor&&r.push("#define REFLECTIVITYCOLOR"),i.glossiness!=null&&r.push("#define GLOSSINESS");else if(i.getClassName()==="PBRMaterial")i.metallicTexture&&(r.push("#define ORMTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.metallicTexture.coordinatesIndex+1}`),r.push("#define METALLICWORKFLOW"),_=!0,g=!0),i.metallic!=null&&(r.push("#define METALLIC"),r.push("#define METALLICWORKFLOW"),g=!0),i.roughness!=null&&(r.push("#define ROUGHNESS"),r.push("#define METALLICWORKFLOW"),g=!0),g?(i.albedoTexture&&(r.push("#define ALBEDOTEXTURE"),r.push(`#define ALBEDO_UV${i.albedoTexture.coordinatesIndex+1}`),i.albedoTexture.gammaSpace&&r.push("#define GAMMAALBEDO"),_=!0),i.albedoColor&&r.push("#define ALBEDOCOLOR")):(i.reflectivityTexture?(r.push("#define SPECULARGLOSSINESSTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.reflectivityTexture.coordinatesIndex+1}`),i.reflectivityTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE"),_=!0):i.reflectivityColor&&r.push("#define REFLECTIVITYCOLOR"),i.microSurface!=null&&r.push("#define GLOSSINESS"));else if(i.getClassName()==="StandardMaterial")i.specularTexture&&(r.push("#define REFLECTIVITYTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.specularTexture.coordinatesIndex+1}`),i.specularTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE"),_=!0),i.specularColor&&r.push("#define REFLECTIVITYCOLOR");else if(i.getClassName()==="OpenPBRMaterial"){let v=i;r.push("#define METALLIC"),r.push("#define ROUGHNESS"),v._useRoughnessFromMetallicTextureGreen&&v.baseMetalnessTexture?(r.push("#define ORMTEXTURE"),r.push(`#define REFLECTIVITY_UV${v.baseMetalnessTexture.coordinatesIndex+1}`),_=!0):v.baseMetalnessTexture?(r.push("#define METALLIC_TEXTURE"),r.push(`#define METALLIC_UV${v.baseMetalnessTexture.coordinatesIndex+1}`),_=!0):v.specularRoughnessTexture&&(r.push("#define ROUGHNESS_TEXTURE"),r.push(`#define ROUGHNESS_UV${v.specularRoughnessTexture.coordinatesIndex+1}`),_=!0),v.baseColorTexture&&(r.push("#define ALBEDOTEXTURE"),r.push(`#define ALBEDO_UV${v.baseColorTexture.coordinatesIndex+1}`),v.baseColorTexture.gammaSpace&&r.push("#define GAMMAALBEDO"),_=!0),v.baseColor&&r.push("#define ALBEDOCOLOR")}}if(this._enableIrradiance&&this.generateIrradianceWithScatterMask&&(r.push("#define IRRADIANCE_SCATTER_MASK"),i.getClassName()==="OpenPBRMaterial")){let g=i;g.subsurfaceWeight>0&&g.subsurfaceWeightTexture&&(r.push("#define SUBSURFACE_WEIGHT"),r.push(`#define SUBSURFACEWEIGHT_UV${g.subsurfaceWeightTexture.coordinatesIndex+1}`),_=!0),g.transmissionWeight>0&&g.transmissionWeightTexture&&(r.push("#define TRANSMISSION_WEIGHT"),r.push(`#define TRANSMISSIONWEIGHT_UV${g.transmissionWeightTexture.coordinatesIndex+1}`),_=!0)}_&&(r.push("#define NEED_UV"),a.isVerticesDataPresent(L.UVKind)&&(s.push(L.UVKind),r.push("#define UV1"),l=!0),a.isVerticesDataPresent(L.UV2Kind)&&(s.push(L.UV2Kind),r.push("#define UV2"),c=!0))}if(this._enableDepth&&(r.push("#define DEPTH"),r.push("#define DEPTH_INDEX "+this._depthIndex)),this._enableNormal&&(r.push("#define NORMAL"),r.push("#define NORMAL_INDEX "+this._normalIndex)),this._enablePosition&&(r.push("#define POSITION"),r.push("#define POSITION_INDEX "+this._positionIndex)),this._enableVelocity&&(r.push("#define VELOCITY"),r.push("#define VELOCITY_INDEX "+this._velocityIndex),this.excludedSkinnedMeshesFromVelocity.indexOf(a)===-1&&r.push("#define BONES_VELOCITY_ENABLED")),this._enableVelocityLinear&&(r.push("#define VELOCITY_LINEAR"),r.push("#define VELOCITY_LINEAR_INDEX "+this._velocityLinearIndex),this.excludedSkinnedMeshesFromVelocity.indexOf(a)===-1&&r.push("#define BONES_VELOCITY_ENABLED")),this._enableReflectivity&&(r.push("#define REFLECTIVITY"),r.push("#define REFLECTIVITY_INDEX "+this._reflectivityIndex)),this._enableScreenspaceDepth&&this._screenspaceDepthIndex!==-1&&(r.push("#define SCREENSPACE_DEPTH_INDEX "+this._screenspaceDepthIndex),r.push("#define SCREENSPACE_DEPTH")),this._enableIrradiance&&this._irradianceIndex!==-1){r.push("#define IRRADIANCE_INDEX "+this._irradianceIndex),r.push("#define IRRADIANCE");let _=this._scene;if(_.environmentTexture){let g={},v=!1,x=0;(i.getClassName()==="OpenPBRMaterial"||i.getClassName()==="StandardMaterial"||i.getClassName()==="PBRMetallicRoughnessMaterial"||i.getClassName()==="PBRSpecularGlossinessMaterial"||i.getClassName()==="PBRMaterial")&&(v=!!i.realtimeFiltering,x=i.realtimeFilteringQuality||0),xf(_,_.environmentTexture,g,v,x,!0);for(let S in g)g[S]&&r.push("#define "+S);g.USEIRRADIANCEMAP||r.push("#define SPHERICAL_HARMONICS");let A=_.postProcessRenderPipelineManager.supportedPipelines.find(S=>S.getClassName()==="IBLShadowsRenderPipeline");if(A){let S=A;S._getAccumulatedTexture()&&(r.push("#define IBL_SHADOW_TEXTURE"),S.coloredShadows&&r.push("#define COLORED_IBL_SHADOWS"))}}}this.generateNormalsInWorldSpace&&r.push("#define NORMAL_WORLDSPACE"),this._normalsAreUnsigned&&r.push("#define ENCODE_NORMAL"),a.useBones&&a.computeBonesUsingShaders&&a.skeleton?(s.push(L.MatricesIndicesKind),s.push(L.MatricesWeightsKind),a.numBoneInfluencers>4&&(s.push(L.MatricesIndicesExtraKind),s.push(L.MatricesWeightsExtraKind)),r.push("#define NUM_BONE_INFLUENCERS "+a.numBoneInfluencers),r.push("#define BONETEXTURE "+a.skeleton.isUsingTextureForMatrices),r.push("#define BonesPerMesh "+(a.skeleton.bones.length+1))):(r.push("#define NUM_BONE_INFLUENCERS 0"),r.push("#define BONETEXTURE false"),r.push("#define BonesPerMesh 0"));let h=a.morphTargetManager?ll(a.morphTargetManager,r,s,a,!0,!0,!1,l,c,f):0;t&&(r.push("#define INSTANCES"),mo(s,this._enableVelocity||this._enableVelocityLinear),e.getRenderingMesh().hasThinInstances&&r.push("#define THIN_INSTANCES")),this._linkedWithPrePass?r.push("#define SCENE_MRT_COUNT "+this._attachmentsFromPrePass.length):r.push("#define SCENE_MRT_COUNT "+this._multiRenderTarget.textures.length),al(i,this._scene,r);let d=this._scene.getEngine(),u=e._getDrawWrapper(void 0,!0),m=u.defines,p=r.join(` +`);return m!==p&&u.setEffect(d.createEffect("geometry",{attributes:s,uniformsNames:dL,samplers:q5,defines:p,onCompiled:null,fallbacks:null,onError:null,uniformBuffersNames:["Scene"],indexParameters:{buffersCount:this._multiRenderTarget.textures.length-1,maxSimultaneousMorphTargets:h},shaderLanguage:this.shaderLanguage},d),p),u.effect.isReady()}getGBuffer(){return this._multiRenderTarget}get samples(){return this._multiRenderTarget.samples}set samples(e){this._multiRenderTarget.samples=e}dispose(){var e,t;this._resizeObserver&&(this._scene.getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null),(e=this._multiRenderTarget)!=null&&e.renderTarget&&this.scene.getEngine()._currentRenderTarget===this._multiRenderTarget.renderTarget&&this.scene.getEngine().unBindFramebuffer((t=this._multiRenderTarget)==null?void 0:t.renderTarget),this.getGBuffer().dispose()}_assignRenderTargetIndices(){let e=[],t=[],i=0;return this._enableDepth&&(this._depthIndex=i,i++,e.push("gBuffer_Depth"),t.push(this._textureTypesAndFormats[n.DEPTH_TEXTURE_TYPE])),this._enableNormal&&(this._normalIndex=i,i++,e.push("gBuffer_Normal"),t.push(this._textureTypesAndFormats[n.NORMAL_TEXTURE_TYPE])),this._enablePosition&&(this._positionIndex=i,i++,e.push("gBuffer_Position"),t.push(this._textureTypesAndFormats[n.POSITION_TEXTURE_TYPE])),this._enableVelocity&&(this._velocityIndex=i,i++,e.push("gBuffer_Velocity"),t.push(this._textureTypesAndFormats[n.VELOCITY_TEXTURE_TYPE])),this._enableVelocityLinear&&(this._velocityLinearIndex=i,i++,e.push("gBuffer_VelocityLinear"),t.push(this._textureTypesAndFormats[n.VELOCITY_LINEAR_TEXTURE_TYPE])),this._enableReflectivity&&(this._reflectivityIndex=i,i++,e.push("gBuffer_Reflectivity"),t.push(this._textureTypesAndFormats[n.REFLECTIVITY_TEXTURE_TYPE])),this._enableScreenspaceDepth&&(this._screenspaceDepthIndex=i,i++,e.push("gBuffer_ScreenspaceDepth"),t.push(this._textureTypesAndFormats[n.SCREENSPACE_DEPTH_TEXTURE_TYPE])),this._enableIrradiance&&(this._irradianceIndex=i,i++,e.push("gBuffer_Irradiance"),t.push(this._textureTypesAndFormats[n.IRRADIANCE_TEXTURE_TYPE])),[i,e,t]}_createRenderTargets(){var g;let e=this._scene.getEngine(),[t,i,r]=this._assignRenderTargetIndices(),s=0;e._caps.textureFloat&&e._caps.textureFloatLinearFiltering?s=1:e._caps.textureHalfFloat&&e._caps.textureHalfFloatLinearFiltering&&(s=2);let a=this._ratioOrDimensions.width!==void 0?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions},o=[],l=[],c=[];for(let v of r)v?(o.push(v.textureType),l.push(v.textureFormat),c.push((g=v.samplingMode)!=null?g:2)):(o.push(s),l.push(5),c.push(2));if(this._normalsAreUnsigned=o[n.NORMAL_TEXTURE_TYPE]===11||o[n.NORMAL_TEXTURE_TYPE]===13,this._multiRenderTarget=new TR("gBuffer",a,t,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,types:o,formats:l,samplingModes:c,depthTextureFormat:this._depthFormat},i.concat("gBuffer_DepthBuffer")),!this.isSupported)return;this._multiRenderTarget.wrapU=ge.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=ge.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null;let f=[!0],h=[!1],d=[!0];for(let v=1;v{v.bindAttachments(this.useSpecificClearForDepthTexture?m:u),v.clear(this._clearColor,!0,!0,!0),this.useSpecificClearForDepthTexture&&(v.bindAttachments(p),v.clear(this._clearDepthColor,!0,!0,!0)),v.bindAttachments(u)}),this._resizeObserver=e.onResizeObservable.add(()=>{if(this._multiRenderTarget){let v=this._ratioOrDimensions.width!==void 0?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions};this._multiRenderTarget.resize(v)}});let _=v=>{let x=v.getRenderingMesh(),A=v.getEffectiveMesh(),S=this._scene,E=S.getEngine(),R=v.getMaterial();if(!R)return;if(A._internalAbstractMeshDataInfo._isActiveIntermediate=!1,(this._enableVelocity||this._enableVelocityLinear)&&!this._previousTransformationMatrices[A.uniqueId]&&(this._previousTransformationMatrices[A.uniqueId]={world:K.Identity(),viewProjection:S.getTransformMatrix()},x.skeleton)){let D=x.skeleton.getTransformMatrices(x);this._previousBonesTransformationMatrices[x.uniqueId]=this._copyBonesTransformationMatrices(D,new Float32Array(D.length))}let I=x._getInstancesRenderList(v._id,!!v.getReplacementMesh());if(I.mustReturn)return;let y=E.getCaps().instancedArrays&&(I.visibleInstances[v._id]!==null||x.hasThinInstances),M=A.getWorldMatrix();if(this.isReady(v,y)){let D=v._getDrawWrapper();if(!D)return;let O=D.effect;E.enableEffect(D),y||x._bind(v,O,R.fillMode),this._useUbo?(Af(O,this._scene.getSceneUniformBuffer()),this._scene.finalizeSceneUbo()):(O.setMatrix("viewProjection",S.getTransformMatrix()),O.setMatrix("view",S.getViewMatrix()),this._scene.bindEyePosition(O,"vEyePosition"));let V;if(!x._instanceDataStorage.isFrozen&&(R.backFaceCulling||R.sideOrientation!==null)){let F=A._getWorldMatrixDeterminant();V=R._getEffectiveOrientation(x),F<0&&(V=V===Ee.ClockWiseSideOrientation?Ee.CounterClockWiseSideOrientation:Ee.ClockWiseSideOrientation)}else V=x._effectiveSideOrientation;if(R._preBind(D,V),R.needAlphaTestingForMesh(A)){let F=R.getAlphaTestTexture();F&&(O.setTexture("diffuseSampler",F),O.setMatrix("diffuseMatrix",F.getTextureMatrix()))}if((R.bumpTexture||R.normalTexture||R.geometryNormalTexture)&&S.getEngine().getCaps().standardDerivatives&&ce.BumpTextureEnabled){let F=R.bumpTexture||R.normalTexture||R.geometryNormalTexture;O.setFloat3("vBumpInfos",F.coordinatesIndex,1/F.level,R.parallaxScaleBias),O.setMatrix("bumpMatrix",F.getTextureMatrix()),O.setTexture("bumpSampler",F),O.setFloat2("vTangentSpaceParams",R.invertNormalMapX?-1:1,R.invertNormalMapY?-1:1)}if(this._enableReflectivity){if(R.getClassName()==="PBRMetallicRoughnessMaterial")R.metallicRoughnessTexture!==null&&(O.setTexture("reflectivitySampler",R.metallicRoughnessTexture),O.setMatrix("reflectivityMatrix",R.metallicRoughnessTexture.getTextureMatrix())),R.metallic!==null&&O.setFloat("metallic",R.metallic),R.roughness!==null&&O.setFloat("glossiness",1-R.roughness),R.baseTexture!==null&&(O.setTexture("albedoSampler",R.baseTexture),O.setMatrix("albedoMatrix",R.baseTexture.getTextureMatrix())),R.baseColor!==null&&O.setColor3("albedoColor",R.baseColor);else if(R.getClassName()==="PBRSpecularGlossinessMaterial")R.specularGlossinessTexture!==null?(O.setTexture("reflectivitySampler",R.specularGlossinessTexture),O.setMatrix("reflectivityMatrix",R.specularGlossinessTexture.getTextureMatrix())):R.specularColor!==null&&O.setColor3("reflectivityColor",R.specularColor),R.glossiness!==null&&O.setFloat("glossiness",R.glossiness);else if(R.getClassName()==="PBRMaterial")R.metallicTexture!==null&&(O.setTexture("reflectivitySampler",R.metallicTexture),O.setMatrix("reflectivityMatrix",R.metallicTexture.getTextureMatrix())),R.metallic!==null&&O.setFloat("metallic",R.metallic),R.roughness!==null&&O.setFloat("glossiness",1-R.roughness),R.roughness!==null||R.metallic!==null||R.metallicTexture!==null?(R.albedoTexture!==null&&(O.setTexture("albedoSampler",R.albedoTexture),O.setMatrix("albedoMatrix",R.albedoTexture.getTextureMatrix())),R.albedoColor!==null&&O.setColor3("albedoColor",R.albedoColor)):(R.reflectivityTexture!==null?(O.setTexture("reflectivitySampler",R.reflectivityTexture),O.setMatrix("reflectivityMatrix",R.reflectivityTexture.getTextureMatrix())):R.reflectivityColor!==null&&O.setColor3("reflectivityColor",R.reflectivityColor),R.microSurface!==null&&O.setFloat("glossiness",R.microSurface));else if(R.getClassName()==="StandardMaterial")R.specularTexture!==null&&(O.setTexture("reflectivitySampler",R.specularTexture),O.setMatrix("reflectivityMatrix",R.specularTexture.getTextureMatrix())),R.specularColor!==null&&O.setColor3("reflectivityColor",R.specularColor);else if(R.getClassName()==="OpenPBRMaterial"){let F=R;F._useRoughnessFromMetallicTextureGreen&&F.baseMetalnessTexture?(O.setTexture("reflectivitySampler",F.baseMetalnessTexture),O.setMatrix("reflectivityMatrix",F.baseMetalnessTexture.getTextureMatrix())):F.baseMetalnessTexture?(O.setTexture("metallicSampler",F.baseMetalnessTexture),O.setMatrix("metallicMatrix",F.baseMetalnessTexture.getTextureMatrix())):F.specularRoughnessTexture&&(O.setTexture("roughnessSampler",F.specularRoughnessTexture),O.setMatrix("roughnessMatrix",F.specularRoughnessTexture.getTextureMatrix())),O.setFloat("metallic",F.baseMetalness),O.setFloat("glossiness",1-F.specularRoughness),F.baseColorTexture!==null&&(O.setTexture("albedoSampler",F.baseColorTexture),O.setMatrix("albedoMatrix",F.baseColorTexture.getTextureMatrix())),F.baseColor!==null&&O.setColor3("albedoColor",F.baseColor)}}if(this._enableIrradiance&&S.environmentTexture){let F=S.environmentTexture,U=S.postProcessRenderPipelineManager.supportedPipelines.find(G=>G.getClassName()==="IBLShadowsRenderPipeline");if(U){let ee=U._getAccumulatedTexture();ee&&(O.setTexture("iblShadowSampler",ee),O.setFloat2("shadowTextureSize",ee.getSize().width,ee.getSize().height))}if(O.setMatrix("reflectionMatrix",F.getReflectionTextureMatrix()),O.setFloat2("vReflectionInfos",F.level*S.iblIntensity,0),O.setTexture("reflectionSampler",F),F.irradianceTexture&&(O.setTexture("irradianceSampler",F.irradianceTexture),F.irradianceTexture._dominantDirection&&O.setVector3("vReflectionDominantDirection",F.irradianceTexture._dominantDirection)),F.sphericalPolynomial){let G=F.sphericalPolynomial;if(G.preScaledHarmonics){let ee=G.preScaledHarmonics;O.setVector3("vSphericalL00",ee.l00),O.setVector3("vSphericalL1_1",ee.l1_1),O.setVector3("vSphericalL10",ee.l10),O.setVector3("vSphericalL11",ee.l11),O.setVector3("vSphericalL2_2",ee.l2_2),O.setVector3("vSphericalL2_1",ee.l2_1),O.setVector3("vSphericalL20",ee.l20),O.setVector3("vSphericalL21",ee.l21),O.setVector3("vSphericalL22",ee.l22)}else O.setFloat3("vSphericalX",G.x.x,G.x.y,G.x.z),O.setFloat3("vSphericalY",G.y.x,G.y.y,G.y.z),O.setFloat3("vSphericalZ",G.z.x,G.z.y,G.z.z),O.setFloat3("vSphericalXX_ZZ",G.xx.x-G.zz.x,G.xx.y-G.zz.y,G.xx.z-G.zz.z),O.setFloat3("vSphericalYY_ZZ",G.yy.x-G.zz.x,G.yy.y-G.zz.y,G.yy.z-G.zz.z),O.setFloat3("vSphericalZZ",G.zz.x,G.zz.y,G.zz.z),O.setFloat3("vSphericalXY",G.xy.x,G.xy.y,G.xy.z),O.setFloat3("vSphericalYZ",G.yz.x,G.yz.y,G.yz.z),O.setFloat3("vSphericalZX",G.zx.x,G.zx.y,G.zx.z)}if(this.generateIrradianceWithScatterMask&&R.getClassName()==="OpenPBRMaterial"){let G=R;O.setFloat("vSubsurfaceWeight",G.subsurfaceWeight),G.subsurfaceWeightTexture&&(O.setTexture("subsurfaceWeightSampler",G.subsurfaceWeightTexture),O.setMatrix("subsurfaceWeightMatrix",G.subsurfaceWeightTexture.getTextureMatrix())),O.setFloat("vTransmissionWeight",G.transmissionWeight),G.transmissionWeightTexture&&(O.setTexture("transmissionWeightSampler",G.transmissionWeightTexture),O.setMatrix("transmissionWeightMatrix",G.transmissionWeightTexture.getTextureMatrix())),O.setFloat("vTransmissionScatterAnisotropy",G.transmissionScatterAnisotropy),O.setFloat("vSubsurfaceScatterAnisotropy",G.subsurfaceScatterAnisotropy)}}if(Fn(O,R,this._scene),x.useBones&&x.computeBonesUsingShaders&&x.skeleton){let F=x.skeleton;if(F.isUsingTextureForMatrices&&O.getUniformIndex("boneTextureInfo")>-1){let U=F.getTransformMatrixTexture(x);O.setTexture("boneSampler",U),O.setFloat2("boneTextureInfo",F._textureWidth,F._textureHeight)}else O.setMatrices("mBones",x.skeleton.getTransformMatrices(x));(this._enableVelocity||this._enableVelocityLinear)&&O.setMatrices("mPreviousBones",this._previousBonesTransformationMatrices[x.uniqueId])}Bn(x,O),x.morphTargetManager&&x.morphTargetManager.isUsingTextureForTargets&&x.morphTargetManager._bind(O),(this._enableVelocity||this._enableVelocityLinear)&&(O.setMatrix("previousWorld",this._previousTransformationMatrices[A.uniqueId].world),O.setMatrix("previousViewProjection",this._previousTransformationMatrices[A.uniqueId].viewProjection)),y&&x.hasThinInstances&&O.setMatrix("world",M),x._processRendering(A,v,O,R.fillMode,I,y,(F,U)=>{F||O.setMatrix("world",U)})}(this._enableVelocity||this._enableVelocityLinear)&&(this._previousTransformationMatrices[A.uniqueId].world=M.clone(),this._previousTransformationMatrices[A.uniqueId].viewProjection=this._scene.getTransformMatrix().clone(),x.skeleton&&this._copyBonesTransformationMatrices(x.skeleton.getTransformMatrices(x),this._previousBonesTransformationMatrices[A.uniqueId]))};this._multiRenderTarget.customIsReadyFunction=(v,x,A)=>{if((A||x===0)&&v.subMeshes)for(let S=0;S{let E;if(this._linkedWithPrePass){if(!this._prePassRenderer.enabled)return;this._scene.getEngine().bindAttachments(this._attachmentsFromPrePass)}if(S.length){for(e.setColorWrite(!1),E=0;E{throw qe("GeometryBufferRendererSceneComponent")}});var Q5,afe,uL=C(()=>{k();ed();Lg();Q5="openpbrUboDeclaration",afe=`uniform vTangentSpaceParams: vec2f;uniform vLightingIntensity: vec4f;uniform pointSize: f32;uniform vDebugMode: vec2f;uniform renderTargetSize: vec2f;uniform cameraInfo: vec4f;uniform backgroundRefractionMatrix: mat4x4f;uniform vBackgroundRefractionInfos: vec3f;uniform vReflectionInfos: vec2f;uniform reflectionMatrix: mat4x4f;uniform vReflectionMicrosurfaceInfos: vec3f;uniform vReflectionPosition: vec3f;uniform vReflectionSize: vec3f;uniform vReflectionFilteringInfo: vec2f;uniform vReflectionDominantDirection: vec3f;uniform vReflectionColor: vec3f;uniform vSphericalL00: vec3f;uniform vSphericalL1_1: vec3f;uniform vSphericalL10: vec3f;uniform vSphericalL11: vec3f;uniform vSphericalL2_2: vec3f;uniform vSphericalL2_1: vec3f;uniform vSphericalL20: vec3f;uniform vSphericalL21: vec3f;uniform vSphericalL22: vec3f;uniform vSphericalX: vec3f;uniform vSphericalY: vec3f;uniform vSphericalZ: vec3f;uniform vSphericalXX_ZZ: vec3f;uniform vSphericalYY_ZZ: vec3f;uniform vSphericalZZ: vec3f;uniform vSphericalXY: vec3f;uniform vSphericalYZ: vec3f;uniform vSphericalZX: vec3f;uniform vBaseWeight: f32;uniform vBaseColor: vec4f;uniform vBaseDiffuseRoughness: f32;uniform vReflectanceInfo: vec4f;uniform vSpecularColor: vec4f;uniform vSpecularAnisotropy: vec3f;uniform vTransmissionWeight : f32;uniform vTransmissionColor : vec3f;uniform vTransmissionDepth : f32;uniform vTransmissionScatter : vec3f;uniform vTransmissionScatterAnisotropy : f32;uniform vTransmissionDispersionScale : f32;uniform vTransmissionDispersionAbbeNumber : f32;uniform vSubsurfaceWeight: f32;uniform vSubsurfaceColor: vec3f;uniform vSubsurfaceRadius: f32;uniform vSubsurfaceRadiusScale: vec3f;uniform vSubsurfaceScatterAnisotropy: f32;uniform vCoatWeight: f32;uniform vCoatColor: vec3f;uniform vCoatRoughness: f32;uniform vCoatRoughnessAnisotropy: f32;uniform vCoatIor: f32;uniform vCoatDarkening : f32;uniform vFuzzWeight: f32;uniform vFuzzColor: vec3f;uniform vFuzzRoughness: f32;uniform vGeometryThinWalled: f32;uniform vGeometryCoatTangent: vec2f;uniform vGeometryThickness: f32;uniform vEmissionColor: vec3f;uniform vThinFilmWeight: f32;uniform vThinFilmThickness: vec2f;uniform vThinFilmIor: f32;uniform vBaseWeightInfos: vec2f;uniform baseWeightMatrix: mat4x4f;uniform vBaseColorInfos: vec2f;uniform baseColorMatrix: mat4x4f;uniform vBaseDiffuseRoughnessInfos: vec2f;uniform baseDiffuseRoughnessMatrix: mat4x4f;uniform vBaseMetalnessInfos: vec2f;uniform baseMetalnessMatrix: mat4x4f;uniform vSpecularWeightInfos: vec2f;uniform specularWeightMatrix: mat4x4f;uniform vSpecularColorInfos: vec2f;uniform specularColorMatrix: mat4x4f;uniform vSpecularRoughnessInfos: vec2f;uniform specularRoughnessMatrix: mat4x4f;uniform vSpecularRoughnessAnisotropyInfos: vec2f;uniform specularRoughnessAnisotropyMatrix: mat4x4f;uniform vTransmissionWeightInfos : vec2f;uniform transmissionWeightMatrix : mat4x4f;uniform vTransmissionColorInfos : vec2f;uniform transmissionColorMatrix : mat4x4f;uniform vTransmissionDepthInfos : vec2f;uniform transmissionDepthMatrix : mat4x4f;uniform vTransmissionScatterInfos : vec2f;uniform transmissionScatterMatrix : mat4x4f;uniform vTransmissionDispersionScaleInfos : vec2f;uniform transmissionDispersionScaleMatrix : mat4x4f;uniform vSubsurfaceWeightInfos: vec2f;uniform subsurfaceWeightMatrix: mat4x4f;uniform vSubsurfaceColorInfos: vec2f;uniform subsurfaceColorMatrix: mat4x4f;uniform vSubsurfaceRadiusScaleInfos: vec2f;uniform subsurfaceRadiusScaleMatrix: mat4x4f;uniform vCoatWeightInfos: vec2f;uniform coatWeightMatrix: mat4x4f;uniform vCoatColorInfos: vec2f;uniform coatColorMatrix: mat4x4f;uniform vCoatRoughnessInfos: vec2f;uniform coatRoughnessMatrix: mat4x4f;uniform vCoatRoughnessAnisotropyInfos: vec2f;uniform coatRoughnessAnisotropyMatrix: mat4x4f;uniform vCoatDarkeningInfos : vec2f;uniform coatDarkeningMatrix : mat4x4f;uniform vFuzzWeightInfos: vec2f;uniform fuzzWeightMatrix: mat4x4f;uniform vFuzzColorInfos: vec2f;uniform fuzzColorMatrix: mat4x4f;uniform vFuzzRoughnessInfos: vec2f;uniform fuzzRoughnessMatrix: mat4x4f;uniform vGeometryNormalInfos: vec2f;uniform geometryNormalMatrix: mat4x4f;uniform vGeometryTangentInfos: vec2f;uniform geometryTangentMatrix: mat4x4f;uniform vGeometryCoatNormalInfos: vec2f;uniform geometryCoatNormalMatrix: mat4x4f;uniform vGeometryCoatTangentInfos: vec2f;uniform geometryCoatTangentMatrix: mat4x4f;uniform vGeometryOpacityInfos: vec2f;uniform geometryOpacityMatrix: mat4x4f;uniform vGeometryThicknessInfos: vec2f;uniform geometryThicknessMatrix: mat4x4f;uniform vEmissionInfos: vec2f;uniform emissionMatrix: mat4x4f;uniform vThinFilmWeightInfos: vec2f;uniform thinFilmWeightMatrix: mat4x4f;uniform vThinFilmThicknessInfos: vec2f;uniform thinFilmThicknessMatrix: mat4x4f;uniform vAmbientOcclusionInfos: vec2f;uniform ambientOcclusionMatrix: mat4x4f; #define ADDITIONAL_UBO_DECLARATION #include #include -`;T.IncludesShadersStoreWGSL[Q5]||(T.IncludesShadersStoreWGSL[Q5]=afe)});var $5,ofe,J5=C(()=>{W();$5="openpbrNormalMapVertexDeclaration",ofe=`#if defined(GEOMETRY_NORMAL) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(FUZZ) +`;T.IncludesShadersStoreWGSL[Q5]||(T.IncludesShadersStoreWGSL[Q5]=afe)});var $5,ofe,J5=C(()=>{k();$5="openpbrNormalMapVertexDeclaration",ofe=`#if defined(GEOMETRY_NORMAL) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(FUZZ) #if defined(TANGENT) && defined(NORMAL) varying vTBN0: vec3f;varying vTBN1: vec3f;varying vTBN2: vec3f; #endif #endif -`;T.IncludesShadersStoreWGSL[$5]||(T.IncludesShadersStoreWGSL[$5]=ofe)});var eY,lfe,tY=C(()=>{W();eY="openpbrNormalMapVertex",lfe=`#if defined(GEOMETRY_NORMAL) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(FUZZ) +`;T.IncludesShadersStoreWGSL[$5]||(T.IncludesShadersStoreWGSL[$5]=ofe)});var eY,lfe,tY=C(()=>{k();eY="openpbrNormalMapVertex",lfe=`#if defined(GEOMETRY_NORMAL) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(FUZZ) #if defined(TANGENT) && defined(NORMAL) var tbnNormal: vec3f=normalize(normalUpdated);var tbnTangent: vec3f=normalize(tangentUpdated.xyz);var tbnBitangent: vec3f=cross(tbnNormal,tbnTangent)*tangentUpdated.w;var matTemp= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz)* mat3x3f(tbnTangent,tbnBitangent,tbnNormal);vertexOutputs.vTBN0=matTemp[0];vertexOutputs.vTBN1=matTemp[1];vertexOutputs.vTBN2=matTemp[2]; #endif #endif -`;T.IncludesShadersStoreWGSL[eY]||(T.IncludesShadersStoreWGSL[eY]=lfe)});var rY={};tt(rY,{openpbrVertexShaderWGSL:()=>cfe});var mL,iY,cfe,nY=C(()=>{W();uL();JA();qm();Ca();ap();rc();nc();wf();ex();tx();sp();J5();sc();gg();ix();Uf();Vf();td();rx();nx();Gf();kf();ac();oc();lc();sx();ax();ox();tY();cc();vg();cx();Eg();fx();mL="openpbrVertexShader",iY=`#define OPENPBR_VERTEX_SHADER +`;T.IncludesShadersStoreWGSL[eY]||(T.IncludesShadersStoreWGSL[eY]=lfe)});var rY={};tt(rY,{openpbrVertexShaderWGSL:()=>cfe});var mL,iY,cfe,nY=C(()=>{k();uL();ex();jm();Ma();sp();ic();rc();Nf();tx();ix();np();J5();nc();gg();rx();Bf();Uf();td();nx();sx();Vf();Gf();sc();ac();oc();ax();ox();lx();tY();lc();vg();fx();Eg();hx();mL="openpbrVertexShader",iY=`#define OPENPBR_VERTEX_SHADER #include #define CUSTOM_VERTEX_BEGIN #ifndef USE_VERTEX_PULLING @@ -13033,7 +13033,7 @@ vertexOutputs.vMainUV2=uv2Updated; #include #include #define CUSTOM_VERTEX_MAIN_END -}`;T.ShadersStoreWGSL[mL]||(T.ShadersStoreWGSL[mL]=iY);cfe={name:mL,shader:iY}});var sY,ffe,pL=C(()=>{W();qm();sY="pbrFragmentExtraDeclaration",ffe=`varying vPositionW: vec3f; +}`;T.ShadersStoreWGSL[mL]||(T.ShadersStoreWGSL[mL]=iY);cfe={name:mL,shader:iY}});var sY,ffe,pL=C(()=>{k();jm();sY="pbrFragmentExtraDeclaration",ffe=`varying vPositionW: vec3f; #if DEBUGMODE>0 varying vClipSpacePosition: vec4f; #endif @@ -13050,7 +13050,7 @@ varying vColor: vec4f; #if defined(CLUSTLIGHT_BATCH) && CLUSTLIGHT_BATCH>0 varying vViewDepth: f32; #endif -`;T.IncludesShadersStoreWGSL[sY]||(T.IncludesShadersStoreWGSL[sY]=ffe)});var aY,hfe,oY=C(()=>{W();id();xR();aY="openpbrFragmentSamplersDeclaration",hfe=`#include(_DEFINENAME_,BASE_COLOR,_VARYINGNAME_,BaseColor,_SAMPLERNAME_,baseColor) +`;T.IncludesShadersStoreWGSL[sY]||(T.IncludesShadersStoreWGSL[sY]=ffe)});var aY,hfe,oY=C(()=>{k();id();RR();aY="openpbrFragmentSamplersDeclaration",hfe=`#include(_DEFINENAME_,BASE_COLOR,_VARYINGNAME_,BaseColor,_SAMPLERNAME_,baseColor) #include(_DEFINENAME_,BASE_WEIGHT,_VARYINGNAME_,BaseWeight,_SAMPLERNAME_,baseWeight) #include(_DEFINENAME_,BASE_DIFFUSE_ROUGHNESS,_VARYINGNAME_,BaseDiffuseRoughness,_SAMPLERNAME_,baseDiffuseRoughness) #include(_DEFINENAME_,BASE_METALNESS,_VARYINGNAME_,BaseMetalness,_SAMPLERNAME_,baseMetalness) @@ -13102,15 +13102,15 @@ var blueNoiseSamplerSampler: sampler;var blueNoiseSampler: texture_2d; #ifdef IBL_CDF_FILTERING var icdfSamplerSampler: sampler;var icdfSampler: texture_2d; #endif -`;T.IncludesShadersStoreWGSL[aY]||(T.IncludesShadersStoreWGSL[aY]=hfe)});var lY,dfe,_L=C(()=>{W();lY="subSurfaceScatteringFunctions",dfe=`fn testLightingForSSS(diffusionProfile: f32)->bool -{return diffusionProfile<1.;}`;T.IncludesShadersStoreWGSL[lY]||(T.IncludesShadersStoreWGSL[lY]=dfe)});var cY,ufe,gL=C(()=>{W();cY="importanceSampling",ufe=`fn hemisphereCosSample(u: vec2f)->vec3f {var phi: f32=2.*PI*u.x;var cosTheta2: f32=1.-u.y;var cosTheta: f32=sqrt(cosTheta2);var sinTheta: f32=sqrt(1.-cosTheta2);return vec3f(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);} +`;T.IncludesShadersStoreWGSL[aY]||(T.IncludesShadersStoreWGSL[aY]=hfe)});var lY,dfe,_L=C(()=>{k();lY="subSurfaceScatteringFunctions",dfe=`fn testLightingForSSS(diffusionProfile: f32)->bool +{return diffusionProfile<1.;}`;T.IncludesShadersStoreWGSL[lY]||(T.IncludesShadersStoreWGSL[lY]=dfe)});var cY,ufe,gL=C(()=>{k();cY="importanceSampling",ufe=`fn hemisphereCosSample(u: vec2f)->vec3f {var phi: f32=2.*PI*u.x;var cosTheta2: f32=1.-u.y;var cosTheta: f32=sqrt(cosTheta2);var sinTheta: f32=sqrt(1.-cosTheta2);return vec3f(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);} fn hemisphereImportanceSampleDggx(u: vec2f,a: f32)->vec3f {var phi: f32=2.*PI*u.x;var cosTheta2: f32=(1.-u.y)/(1.+(a+1.)*((a-1.)*u.y));var cosTheta: f32=sqrt(cosTheta2);var sinTheta: f32=sqrt(1.-cosTheta2);return vec3f(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);} fn hemisphereImportanceSampleDggxAnisotropic(Xi: vec2f,alphaTangent: f32,alphaBitangent: f32)->vec3f {let alphaT: f32=max(alphaTangent,0.0001);let alphaB: f32=max(alphaBitangent,0.0001);var phi: f32=atan(alphaB/alphaT*tan(2.0f*PI*Xi.x));if (Xi.x>0.5) {phi+=PI; } let cosPhi: f32=cos(phi);let sinPhi: f32=sin(phi);let alpha2: f32=(cosPhi*cosPhi)/(alphaT*alphaT) + (sinPhi*sinPhi)/(alphaB*alphaB);let tanTheta2: f32=Xi.y/(1.0f-Xi.y)/alpha2;let cosTheta: f32=1.0f/sqrt(1.0f+tanTheta2);let sinTheta: f32=sqrt(max(0.0f,1.0f-cosTheta*cosTheta));return vec3f(sinTheta*cosPhi,sinTheta*sinPhi,cosTheta);} fn hemisphereImportanceSampleDCharlie(u: vec2f,a: f32)->vec3f { -var phi: f32=2.*PI*u.x;var sinTheta: f32=pow(u.y,a/(2.*a+1.));var cosTheta: f32=sqrt(1.-sinTheta*sinTheta);return vec3f(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}`;T.IncludesShadersStoreWGSL[cY]||(T.IncludesShadersStoreWGSL[cY]=ufe)});var fY,mfe,vL=C(()=>{W();fY="pbrHelperFunctions",mfe=`#define MINIMUMVARIANCE 0.0005 +var phi: f32=2.*PI*u.x;var sinTheta: f32=pow(u.y,a/(2.*a+1.));var cosTheta: f32=sqrt(1.-sinTheta*sinTheta);return vec3f(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}`;T.IncludesShadersStoreWGSL[cY]||(T.IncludesShadersStoreWGSL[cY]=ufe)});var fY,mfe,vL=C(()=>{k();fY="pbrHelperFunctions",mfe=`#define MINIMUMVARIANCE 0.0005 fn convertRoughnessToAverageSlope(roughness: f32)->f32 {return roughness*roughness+MINIMUMVARIANCE;} fn fresnelGrazingReflectance(reflectance0: f32)->f32 {var reflectance90: f32=saturate(reflectance0*25.0);return reflectance90;} @@ -13144,7 +13144,7 @@ clearCoatIntensity);return clearCoatAbsorption;} fn computeDefaultMicroSurface(microSurface: f32,reflectivityColor: vec3f)->f32 {const kReflectivityNoAlphaWorkflow_SmoothnessMax: f32=0.95;var reflectivityLuminance: f32=getLuminance(reflectivityColor);var reflectivityLuma: f32=sqrt(reflectivityLuminance);var resultMicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;return resultMicroSurface;} #endif -`;T.IncludesShadersStoreWGSL[fY]||(T.IncludesShadersStoreWGSL[fY]=mfe)});var hY,pfe,EL=C(()=>{W();MP();hY="pbrDirectLightingSetupFunctions",pfe=`struct preLightingInfo +`;T.IncludesShadersStoreWGSL[fY]||(T.IncludesShadersStoreWGSL[fY]=mfe)});var hY,pfe,EL=C(()=>{k();MP();hY="pbrDirectLightingSetupFunctions",pfe=`struct preLightingInfo {lightOffset: vec3f, lightDistanceSquared: f32, lightDistance: f32, @@ -13189,7 +13189,7 @@ result.areaLightFresnel=data.Fresnel;result.areaLightSpecular=data.Specular; #endif result.areaLightDiffuse=data.Diffuse;result.LdotV=0.;result.roughness=0.;result.diffuseRoughness=0.;result.surfaceAlbedo=vec3f(0.);return result;} #endif -`;T.IncludesShadersStoreWGSL[hY]||(T.IncludesShadersStoreWGSL[hY]=pfe)});var dY,_fe,SL=C(()=>{W();dY="pbrDirectLightingFalloffFunctions",_fe=`fn computeDistanceLightFalloff_Standard(lightOffset: vec3f,range: f32)->f32 +`;T.IncludesShadersStoreWGSL[hY]||(T.IncludesShadersStoreWGSL[hY]=pfe)});var dY,_fe,SL=C(()=>{k();dY="pbrDirectLightingFalloffFunctions",_fe=`fn computeDistanceLightFalloff_Standard(lightOffset: vec3f,range: f32)->f32 {return max(0.,1.0-length(lightOffset)/range);} fn computeDistanceLightFalloff_Physical(lightDistanceSquared: f32)->f32 {return 1.0/maxEps(lightDistanceSquared);} @@ -13225,7 +13225,7 @@ return computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenter #else return computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent); #endif -}`;T.IncludesShadersStoreWGSL[dY]||(T.IncludesShadersStoreWGSL[dY]=_fe)});var uY,gfe,TL=C(()=>{W();uY="hdrFilteringFunctions",gfe=`#ifdef NUM_SAMPLES +}`;T.IncludesShadersStoreWGSL[dY]||(T.IncludesShadersStoreWGSL[dY]=_fe)});var uY,gfe,TL=C(()=>{k();uY="hdrFilteringFunctions",gfe=`#ifdef NUM_SAMPLES #if NUM_SAMPLES>0 fn radicalInverse_VdC(value: u32)->f32 {var bits=(value<<16u) | (value>>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 f32(bits)*2.3283064365386963e-10; } @@ -13342,11 +13342,11 @@ result=result/weight;return result;} #endif #endif #endif -`;T.IncludesShadersStoreWGSL[uY]||(T.IncludesShadersStoreWGSL[uY]=gfe)});var mY,vfe,AL=C(()=>{W();mY="pbrBlockReflectance0",vfe=`var reflectanceF0: f32=reflectivityOut.reflectanceF0;var specularEnvironmentR0: vec3f=reflectivityOut.colorReflectanceF0;var specularEnvironmentR90: vec3f= reflectivityOut.reflectanceF90; +`;T.IncludesShadersStoreWGSL[uY]||(T.IncludesShadersStoreWGSL[uY]=gfe)});var mY,vfe,AL=C(()=>{k();mY="pbrBlockReflectance0",vfe=`var reflectanceF0: f32=reflectivityOut.reflectanceF0;var specularEnvironmentR0: vec3f=reflectivityOut.colorReflectanceF0;var specularEnvironmentR90: vec3f= reflectivityOut.reflectanceF90; #ifdef ALPHAFRESNEL var reflectance90: f32=fresnelGrazingReflectance(reflectanceF0);specularEnvironmentR90=specularEnvironmentR90*reflectance90; #endif -`;T.IncludesShadersStoreWGSL[mY]||(T.IncludesShadersStoreWGSL[mY]=vfe)});var pY,Efe,xL=C(()=>{W();CP();AL();pY="pbrDirectLightingFunctions",Efe=`#define CLEARCOATREFLECTANCE90 1.0 +`;T.IncludesShadersStoreWGSL[mY]||(T.IncludesShadersStoreWGSL[mY]=vfe)});var pY,Efe,xL=C(()=>{k();CP();AL();pY="pbrDirectLightingFunctions",Efe=`#define CLEARCOATREFLECTANCE90 1.0 struct lightingInfo {diffuse: vec3f, #ifdef SS_TRANSLUCENCY @@ -13568,7 +13568,7 @@ result.sheen+=info.sheen; batchOffset+=CLUSTLIGHT_BATCH;} return result;} #endif -`;T.IncludesShadersStoreWGSL[pY]||(T.IncludesShadersStoreWGSL[pY]=Efe)});var _Y,Sfe,gY=C(()=>{W();_Y="openpbrNormalMapFragmentMainFunctions",Sfe=`#if defined(GEOMETRY_NORMAL) || defined(GEOMETRY_COAT_NORMAL) || defined(ANISOTROPIC) || defined(FUZZ) || defined(DETAIL) +`;T.IncludesShadersStoreWGSL[pY]||(T.IncludesShadersStoreWGSL[pY]=Efe)});var _Y,Sfe,gY=C(()=>{k();_Y="openpbrNormalMapFragmentMainFunctions",Sfe=`#if defined(GEOMETRY_NORMAL) || defined(GEOMETRY_COAT_NORMAL) || defined(ANISOTROPIC) || defined(FUZZ) || defined(DETAIL) #if defined(TANGENT) && defined(NORMAL) varying vTBN0: vec3f;varying vTBN1: vec3f;varying vTBN2: vec3f; #endif @@ -13608,7 +13608,7 @@ fn perturbNormal(cotangentFrame: mat3x3f,textureSample: vec3f,scale: f32)->vec3f fn cotangent_frame(normal: vec3f,p: vec3f,uv: vec2f,tangentSpaceParams: vec2f)->mat3x3f {var dp1: vec3f=dpdx(p);var dp2: vec3f=dpdy(p);var duv1: vec2f=dpdx(uv);var duv2: vec2f=dpdy(uv);var dp2perp: vec3f=cross(dp2,normal);var dp1perp: vec3f=cross(normal,dp1);var tangent: vec3f=dp2perp*duv1.x+dp1perp*duv2.x;var bitangent: vec3f=dp2perp*duv1.y+dp1perp*duv2.y;tangent*=tangentSpaceParams.x;bitangent*=tangentSpaceParams.y;var det: f32=max(dot(tangent,tangent),dot(bitangent,bitangent));var invmax: f32=select(inverseSqrt(det),0.0,det==0.0);return mat3x3f(tangent*invmax,bitangent*invmax,normal);} #endif -`;T.IncludesShadersStoreWGSL[_Y]||(T.IncludesShadersStoreWGSL[_Y]=Sfe)});var vY,Tfe,EY=C(()=>{W();id();vY="openpbrNormalMapFragmentFunctions",Tfe=`#if defined(GEOMETRY_NORMAL) +`;T.IncludesShadersStoreWGSL[_Y]||(T.IncludesShadersStoreWGSL[_Y]=Sfe)});var vY,Tfe,EY=C(()=>{k();id();vY="openpbrNormalMapFragmentFunctions",Tfe=`#if defined(GEOMETRY_NORMAL) #include(_DEFINENAME_,GEOMETRY_NORMAL,_VARYINGNAME_,GeometryNormal,_SAMPLERNAME_,geometryNormal) #endif #if defined(GEOMETRY_COAT_NORMAL) @@ -13641,7 +13641,7 @@ return -texCoordOffset; #endif } #endif -`;T.IncludesShadersStoreWGSL[vY]||(T.IncludesShadersStoreWGSL[vY]=Tfe)});var SY,Afe,TY=C(()=>{W();SY="openpbrConductorReflectance",Afe=`#define pbr_inline +`;T.IncludesShadersStoreWGSL[vY]||(T.IncludesShadersStoreWGSL[vY]=Tfe)});var SY,Afe,TY=C(()=>{k();SY="openpbrConductorReflectance",Afe=`#define pbr_inline fn conductorReflectance(baseColor: vec3f,specularColor: vec3f,specularWeight: f32)->ReflectanceParams {var outParams: ReflectanceParams; #if (CONDUCTOR_SPECULAR_MODEL==CONDUCTOR_SPECULAR_MODEL_OPENPBR) @@ -13649,9 +13649,9 @@ outParams.coloredF0=baseColor*specularWeight;outParams.coloredF90=specularColor* #else outParams.coloredF0=baseColor;outParams.coloredF90=vec3f(1.0f); #endif -outParams.F0=1.0f;outParams.F90=1.0f;return outParams;}`;T.IncludesShadersStoreWGSL[SY]||(T.IncludesShadersStoreWGSL[SY]=Afe)});var AY,xfe,xY=C(()=>{W();AY="openpbrAmbientOcclusionFunctions",xfe=`fn compute_specular_occlusion(n_dot_v: f32,metallic: f32,ambient_occlusion: f32,roughness: f32)->f32 +outParams.F0=1.0f;outParams.F90=1.0f;return outParams;}`;T.IncludesShadersStoreWGSL[SY]||(T.IncludesShadersStoreWGSL[SY]=Afe)});var AY,xfe,xY=C(()=>{k();AY="openpbrAmbientOcclusionFunctions",xfe=`fn compute_specular_occlusion(n_dot_v: f32,metallic: f32,ambient_occlusion: f32,roughness: f32)->f32 {let specular_occlusion: f32=saturate(pow(n_dot_v+ambient_occlusion,exp2(-16.0*roughness-1.0))-1.0+ambient_occlusion);return mix(specular_occlusion,1.0,metallic*square(1.0-roughness));} -`;T.IncludesShadersStoreWGSL[AY]||(T.IncludesShadersStoreWGSL[AY]=xfe)});var RY,Rfe,bY=C(()=>{W();RY="openpbrVolumeFunctions",Rfe=`struct OpenPBRHomogeneousVolume {extinction_coeff: vec3f, +`;T.IncludesShadersStoreWGSL[AY]||(T.IncludesShadersStoreWGSL[AY]=xfe)});var RY,Rfe,bY=C(()=>{k();RY="openpbrVolumeFunctions",Rfe=`struct OpenPBRHomogeneousVolume {extinction_coeff: vec3f, ss_albedo: vec3f, multi_scatter_color: vec3f, absorption_coeff: vec3f, @@ -13708,7 +13708,7 @@ let filter_samples_scale: f32=samples_scale(pixels_to_projective(overscan_size_i return vec3f(select(unconvolved_irradiance.r,irradiance_sum.r/weight_sum.r,weight_sum.r>=1e-5f), select(unconvolved_irradiance.g,irradiance_sum.g/weight_sum.g,weight_sum.g>=1e-5f), select(unconvolved_irradiance.b,irradiance_sum.b/weight_sum.b,weight_sum.b>=1e-5f));} -`;T.IncludesShadersStoreWGSL[RY]||(T.IncludesShadersStoreWGSL[RY]=Rfe)});var IY,bfe,RL=C(()=>{W();IY="pbrBlockNormalGeometric",bfe=`var viewDirectionW: vec3f=normalize(scene.vEyePosition.xyz-input.vPositionW); +`;T.IncludesShadersStoreWGSL[RY]||(T.IncludesShadersStoreWGSL[RY]=Rfe)});var IY,bfe,RL=C(()=>{k();IY="pbrBlockNormalGeometric",bfe=`var viewDirectionW: vec3f=normalize(scene.vEyePosition.xyz-input.vPositionW); #ifdef NORMAL var normalW: vec3f=normalize(input.vNormalW); #else @@ -13718,7 +13718,7 @@ var geometricNormalW: vec3f=normalW; #if defined(TWOSIDEDLIGHTING) && defined(NORMAL) geometricNormalW=select(-geometricNormalW,geometricNormalW,fragmentInputs.frontFacing); #endif -`;T.IncludesShadersStoreWGSL[IY]||(T.IncludesShadersStoreWGSL[IY]=bfe)});var MY,Ife,CY=C(()=>{W();MY="openpbrNormalMapFragment",Ife=`var uvOffset: vec2f= vec2f(0.0,0.0); +`;T.IncludesShadersStoreWGSL[IY]||(T.IncludesShadersStoreWGSL[IY]=bfe)});var MY,Ife,CY=C(()=>{k();MY="openpbrNormalMapFragment",Ife=`var uvOffset: vec2f= vec2f(0.0,0.0); #if defined(GEOMETRY_NORMAL) || defined(GEOMETRY_COAT_NORMAL) || defined(PARALLAX) || defined(DETAIL) #ifdef NORMALXYSCALE var normalScale: f32=1.0; @@ -13773,7 +13773,7 @@ normalW=perturbNormalBase(TBN,blendedNormal,uniforms.vGeometryNormalInfos.y); #elif defined(DETAIL) detailNormal=vec3f(detailNormal.xy*uniforms.vDetailInfos.z,detailNormal.z);normalW=perturbNormalBase(TBN,detailNormal,uniforms.vDetailInfos.z); #endif -`;T.IncludesShadersStoreWGSL[MY]||(T.IncludesShadersStoreWGSL[MY]=Ife)});var yY,Mfe,PY=C(()=>{W();yY="openpbrBlockNormalFinal",Mfe=`#if defined(FORCENORMALFORWARD) && defined(NORMAL) +`;T.IncludesShadersStoreWGSL[MY]||(T.IncludesShadersStoreWGSL[MY]=Ife)});var yY,Mfe,PY=C(()=>{k();yY="openpbrBlockNormalFinal",Mfe=`#if defined(FORCENORMALFORWARD) && defined(NORMAL) var faceNormal: vec3f=normalize(cross(dpdx(fragmentInputs.vPositionW),dpdy(fragmentInputs.vPositionW)))*scene.vEyePosition.w; #if defined(TWOSIDEDLIGHTING) faceNormal=select(-faceNormal,faceNormal,fragmentInputs.frontFacing); @@ -13787,7 +13787,7 @@ normalW=select(normalW,-normalW,fragmentInputs.frontFacing);coatNormalW=select(c normalW=select(-normalW,normalW,fragmentInputs.frontFacing);coatNormalW=select(-coatNormalW,coatNormalW,fragmentInputs.frontFacing); #endif #endif -`;T.IncludesShadersStoreWGSL[yY]||(T.IncludesShadersStoreWGSL[yY]=Mfe)});var DY,Cfe,LY=C(()=>{W();DY="openpbrBaseLayerData",Cfe=`var base_color=vec3f(0.8);var base_metalness: f32=0.0;var base_diffuse_roughness: f32=0.0;var specular_weight: f32=1.0;var specular_roughness: f32=0.3;var specular_color: vec3f=vec3f(1.0);var specular_roughness_anisotropy: f32=0.0;var specular_ior: f32=1.5;var alpha: f32=1.0;var geometry_tangent: vec2f=vec2f(1.0,0.0);var geometry_thickness: f32=0.0; +`;T.IncludesShadersStoreWGSL[yY]||(T.IncludesShadersStoreWGSL[yY]=Mfe)});var DY,Cfe,LY=C(()=>{k();DY="openpbrBaseLayerData",Cfe=`var base_color=vec3f(0.8);var base_metalness: f32=0.0;var base_diffuse_roughness: f32=0.0;var specular_weight: f32=1.0;var specular_roughness: f32=0.3;var specular_color: vec3f=vec3f(1.0);var specular_roughness_anisotropy: f32=0.0;var specular_ior: f32=1.5;var alpha: f32=1.0;var geometry_tangent: vec2f=vec2f(1.0,0.0);var geometry_thickness: f32=0.0; #ifdef BASE_WEIGHT let baseWeightFromTexture: vec4f=textureSample(baseWeightSampler,baseWeightSamplerSampler,fragmentInputs.vBaseWeightUV+uvOffset); #endif @@ -13913,7 +13913,7 @@ let detailRoughness: f32=mix(0.5f,detailColor.b,vDetailInfos.w);let loLerp: f32= #ifdef USE_GLTF_STYLE_ANISOTROPY let baseAlpha: f32=specular_roughness*specular_roughness;let roughnessT: f32=mix(baseAlpha,1.0f,specular_roughness_anisotropy*specular_roughness_anisotropy);let roughnessB: f32=baseAlpha;specular_roughness_anisotropy=1.0f-roughnessB/max(roughnessT,0.00001f);specular_roughness=sqrt(roughnessT/sqrt(2.0f/(1.0f+(1.0f-specular_roughness_anisotropy)*(1.0f-specular_roughness_anisotropy)))); #endif -`;T.IncludesShadersStoreWGSL[DY]||(T.IncludesShadersStoreWGSL[DY]=Cfe)});var OY,yfe,NY=C(()=>{W();OY="openpbrCoatLayerData",yfe=`var coat_weight: f32=0.0f;var coat_color: vec3f=vec3f(1.0f);var coat_roughness: f32=0.0f;var coat_roughness_anisotropy: f32=0.0f;var coat_ior: f32=1.6f;var coat_darkening: f32=1.0f;var geometry_coat_tangent: vec2f=vec2f(1.0f,0.0f); +`;T.IncludesShadersStoreWGSL[DY]||(T.IncludesShadersStoreWGSL[DY]=Cfe)});var OY,yfe,NY=C(()=>{k();OY="openpbrCoatLayerData",yfe=`var coat_weight: f32=0.0f;var coat_color: vec3f=vec3f(1.0f);var coat_roughness: f32=0.0f;var coat_roughness_anisotropy: f32=0.0f;var coat_ior: f32=1.6f;var coat_darkening: f32=1.0f;var geometry_coat_tangent: vec2f=vec2f(1.0f,0.0f); #ifdef COAT_WEIGHT var coatWeightFromTexture: vec4f=textureSample(coatWeightSampler,coatWeightSamplerSampler,fragmentInputs.vCoatWeightUV+uvOffset); #endif @@ -13965,7 +13965,7 @@ coat_darkening*=coatDarkeningFromTexture.r; #ifdef USE_GLTF_STYLE_ANISOTROPY let coatAlpha: f32=coat_roughness*coat_roughness;let coatRoughnessT: f32=mix(coatAlpha,1.0f,coat_roughness_anisotropy*coat_roughness_anisotropy);let coatRoughnessB: f32=coatAlpha;coat_roughness_anisotropy=1.0f-coatRoughnessB/max(coatRoughnessT,0.00001f);coat_roughness=sqrt(coatRoughnessT/sqrt(2.0f/(1.0f+(1.0f-coat_roughness_anisotropy)*(1.0f-coat_roughness_anisotropy)))); #endif -`;T.IncludesShadersStoreWGSL[OY]||(T.IncludesShadersStoreWGSL[OY]=yfe)});var wY,Pfe,FY=C(()=>{W();wY="openpbrThinFilmLayerData",Pfe=`#ifdef THIN_FILM +`;T.IncludesShadersStoreWGSL[OY]||(T.IncludesShadersStoreWGSL[OY]=yfe)});var wY,Pfe,FY=C(()=>{k();wY="openpbrThinFilmLayerData",Pfe=`#ifdef THIN_FILM var thin_film_weight: f32=uniforms.vThinFilmWeight;var thin_film_thickness: f32=uniforms.vThinFilmThickness.r*1000.0f; var thin_film_ior: f32=uniforms.vThinFilmIor; #ifdef THIN_FILM_WEIGHT @@ -13982,7 +13982,7 @@ thin_film_thickness*=thinFilmThicknessFromTexture; #endif let thin_film_ior_scale: f32=clamp(2.0f*abs(thin_film_ior-1.0f),0.0f,1.0f); #endif -`;T.IncludesShadersStoreWGSL[wY]||(T.IncludesShadersStoreWGSL[wY]=Pfe)});var BY,Dfe,UY=C(()=>{W();BY="openpbrFuzzLayerData",Dfe=`var fuzz_weight: f32=0.0f;var fuzz_color: vec3f=vec3f(1.0f);var fuzz_roughness: f32=0.0f; +`;T.IncludesShadersStoreWGSL[wY]||(T.IncludesShadersStoreWGSL[wY]=Pfe)});var BY,Dfe,UY=C(()=>{k();BY="openpbrFuzzLayerData",Dfe=`var fuzz_weight: f32=0.0f;var fuzz_color: vec3f=vec3f(1.0f);var fuzz_roughness: f32=0.0f; #ifdef FUZZ #ifdef FUZZ_WEIGHT let fuzzWeightFromTexture: vec4f=textureSample(fuzzWeightSampler,fuzzWeightSamplerSampler,fragmentInputs.vFuzzWeightUV+uvOffset); @@ -14011,11 +14011,11 @@ fuzz_roughness*=fuzzRoughnessFromTexture.a; fuzz_roughness*=fuzzRoughnessFromTexture.r; #endif #endif -`;T.IncludesShadersStoreWGSL[BY]||(T.IncludesShadersStoreWGSL[BY]=Dfe)});var VY,Lfe,GY=C(()=>{W();VY="openpbrAmbientOcclusionData",Lfe=`var ambient_occlusion: vec3f=vec3f(1.0f,1.0f,1.0f);var specular_ambient_occlusion: f32=1.0f;var coat_specular_ambient_occlusion: f32=1.0f; +`;T.IncludesShadersStoreWGSL[BY]||(T.IncludesShadersStoreWGSL[BY]=Dfe)});var VY,Lfe,GY=C(()=>{k();VY="openpbrAmbientOcclusionData",Lfe=`var ambient_occlusion: vec3f=vec3f(1.0f,1.0f,1.0f);var specular_ambient_occlusion: f32=1.0f;var coat_specular_ambient_occlusion: f32=1.0f; #ifdef AMBIENT_OCCLUSION var ambientOcclusionFromTexture: vec3f=textureSample(ambientOcclusionSampler,ambientOcclusionSamplerSampler,fragmentInputs.vAmbientOcclusionUV+uvOffset).rgb;ambient_occlusion=vec3f(ambientOcclusionFromTexture.r*uniforms.vAmbientOcclusionInfos.y+(1.0f-uniforms.vAmbientOcclusionInfos.y)); #endif -`;T.IncludesShadersStoreWGSL[VY]||(T.IncludesShadersStoreWGSL[VY]=Lfe)});var kY,Ofe,WY=C(()=>{W();kY="openpbrBackgroundTransmission",Ofe=`var slab_translucent_background: vec4f=vec4f(0.,0.,0.,1.); +`;T.IncludesShadersStoreWGSL[VY]||(T.IncludesShadersStoreWGSL[VY]=Lfe)});var kY,Ofe,WY=C(()=>{k();kY="openpbrBackgroundTransmission",Ofe=`var slab_translucent_background: vec4f=vec4f(0.,0.,0.,1.); #ifdef REFRACTED_BACKGROUND {let refractionLOD: f32=min(transmission_roughness,0.7)*uniforms.vBackgroundRefractionInfos.x;let lodTexelSize: f32=pow(2.0f,refractionLOD-uniforms.vBackgroundRefractionInfos.x); #ifdef DISPERSION @@ -14043,7 +14043,7 @@ let noiseOffset: vec2f=noise.xy*lodTexelSize;slab_translucent_background=texture #endif } #endif -`;T.IncludesShadersStoreWGSL[kY]||(T.IncludesShadersStoreWGSL[kY]=Ofe)});var HY,Nfe,zY=C(()=>{W();HY="openpbrEnvironmentLighting",Nfe=`#if defined(REFLECTION) || defined(REFRACTED_BACKGROUND) +`;T.IncludesShadersStoreWGSL[kY]||(T.IncludesShadersStoreWGSL[kY]=Ofe)});var HY,Nfe,zY=C(()=>{k();HY="openpbrEnvironmentLighting",Nfe=`#if defined(REFLECTION) || defined(REFRACTED_BACKGROUND) var coatAbsorption=vec3f(1.0f);var coatIblFresnel: f32=0.0;if (coat_weight>0.0) {coatIblFresnel=computeDielectricIblFresnel(coatReflectance,coatGeoInfo.environmentBrdf);let hemisphere_avg_fresnel: f32=coatReflectance.F0+0.5f*(1.0f-coatReflectance.F0);var averageReflectance: f32=(coatIblFresnel+hemisphere_avg_fresnel)*0.5f;let roughnessFactor=1.0f-coat_roughness*0.5f;averageReflectance*=roughnessFactor;var darkened_transmission: f32=(1.0f-averageReflectance)*(1.0f-averageReflectance);darkened_transmission=mix(1.0,darkened_transmission,coat_darkening);var sin2: f32=1.0f-coatGeoInfo.NdotV*coatGeoInfo.NdotV;sin2=sin2/(coat_ior*coat_ior);let cos_t: f32=sqrt(1.0f-sin2);let coatPathLength=1.0f/cos_t;let colored_transmission: vec3f=pow(coat_color,vec3f(coatPathLength));coatAbsorption=mix(vec3f(1.0f),colored_transmission*darkened_transmission,coat_weight);} #endif #ifdef REFLECTION @@ -14337,7 +14337,7 @@ slab_translucent_base_ibl=slab_translucent_background.rgb*volume_absorption*tran #endif let material_dielectric_base_ibl: vec3f=mix(black,slab_translucent_base_ibl.rgb,surface_translucency_weight);let material_dielectric_gloss_ibl: vec3f=material_dielectric_base_ibl*(baseGeoInfo.NdotV);let material_base_substrate_ibl: vec3f=mix(material_dielectric_gloss_ibl,black,base_metalness);let material_coated_base_ibl: vec3f=layer(material_base_substrate_ibl,black,coatIblFresnel,coatAbsorption,vec3f(1.0f));material_surface_ibl=material_coated_base_ibl; #endif -`;T.IncludesShadersStoreWGSL[HY]||(T.IncludesShadersStoreWGSL[HY]=Nfe)});var XY,wfe,YY=C(()=>{W();XY="openpbrDirectLightingInit",wfe=`#ifdef LIGHT{X} +`;T.IncludesShadersStoreWGSL[HY]||(T.IncludesShadersStoreWGSL[HY]=Nfe)});var XY,wfe,YY=C(()=>{k();XY="openpbrDirectLightingInit",wfe=`#ifdef LIGHT{X} var preInfo{X}: preLightingInfo;var preInfoCoat{X}: preLightingInfo;let lightColor{X}: vec4f=light{X}.vLightDiffuse;var shadow{X}: f32=1.0f; #if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}) #else @@ -14408,7 +14408,7 @@ preInfo{X}.roughness=adjustRoughnessFromLightProperties(specular_roughness,light preInfo{X}.diffuseRoughness=base_diffuse_roughness;preInfo{X}.surfaceAlbedo=base_color.rgb; #endif #endif -`;T.IncludesShadersStoreWGSL[XY]||(T.IncludesShadersStoreWGSL[XY]=wfe)});var KY,Ffe,jY=C(()=>{W();KY="openpbrDirectLighting",Ffe=`#ifdef LIGHT{X} +`;T.IncludesShadersStoreWGSL[XY]||(T.IncludesShadersStoreWGSL[XY]=wfe)});var KY,Ffe,jY=C(()=>{k();KY="openpbrDirectLighting",Ffe=`#ifdef LIGHT{X} {var slab_diffuse: vec3f=vec3f(0.f,0.f,0.f);var slab_translucent: vec3f=vec3f(0.f,0.f,0.f);var slab_glossy: vec3f=vec3f(0.f,0.f,0.f);var specularFresnel: f32=0.0f;var specularColoredFresnel: vec3f=vec3f(0.f,0.f,0.f);var slab_metal: vec3f=vec3f(0.f,0.f,0.f);var slab_coat: vec3f=vec3f(0.f,0.f,0.f);var coatFresnel: f32=0.0f;var slab_fuzz: vec3f=vec3f(0.f,0.f,0.f);var fuzzFresnel: f32=0.0f; #ifdef HEMILIGHT{X} slab_diffuse=computeHemisphericDiffuseLighting(preInfo{X},lightColor{X}.rgb,light{X}.vLightGround); @@ -14563,7 +14563,7 @@ total_direct_diffuse+=slab_diffuse; #endif let material_dielectric_base: vec3f=mix(slab_diffuse*base_color.rgb,slab_translucent,surface_translucency_weight);let material_dielectric_gloss: vec3f=material_dielectric_base*(1.0f-specularFresnel)+slab_glossy*specularColoredFresnel;let material_base_substrate: vec3f=mix(material_dielectric_gloss,slab_metal,base_metalness);let material_coated_base: vec3f=layer(material_base_substrate,slab_coat,coatFresnel,coatAbsorption,vec3f(1.0f));material_surface_direct+=layer(material_coated_base,slab_fuzz,fuzzFresnel*fuzz_weight,vec3f(1.0f),fuzz_color);} #endif -`;T.IncludesShadersStoreWGSL[KY]||(T.IncludesShadersStoreWGSL[KY]=Ffe)});var qY,Bfe,bL=C(()=>{W();qY="pbrBlockImageProcessing",Bfe=`#if defined(IMAGEPROCESSINGPOSTPROCESS) || defined(SS_SCATTERING) +`;T.IncludesShadersStoreWGSL[KY]||(T.IncludesShadersStoreWGSL[KY]=Ffe)});var qY,Bfe,bL=C(()=>{k();qY="pbrBlockImageProcessing",Bfe=`#if defined(IMAGEPROCESSINGPOSTPROCESS) || defined(SS_SCATTERING) #if !defined(SKIPFINALCOLORCLAMP) finalColor=vec4f(clamp(finalColor.rgb,vec3f(0.),vec3f(30.0)),finalColor.a); #endif @@ -14574,7 +14574,7 @@ finalColor=vec4f(finalColor.rgb,finalColor.a*mesh.visibility); #ifdef PREMULTIPLYALPHA finalColor=vec4f(finalColor.rgb*finalColor.a,finalColor.a);; #endif -`;T.IncludesShadersStoreWGSL[qY]||(T.IncludesShadersStoreWGSL[qY]=Bfe)});var ZY,Ufe,QY=C(()=>{W();ZY="openpbrBlockPrePass",Ufe=`#if SCENE_MRT_COUNT>0 +`;T.IncludesShadersStoreWGSL[qY]||(T.IncludesShadersStoreWGSL[qY]=Bfe)});var ZY,Ufe,QY=C(()=>{k();ZY="openpbrBlockPrePass",Ufe=`#if SCENE_MRT_COUNT>0 var writeGeometryInfo: f32=select(0.0,1.0,finalColor.a>ALPHATESTVALUE);var fragData: array,SCENE_MRT_COUNT>; #ifdef PREPASS_POSITION fragData[PREPASS_POSITION_INDEX]= vec4f(fragmentInputs.vPositionW,writeGeometryInfo); @@ -14664,7 +14664,7 @@ fragmentOutputs.fragData6=fragData[6]; fragmentOutputs.fragData7=fragData[7]; #endif #endif -`;T.IncludesShadersStoreWGSL[ZY]||(T.IncludesShadersStoreWGSL[ZY]=Ufe)});var $Y,Vfe,IL=C(()=>{W();$Y="pbrDebug",Vfe=`#if DEBUGMODE>0 +`;T.IncludesShadersStoreWGSL[ZY]||(T.IncludesShadersStoreWGSL[ZY]=Ufe)});var $Y,Vfe,IL=C(()=>{k();$Y="pbrDebug",Vfe=`#if DEBUGMODE>0 if (input.vClipSpacePosition.x/input.vClipSpacePosition.w>=uniforms.vDebugMode.x) {var color: vec3f; #if DEBUGMODE==1 color=fragmentInputs.vPositionW.rgb; @@ -14848,7 +14848,7 @@ return fragmentOutputs; #endif } #endif -`;T.IncludesShadersStoreWGSL[$Y]||(T.IncludesShadersStoreWGSL[$Y]=Vfe)});var e8={};tt(e8,{openpbrPixelShaderWGSL:()=>Gfe});var ML,JY,Gfe,t8=C(()=>{W();hx();dx();uL();pL();ux();oY();px();fc();td();Sg();Ca();_L();gL();vL();_x();mx();sp();EL();SL();ap();TL();xL();RR();gY();EY();Og();aL();TY();xY();oL();lL();bY();hc();RL();CY();PY();LY();fL();cL();NY();FY();UY();GY();Sx();WY();zY();YY();jY();Tx();Tg();bL();QY();Ax();IL();ML="openpbrPixelShader",JY=`#define OPENPBR_FRAGMENT_SHADER +`;T.IncludesShadersStoreWGSL[$Y]||(T.IncludesShadersStoreWGSL[$Y]=Vfe)});var e8={};tt(e8,{openpbrPixelShaderWGSL:()=>Gfe});var ML,JY,Gfe,t8=C(()=>{k();dx();ux();uL();pL();mx();oY();_x();cc();td();Sg();Ma();_L();gL();vL();gx();px();np();EL();SL();sp();TL();xL();bR();gY();EY();Og();aL();TY();xY();oL();lL();bY();fc();RL();CY();PY();LY();fL();cL();NY();FY();UY();GY();Tx();WY();zY();YY();jY();Ax();Tg();bL();QY();xx();IL();ML="openpbrPixelShader",JY=`#define OPENPBR_FRAGMENT_SHADER #define CUSTOM_FRAGMENT_BEGIN #include[SCENE_MRT_COUNT] #include @@ -15072,7 +15072,7 @@ if (fragDepth==nearestDepth) {fragmentOutputs.frontColor=vec4f(fragmentOutputs.f #include #define CUSTOM_FRAGMENT_MAIN_END } -`;T.ShadersStoreWGSL[ML]||(T.ShadersStoreWGSL[ML]=JY);Gfe={name:ML,shader:JY}});var i8,kfe,r8=C(()=>{W();cD();xx();i8="openpbrVertexDeclaration",kfe=`#include +`;T.ShadersStoreWGSL[ML]||(T.ShadersStoreWGSL[ML]=JY);Gfe={name:ML,shader:JY}});var i8,kfe,r8=C(()=>{k();cD();Rx();i8="openpbrVertexDeclaration",kfe=`#include #ifdef BASE_COLOR uniform vec2 vBaseColorInfos;uniform mat4 baseColorMatrix; #endif @@ -15199,22 +15199,22 @@ uniform vec4 vDetailInfos;uniform mat4 detailMatrix; #endif #include #define ADDITIONAL_VERTEX_DECLARATION -`;T.IncludesShadersStore[i8]||(T.IncludesShadersStore[i8]=kfe)});var n8,Wfe,CL=C(()=>{W();rd();Ng();n8="openpbrUboDeclaration",Wfe=`layout(std140,column_major) uniform;uniform Material {vec2 vTangentSpaceParams;vec4 vLightingIntensity;float pointSize;vec2 vDebugMode;vec2 renderTargetSize;vec4 cameraInfo;mat4 backgroundRefractionMatrix;vec3 vBackgroundRefractionInfos;vec2 vReflectionInfos;mat4 reflectionMatrix;vec3 vReflectionMicrosurfaceInfos;vec3 vReflectionPosition;vec3 vReflectionSize;vec2 vReflectionFilteringInfo;vec3 vReflectionDominantDirection;vec3 vReflectionColor;vec3 vSphericalL00;vec3 vSphericalL1_1;vec3 vSphericalL10;vec3 vSphericalL11;vec3 vSphericalL2_2;vec3 vSphericalL2_1;vec3 vSphericalL20;vec3 vSphericalL21;vec3 vSphericalL22;vec3 vSphericalX;vec3 vSphericalY;vec3 vSphericalZ;vec3 vSphericalXX_ZZ;vec3 vSphericalYY_ZZ;vec3 vSphericalZZ;vec3 vSphericalXY;vec3 vSphericalYZ;vec3 vSphericalZX;float vBaseWeight;vec4 vBaseColor;float vBaseDiffuseRoughness;vec4 vReflectanceInfo;vec4 vSpecularColor;vec3 vSpecularAnisotropy;float vTransmissionWeight;vec3 vTransmissionColor;float vTransmissionDepth;vec3 vTransmissionScatter;float vTransmissionScatterAnisotropy;float vTransmissionDispersionScale;float vTransmissionDispersionAbbeNumber;float vSubsurfaceWeight;vec3 vSubsurfaceColor;float vSubsurfaceRadius;vec3 vSubsurfaceRadiusScale;float vSubsurfaceScatterAnisotropy;float vCoatWeight;vec3 vCoatColor;float vCoatRoughness;float vCoatRoughnessAnisotropy;float vCoatIor;float vCoatDarkening;float vFuzzWeight;vec3 vFuzzColor;float vFuzzRoughness;float vGeometryThinWalled;vec2 vGeometryCoatTangent;float vGeometryThickness;vec3 vEmissionColor;float vThinFilmWeight;vec2 vThinFilmThickness;float vThinFilmIor;vec2 vBaseWeightInfos;mat4 baseWeightMatrix;vec2 vBaseColorInfos;mat4 baseColorMatrix;vec2 vBaseDiffuseRoughnessInfos;mat4 baseDiffuseRoughnessMatrix;vec2 vBaseMetalnessInfos;mat4 baseMetalnessMatrix;vec2 vSpecularWeightInfos;mat4 specularWeightMatrix;vec2 vSpecularColorInfos;mat4 specularColorMatrix;vec2 vSpecularRoughnessInfos;mat4 specularRoughnessMatrix;vec2 vSpecularRoughnessAnisotropyInfos;mat4 specularRoughnessAnisotropyMatrix;vec2 vTransmissionWeightInfos;mat4 transmissionWeightMatrix;vec2 vTransmissionColorInfos;mat4 transmissionColorMatrix;vec2 vTransmissionDepthInfos;mat4 transmissionDepthMatrix;vec2 vTransmissionScatterInfos;mat4 transmissionScatterMatrix;vec2 vTransmissionDispersionScaleInfos;mat4 transmissionDispersionScaleMatrix;vec2 vSubsurfaceWeightInfos;mat4 subsurfaceWeightMatrix;vec2 vSubsurfaceColorInfos;mat4 subsurfaceColorMatrix;vec2 vSubsurfaceRadiusScaleInfos;mat4 subsurfaceRadiusScaleMatrix;vec2 vCoatWeightInfos;mat4 coatWeightMatrix;vec2 vCoatColorInfos;mat4 coatColorMatrix;vec2 vCoatRoughnessInfos;mat4 coatRoughnessMatrix;vec2 vCoatRoughnessAnisotropyInfos;mat4 coatRoughnessAnisotropyMatrix;vec2 vCoatDarkeningInfos;mat4 coatDarkeningMatrix;vec2 vFuzzWeightInfos;mat4 fuzzWeightMatrix;vec2 vFuzzColorInfos;mat4 fuzzColorMatrix;vec2 vFuzzRoughnessInfos;mat4 fuzzRoughnessMatrix;vec2 vGeometryNormalInfos;mat4 geometryNormalMatrix;vec2 vGeometryTangentInfos;mat4 geometryTangentMatrix;vec2 vGeometryCoatNormalInfos;mat4 geometryCoatNormalMatrix;vec2 vGeometryCoatTangentInfos;mat4 geometryCoatTangentMatrix;vec2 vGeometryOpacityInfos;mat4 geometryOpacityMatrix;vec2 vGeometryThicknessInfos;mat4 geometryThicknessMatrix;vec2 vEmissionColorInfos;mat4 emissionColorMatrix;vec2 vThinFilmWeightInfos;mat4 thinFilmWeightMatrix;vec2 vThinFilmThicknessInfos;mat4 thinFilmThicknessMatrix;vec2 vAmbientOcclusionInfos;mat4 ambientOcclusionMatrix; +`;T.IncludesShadersStore[i8]||(T.IncludesShadersStore[i8]=kfe)});var n8,Wfe,CL=C(()=>{k();rd();Ng();n8="openpbrUboDeclaration",Wfe=`layout(std140,column_major) uniform;uniform Material {vec2 vTangentSpaceParams;vec4 vLightingIntensity;float pointSize;vec2 vDebugMode;vec2 renderTargetSize;vec4 cameraInfo;mat4 backgroundRefractionMatrix;vec3 vBackgroundRefractionInfos;vec2 vReflectionInfos;mat4 reflectionMatrix;vec3 vReflectionMicrosurfaceInfos;vec3 vReflectionPosition;vec3 vReflectionSize;vec2 vReflectionFilteringInfo;vec3 vReflectionDominantDirection;vec3 vReflectionColor;vec3 vSphericalL00;vec3 vSphericalL1_1;vec3 vSphericalL10;vec3 vSphericalL11;vec3 vSphericalL2_2;vec3 vSphericalL2_1;vec3 vSphericalL20;vec3 vSphericalL21;vec3 vSphericalL22;vec3 vSphericalX;vec3 vSphericalY;vec3 vSphericalZ;vec3 vSphericalXX_ZZ;vec3 vSphericalYY_ZZ;vec3 vSphericalZZ;vec3 vSphericalXY;vec3 vSphericalYZ;vec3 vSphericalZX;float vBaseWeight;vec4 vBaseColor;float vBaseDiffuseRoughness;vec4 vReflectanceInfo;vec4 vSpecularColor;vec3 vSpecularAnisotropy;float vTransmissionWeight;vec3 vTransmissionColor;float vTransmissionDepth;vec3 vTransmissionScatter;float vTransmissionScatterAnisotropy;float vTransmissionDispersionScale;float vTransmissionDispersionAbbeNumber;float vSubsurfaceWeight;vec3 vSubsurfaceColor;float vSubsurfaceRadius;vec3 vSubsurfaceRadiusScale;float vSubsurfaceScatterAnisotropy;float vCoatWeight;vec3 vCoatColor;float vCoatRoughness;float vCoatRoughnessAnisotropy;float vCoatIor;float vCoatDarkening;float vFuzzWeight;vec3 vFuzzColor;float vFuzzRoughness;float vGeometryThinWalled;vec2 vGeometryCoatTangent;float vGeometryThickness;vec3 vEmissionColor;float vThinFilmWeight;vec2 vThinFilmThickness;float vThinFilmIor;vec2 vBaseWeightInfos;mat4 baseWeightMatrix;vec2 vBaseColorInfos;mat4 baseColorMatrix;vec2 vBaseDiffuseRoughnessInfos;mat4 baseDiffuseRoughnessMatrix;vec2 vBaseMetalnessInfos;mat4 baseMetalnessMatrix;vec2 vSpecularWeightInfos;mat4 specularWeightMatrix;vec2 vSpecularColorInfos;mat4 specularColorMatrix;vec2 vSpecularRoughnessInfos;mat4 specularRoughnessMatrix;vec2 vSpecularRoughnessAnisotropyInfos;mat4 specularRoughnessAnisotropyMatrix;vec2 vTransmissionWeightInfos;mat4 transmissionWeightMatrix;vec2 vTransmissionColorInfos;mat4 transmissionColorMatrix;vec2 vTransmissionDepthInfos;mat4 transmissionDepthMatrix;vec2 vTransmissionScatterInfos;mat4 transmissionScatterMatrix;vec2 vTransmissionDispersionScaleInfos;mat4 transmissionDispersionScaleMatrix;vec2 vSubsurfaceWeightInfos;mat4 subsurfaceWeightMatrix;vec2 vSubsurfaceColorInfos;mat4 subsurfaceColorMatrix;vec2 vSubsurfaceRadiusScaleInfos;mat4 subsurfaceRadiusScaleMatrix;vec2 vCoatWeightInfos;mat4 coatWeightMatrix;vec2 vCoatColorInfos;mat4 coatColorMatrix;vec2 vCoatRoughnessInfos;mat4 coatRoughnessMatrix;vec2 vCoatRoughnessAnisotropyInfos;mat4 coatRoughnessAnisotropyMatrix;vec2 vCoatDarkeningInfos;mat4 coatDarkeningMatrix;vec2 vFuzzWeightInfos;mat4 fuzzWeightMatrix;vec2 vFuzzColorInfos;mat4 fuzzColorMatrix;vec2 vFuzzRoughnessInfos;mat4 fuzzRoughnessMatrix;vec2 vGeometryNormalInfos;mat4 geometryNormalMatrix;vec2 vGeometryTangentInfos;mat4 geometryTangentMatrix;vec2 vGeometryCoatNormalInfos;mat4 geometryCoatNormalMatrix;vec2 vGeometryCoatTangentInfos;mat4 geometryCoatTangentMatrix;vec2 vGeometryOpacityInfos;mat4 geometryOpacityMatrix;vec2 vGeometryThicknessInfos;mat4 geometryThicknessMatrix;vec2 vEmissionColorInfos;mat4 emissionColorMatrix;vec2 vThinFilmWeightInfos;mat4 thinFilmWeightMatrix;vec2 vThinFilmThicknessInfos;mat4 thinFilmThicknessMatrix;vec2 vAmbientOcclusionInfos;mat4 ambientOcclusionMatrix; #define ADDITIONAL_UBO_DECLARATION }; #include #include -`;T.IncludesShadersStore[n8]||(T.IncludesShadersStore[n8]=Wfe)});var s8,Hfe,a8=C(()=>{W();s8="openpbrNormalMapVertexDeclaration",Hfe=`#if defined(GEOMETRY_NORMAL) || defined(PARALLAX) || defined(GEOMETRY_COAT_NORMAL) || defined(ANISOTROPIC) || defined(FUZZ) +`;T.IncludesShadersStore[n8]||(T.IncludesShadersStore[n8]=Wfe)});var s8,Hfe,a8=C(()=>{k();s8="openpbrNormalMapVertexDeclaration",Hfe=`#if defined(GEOMETRY_NORMAL) || defined(PARALLAX) || defined(GEOMETRY_COAT_NORMAL) || defined(ANISOTROPIC) || defined(FUZZ) #if defined(TANGENT) && defined(NORMAL) varying mat3 vTBN; #endif #endif -`;T.IncludesShadersStore[s8]||(T.IncludesShadersStore[s8]=Hfe)});var o8,zfe,l8=C(()=>{W();o8="openpbrNormalMapVertex",zfe=`#if defined(GEOMETRY_NORMAL) || defined(PARALLAX) || defined(GEOMETRY_COAT_NORMAL) || defined(ANISOTROPIC) || defined(FUZZ) +`;T.IncludesShadersStore[s8]||(T.IncludesShadersStore[s8]=Hfe)});var o8,zfe,l8=C(()=>{k();o8="openpbrNormalMapVertex",zfe=`#if defined(GEOMETRY_NORMAL) || defined(PARALLAX) || defined(GEOMETRY_COAT_NORMAL) || defined(ANISOTROPIC) || defined(FUZZ) #if defined(TANGENT) && defined(NORMAL) vec3 tbnNormal=normalize(normalUpdated);vec3 tbnTangent=normalize(tangentUpdated.xyz);vec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;vTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal); #endif #endif -`;T.IncludesShadersStore[o8]||(T.IncludesShadersStore[o8]=zfe)});var f8={};tt(f8,{openpbrVertexShader:()=>Xfe});var yL,c8,Xfe,h8=C(()=>{W();r8();CL();Rx();Zm();ya();rp();dc();uc();Ff();bx();Ix();np();a8();mc();Ag();Mx();Cx();Wf();Hf();nd();zf();Xf();pc();_c();gc();yx();Px();Dx();l8();vc();xg();Ox();Rg();Nx();yL="openpbrVertexShader",c8=`#define OPENPBR_VERTEX_SHADER +`;T.IncludesShadersStore[o8]||(T.IncludesShadersStore[o8]=zfe)});var f8={};tt(f8,{openpbrVertexShader:()=>Xfe});var yL,c8,Xfe,h8=C(()=>{k();r8();CL();bx();qm();Ca();ip();hc();dc();wf();Ix();Mx();rp();a8();uc();Ag();Cx();yx();kf();Wf();nd();Hf();zf();mc();pc();_c();Px();Dx();Lx();l8();gc();xg();Nx();Rg();wx();yL="openpbrVertexShader",c8=`#define OPENPBR_VERTEX_SHADER #define CUSTOM_VERTEX_EXTENSION precision highp float; #include<__decl__openpbrVertex> @@ -15435,7 +15435,7 @@ gl_PointSize=pointSize; #include #define CUSTOM_VERTEX_MAIN_END } -`;T.ShadersStore[yL]||(T.ShadersStore[yL]=c8);Xfe={name:yL,shader:c8}});var d8,Yfe,u8=C(()=>{W();qD();wx();d8="openpbrFragmentDeclaration",Yfe=`uniform float vBaseWeight;uniform vec4 vBaseColor;uniform float vBaseDiffuseRoughness;uniform vec4 vReflectanceInfo;uniform vec4 vSpecularColor;uniform vec3 vSpecularAnisotropy;uniform float vTransmissionWeight;uniform vec3 vTransmissionColor;uniform float vTransmissionDepth;uniform vec3 vTransmissionScatter;uniform float vTransmissionScatterAnisotropy;uniform float vTransmissionDispersionScale;uniform float vTransmissionDispersionAbbeNumber;uniform float vSubsurfaceWeight;uniform vec3 vSubsurfaceColor;uniform float vSubsurfaceRadius;uniform vec3 vSubsurfaceRadiusScale;uniform float vSubsurfaceScatterAnisotropy;uniform float vCoatWeight;uniform vec3 vCoatColor;uniform float vCoatRoughness;uniform float vCoatRoughnessAnisotropy;uniform float vCoatIor;uniform float vCoatDarkening;uniform float vFuzzWeight;uniform vec3 vFuzzColor;uniform float vFuzzRoughness;uniform vec2 vGeometryCoatTangent;uniform float vGeometryThickness;uniform vec3 vEmissionColor;uniform float vThinFilmWeight;uniform vec2 vThinFilmThickness;uniform float vThinFilmIor;uniform float vGeometryThinWalled;uniform vec4 vLightingIntensity;uniform float visibility;uniform vec2 renderTargetSize; +`;T.ShadersStore[yL]||(T.ShadersStore[yL]=c8);Xfe={name:yL,shader:c8}});var d8,Yfe,u8=C(()=>{k();qD();Fx();d8="openpbrFragmentDeclaration",Yfe=`uniform float vBaseWeight;uniform vec4 vBaseColor;uniform float vBaseDiffuseRoughness;uniform vec4 vReflectanceInfo;uniform vec4 vSpecularColor;uniform vec3 vSpecularAnisotropy;uniform float vTransmissionWeight;uniform vec3 vTransmissionColor;uniform float vTransmissionDepth;uniform vec3 vTransmissionScatter;uniform float vTransmissionScatterAnisotropy;uniform float vTransmissionDispersionScale;uniform float vTransmissionDispersionAbbeNumber;uniform float vSubsurfaceWeight;uniform vec3 vSubsurfaceColor;uniform float vSubsurfaceRadius;uniform vec3 vSubsurfaceRadiusScale;uniform float vSubsurfaceScatterAnisotropy;uniform float vCoatWeight;uniform vec3 vCoatColor;uniform float vCoatRoughness;uniform float vCoatRoughnessAnisotropy;uniform float vCoatIor;uniform float vCoatDarkening;uniform float vFuzzWeight;uniform vec3 vFuzzColor;uniform float vFuzzRoughness;uniform vec2 vGeometryCoatTangent;uniform float vGeometryThickness;uniform vec3 vEmissionColor;uniform float vThinFilmWeight;uniform vec2 vThinFilmThickness;uniform float vThinFilmIor;uniform float vGeometryThinWalled;uniform vec4 vLightingIntensity;uniform float visibility;uniform vec2 renderTargetSize; #ifdef BASE_COLOR uniform vec2 vBaseColorInfos; #endif @@ -15584,7 +15584,7 @@ uniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;unifo uniform mat4 backgroundRefractionMatrix;uniform vec3 vBackgroundRefractionInfos; #endif #define ADDITIONAL_FRAGMENT_DECLARATION -`;T.IncludesShadersStore[d8]||(T.IncludesShadersStore[d8]=Yfe)});var m8,Kfe,PL=C(()=>{W();Zm();m8="pbrFragmentExtraDeclaration",Kfe=`varying vec3 vPositionW; +`;T.IncludesShadersStore[d8]||(T.IncludesShadersStore[d8]=Yfe)});var m8,Kfe,PL=C(()=>{k();qm();m8="pbrFragmentExtraDeclaration",Kfe=`varying vec3 vPositionW; #if DEBUGMODE>0 varying vec4 vClipSpacePosition; #endif @@ -15601,7 +15601,7 @@ varying vec4 vColor; #if defined(CLUSTLIGHT_BATCH) && CLUSTLIGHT_BATCH>0 varying float vViewDepth; #endif -`;T.IncludesShadersStore[m8]||(T.IncludesShadersStore[m8]=Kfe)});var p8,jfe,_8=C(()=>{W();sd();TR();p8="openpbrFragmentSamplersDeclaration",jfe=`#include(_DEFINENAME_,BASE_COLOR,_VARYINGNAME_,BaseColor,_SAMPLERNAME_,baseColor) +`;T.IncludesShadersStore[m8]||(T.IncludesShadersStore[m8]=Kfe)});var p8,jfe,_8=C(()=>{k();sd();AR();p8="openpbrFragmentSamplersDeclaration",jfe=`#include(_DEFINENAME_,BASE_COLOR,_VARYINGNAME_,BaseColor,_SAMPLERNAME_,baseColor) #include(_DEFINENAME_,BASE_WEIGHT,_VARYINGNAME_,BaseWeight,_SAMPLERNAME_,baseWeight) #include(_DEFINENAME_,BASE_DIFFUSE_ROUGHNESS,_VARYINGNAME_,BaseDiffuseRoughness,_SAMPLERNAME_,baseDiffuseRoughness) #include(_DEFINENAME_,BASE_METALNESS,_VARYINGNAME_,BaseMetalness,_SAMPLERNAME_,baseMetalness) @@ -15653,15 +15653,15 @@ uniform sampler2D blueNoiseSampler; #ifdef IBL_CDF_FILTERING uniform sampler2D icdfSampler; #endif -`;T.IncludesShadersStore[p8]||(T.IncludesShadersStore[p8]=jfe)});var g8,qfe,DL=C(()=>{W();g8="subSurfaceScatteringFunctions",qfe=`bool testLightingForSSS(float diffusionProfile) -{return diffusionProfile<1.;}`;T.IncludesShadersStore[g8]||(T.IncludesShadersStore[g8]=qfe)});var v8,Zfe,LL=C(()=>{W();v8="importanceSampling",Zfe=`vec3 hemisphereCosSample(vec2 u) {float phi=2.*PI*u.x;float cosTheta2=1.-u.y;float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);} +`;T.IncludesShadersStore[p8]||(T.IncludesShadersStore[p8]=jfe)});var g8,qfe,DL=C(()=>{k();g8="subSurfaceScatteringFunctions",qfe=`bool testLightingForSSS(float diffusionProfile) +{return diffusionProfile<1.;}`;T.IncludesShadersStore[g8]||(T.IncludesShadersStore[g8]=qfe)});var v8,Zfe,LL=C(()=>{k();v8="importanceSampling",Zfe=`vec3 hemisphereCosSample(vec2 u) {float phi=2.*PI*u.x;float cosTheta2=1.-u.y;float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);} vec3 hemisphereImportanceSampleDggx(vec2 u,float a) {float phi=2.*PI*u.x;float cosTheta2=(1.-u.y)/(1.+(a+1.)*((a-1.)*u.y));float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);} vec3 hemisphereImportanceSampleDggxAnisotropic(vec2 Xi,float alphaTangent,float alphaBitangent) {alphaTangent=max(alphaTangent,0.0001);alphaBitangent=max(alphaBitangent,0.0001);float phi=atan(alphaBitangent/alphaTangent*tan(2.0*3.14159265*Xi.x));if (Xi.x>0.5) phi+=3.14159265; float cosPhi=cos(phi);float sinPhi=sin(phi);float alpha2=(cosPhi*cosPhi)/(alphaTangent*alphaTangent) + (sinPhi*sinPhi)/(alphaBitangent*alphaBitangent);float tanTheta2=Xi.y/(1.0-Xi.y)/alpha2;float cosTheta=1.0/sqrt(1.0+tanTheta2);float sinTheta=sqrt(max(0.0,1.0-cosTheta*cosTheta));return vec3(sinTheta*cosPhi,sinTheta*sinPhi,cosTheta);} vec3 hemisphereImportanceSampleDCharlie(vec2 u,float a) { -float phi=2.*PI*u.x;float sinTheta=pow(u.y,a/(2.*a+1.));float cosTheta=sqrt(1.-sinTheta*sinTheta);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}`;T.IncludesShadersStore[v8]||(T.IncludesShadersStore[v8]=Zfe)});var E8,Qfe,OL=C(()=>{W();E8="pbrHelperFunctions",Qfe=`#define MINIMUMVARIANCE 0.0005 +float phi=2.*PI*u.x;float sinTheta=pow(u.y,a/(2.*a+1.));float cosTheta=sqrt(1.-sinTheta*sinTheta);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}`;T.IncludesShadersStore[v8]||(T.IncludesShadersStore[v8]=Zfe)});var E8,Qfe,OL=C(()=>{k();E8="pbrHelperFunctions",Qfe=`#define MINIMUMVARIANCE 0.0005 float convertRoughnessToAverageSlope(float roughness) {return square(roughness)+MINIMUMVARIANCE;} float fresnelGrazingReflectance(float reflectance0) {float reflectance90=saturate(reflectance0*25.0);return reflectance90;} @@ -15696,7 +15696,7 @@ clearCoatIntensity);return clearCoatAbsorption;} float computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor) {const float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;float reflectivityLuminance=getLuminance(reflectivityColor);float reflectivityLuma=sqrt(reflectivityLuminance);microSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;return microSurface;} #endif -`;T.IncludesShadersStore[E8]||(T.IncludesShadersStore[E8]=Qfe)});var S8,$fe,NL=C(()=>{W();FP();S8="pbrDirectLightingSetupFunctions",$fe=`struct preLightingInfo +`;T.IncludesShadersStore[E8]||(T.IncludesShadersStore[E8]=Qfe)});var S8,$fe,NL=C(()=>{k();FP();S8="pbrDirectLightingSetupFunctions",$fe=`struct preLightingInfo {vec3 lightOffset;float lightDistanceSquared;float lightDistance;float attenuation;vec3 L;vec3 H;float NdotV;float NdotLUnclamped;float NdotL;float VdotH;float LdotV;float roughness;float diffuseRoughness;vec3 surfaceAlbedo; #ifdef IRIDESCENCE float iridescenceIntensity; @@ -15729,7 +15729,7 @@ result.areaLightFresnel=data.Fresnel;result.areaLightSpecular=data.Specular; #endif result.areaLightDiffuse=data.Diffuse;result.LdotV=0.;result.roughness=0.;result.diffuseRoughness=0.;result.surfaceAlbedo=vec3(0.);return result;} #endif -`;T.IncludesShadersStore[S8]||(T.IncludesShadersStore[S8]=$fe)});var T8,Jfe,wL=C(()=>{W();T8="pbrDirectLightingFalloffFunctions",Jfe=`float computeDistanceLightFalloff_Standard(vec3 lightOffset,float range) +`;T.IncludesShadersStore[S8]||(T.IncludesShadersStore[S8]=$fe)});var T8,Jfe,wL=C(()=>{k();T8="pbrDirectLightingFalloffFunctions",Jfe=`float computeDistanceLightFalloff_Standard(vec3 lightOffset,float range) {return max(0.,1.0-length(lightOffset)/range);} float computeDistanceLightFalloff_Physical(float lightDistanceSquared) {return 1.0/maxEps(lightDistanceSquared);} @@ -15765,7 +15765,7 @@ return computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenter #else return computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent); #endif -}`;T.IncludesShadersStore[T8]||(T.IncludesShadersStore[T8]=Jfe)});var A8,ehe,FL=C(()=>{W();A8="hdrFilteringFunctions",ehe=`#if NUM_SAMPLES +}`;T.IncludesShadersStore[T8]||(T.IncludesShadersStore[T8]=Jfe)});var A8,ehe,FL=C(()=>{k();A8="hdrFilteringFunctions",ehe=`#if NUM_SAMPLES #if NUM_SAMPLES>0 #if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) float radicalInverse_VdC(uint bits) @@ -15910,7 +15910,7 @@ result=result/weight;return result;} #endif #endif #endif -`;T.IncludesShadersStore[A8]||(T.IncludesShadersStore[A8]=ehe)});var x8,the,BL=C(()=>{W();x8="pbrDirectLightingFunctions",the=`#define CLEARCOATREFLECTANCE90 1.0 +`;T.IncludesShadersStore[A8]||(T.IncludesShadersStore[A8]=ehe)});var x8,the,BL=C(()=>{k();x8="pbrDirectLightingFunctions",the=`#define CLEARCOATREFLECTANCE90 1.0 struct lightingInfo {vec3 diffuse; #ifdef SS_TRANSLUCENCY @@ -16016,7 +16016,7 @@ float visibility=visibility_CharlieSheen(info.NdotL,info.NdotV,alphaG); float visibility=visibility_Ashikhmin(info.NdotL,info.NdotV);/* #endif */ float sheenTerm=fresnel*distribution*visibility;return sheenTerm*info.attenuation*info.NdotL*lightColor;} #endif -`;T.IncludesShadersStore[x8]||(T.IncludesShadersStore[x8]=the)});var R8,ihe,b8=C(()=>{W();R8="openpbrNormalMapFragmentMainFunctions",ihe=`#if defined(GEOMETRY_NORMAL) || defined(GEOMETRY_COAT_NORMAL) || defined(ANISOTROPIC) || defined(FUZZ) || defined(DETAIL) +`;T.IncludesShadersStore[x8]||(T.IncludesShadersStore[x8]=the)});var R8,ihe,b8=C(()=>{k();R8="openpbrNormalMapFragmentMainFunctions",ihe=`#if defined(GEOMETRY_NORMAL) || defined(GEOMETRY_COAT_NORMAL) || defined(ANISOTROPIC) || defined(FUZZ) || defined(DETAIL) #if defined(TANGENT) && defined(NORMAL) varying mat3 vTBN; #endif @@ -16077,7 +16077,7 @@ vec3 perturbNormal(mat3 cotangentFrame,vec3 textureSample,float scale) mat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv,vec2 tangentSpaceParams) {vec3 dp1=dFdx(p);vec3 dp2=dFdy(p);vec2 duv1=dFdx(uv);vec2 duv2=dFdy(uv);vec3 dp2perp=cross(dp2,normal);vec3 dp1perp=cross(normal,dp1);vec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;vec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;tangent*=tangentSpaceParams.x;bitangent*=tangentSpaceParams.y;float det=max(dot(tangent,tangent),dot(bitangent,bitangent));float invmax=det==0.0 ? 0.0 : inversesqrt(det);return mat3(tangent*invmax,bitangent*invmax,normal);} #endif -`;T.IncludesShadersStore[R8]||(T.IncludesShadersStore[R8]=ihe)});var I8,rhe,M8=C(()=>{W();sd();I8="openpbrNormalMapFragmentFunctions",rhe=`#if defined(GEOMETRY_NORMAL) +`;T.IncludesShadersStore[R8]||(T.IncludesShadersStore[R8]=ihe)});var I8,rhe,M8=C(()=>{k();sd();I8="openpbrNormalMapFragmentFunctions",rhe=`#if defined(GEOMETRY_NORMAL) #include(_DEFINENAME_,GEOMETRY_NORMAL,_VARYINGNAME_,GeometryNormal,_SAMPLERNAME_,geometryNormal) #endif #if defined(GEOMETRY_COAT_NORMAL) @@ -16110,7 +16110,7 @@ return -texCoordOffset; #endif } #endif -`;T.IncludesShadersStore[I8]||(T.IncludesShadersStore[I8]=rhe)});var C8,nhe,y8=C(()=>{W();C8="openpbrConductorReflectance",nhe=`#define pbr_inline +`;T.IncludesShadersStore[I8]||(T.IncludesShadersStore[I8]=rhe)});var C8,nhe,y8=C(()=>{k();C8="openpbrConductorReflectance",nhe=`#define pbr_inline ReflectanceParams conductorReflectance(in vec3 baseColor,in vec3 specularColor,in float specularWeight) {ReflectanceParams outParams; #if (CONDUCTOR_SPECULAR_MODEL==CONDUCTOR_SPECULAR_MODEL_OPENPBR) @@ -16118,9 +16118,9 @@ outParams.coloredF0=baseColor*specularWeight;outParams.coloredF90=specularColor* #else outParams.coloredF0=baseColor;outParams.coloredF90=vec3(1.0); #endif -outParams.F0=1.0;outParams.F90=1.0;return outParams;}`;T.IncludesShadersStore[C8]||(T.IncludesShadersStore[C8]=nhe)});var P8,she,D8=C(()=>{W();P8="openpbrAmbientOcclusionFunctions",she=`float compute_specular_occlusion(const float n_dot_v,const float metallic,const float ambient_occlusion,const float roughness) +outParams.F0=1.0;outParams.F90=1.0;return outParams;}`;T.IncludesShadersStore[C8]||(T.IncludesShadersStore[C8]=nhe)});var P8,she,D8=C(()=>{k();P8="openpbrAmbientOcclusionFunctions",she=`float compute_specular_occlusion(const float n_dot_v,const float metallic,const float ambient_occlusion,const float roughness) {float specular_occlusion=saturate(pow(n_dot_v+ambient_occlusion,exp2(-16.0*roughness-1.0))-1.0+ambient_occlusion);return mix(specular_occlusion,1.0,metallic*square(1.0-roughness));} -`;T.IncludesShadersStore[P8]||(T.IncludesShadersStore[P8]=she)});var L8,ahe,O8=C(()=>{W();L8="openpbrVolumeFunctions",ahe=`struct OpenPBRHomogeneousVolume {vec3 extinction_coeff; +`;T.IncludesShadersStore[P8]||(T.IncludesShadersStore[P8]=she)});var L8,ahe,O8=C(()=>{k();L8="openpbrVolumeFunctions",ahe=`struct OpenPBRHomogeneousVolume {vec3 extinction_coeff; vec3 ss_albedo; vec3 multi_scatter_color; vec3 absorption_coeff; @@ -16176,7 +16176,7 @@ float filter_samples_scale=samples_scale(pixels_to_projective(overscan_size_in_p {vec3 weights=sss_irradiance.a/sss_samples_pdf(icdf,dz)*sss_pdf(dist,d.rgb);irradiance_sum+=weights*sss_irradiance.rgb;weight_sum+=weights;}} return vec3(weight_sum.r<1e-5f ? unconvolved_irradiance.r : irradiance_sum.r/weight_sum.r, weight_sum.g<1e-5f ? unconvolved_irradiance.g : irradiance_sum.g/weight_sum.g, -weight_sum.b<1e-5f ? unconvolved_irradiance.b : irradiance_sum.b/weight_sum.b);}`;T.IncludesShadersStore[L8]||(T.IncludesShadersStore[L8]=ahe)});var N8,ohe,UL=C(()=>{W();N8="pbrBlockNormalGeometric",ohe=`vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW); +weight_sum.b<1e-5f ? unconvolved_irradiance.b : irradiance_sum.b/weight_sum.b);}`;T.IncludesShadersStore[L8]||(T.IncludesShadersStore[L8]=ahe)});var N8,ohe,UL=C(()=>{k();N8="pbrBlockNormalGeometric",ohe=`vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW); #ifdef NORMAL vec3 normalW=normalize(vNormalW); #else @@ -16186,7 +16186,7 @@ vec3 geometricNormalW=normalW; #if defined(TWOSIDEDLIGHTING) && defined(NORMAL) geometricNormalW=gl_FrontFacing ? geometricNormalW : -geometricNormalW; #endif -`;T.IncludesShadersStore[N8]||(T.IncludesShadersStore[N8]=ohe)});var w8,lhe,F8=C(()=>{W();w8="openpbrNormalMapFragment",lhe=`vec2 uvOffset=vec2(0.0,0.0); +`;T.IncludesShadersStore[N8]||(T.IncludesShadersStore[N8]=ohe)});var w8,lhe,F8=C(()=>{k();w8="openpbrNormalMapFragment",lhe=`vec2 uvOffset=vec2(0.0,0.0); #if defined(GEOMETRY_NORMAL) || defined(GEOMETRY_COAT_NORMAL) || defined(PARALLAX) || defined(DETAIL) #ifdef NORMALXYSCALE float normalScale=1.0; @@ -16241,7 +16241,7 @@ normalW=perturbNormalBase(TBN,blendedNormal,vGeometryNormalInfos.y); #elif defined(DETAIL) detailNormal.xy*=vDetailInfos.z;normalW=perturbNormalBase(TBN,detailNormal,vDetailInfos.z); #endif -`;T.IncludesShadersStore[w8]||(T.IncludesShadersStore[w8]=lhe)});var B8,che,U8=C(()=>{W();B8="openpbrBlockNormalFinal",che=`#if defined(FORCENORMALFORWARD) && defined(NORMAL) +`;T.IncludesShadersStore[w8]||(T.IncludesShadersStore[w8]=lhe)});var B8,che,U8=C(()=>{k();B8="openpbrBlockNormalFinal",che=`#if defined(FORCENORMALFORWARD) && defined(NORMAL) vec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w; #if defined(TWOSIDEDLIGHTING) faceNormal=gl_FrontFacing ? faceNormal : -faceNormal; @@ -16255,7 +16255,7 @@ normalW=gl_FrontFacing ? -normalW : normalW;coatNormalW=gl_FrontFacing ? -coatNo normalW=gl_FrontFacing ? normalW : -normalW;coatNormalW=gl_FrontFacing ? coatNormalW : -coatNormalW; #endif #endif -`;T.IncludesShadersStore[B8]||(T.IncludesShadersStore[B8]=che)});var V8,fhe,G8=C(()=>{W();V8="openpbrBaseLayerData",fhe=`vec3 base_color=vec3(0.8);float base_metalness=0.0;float base_diffuse_roughness=0.0;float specular_weight=1.0;float specular_roughness=0.3;vec3 specular_color=vec3(1.0);float specular_roughness_anisotropy=0.0;float specular_ior=1.5;float alpha=1.0;vec2 geometry_tangent=vec2(1.0,0.0);float geometry_thickness=0.0; +`;T.IncludesShadersStore[B8]||(T.IncludesShadersStore[B8]=che)});var V8,fhe,G8=C(()=>{k();V8="openpbrBaseLayerData",fhe=`vec3 base_color=vec3(0.8);float base_metalness=0.0;float base_diffuse_roughness=0.0;float specular_weight=1.0;float specular_roughness=0.3;vec3 specular_color=vec3(1.0);float specular_roughness_anisotropy=0.0;float specular_ior=1.5;float alpha=1.0;vec2 geometry_tangent=vec2(1.0,0.0);float geometry_thickness=0.0; #ifdef BASE_WEIGHT vec4 baseWeightFromTexture=texture2D(baseWeightSampler,vBaseWeightUV+uvOffset); #endif @@ -16381,7 +16381,7 @@ float detailRoughness=mix(0.5,detailColor.b,vDetailInfos.w);float loLerp=mix(0., #ifdef USE_GLTF_STYLE_ANISOTROPY float baseAlpha=specular_roughness*specular_roughness;float roughnessT=mix(baseAlpha,1.0,specular_roughness_anisotropy*specular_roughness_anisotropy);float roughnessB=baseAlpha;specular_roughness_anisotropy=1.0-roughnessB/max(roughnessT,0.00001);specular_roughness=sqrt(roughnessT/sqrt(2.0/(1.0+(1.0-specular_roughness_anisotropy)*(1.0-specular_roughness_anisotropy)))); #endif -`;T.IncludesShadersStore[V8]||(T.IncludesShadersStore[V8]=fhe)});var k8,hhe,W8=C(()=>{W();k8="openpbrCoatLayerData",hhe=`float coat_weight=0.0;vec3 coat_color=vec3(1.0);float coat_roughness=0.0;float coat_roughness_anisotropy=0.0;float coat_ior=1.6;float coat_darkening=1.0;vec2 geometry_coat_tangent=vec2(1.0,0.0); +`;T.IncludesShadersStore[V8]||(T.IncludesShadersStore[V8]=fhe)});var k8,hhe,W8=C(()=>{k();k8="openpbrCoatLayerData",hhe=`float coat_weight=0.0;vec3 coat_color=vec3(1.0);float coat_roughness=0.0;float coat_roughness_anisotropy=0.0;float coat_ior=1.6;float coat_darkening=1.0;vec2 geometry_coat_tangent=vec2(1.0,0.0); #ifdef COAT_WEIGHT vec4 coatWeightFromTexture=texture2D(coatWeightSampler,vCoatWeightUV+uvOffset); #endif @@ -16433,7 +16433,7 @@ coat_darkening*=coatDarkeningFromTexture.r; #ifdef USE_GLTF_STYLE_ANISOTROPY float coatAlpha=coat_roughness*coat_roughness;float coatRoughnessT=mix(coatAlpha,1.0,coat_roughness_anisotropy*coat_roughness_anisotropy);float coatRoughnessB=coatAlpha;coat_roughness_anisotropy=1.0-coatRoughnessB/max(coatRoughnessT,0.00001);coat_roughness=sqrt(coatRoughnessT/sqrt(2.0/(1.0+(1.0-coat_roughness_anisotropy)*(1.0-coat_roughness_anisotropy)))); #endif -`;T.IncludesShadersStore[k8]||(T.IncludesShadersStore[k8]=hhe)});var H8,dhe,z8=C(()=>{W();H8="openpbrThinFilmLayerData",dhe=`#ifdef THIN_FILM +`;T.IncludesShadersStore[k8]||(T.IncludesShadersStore[k8]=hhe)});var H8,dhe,z8=C(()=>{k();H8="openpbrThinFilmLayerData",dhe=`#ifdef THIN_FILM float thin_film_weight=vThinFilmWeight;float thin_film_thickness=vThinFilmThickness.r*1000.0; float thin_film_ior=vThinFilmIor; #ifdef THIN_FILM_WEIGHT @@ -16450,7 +16450,7 @@ thin_film_thickness*=thinFilmThicknessFromTexture; #endif float thin_film_ior_scale=clamp(2.0f*abs(thin_film_ior-1.0f),0.0f,1.0f); #endif -`;T.IncludesShadersStore[H8]||(T.IncludesShadersStore[H8]=dhe)});var X8,uhe,Y8=C(()=>{W();X8="openpbrFuzzLayerData",uhe=`float fuzz_weight=0.0;vec3 fuzz_color=vec3(1.0);float fuzz_roughness=0.0; +`;T.IncludesShadersStore[H8]||(T.IncludesShadersStore[H8]=dhe)});var X8,uhe,Y8=C(()=>{k();X8="openpbrFuzzLayerData",uhe=`float fuzz_weight=0.0;vec3 fuzz_color=vec3(1.0);float fuzz_roughness=0.0; #ifdef FUZZ #ifdef FUZZ_WEIGHT vec4 fuzzWeightFromTexture=texture2D(fuzzWeightSampler,vFuzzWeightUV+uvOffset); @@ -16479,11 +16479,11 @@ fuzz_roughness*=fuzzRoughnessFromTexture.a; fuzz_roughness*=fuzzRoughnessFromTexture.r; #endif #endif -`;T.IncludesShadersStore[X8]||(T.IncludesShadersStore[X8]=uhe)});var K8,mhe,j8=C(()=>{W();K8="openpbrAmbientOcclusionData",mhe=`vec3 ambient_occlusion=vec3(1.0);float specular_ambient_occlusion=1.0;float coat_specular_ambient_occlusion=1.0; +`;T.IncludesShadersStore[X8]||(T.IncludesShadersStore[X8]=uhe)});var K8,mhe,j8=C(()=>{k();K8="openpbrAmbientOcclusionData",mhe=`vec3 ambient_occlusion=vec3(1.0);float specular_ambient_occlusion=1.0;float coat_specular_ambient_occlusion=1.0; #ifdef AMBIENT_OCCLUSION vec3 ambientOcclusionFromTexture=texture2D(ambientOcclusionSampler,vAmbientOcclusionUV+uvOffset).rgb;ambient_occlusion=vec3(ambientOcclusionFromTexture.r*vAmbientOcclusionInfos.y+(1.0-vAmbientOcclusionInfos.y)); #endif -`;T.IncludesShadersStore[K8]||(T.IncludesShadersStore[K8]=mhe)});var q8,phe,Z8=C(()=>{W();q8="openpbrBackgroundTransmission",phe=`vec4 slab_translucent_background=vec4(0.,0.,0.,1.); +`;T.IncludesShadersStore[K8]||(T.IncludesShadersStore[K8]=mhe)});var q8,phe,Z8=C(()=>{k();q8="openpbrBackgroundTransmission",phe=`vec4 slab_translucent_background=vec4(0.,0.,0.,1.); #ifdef REFRACTED_BACKGROUND {float refractionLOD=min(transmission_roughness,0.7)*vBackgroundRefractionInfos.x;float lodTexelSize=pow(2.0,refractionLOD-vBackgroundRefractionInfos.x); #ifdef DISPERSION @@ -16511,7 +16511,7 @@ vec2 noiseOffset=noise.xy*lodTexelSize;slab_translucent_background=texture2DLodE #endif } #endif -`;T.IncludesShadersStore[q8]||(T.IncludesShadersStore[q8]=phe)});var Q8,_he,$8=C(()=>{W();Q8="openpbrEnvironmentLighting",_he=`#if defined(REFLECTION) || defined(REFRACTED_BACKGROUND) +`;T.IncludesShadersStore[q8]||(T.IncludesShadersStore[q8]=phe)});var Q8,_he,$8=C(()=>{k();Q8="openpbrEnvironmentLighting",_he=`#if defined(REFLECTION) || defined(REFRACTED_BACKGROUND) vec3 coatAbsorption=vec3(1.0);float coatIblFresnel=0.0;if (coat_weight>0.0) {coatIblFresnel=computeDielectricIblFresnel(coatReflectance,coatGeoInfo.environmentBrdf);float hemisphere_avg_fresnel=coatReflectance.F0+0.5*(1.0-coatReflectance.F0);float averageReflectance=(coatIblFresnel+hemisphere_avg_fresnel)*0.5;float roughnessFactor=1.0-coat_roughness*0.5;averageReflectance*=roughnessFactor;float darkened_transmission=(1.0-averageReflectance)*(1.0-averageReflectance);darkened_transmission=mix(1.0,darkened_transmission,coat_darkening);float sin2=1.0-coatGeoInfo.NdotV*coatGeoInfo.NdotV;sin2=sin2/(coat_ior*coat_ior);float cos_t=sqrt(1.0-sin2);float coatPathLength=1.0/cos_t;vec3 colored_transmission=pow(coat_color,vec3(coatPathLength));coatAbsorption=mix(vec3(1.0),colored_transmission*darkened_transmission,coat_weight);} #endif #ifdef REFLECTION @@ -16793,7 +16793,7 @@ slab_translucent_base_ibl=slab_translucent_background.rgb*volume_absorption*tran #endif vec3 material_dielectric_base_ibl=mix(black,slab_translucent_base_ibl.rgb,surface_translucency_weight);vec3 material_dielectric_gloss_ibl=material_dielectric_base_ibl*(baseGeoInfo.NdotV);vec3 material_base_substrate_ibl=mix(material_dielectric_gloss_ibl,black,base_metalness);vec3 material_coated_base_ibl=layer(material_base_substrate_ibl,black,coatIblFresnel,coatAbsorption,vec3(1.0));material_surface_ibl=material_coated_base_ibl; #endif -`;T.IncludesShadersStore[Q8]||(T.IncludesShadersStore[Q8]=_he)});var J8,ghe,e6=C(()=>{W();J8="openpbrDirectLightingInit",ghe=`#ifdef LIGHT{X} +`;T.IncludesShadersStore[Q8]||(T.IncludesShadersStore[Q8]=_he)});var J8,ghe,e6=C(()=>{k();J8="openpbrDirectLightingInit",ghe=`#ifdef LIGHT{X} preLightingInfo preInfo{X};preLightingInfo preInfoCoat{X};vec4 lightColor{X}=light{X}.vLightDiffuse;float shadow{X}=1.; #if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}) #else @@ -16864,7 +16864,7 @@ preInfo{X}.roughness=adjustRoughnessFromLightProperties(specular_roughness,light preInfo{X}.diffuseRoughness=base_diffuse_roughness;preInfo{X}.surfaceAlbedo=base_color.rgb; #endif #endif -`;T.IncludesShadersStore[J8]||(T.IncludesShadersStore[J8]=ghe)});var t6,vhe,i6=C(()=>{W();t6="openpbrDirectLighting",vhe=`#ifdef LIGHT{X} +`;T.IncludesShadersStore[J8]||(T.IncludesShadersStore[J8]=ghe)});var t6,vhe,i6=C(()=>{k();t6="openpbrDirectLighting",vhe=`#ifdef LIGHT{X} {vec3 slab_diffuse=vec3(0.,0.,0.);vec3 slab_translucent=vec3(0.,0.,0.);vec3 slab_glossy=vec3(0.,0.,0.);float specularFresnel=0.0;vec3 specularColoredFresnel=vec3(0.,0.,0.);vec3 slab_metal=vec3(0.,0.,0.);vec3 slab_coat=vec3(0.,0.,0.);float coatFresnel=0.0;vec3 slab_fuzz=vec3(0.,0.,0.);float fuzzFresnel=0.0; #ifdef HEMILIGHT{X} slab_diffuse=computeHemisphericDiffuseLighting(preInfo{X},lightColor{X}.rgb,light{X}.vLightGround); @@ -17019,7 +17019,7 @@ total_direct_diffuse+=slab_diffuse; #endif vec3 material_dielectric_base=mix(slab_diffuse*base_color.rgb,slab_translucent,surface_translucency_weight);vec3 material_dielectric_gloss=material_dielectric_base*(1.0-specularFresnel)+slab_glossy*specularColoredFresnel;vec3 material_base_substrate=mix(material_dielectric_gloss,slab_metal,base_metalness);vec3 material_coated_base=layer(material_base_substrate,slab_coat,coatFresnel,coatAbsorption,vec3(1.0));material_surface_direct+=layer(material_coated_base,slab_fuzz,fuzzFresnel*fuzz_weight,vec3(1.0),fuzz_color);} #endif -`;T.IncludesShadersStore[t6]||(T.IncludesShadersStore[t6]=vhe)});var r6,Ehe,VL=C(()=>{W();r6="pbrBlockImageProcessing",Ehe=`#if defined(IMAGEPROCESSINGPOSTPROCESS) || defined(SS_SCATTERING) +`;T.IncludesShadersStore[t6]||(T.IncludesShadersStore[t6]=vhe)});var r6,Ehe,VL=C(()=>{k();r6="pbrBlockImageProcessing",Ehe=`#if defined(IMAGEPROCESSINGPOSTPROCESS) || defined(SS_SCATTERING) #if !defined(SKIPFINALCOLORCLAMP) finalColor.rgb=clamp(finalColor.rgb,0.,30.0); #endif @@ -17030,7 +17030,7 @@ finalColor.a*=visibility; #ifdef PREMULTIPLYALPHA finalColor.rgb*=finalColor.a; #endif -`;T.IncludesShadersStore[r6]||(T.IncludesShadersStore[r6]=Ehe)});var n6,She,s6=C(()=>{W();n6="openpbrBlockPrePass",She=`#if SCENE_MRT_COUNT>0 +`;T.IncludesShadersStore[r6]||(T.IncludesShadersStore[r6]=Ehe)});var n6,She,s6=C(()=>{k();n6="openpbrBlockPrePass",She=`#if SCENE_MRT_COUNT>0 float writeGeometryInfo=finalColor.a>ALPHATESTVALUE ? 1.0 : 0.0; #ifdef PREPASS_POSITION gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo); @@ -17096,7 +17096,7 @@ gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4( 0.0,0.0,0.0,1.0 )*writeGeometryInf #endif #endif #endif -`;T.IncludesShadersStore[n6]||(T.IncludesShadersStore[n6]=She)});var a6,The,GL=C(()=>{W();a6="pbrDebug",The=`#if DEBUGMODE>0 +`;T.IncludesShadersStore[n6]||(T.IncludesShadersStore[n6]=She)});var a6,The,GL=C(()=>{k();a6="pbrDebug",The=`#if DEBUGMODE>0 if (vClipSpacePosition.x/vClipSpacePosition.w>=vDebugMode.x) { #if DEBUGMODE==1 gl_FragColor.rgb=vPositionW.rgb; @@ -17280,7 +17280,7 @@ return; #endif } #endif -`;T.IncludesShadersStore[a6]||(T.IncludesShadersStore[a6]=The)});var l6={};tt(l6,{openpbrPixelShader:()=>Ahe});var kL,o6,Ahe,c6=C(()=>{W();Fx();Bx();u8();CL();PL();Ux();Vx();_8();kx();Ec();nd();bg();ya();DL();LL();OL();Wx();Gx();np();NL();wL();rp();FL();BL();AR();b8();M8();wg();ZD();y8();D8();QD();$D();O8();Sc();UL();F8();U8();G8();eL();JD();W8();z8();Y8();j8();Yx();Z8();$8();e6();i6();Kx();Ig();VL();s6();jx();GL();kL="openpbrPixelShader",o6=`#define OPENPBR_FRAGMENT_SHADER +`;T.IncludesShadersStore[a6]||(T.IncludesShadersStore[a6]=The)});var l6={};tt(l6,{openpbrPixelShader:()=>Ahe});var kL,o6,Ahe,c6=C(()=>{k();Bx();Ux();u8();CL();PL();Vx();Gx();_8();Wx();vc();nd();bg();Ca();DL();LL();OL();Hx();kx();rp();NL();wL();ip();FL();BL();xR();b8();M8();wg();ZD();y8();D8();QD();$D();O8();Ec();UL();F8();U8();G8();eL();JD();W8();z8();Y8();j8();Kx();Z8();$8();e6();i6();jx();Ig();VL();s6();qx();GL();kL="openpbrPixelShader",o6=`#define OPENPBR_FRAGMENT_SHADER #define CUSTOM_FRAGMENT_EXTENSION #if defined(GEOMETRY_NORMAL) || defined(GEOMETRY_COAT_NORMAL) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA) #extension GL_OES_standard_derivatives : enable @@ -17515,11 +17515,11 @@ if (fragDepth==nearestDepth) {frontColor.rgb+=finalColor.rgb*finalColor.a*alphaM #include #define CUSTOM_FRAGMENT_MAIN_END } -`;T.ShadersStore[kL]||(T.ShadersStore[kL]=o6);Ahe={name:kL,shader:o6}});var f6={};tt(f6,{OpenPBRMaterial:()=>Ne,OpenPBRMaterialDefines:()=>Kg});var op,bR,si,Ti,WL,HL,Kg,zL,Ne,h6=C(()=>{Gt();Ut();ER();zt();q_();Fr();Hi();Vn();Tr();Oa();jA();Lf();ol();_g();Un();Gi();qA();KA();Da();yt();ZA();QA();d5();Ve();$A();pg();so();bi();Z5();op={effect:null,subMesh:null},bR=class n{populateVectorFromLinkedProperties(e){let t=e.dimension[0];for(let i in this.linkedProperties){let r=this.linkedProperties[i],s=r.numComponents;if(tt-s){s==1?te.Error(`Float property ${r.name} has an offset that is too large.`):te.Error(`Vector${s} property ${r.name} won't fit in Vector${t} or has an offset that is too large.`);return}typeof r.value=="number"?n._tmpArray[r.targetUniformComponentOffset]=r.value:r.value.toArray(n._tmpArray,r.targetUniformComponentOffset)}e.fromArray(n._tmpArray)}constructor(e,t){this.linkedProperties={},this.firstLinkedKey="",this.name=e,this.numComponents=t}};bR._tmpArray=[0,0,0,0];si=class{constructor(e,t,i,r,s=0,a){this.targetUniformComponentNum=4,this.targetUniformComponentOffset=0,this.name=e,this.targetUniformName=i,this.defaultValue=t,this.value=t,this.targetUniformComponentNum=r,this.targetUniformComponentOffset=s,this.requiredDefine=a}get numComponents(){return typeof this.defaultValue=="number"?1:this.defaultValue.dimension[0]}},Ti=class{get samplerName(){return this.samplerPrefix+"Sampler"}get samplerInfoName(){return"v"+this.samplerPrefix.charAt(0).toUpperCase()+this.samplerPrefix.slice(1)+"Infos"}get samplerMatrixName(){return this.samplerPrefix+"Matrix"}constructor(e,t,i){this.value=null,this.samplerPrefix="",this.textureDefine="",this.name=e,this.samplerPrefix=t,this.textureDefine=i}},WL=class extends Km(Ym(xr)){},HL=class extends h5(WL){},Kg=class extends zm(HL){constructor(e){super(e),this.NUM_SAMPLES="0",this.REALTIME_FILTERING=!1,this.IBL_CDF_FILTERING=!1,this.LIGHTCOUNT=0,this.VERTEXCOLOR=!1,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.VERTEXALPHA=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHABLEND=!1,this.ALPHA_FROM_BASE_COLOR_TEXTURE=!1,this.ALPHATESTVALUE="0.5",this.PREMULTIPLYALPHA=!1,this.REFLECTIVITY_GAMMA=!1,this.REFLECTIVITYDIRECTUV=0,this.SPECULARTERM=!1,this.LODBASEDMICROSFURACE=!0,this.SPECULAR_ROUGHNESS_FROM_METALNESS_TEXTURE_GREEN=!1,this.BASE_METALNESS_FROM_METALNESS_TEXTURE_BLUE=!1,this.AOSTOREINMETALMAPRED=!1,this.SPECULAR_WEIGHT_IN_ALPHA=!1,this.SPECULAR_WEIGHT_FROM_SPECULAR_COLOR_TEXTURE=!1,this.SPECULAR_ROUGHNESS_ANISOTROPY_FROM_TANGENT_TEXTURE=!1,this.COAT_ROUGHNESS_FROM_GREEN_CHANNEL=!1,this.COAT_ROUGHNESS_ANISOTROPY_FROM_TANGENT_TEXTURE=!1,this.USE_GLTF_STYLE_ANISOTROPY=!1,this.THIN_FILM_THICKNESS_FROM_THIN_FILM_TEXTURE=!1,this.FUZZ_ROUGHNESS_FROM_TEXTURE_ALPHA=!1,this.GEOMETRY_THICKNESS_FROM_GREEN_CHANNEL=!1,this.ENVIRONMENTBRDF=!1,this.ENVIRONMENTBRDF_RGBD=!1,this.FUZZENVIRONMENTBRDF=!1,this.NORMAL=!1,this.TANGENT=!1,this.OBJECTSPACE_NORMALMAP=!1,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.NORMALXYSCALE=!0,this.ANISOTROPIC=!1,this.ANISOTROPIC_OPENPBR=!0,this.ANISOTROPIC_BASE=!1,this.ANISOTROPIC_COAT=!1,this.FUZZ_IBL_SAMPLES=6,this.REFRACTION_HIGH_QUALITY_BLUR=!1,this.FUZZ=!1,this.THIN_FILM=!1,this.IRIDESCENCE=!1,this.DISPERSION=!1,this.SCATTERING=!1,this.USE_IRRADIANCE_TEXTURE_FOR_SCATTERING=!1,this.SSS_SAMPLE_COUNT=16,this.USE_IRRADIANCE_TEXTURE_FOR_SCATTERING_GBUFFER=!1,this.TRANSMISSION_SLAB=!1,this.TRANSMISSION_SLAB_VOLUME=!1,this.SUBSURFACE_SLAB=!1,this.GEOMETRY_THIN_WALLED=!1,this.REFRACTED_BACKGROUND=!1,this.REFRACTED_LIGHTS=!1,this.REFRACTED_ENVIRONMENT=!1,this.REFRACTED_ENVIRONMENT_OPPOSITEZ=!1,this.REFRACTED_ENVIRONMENT_LOCAL_CUBE=!1,this.RADIANCEOCCLUSION=!1,this.HORIZONOCCLUSION=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.NONUNIFORMSCALING=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_POSITION=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.MORPHTARGETS_UV2=!1,this.MORPHTARGETS_COLOR=!1,this.MORPHTARGETTEXTURE_HASPOSITIONS=!1,this.MORPHTARGETTEXTURE_HASNORMALS=!1,this.MORPHTARGETTEXTURE_HASTANGENTS=!1,this.MORPHTARGETTEXTURE_HASUVS=!1,this.MORPHTARGETTEXTURE_HASUV2S=!1,this.MORPHTARGETTEXTURE_HASCOLORS=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.USEPHYSICALLIGHTFALLOFF=!1,this.USEGLTFLIGHTFALLOFF=!1,this.TWOSIDEDLIGHTING=!1,this.MIRRORED=!1,this.SHADOWFLOAT=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.LOGARITHMICDEPTH=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.AREALIGHTSUPPORTED=!0,this.FORCENORMALFORWARD=!1,this.SPECULARAA=!1,this.UNLIT=!1,this.DECAL_AFTER_DETAIL=!1,this.DEBUGMODE=0,this.USE_VERTEX_PULLING=!1,this.VERTEX_PULLING_USE_INDEX_BUFFER=!1,this.VERTEX_PULLING_INDEX_BUFFER_32BITS=!1,this.RIGHT_HANDED=!1,this.CLUSTLIGHT_SLICES=0,this.CLUSTLIGHT_BATCH=0,this.BRDF_V_HEIGHT_CORRELATED=!0,this.MS_BRDF_ENERGY_CONSERVATION=!0,this.SPHERICAL_HARMONICS=!0,this.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=!0,this.MIX_IBL_RADIANCE_WITH_IRRADIANCE=!0,this.LEGACY_SPECULAR_ENERGY_CONSERVATION=!1,this.BASE_DIFFUSE_MODEL=0,this.DIELECTRIC_SPECULAR_MODEL=1,this.CONDUCTOR_SPECULAR_MODEL=1,this.rebuild()}reset(){super.reset(),this.ALPHATESTVALUE="0.5",this.NORMALXYSCALE=!0}},zL=class extends jm(hl){},Ne=class n extends zL{get geometryTangentAngle(){return Math.atan2(this.geometryTangent.y,this.geometryTangent.x)}set geometryTangentAngle(e){this.geometryTangent=new we(Math.cos(e),Math.sin(e))}get geometryCoatTangentAngle(){return Math.atan2(this.geometryCoatTangent.y,this.geometryCoatTangent.x)}set geometryCoatTangentAngle(e){this.geometryCoatTangent=new we(Math.cos(e),Math.sin(e))}get sssQuality(){return this._sssQuality}set sssQuality(e){this._sssQuality!==e&&(this._sssQuality=e,this.markAsDirty(1))}get sssIrradianceTexture(){return this._sssIrradianceTexture}set sssIrradianceTexture(e){this._sssIrradianceTexture!==e&&(this._sssIrradianceTexture=e,this._markAllSubMeshesAsTexturesDirty())}get sssDepthTexture(){return this._sssDepthTexture}set sssDepthTexture(e){this._sssDepthTexture!==e&&(this._sssDepthTexture=e,this._markAllSubMeshesAsTexturesDirty())}get hasTransparency(){return this.subsurfaceWeight>0||this.transmissionWeight>0}get hasScattering(){return this.transmissionWeight>0&&this.transmissionDepth>0&&!this.transmissionScatter.equals(ge.BlackReadOnly)||this.subsurfaceWeight>0}get usePhysicalLightFalloff(){return this._lightFalloff===Ee.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=Ee.LIGHTFALLOFF_PHYSICAL:this._lightFalloff=Ee.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===Ee.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=Ee.LIGHTFALLOFF_GLTF:this._lightFalloff=Ee.LIGHTFALLOFF_STANDARD)}get backgroundRefractionTexture(){return this._backgroundRefractionTexture}set backgroundRefractionTexture(e){this._backgroundRefractionTexture=e,this._markAllSubMeshesAsTexturesDirty()}get refractionHighQualityBlur(){return this._refractionHighQualityBlur}set refractionHighQualityBlur(e){this._refractionHighQualityBlur!==e&&(this._refractionHighQualityBlur=e,this.markAsDirty(1))}get realTimeFiltering(){return this._realTimeFiltering}set realTimeFiltering(e){this._realTimeFiltering=e,this.markAsDirty(1)}get realTimeFilteringQuality(){return this._realTimeFilteringQuality}set realTimeFilteringQuality(e){this._realTimeFilteringQuality=e,this.markAsDirty(1)}get fuzzSampleNumber(){return this._fuzzSampleNumber}set fuzzSampleNumber(e){this._fuzzSampleNumber=e,this.markAsDirty(1)}get canRenderToMRT(){return!0}constructor(e,t,i=!1){var s;super(e,t,void 0,i||n.ForceGLSL),this._baseWeight=new si("base_weight",1,"vBaseWeight",1),this._baseWeightTexture=new Ti("base_weight","baseWeight","BASE_WEIGHT"),this._baseColor=new si("base_color",ge.White(),"vBaseColor",4),this._baseColorTexture=new Ti("base_color","baseColor","BASE_COLOR"),this._baseDiffuseRoughness=new si("base_diffuse_roughness",0,"vBaseDiffuseRoughness",1),this._baseDiffuseRoughnessTexture=new Ti("base_diffuse_roughness","baseDiffuseRoughness","BASE_DIFFUSE_ROUGHNESS"),this._baseMetalness=new si("base_metalness",0,"vReflectanceInfo",4,0),this._baseMetalnessTexture=new Ti("base_metalness","baseMetalness","BASE_METALNESS"),this._specularWeight=new si("specular_weight",1,"vReflectanceInfo",4,3),this._specularWeightTexture=new Ti("specular_weight","specularWeight","SPECULAR_WEIGHT"),this._specularColor=new si("specular_color",ge.White(),"vSpecularColor",4),this._specularColorTexture=new Ti("specular_color","specularColor","SPECULAR_COLOR"),this._specularRoughness=new si("specular_roughness",.3,"vReflectanceInfo",4,1),this._specularRoughnessTexture=new Ti("specular_roughness","specularRoughness","SPECULAR_ROUGHNESS"),this._specularRoughnessAnisotropy=new si("specular_roughness_anisotropy",0,"vSpecularAnisotropy",3,2),this._specularRoughnessAnisotropyTexture=new Ti("specular_roughness_anisotropy","specularRoughnessAnisotropy","SPECULAR_ROUGHNESS_ANISOTROPY"),this._specularIor=new si("specular_ior",1.5,"vReflectanceInfo",4,2),this._transmissionWeight=new si("transmission_weight",0,"vTransmissionWeight",1),this._transmissionWeightTexture=new Ti("transmission_weight","transmissionWeight","TRANSMISSION_WEIGHT"),this._transmissionColor=new si("transmission_color",ge.White(),"vTransmissionColor",3,0),this._transmissionColorTexture=new Ti("transmission_color","transmissionColor","TRANSMISSION_COLOR"),this._transmissionDepth=new si("transmission_depth",0,"vTransmissionDepth",1,0),this._transmissionDepthTexture=new Ti("transmission_depth","transmissionDepth","TRANSMISSION_DEPTH"),this._transmissionScatter=new si("transmission_scatter",ge.Black(),"vTransmissionScatter",3,0),this._transmissionScatterTexture=new Ti("transmission_scatter","transmissionScatter","TRANSMISSION_SCATTER"),this._transmissionScatterAnisotropy=new si("transmission_scatter_anisotropy",0,"vTransmissionScatterAnisotropy",1,0),this._transmissionDispersionScale=new si("transmission_dispersion_scale",0,"vTransmissionDispersionScale",1,0),this._transmissionDispersionScaleTexture=new Ti("transmission_dispersion_scale","transmissionDispersionScale","TRANSMISSION_DISPERSION_SCALE"),this._transmissionDispersionAbbeNumber=new si("transmission_dispersion_abbe_number",20,"vTransmissionDispersionAbbeNumber",1,0),this._subsurfaceWeight=new si("subsurface_weight",0,"vSubsurfaceWeight",1,0,"SUBSURFACE_SLAB"),this._subsurfaceWeightTexture=new Ti("subsurface_weight","subsurfaceWeight","SUBSURFACE_WEIGHT"),this._subsurfaceColor=new si("subsurface_color",new ge(.8,.8,.8),"vSubsurfaceColor",3,0,"SUBSURFACE_SLAB"),this._subsurfaceColorTexture=new Ti("subsurface_color","subsurfaceColor","SUBSURFACE_COLOR"),this._subsurfaceRadius=new si("subsurface_radius",.1,"vSubsurfaceRadius",1,0,"SUBSURFACE_SLAB"),this._subsurfaceRadiusScale=new si("subsurface_radius_scale",new ge(1,.5,.25),"vSubsurfaceRadiusScale",3,0,"SUBSURFACE_SLAB"),this._subsurfaceRadiusScaleTexture=new Ti("subsurface_radius_scale","subsurfaceRadiusScale","SUBSURFACE_RADIUS_SCALE"),this._subsurfaceScatterAnisotropy=new si("subsurface_scatter_anisotropy",0,"vSubsurfaceScatterAnisotropy",1,0,"SUBSURFACE_SLAB"),this._coatWeight=new si("coat_weight",0,"vCoatWeight",1,0),this._coatWeightTexture=new Ti("coat_weight","coatWeight","COAT_WEIGHT"),this._coatColor=new si("coat_color",ge.White(),"vCoatColor",3,0),this._coatColorTexture=new Ti("coat_color","coatColor","COAT_COLOR"),this._coatRoughness=new si("coat_roughness",0,"vCoatRoughness",1,0),this._coatRoughnessTexture=new Ti("coat_roughness","coatRoughness","COAT_ROUGHNESS"),this._coatRoughnessAnisotropy=new si("coat_roughness_anisotropy",0,"vCoatRoughnessAnisotropy",1),this._coatRoughnessAnisotropyTexture=new Ti("coat_roughness_anisotropy","coatRoughnessAnisotropy","COAT_ROUGHNESS_ANISOTROPY"),this._coatIor=new si("coat_ior",1.5,"vCoatIor",1,0),this._coatDarkening=new si("coat_darkening",1,"vCoatDarkening",1,0),this._coatDarkeningTexture=new Ti("coat_darkening","coatDarkening","COAT_DARKENING"),this.useCoatRoughnessFromWeightTexture=!1,this._fuzzWeight=new si("fuzz_weight",0,"vFuzzWeight",1,0),this._fuzzWeightTexture=new Ti("fuzz_weight","fuzzWeight","FUZZ_WEIGHT"),this._fuzzColor=new si("fuzz_color",ge.White(),"vFuzzColor",3,0),this._fuzzColorTexture=new Ti("fuzz_color","fuzzColor","FUZZ_COLOR"),this._fuzzRoughness=new si("fuzz_roughness",.5,"vFuzzRoughness",1,0),this._fuzzRoughnessTexture=new Ti("fuzz_roughness","fuzzRoughness","FUZZ_ROUGHNESS"),this._geometryThinWalled=new si("geometry_thin_walled",0,"vGeometryThinWalled",1,0),this._geometryNormalTexture=new Ti("geometry_normal","geometryNormal","GEOMETRY_NORMAL"),this._geometryTangent=new si("geometry_tangent",new we(1,0),"vSpecularAnisotropy",3,0),this._geometryTangentTexture=new Ti("geometry_tangent","geometryTangent","GEOMETRY_TANGENT"),this._geometryCoatNormalTexture=new Ti("geometry_coat_normal","geometryCoatNormal","GEOMETRY_COAT_NORMAL"),this._geometryCoatTangent=new si("geometry_coat_tangent",new we(1,0),"vGeometryCoatTangent",2,0),this._geometryCoatTangentTexture=new Ti("geometry_coat_tangent","geometryCoatTangent","GEOMETRY_COAT_TANGENT"),this._geometryOpacity=new si("geometry_opacity",1,"vBaseColor",4,3),this._geometryOpacityTexture=new Ti("geometry_opacity","geometryOpacity","GEOMETRY_OPACITY"),this._geometryThickness=new si("geometry_thickness",0,"vGeometryThickness",1,0),this._geometryThicknessTexture=new Ti("geometry_thickness","geometryThickness","GEOMETRY_THICKNESS"),this._emissionLuminance=new si("emission_luminance",1,"vLightingIntensity",4,1),this._emissionColor=new si("emission_color",ge.Black(),"vEmissionColor",3),this._emissionColorTexture=new Ti("emission_color","emissionColor","EMISSION_COLOR"),this._thinFilmWeight=new si("thin_film_weight",0,"vThinFilmWeight",1,0),this._thinFilmWeightTexture=new Ti("thin_film_weight","thinFilmWeight","THIN_FILM_WEIGHT"),this._thinFilmThickness=new si("thin_film_thickness",.5,"vThinFilmThickness",2,0),this._thinFilmThicknessMin=new si("thin_film_thickness_min",0,"vThinFilmThickness",2,1),this._thinFilmThicknessTexture=new Ti("thin_film_thickness","thinFilmThickness","THIN_FILM_THICKNESS"),this._thinFilmIor=new si("thin_film_ior",1.4,"vThinFilmIor",1,0),this._ambientOcclusionTexture=new Ti("ambient_occlusion","ambientOcclusion","AMBIENT_OCCLUSION"),this._sssQuality=n.SSS_QUALITY_MEDIUM,this._sssIrradianceTexture=null,this._sssDepthTexture=null,this._uniformsList={},this._uniformsArray=[],this._samplersList={},this._samplerDefines={},this.directIntensity=1,this.environmentIntensity=1,this.useSpecularWeightFromTextureAlpha=!1,this.forceAlphaTest=!1,this.alphaCutOff=.4,this.useAmbientOcclusionFromMetallicTextureRed=!1,this.useAmbientInGrayScale=!1,this.useObjectSpaceNormalMap=!1,this.useParallax=!1,this.useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this.disableLighting=!1,this.forceIrradianceInFragment=!1,this.maxSimultaneousLights=4,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.twoSidedLighting=!1,this.useAlphaFresnel=!1,this.useLinearAlphaFresnel=!1,this.environmentBRDFTexture=null,this.forceNormalForward=!1,this.enableSpecularAntiAliasing=!1,this.useHorizonOcclusion=!0,this.useRadianceOcclusion=!0,this.unlit=!1,this.applyDecalMapAfterDetailMap=!1,this._lightingInfos=new Ri(this.directIntensity,1,this.environmentIntensity,1),this._radianceTexture=null,this._useSpecularWeightFromAlpha=!1,this._useSpecularWeightFromSpecularColorTexture=!1,this._useSpecularRoughnessAnisotropyFromTangentTexture=!1,this._useCoatRoughnessAnisotropyFromTangentTexture=!1,this._useCoatRoughnessFromGreenChannel=!1,this._useGltfStyleAnisotropy=!1,this._useFuzzRoughnessFromTextureAlpha=!1,this._useHorizonOcclusion=!0,this._useRadianceOcclusion=!0,this._useAlphaFromBaseColorTexture=!1,this._useAmbientOcclusionFromMetallicTextureRed=!1,this._useRoughnessFromMetallicTextureGreen=!1,this._useMetallicFromMetallicTextureBlue=!1,this._useThinFilmThicknessFromTextureGreen=!1,this._useGeometryThicknessFromGreenChannel=!1,this._lightFalloff=Ee.LIGHTFALLOFF_PHYSICAL,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this._parallaxScaleBias=.05,this._disableLighting=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._alphaCutOff=.4,this._useAlphaFresnel=!1,this._useLinearAlphaFresnel=!1,this._environmentBRDFTexture=null,this._environmentFuzzBRDFTexture=null,this._backgroundRefractionTexture=null,this._refractionHighQualityBlur=!0,this._forceIrradianceInFragment=!1,this._realTimeFiltering=!1,this._realTimeFilteringQuality=8,this._fuzzSampleNumber=4,this._forceNormalForward=!1,this._enableSpecularAntiAliasing=!1,this._renderTargets=new wi(16),this._unlit=!1,this._applyDecalMapAfterDetailMap=!1,this._debugMode=0,this._shadersLoaded=!1,this._breakShaderLoadedCheck=!1,this._vertexPullingMetadata=null,this.debugMode=0,this.debugLimit=-1,this.debugFactor=1,this._cacheHasRenderTargetTextures=!1,this._transparencyMode=Ee.MATERIAL_OPAQUE,this.getScene()&&!((s=this.getScene())!=null&&s.getEngine().isWebGPU)&&this.getScene().getEngine().webGLVersion<2&&te.Error("OpenPBRMaterial: WebGL 2.0 or above is required for this material."),n._noiseTextures[this.getScene().uniqueId]||(n._noiseTextures[this.getScene().uniqueId]=new _e(pe.GetAssetUrl("https://assets.babylonjs.com/core/blue_noise/blue_noise_rgb.png"),this.getScene(),!1,!0,1),this.getScene().onDisposeObservable.addOnce(()=>{var a;(a=n._noiseTextures[this.getScene().uniqueId])==null||a.dispose(),delete n._noiseTextures[this.getScene().uniqueId]})),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),le.ReflectionTextureEnabled&&this._radianceTexture&&this._radianceTexture.isRenderTarget&&this._renderTargets.push(this._radianceTexture),le.RefractionTextureEnabled&&this._backgroundRefractionTexture&&this._backgroundRefractionTexture.isRenderTarget&&this._renderTargets.push(this._backgroundRefractionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=f5(this.getScene()),this._environmentFuzzBRDFTexture=KD(this.getScene()),this.prePassConfiguration=new ys,this._propertyList={};for(let a of Object.getOwnPropertyNames(this)){let o=this[a];o instanceof si&&(this._propertyList[a]=o)}Object.keys(this._propertyList).forEach(a=>{let o=this._propertyList[a],l=this._uniformsList[o.targetUniformName];l?l.numComponents!==o.targetUniformComponentNum?te.Error(`Uniform ${o.targetUniformName} already exists of size ${l.numComponents}, but trying to set it to ${o.targetUniformComponentNum}.`):l.requiredDefine!==o.requiredDefine&&(l.requiredDefine=void 0):(l=new bR(o.targetUniformName,o.targetUniformComponentNum),l.requiredDefine=o.requiredDefine,this._uniformsList[o.targetUniformName]=l),l.firstLinkedKey===""&&(l.firstLinkedKey=o.name),l.linkedProperties[o.name]=o}),this._uniformsArray=Object.values(this._uniformsList),this._samplersList={};for(let a of Object.getOwnPropertyNames(this)){let o=this[a];o instanceof Ti&&(this._samplersList[a]=o)}for(let a in this._samplersList){let l=this._samplersList[a].textureDefine;this._samplerDefines[l]={type:"boolean",default:!1},this._samplerDefines[l+"DIRECTUV"]={type:"number",default:0},this._samplerDefines[l+"_GAMMA"]={type:"boolean",default:!1}}this._baseWeight,this._baseWeightTexture,this._baseColor,this._baseColorTexture,this._baseDiffuseRoughness,this._baseDiffuseRoughnessTexture,this._baseMetalness,this._baseMetalnessTexture,this._specularWeight,this._specularWeightTexture,this._specularColor,this._specularColorTexture,this._specularRoughness,this._specularIor,this._specularRoughnessTexture,this._specularRoughnessAnisotropy,this._specularRoughnessAnisotropyTexture,this._transmissionWeight,this._transmissionWeightTexture,this._transmissionColor,this._transmissionColorTexture,this._transmissionDepth,this._transmissionDepthTexture,this._transmissionScatter,this._transmissionScatterTexture,this._transmissionScatterAnisotropy,this._transmissionDispersionScale,this._transmissionDispersionScaleTexture,this._transmissionDispersionAbbeNumber,this._subsurfaceWeight,this._subsurfaceWeightTexture,this._subsurfaceColor,this._subsurfaceColorTexture,this._subsurfaceRadius,this._subsurfaceRadiusScale,this._subsurfaceRadiusScaleTexture,this._subsurfaceScatterAnisotropy,this._coatWeight,this._coatWeightTexture,this._coatColor,this._coatColorTexture,this._coatRoughness,this._coatRoughnessTexture,this._coatRoughnessAnisotropy,this._coatRoughnessAnisotropyTexture,this._coatIor,this._coatDarkening,this._coatDarkeningTexture,this._fuzzWeight,this._fuzzWeightTexture,this._fuzzColor,this._fuzzColorTexture,this._fuzzRoughness,this._fuzzRoughnessTexture,this._geometryThinWalled,this._geometryNormalTexture,this._geometryTangent,this._geometryTangentTexture,this._geometryCoatNormalTexture,this._geometryCoatTangent,this._geometryCoatTangentTexture,this._geometryOpacity,this._geometryOpacityTexture,this._geometryThickness,this._geometryThicknessTexture,this._thinFilmWeight,this._thinFilmWeightTexture,this._thinFilmThickness,this._thinFilmThicknessMin,this._thinFilmThicknessTexture,this._thinFilmIor,this._emissionLuminance,this._emissionColor,this._emissionColorTexture,this._ambientOcclusionTexture}get hasRenderTargetTextures(){return le.ReflectionTextureEnabled&&this._radianceTexture&&this._radianceTexture.isRenderTarget||le.RefractionTextureEnabled&&this._backgroundRefractionTexture&&this._backgroundRefractionTexture.isRenderTarget?!0:this._cacheHasRenderTargetTextures}get isPrePassCapable(){return!this.disableDepthWrite}getClassName(){return"OpenPBRMaterial"}get transparencyMode(){return this._transparencyMode}set transparencyMode(e){this._transparencyMode!==e&&(this._transparencyMode=e,this._markAllSubMeshesAsTexturesAndMiscDirty())}_shouldUseAlphaFromBaseColorTexture(){return this._hasAlphaChannel()&&this._transparencyMode!==Ee.MATERIAL_OPAQUE&&!this.geometryOpacityTexture}_hasAlphaChannel(){return this.baseColorTexture!=null&&this.baseColorTexture.hasAlpha&&this._useAlphaFromBaseColorTexture||this.geometryOpacityTexture!=null}clone(e,t=!0,i=""){let r=it.Clone(()=>new n(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return r.id=e,r.name=e,this.stencil.copyTo(r.stencil),this._clonePlugins(r,i),r}serialize(){let e=super.serialize();return e.customType="BABYLON.OpenPBRMaterial",e}static Parse(e,t,i){let r=it.Parse(()=>new n(e.name,t),e,t,i);return e.stencil&&r.stencil.parse(e.stencil,t,i),Ee._ParsePlugins(e,r,t,i),r}forceCompilation(e,t,i){let r={clipPlane:!1,useInstances:!1,...i};this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(4,this._eventInfo),(()=>{if(this._breakShaderLoadedCheck)return;let a=new Kg({...this._eventInfo.defineNames||{},...this._samplerDefines||{}}),o=this._prepareEffect(e,e,a,void 0,void 0,r.useInstances,r.clipPlane);this._onEffectCreatedObservable&&(op.effect=o,op.subMesh=null,this._onEffectCreatedObservable.notifyObservers(op)),o.isReady()?t&&t(this):o.onCompileObservable.add(()=>{t&&t(this)})})()}isReadyForSubMesh(e,t,i){var d;this._uniformBufferLayoutBuilt||this.buildUniformLayout();let r=t._drawWrapper;if(r.effect&&this.isFrozen&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(4,this._eventInfo),t.materialDefines=new Kg({...this._eventInfo.defineNames||{},...this._samplerDefines||{}}));let s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let a=this.getScene(),o=a.getEngine();if(s._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,a.texturesEnabled)){for(let m in this._samplersList){let p=this._samplersList[m];if(p.value&&!p.value.isReadyOrNotBlocking())return!1}let u=this._getRadianceTexture();if(u&&le.ReflectionTextureEnabled){if(!u.isReadyOrNotBlocking())return!1;if(u.irradianceTexture){if(!u.irradianceTexture.isReadyOrNotBlocking())return!1}else if(!u.sphericalPolynomial&&((d=u.getInternalTexture())!=null&&d._sphericalPolynomialPromise))return!1}if(this._environmentBRDFTexture&&le.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady()||this._environmentFuzzBRDFTexture&&le.ReflectionTextureEnabled&&!this._environmentFuzzBRDFTexture.isReady()||this._backgroundRefractionTexture&&le.RefractionTextureEnabled&&!this._backgroundRefractionTexture.isReadyOrNotBlocking()||n._noiseTextures[a.uniqueId]&&!n._noiseTextures[a.uniqueId].isReady()||this._sssIrradianceTexture&&this._sssDepthTexture&&(!this._sssIrradianceTexture.isReady()||!this._sssDepthTexture.isReady()))return!1}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh||s._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;if(s.AREALIGHTUSED){for(let u=0;u{e.addUniform(t.name,t.numComponents)}),Object.values(this._samplersList).forEach(t=>{e.addUniform(t.samplerInfoName,2),e.addUniform(t.samplerMatrixName,16)}),super.buildUniformLayout()}bindPropertiesForSubMesh(e,t,i,r){if(this.geometryThickness===0)e.updateFloat("vGeometryThickness",0);else{r.getRenderingMesh().getWorldMatrix().decompose($.Vector3[0]);let s=Math.max(Math.abs($.Vector3[0].x),Math.abs($.Vector3[0].y),Math.abs($.Vector3[0].z));e.updateFloat("vGeometryThickness",this.geometryThickness*s)}}bindForSubMesh(e,t,i){var h;let r=this.getScene(),s=i.materialDefines;if(!s)return;let a=i.effect;if(!a)return;this._activeEffect=a,t.getMeshUniformBuffer().bindToEffect(a,"Mesh"),t.transferToEffect(e);let o=r.getEngine();this._uniformBuffer.bindToEffect(a,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,r,t,e,this.isFrozen),Hn.Bind(o.currentRenderPassId,this._activeEffect,t,e,this);let l=r.activeCamera;l?this._uniformBuffer.updateFloat4("cameraInfo",l.minZ,l.maxZ,0,0):this._uniformBuffer.updateFloat4("cameraInfo",0,0,0,0),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),s.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));let c=this._mustRebind(r,a,i,t.visibility);bs(t,this._activeEffect,this.prePassConfiguration),this._vertexPullingMetadata&&Nf(this._activeEffect,this._vertexPullingMetadata);let f=this._uniformBuffer;if(c){this.bindViewProjection(a);let d=this._getRadianceTexture();if(!f.useUbo||!this.isFrozen||!f.isSync||i._drawWrapper._forceRebindOnNextCall){if(r.texturesEnabled){for(let m in this._samplersList){let p=this._samplersList[m];p.value&&(f.updateFloat2(p.samplerInfoName,p.value.coordinatesIndex,p.value.level),ni(p.value,f,p.samplerPrefix))}(this.geometryNormalTexture||this.geometryCoatNormalTexture)&&(r._mirroredCameraPosition?f.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):f.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),Em(r,s,f,ge.White(),d,this.realTimeFiltering,!0,!0,!0,!0,!0)}this.pointsCloud&&f.updateFloat("pointSize",this.pointSize);let u=this._uniformsArray;for(let m=0,p=u.length;m0&&e.push(i.value)}return this._radianceTexture&&this._radianceTexture.animations&&this._radianceTexture.animations.length>0&&e.push(this._radianceTexture),e}getActiveTextures(){let e=super.getActiveTextures();for(let t in this._samplersList){let i=this._samplersList[t];i.value&&e.push(i.value)}return this._radianceTexture&&e.push(this._radianceTexture),e}hasTexture(e){if(super.hasTexture(e))return!0;for(let t in this._samplersList)if(this._samplersList[t].value===e)return!0;return this._radianceTexture===e}setPrePassRenderer(){return!1}dispose(e,t){var i,r;if(this._breakShaderLoadedCheck=!0,t){this._environmentBRDFTexture&&this.getScene().openPBREnvironmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),this._environmentFuzzBRDFTexture&&this.getScene().environmentFuzzBRDFTexture!==this._environmentFuzzBRDFTexture&&this._environmentFuzzBRDFTexture.dispose(),this._backgroundRefractionTexture=null;for(let s in this._samplersList)(i=this._samplersList[s].value)==null||i.dispose();(r=this._radianceTexture)==null||r.dispose()}this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}_getRadianceTexture(){return this._radianceTexture?this._radianceTexture:this.getScene().environmentTexture}_prepareEffect(e,t,i,r=null,s=null,a=null,o=null){if(this._prepareDefines(e,t,i,a,o),!i.isDirty)return null;i.markAsProcessed();let c=this.getScene().getEngine(),f=new Wn,h=0;i.USESPHERICALINVERTEX&&f.addFallback(h++,"USESPHERICALINVERTEX"),i.FOG&&f.addFallback(h,"FOG"),i.SPECULARAA&&f.addFallback(h,"SPECULARAA"),i.POINTSIZE&&f.addFallback(h,"POINTSIZE"),i.LOGARITHMICDEPTH&&f.addFallback(h,"LOGARITHMICDEPTH"),i.PARALLAX&&f.addFallback(h,"PARALLAX"),i.PARALLAX_RHS&&f.addFallback(h,"PARALLAX_RHS"),i.PARALLAXOCCLUSION&&f.addFallback(h++,"PARALLAXOCCLUSION"),i.ENVIRONMENTBRDF&&f.addFallback(h++,"ENVIRONMENTBRDF"),i.TANGENT&&f.addFallback(h++,"TANGENT"),h=Rm(i,f,this._maxSimultaneousLights,h),i.SPECULARTERM&&f.addFallback(h++,"SPECULARTERM"),i.USESPHERICALFROMREFLECTIONMAP&&f.addFallback(h++,"USESPHERICALFROMREFLECTIONMAP"),i.USEIRRADIANCEMAP&&f.addFallback(h++,"USEIRRADIANCEMAP"),i.NORMAL&&f.addFallback(h++,"NORMAL"),i.VERTEXCOLOR&&f.addFallback(h++,"VERTEXCOLOR"),i.MORPHTARGETS&&f.addFallback(h++,"MORPHTARGETS"),i.MULTIVIEW&&f.addFallback(0,"MULTIVIEW");let d=[L.PositionKind];i.NORMAL&&d.push(L.NormalKind),i.TANGENT&&d.push(L.TangentKind);for(let S=1;S<=6;++S)i["UV"+S]&&d.push(`uv${S===1?"":S}`);i.VERTEXCOLOR&&d.push(L.ColorKind),Am(d,e,i,f),xm(d,i),Qh(d,e,i),Sm(d,e,i);let u="openpbr",m=["world","view","viewProjection","projection","vEyePosition","inverseProjection","renderTargetSize","vLightsType","visibility","vFogInfos","vFogColor","pointSize","mBones","normalMatrix","vLightingIntensity","logarithmicDepthConstant","vTangentSpaceParams","boneTextureInfo","vDebugMode","morphTargetTextureInfo","morphTargetTextureIndices","cameraInfo","backgroundRefractionMatrix","vBackgroundRefractionInfos"];for(let S in this._uniformsList)m.push(S);let p=["environmentBrdfSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler","areaLightsLTC1Sampler","areaLightsLTC2Sampler"];i.FUZZENVIRONMENTBRDF&&p.push("environmentFuzzBrdfSampler"),i.REFRACTED_BACKGROUND&&p.push("backgroundRefractionSampler"),(i.ANISOTROPIC||i.FUZZ||i.REFRACTED_BACKGROUND||i.USE_IRRADIANCE_TEXTURE_FOR_SCATTERING)&&p.push("blueNoiseSampler"),i.USE_IRRADIANCE_TEXTURE_FOR_SCATTERING&&(p.push("sceneIrradianceSampler"),p.push("sceneDepthSampler"));for(let S in this._samplersList){let E=this._samplersList[S];p.push(E.samplerName),m.push(E.samplerInfoName),m.push(E.samplerMatrixName)}bf(m,p,!0);let _=["Material","Scene","Mesh"],g={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:i.NUM_MORPH_INFLUENCERS};if(this._eventInfo.fallbacks=f,this._eventInfo.fallbackRank=h,this._eventInfo.defines=i,this._eventInfo.uniforms=m,this._eventInfo.attributes=d,this._eventInfo.samplers=p,this._eventInfo.uniformBuffersNames=_,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=g,this._callbackPluginEventGeneric(128,this._eventInfo),Hn.AddUniformsAndSamplers(m,p),ys.AddUniforms(m),ys.AddSamplers(p),wn(m),this._useVertexPulling){let S=t==null?void 0:t.geometry;S&&(this._vertexPullingMetadata=Of(S),this._vertexPullingMetadata&&this._vertexPullingMetadata.forEach((E,R)=>{m.push(`vp_${R}_info`)}))}else this._vertexPullingMetadata=null;kt&&(kt.PrepareUniforms(m,i),kt.PrepareSamplers(p,i)),Om({uniformsNames:m,uniformBuffersNames:_,samplers:p,defines:i,maxSimultaneousLights:this._maxSimultaneousLights,shaderLanguage:this._shaderLanguage});let v={};this.customShaderNameResolve&&(u=this.customShaderNameResolve(u,m,_,p,i,d,v));let x=i.toString(),A=c.createEffect(u,{attributes:d,uniformsNames:m,uniformBuffersNames:_,samplers:p,defines:x,fallbacks:f,onCompiled:r,onError:s,indexParameters:g,processFinalCode:v.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:i.PREPASS,shaderLanguage:this._shaderLanguage,extraInitializationsAsync:this._shadersLoaded?void 0:async()=>{this.shaderLanguage===1?await Promise.all([Promise.resolve().then(()=>(nY(),rY)),Promise.resolve().then(()=>(t8(),e8))]):await Promise.all([Promise.resolve().then(()=>(h8(),f8)),Promise.resolve().then(()=>(c6(),l6))]),this._shadersLoaded=!0}},c);return this._eventInfo.customCode=void 0,A}_prepareDefines(e,t,i,r=null,s=null){var h;let a=t.hasThinInstances,o=this.getScene(),l=o.getEngine();Mm(o,e,i,!0,this._maxSimultaneousLights,this._disableLighting),i._needNormals=!0,Pm(o,i);let c=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(Lm(o,i,this.canRenderToMRT&&!c),Dm(o,i,c),Hn.PrepareDefines(l.currentRenderPassId,e,i),i._areTexturesDirty){i._needUVs=!1;for(let d=1;d<=6;++d)i["MAINUV"+d]=!1;if(o.texturesEnabled){for(let m in this._samplersList){let p=this._samplersList[m];p.value?(ri(p.value,i,p.textureDefine),i[p.textureDefine+"_GAMMA"]=p.value.gammaSpace):i[p.textureDefine]=!1}let d=this._getRadianceTexture(),u=this._forceIrradianceInFragment||this.realTimeFiltering||this._twoSidedLighting||l.getCaps().maxVaryingVectors<=8||this._baseDiffuseRoughnessTexture!=null;if(Rf(o,d,i,this.realTimeFiltering,this.realTimeFilteringQuality,!u),this._baseMetalnessTexture&&(i.AOSTOREINMETALMAPRED=this._useAmbientOcclusionFromMetallicTextureRed),i.SPECULAR_WEIGHT_IN_ALPHA=this._useSpecularWeightFromAlpha,i.SPECULAR_WEIGHT_FROM_SPECULAR_COLOR_TEXTURE=this._useSpecularWeightFromSpecularColorTexture,i.SPECULAR_ROUGHNESS_ANISOTROPY_FROM_TANGENT_TEXTURE=this._useSpecularRoughnessAnisotropyFromTangentTexture,i.COAT_ROUGHNESS_ANISOTROPY_FROM_TANGENT_TEXTURE=this._useCoatRoughnessAnisotropyFromTangentTexture,i.COAT_ROUGHNESS_FROM_GREEN_CHANNEL=this._useCoatRoughnessFromGreenChannel,i.SPECULAR_ROUGHNESS_FROM_METALNESS_TEXTURE_GREEN=this._useRoughnessFromMetallicTextureGreen,i.FUZZ_ROUGHNESS_FROM_TEXTURE_ALPHA=this._useFuzzRoughnessFromTextureAlpha,i.BASE_METALNESS_FROM_METALNESS_TEXTURE_BLUE=this._useMetallicFromMetallicTextureBlue,i.THIN_FILM_THICKNESS_FROM_THIN_FILM_TEXTURE=this._useThinFilmThicknessFromTextureGreen,i.GEOMETRY_THICKNESS_FROM_GREEN_CHANNEL=this._useGeometryThicknessFromGreenChannel,this.geometryNormalTexture?(this._useParallax&&this.baseColorTexture&&le.DiffuseTextureEnabled?(i.PARALLAX=!0,i.PARALLAX_RHS=o.useRightHandedSystem,i.PARALLAXOCCLUSION=!!this._useParallaxOcclusion):i.PARALLAX=!1,i.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap):(i.PARALLAX=!1,i.PARALLAX_RHS=!1,i.PARALLAXOCCLUSION=!1,i.OBJECTSPACE_NORMALMAP=!1),this._environmentBRDFTexture&&le.ReflectionTextureEnabled?(i.ENVIRONMENTBRDF=!0,i.ENVIRONMENTBRDF_RGBD=this._environmentBRDFTexture.isRGBD):(i.ENVIRONMENTBRDF=!1,i.ENVIRONMENTBRDF_RGBD=!1),this._environmentFuzzBRDFTexture?i.FUZZENVIRONMENTBRDF=!0:i.FUZZENVIRONMENTBRDF=!1,this.hasTransparency){i.REFRACTED_BACKGROUND=!!this._backgroundRefractionTexture&&le.RefractionTextureEnabled,i.REFRACTION_HIGH_QUALITY_BLUR=this._refractionHighQualityBlur,i.REFRACTED_LIGHTS=!0;let m=this._getRadianceTexture();m?(i.REFRACTED_ENVIRONMENT=le.RefractionTextureEnabled,i.REFRACTED_ENVIRONMENT_OPPOSITEZ=this.getScene().useRightHandedSystem?!m.invertZ:m.invertZ,i.REFRACTED_ENVIRONMENT_LOCAL_CUBE=m.isCube&&m.boundingBoxSize):i.REFRACTED_ENVIRONMENT=!1}else i.REFRACTED_BACKGROUND=!1,i.REFRACTED_LIGHTS=!1,i.REFRACTED_ENVIRONMENT=!1;this._shouldUseAlphaFromBaseColorTexture()?i.ALPHA_FROM_BASE_COLOR_TEXTURE=!0:i.ALPHA_FROM_BASE_COLOR_TEXTURE=!1}this._lightFalloff===Ee.LIGHTFALLOFF_STANDARD?(i.USEPHYSICALLIGHTFALLOFF=!1,i.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===Ee.LIGHTFALLOFF_GLTF?(i.USEPHYSICALLIGHTFALLOFF=!1,i.USEGLTFLIGHTFALLOFF=!0):(i.USEPHYSICALLIGHTFALLOFF=!0,i.USEGLTFLIGHTFALLOFF=!1),!this.backFaceCulling&&this._twoSidedLighting?i.TWOSIDEDLIGHTING=!0:i.TWOSIDEDLIGHTING=!1,i.MIRRORED=!!o._mirroredCameraPosition,i.SPECULARAA=l.getCaps().standardDerivatives&&this._enableSpecularAntiAliasing}(i._areTexturesDirty||i._areMiscDirty)&&(i.ALPHATESTVALUE=`${this._alphaCutOff}${this._alphaCutOff%1===0?".":""}`,i.PREMULTIPLYALPHA=this.alphaMode===7||this.alphaMode===8,i.ALPHABLEND=this.needAlphaBlendingForMesh(e)),i._areImageProcessingDirty&&this._imageProcessingConfiguration&&this._imageProcessingConfiguration.prepareDefines(i),i.FORCENORMALFORWARD=this._forceNormalForward,i.RADIANCEOCCLUSION=this._useRadianceOcclusion,i.HORIZONOCCLUSION=this._useHorizonOcclusion,(this.specularRoughnessAnisotropy>0||this.coatRoughnessAnisotropy>0)&&n._noiseTextures[o.uniqueId]&&le.ReflectionTextureEnabled?(i.ANISOTROPIC=!0,e.isVerticesDataPresent(L.TangentKind)||(i._needUVs=!0,i.MAINUV1=!0),this._useGltfStyleAnisotropy&&(i.USE_GLTF_STYLE_ANISOTROPY=!0),i.ANISOTROPIC_BASE=this.specularRoughnessAnisotropy>0,i.ANISOTROPIC_COAT=this.coatRoughnessAnisotropy>0):(i.ANISOTROPIC=!1,i.USE_GLTF_STYLE_ANISOTROPY=!1,i.ANISOTROPIC_BASE=!1,i.ANISOTROPIC_COAT=!1),i.THIN_FILM=this.thinFilmWeight>0,i.IRIDESCENCE=this.thinFilmWeight>0,i.DISPERSION=this.transmissionDispersionScale>0,i.SCATTERING=this.hasScattering;let f=[8,16,32];if(i.SSS_SAMPLE_COUNT=(h=f[this._sssQuality])!=null?h:16,i.TRANSMISSION_SLAB=this.transmissionWeight>0,i.TRANSMISSION_SLAB_VOLUME=this.transmissionWeight>0&&this.transmissionDepth>0,i.SUBSURFACE_SLAB=this.subsurfaceWeight>0,!i.PREPASS&&(i.SUBSURFACE_SLAB||i.TRANSMISSION_SLAB_VOLUME)){let d=!1;if(!this.sssIrradianceTexture&&o.geometryBufferRenderer){let u=o.geometryBufferRenderer.getTextureIndex(ss.IRRADIANCE_TEXTURE_TYPE);this.sssIrradianceTexture=o.geometryBufferRenderer.getGBuffer().textures[u],d=!0}if(!this.sssDepthTexture&&o.geometryBufferRenderer){let u=o.geometryBufferRenderer.getTextureIndex(ss.SCREENSPACE_DEPTH_TEXTURE_TYPE);this.sssDepthTexture=o.geometryBufferRenderer.getGBuffer().textures[u],d=!0}this.sssIrradianceTexture&&this.sssDepthTexture&&(i.USE_IRRADIANCE_TEXTURE_FOR_SCATTERING=!0,d&&(i.USE_IRRADIANCE_TEXTURE_FOR_SCATTERING_GBUFFER=!0))}i.FUZZ=this.fuzzWeight>0&&le.ReflectionTextureEnabled,i.GEOMETRY_THIN_WALLED=this.geometryThinWalled!=0,i.FUZZ?(e.isVerticesDataPresent(L.TangentKind)||(i._needUVs=!0,i.MAINUV1=!0),this._environmentFuzzBRDFTexture=KD(this.getScene()),i.FUZZ_IBL_SAMPLES=this.fuzzSampleNumber):(this._environmentFuzzBRDFTexture=null,i.FUZZENVIRONMENTBRDF=!1,i.FUZZ_IBL_SAMPLES=0),i._areMiscDirty&&(bm(e,o,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this.needAlphaTestingForMesh(e),i,this._applyDecalMapAfterDetailMap,this._useVertexPulling,t,this._isVertexOutputInvariant),i.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent(L.NormalKind),i.DEBUGMODE=this._debugMode),Cm(o,l,this,i,!!r,s,a),this._eventInfo.defines=i,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),ym(e,i,!0,!0,!0,this._transparencyMode!==Ee.MATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}};Ne.SSS_QUALITY_LOW=0;Ne.SSS_QUALITY_MEDIUM=1;Ne.SSS_QUALITY_HIGH=2;Ne._noiseTextures={};Ne.ForceGLSL=!1;P([dt("_markAllSubMeshesAsTexturesDirty","baseWeight")],Ne.prototype,"_baseWeight",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","baseWeightTexture")],Ne.prototype,"_baseWeightTexture",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","baseColor")],Ne.prototype,"_baseColor",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","baseColorTexture")],Ne.prototype,"_baseColorTexture",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","baseDiffuseRoughness")],Ne.prototype,"_baseDiffuseRoughness",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","baseDiffuseRoughnessTexture")],Ne.prototype,"_baseDiffuseRoughnessTexture",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","baseMetalness")],Ne.prototype,"_baseMetalness",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","baseMetalnessTexture")],Ne.prototype,"_baseMetalnessTexture",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","specularWeight")],Ne.prototype,"_specularWeight",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","specularWeightTexture")],Ne.prototype,"_specularWeightTexture",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","specularColor")],Ne.prototype,"_specularColor",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","specularColorTexture")],Ne.prototype,"_specularColorTexture",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","specularRoughness")],Ne.prototype,"_specularRoughness",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","specularRoughnessTexture")],Ne.prototype,"_specularRoughnessTexture",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","specularRoughnessAnisotropy")],Ne.prototype,"_specularRoughnessAnisotropy",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","specularRoughnessAnisotropyTexture")],Ne.prototype,"_specularRoughnessAnisotropyTexture",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","specularIor")],Ne.prototype,"_specularIor",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","transmissionWeight")],Ne.prototype,"_transmissionWeight",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","transmissionWeightTexture")],Ne.prototype,"_transmissionWeightTexture",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","transmissionColor")],Ne.prototype,"_transmissionColor",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","transmissionColorTexture")],Ne.prototype,"_transmissionColorTexture",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","transmissionDepth")],Ne.prototype,"_transmissionDepth",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","transmissionDepthTexture")],Ne.prototype,"_transmissionDepthTexture",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","transmissionScatter")],Ne.prototype,"_transmissionScatter",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","transmissionScatterTexture")],Ne.prototype,"_transmissionScatterTexture",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","transmissionScatterAnisotropy")],Ne.prototype,"_transmissionScatterAnisotropy",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","transmissionDispersionScale")],Ne.prototype,"_transmissionDispersionScale",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","transmissionDispersionScaleTexture")],Ne.prototype,"_transmissionDispersionScaleTexture",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","transmissionDispersionAbbeNumber")],Ne.prototype,"_transmissionDispersionAbbeNumber",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","subsurfaceWeight")],Ne.prototype,"_subsurfaceWeight",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","subsurfaceWeightTexture")],Ne.prototype,"_subsurfaceWeightTexture",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","subsurfaceColor")],Ne.prototype,"_subsurfaceColor",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","subsurfaceColorTexture")],Ne.prototype,"_subsurfaceColorTexture",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","subsurfaceRadius")],Ne.prototype,"_subsurfaceRadius",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","subsurfaceRadiusScale")],Ne.prototype,"_subsurfaceRadiusScale",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","subsurfaceRadiusScaleTexture")],Ne.prototype,"_subsurfaceRadiusScaleTexture",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","subsurfaceScatterAnisotropy")],Ne.prototype,"_subsurfaceScatterAnisotropy",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","coatWeight")],Ne.prototype,"_coatWeight",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","coatWeightTexture")],Ne.prototype,"_coatWeightTexture",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","coatColor")],Ne.prototype,"_coatColor",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","coatColorTexture")],Ne.prototype,"_coatColorTexture",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","coatRoughness")],Ne.prototype,"_coatRoughness",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","coatRoughnessTexture")],Ne.prototype,"_coatRoughnessTexture",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","coatRoughnessAnisotropy")],Ne.prototype,"_coatRoughnessAnisotropy",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","coatRoughnessAnisotropyTexture")],Ne.prototype,"_coatRoughnessAnisotropyTexture",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","coatIor")],Ne.prototype,"_coatIor",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","coatDarkening")],Ne.prototype,"_coatDarkening",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","coatDarkeningTexture")],Ne.prototype,"_coatDarkeningTexture",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","fuzzWeight")],Ne.prototype,"_fuzzWeight",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","fuzzWeightTexture")],Ne.prototype,"_fuzzWeightTexture",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","fuzzColor")],Ne.prototype,"_fuzzColor",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","fuzzColorTexture")],Ne.prototype,"_fuzzColorTexture",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","fuzzRoughness")],Ne.prototype,"_fuzzRoughness",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","fuzzRoughnessTexture")],Ne.prototype,"_fuzzRoughnessTexture",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","geometryThinWalled")],Ne.prototype,"_geometryThinWalled",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","geometryNormalTexture")],Ne.prototype,"_geometryNormalTexture",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","geometryTangent")],Ne.prototype,"_geometryTangent",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","geometryTangentTexture")],Ne.prototype,"_geometryTangentTexture",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","geometryCoatNormalTexture")],Ne.prototype,"_geometryCoatNormalTexture",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","geometryCoatTangent")],Ne.prototype,"_geometryCoatTangent",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","geometryCoatTangentTexture")],Ne.prototype,"_geometryCoatTangentTexture",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","geometryOpacity")],Ne.prototype,"_geometryOpacity",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","geometryOpacityTexture")],Ne.prototype,"_geometryOpacityTexture",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","geometryThickness")],Ne.prototype,"_geometryThickness",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","geometryThicknessTexture")],Ne.prototype,"_geometryThicknessTexture",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","emissionLuminance")],Ne.prototype,"_emissionLuminance",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","emissionColor")],Ne.prototype,"_emissionColor",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","emissionColorTexture")],Ne.prototype,"_emissionColorTexture",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","thinFilmWeight")],Ne.prototype,"_thinFilmWeight",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","thinFilmWeightTexture")],Ne.prototype,"_thinFilmWeightTexture",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","thinFilmThickness")],Ne.prototype,"_thinFilmThickness",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","thinFilmThicknessMin")],Ne.prototype,"_thinFilmThicknessMin",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","thinFilmThicknessTexture")],Ne.prototype,"_thinFilmThicknessTexture",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","thinFilmIor")],Ne.prototype,"_thinFilmIor",void 0);P([dt("_markAllSubMeshesAsTexturesDirty","ambientOcclusionTexture")],Ne.prototype,"_ambientOcclusionTexture",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"directIntensity",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"environmentIntensity",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"useSpecularWeightFromTextureAlpha",void 0);P([w(),oe("_markAllSubMeshesAsTexturesAndMiscDirty")],Ne.prototype,"forceAlphaTest",void 0);P([w(),oe("_markAllSubMeshesAsTexturesAndMiscDirty")],Ne.prototype,"alphaCutOff",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"useAmbientInGrayScale",void 0);P([w()],Ne.prototype,"usePhysicalLightFalloff",null);P([w()],Ne.prototype,"useGLTFLightFalloff",null);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"useObjectSpaceNormalMap",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"useParallax",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"useParallaxOcclusion",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"parallaxScaleBias",void 0);P([w(),oe("_markAllSubMeshesAsLightsDirty")],Ne.prototype,"disableLighting",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"forceIrradianceInFragment",void 0);P([w(),oe("_markAllSubMeshesAsLightsDirty")],Ne.prototype,"maxSimultaneousLights",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"invertNormalMapX",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"invertNormalMapY",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"twoSidedLighting",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"useAlphaFresnel",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"useLinearAlphaFresnel",void 0);P([oe("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"environmentBRDFTexture",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"forceNormalForward",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"enableSpecularAntiAliasing",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"useHorizonOcclusion",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"useRadianceOcclusion",void 0);P([w(),oe("_markAllSubMeshesAsMiscDirty")],Ne.prototype,"unlit",void 0);P([w(),oe("_markAllSubMeshesAsMiscDirty")],Ne.prototype,"applyDecalMapAfterDetailMap",void 0);P([oe("_markAllSubMeshesAsMiscDirty")],Ne.prototype,"debugMode",void 0);P([w()],Ne.prototype,"transparencyMode",null);wt("BABYLON.OpenPBRMaterial",Ne)});var d6={};tt(d6,{OpenPBRMaterialLoadingAdapter:()=>XL});var XL,u6=C(()=>{zt();XL=class{constructor(e){this._diffuseTransmissionTint=ge.White(),this._diffuseTransmissionTintTexture=null,this._material=e}get material(){return this._material}get isUnlit(){return this._material.unlit}set isUnlit(e){this._material.unlit=e}set backFaceCulling(e){this._material.backFaceCulling=e}get backFaceCulling(){return this._material.backFaceCulling}set twoSidedLighting(e){this._material.twoSidedLighting=e}get twoSidedLighting(){return this._material.twoSidedLighting}set alphaCutOff(e){}get alphaCutOff(){return .5}set useAlphaFromBaseColorTexture(e){this._material._useAlphaFromBaseColorTexture=e}get useAlphaFromBaseColorTexture(){return!1}get transparencyAsAlphaCoverage(){return!1}set transparencyAsAlphaCoverage(e){}set baseColor(e){this._material.baseColor=e}get baseColor(){return this._material.baseColor}set baseColorTexture(e){this._material.baseColorTexture=e}get baseColorTexture(){return this._material.baseColorTexture}set baseDiffuseRoughness(e){this._material.baseDiffuseRoughness=e}get baseDiffuseRoughness(){return this._material.baseDiffuseRoughness}set baseDiffuseRoughnessTexture(e){this._material.baseDiffuseRoughnessTexture=e}get baseDiffuseRoughnessTexture(){return this._material.baseDiffuseRoughnessTexture}set baseMetalness(e){this._material.baseMetalness=e}get baseMetalness(){return this._material.baseMetalness}set baseMetalnessTexture(e){this._material.baseMetalnessTexture=e}get baseMetalnessTexture(){return this._material.baseMetalnessTexture}set useRoughnessFromMetallicTextureGreen(e){this._material._useRoughnessFromMetallicTextureGreen=e}set useMetallicFromMetallicTextureBlue(e){this._material._useMetallicFromMetallicTextureBlue=e}enableSpecularEdgeColor(e=!1){}set specularWeight(e){this._material.specularWeight=e}get specularWeight(){return this._material.specularWeight}set specularWeightTexture(e){this._material.specularColorTexture===e?(this._material.specularWeightTexture=null,this._material._useSpecularWeightFromSpecularColorTexture=!0,this._material._useSpecularWeightFromAlpha=!0):this._material.specularWeightTexture=e}get specularWeightTexture(){return this._material.specularWeightTexture}set specularColor(e){this._material.specularColor=e}get specularColor(){return this._material.specularColor}set specularColorTexture(e){this._material.specularColorTexture=e,this._material.specularWeightTexture===this._material.specularColorTexture&&(this._material.specularWeightTexture=null,this._material._useSpecularWeightFromSpecularColorTexture=!0,this._material._useSpecularWeightFromAlpha=!0)}get specularColorTexture(){return this._material.specularColorTexture}set specularRoughness(e){this._material.specularRoughness=e}get specularRoughness(){return this._material.specularRoughness}set specularRoughnessTexture(e){this._material.specularRoughnessTexture=e}get specularRoughnessTexture(){return this._material.specularRoughnessTexture}set specularIor(e){this._material.specularIor=e}get specularIor(){return this._material.specularIor}set emissionColor(e){this._material.emissionColor=e}get emissionColor(){return this._material.emissionColor}set emissionLuminance(e){this._material.emissionLuminance=e}get emissionLuminance(){return this._material.emissionLuminance}set emissionColorTexture(e){this._material.emissionColorTexture=e}get emissionColorTexture(){return this._material.emissionColorTexture}set ambientOcclusionTexture(e){this._material.ambientOcclusionTexture=e}get ambientOcclusionTexture(){return this._material.ambientOcclusionTexture}set ambientOcclusionTextureStrength(e){let t=this._material.ambientOcclusionTexture;t&&(t.level=e)}get ambientOcclusionTextureStrength(){var t;let e=this._material.ambientOcclusionTexture;return(t=e==null?void 0:e.level)!=null?t:1}configureCoat(){}set coatWeight(e){this._material.coatWeight=e}get coatWeight(){return this._material.coatWeight}set coatWeightTexture(e){this._material.coatWeightTexture=e}get coatWeightTexture(){return this._material.coatWeightTexture}set coatColor(e){this._material.coatColor=e}set coatColorTexture(e){this._material.coatColorTexture=e}set coatRoughness(e){this._material.coatRoughness=e}get coatRoughness(){return this._material.coatRoughness}set coatRoughnessTexture(e){this._material.coatRoughnessTexture=e,e&&(this._material._useCoatRoughnessFromGreenChannel=!0)}get coatRoughnessTexture(){return this._material.coatRoughnessTexture}set coatIor(e){this._material.coatIor=e}set coatDarkening(e){this._material.coatDarkening=e}set coatDarkeningTexture(e){this._material.coatDarkeningTexture=e}set coatRoughnessAnisotropy(e){this._material.coatRoughnessAnisotropy=e}get coatRoughnessAnisotropy(){return this._material.coatRoughnessAnisotropy}set geometryCoatTangentAngle(e){this._material.geometryCoatTangentAngle=e}set geometryCoatTangentTexture(e){this._material.geometryCoatTangentTexture=e,e&&(this._material._useCoatRoughnessAnisotropyFromTangentTexture=!0)}get geometryCoatTangentTexture(){return this._material.geometryCoatTangentTexture}configureTransmission(){this._material.geometryThinWalled=1,this._material.transmissionDepth=0}set transmissionWeight(e){this._material.transmissionWeight=e}set transmissionWeightTexture(e){this._material.transmissionWeightTexture=e}get transmissionWeight(){return this._material.transmissionWeight}set transmissionScatter(e){this._material.transmissionScatter=e}get transmissionScatter(){return this._material.transmissionScatter}set transmissionScatterTexture(e){this._material.transmissionScatterTexture=e}get transmissionScatterTexture(){return this._material.transmissionScatterTexture}set transmissionScatterAnisotropy(e){this._material.transmissionScatterAnisotropy=e}set transmissionDispersionAbbeNumber(e){this._material.transmissionDispersionAbbeNumber=e}set transmissionDispersionScale(e){this._material.transmissionDispersionScale=e}set transmissionDepth(e){e!==Number.MAX_VALUE||this._material.transmissionDepth!==0?this._material.transmissionDepth=e:this._material.transmissionDepth=0}get transmissionDepth(){return this._material.transmissionDepth}set transmissionColor(e){e.equals(ge.White())||(this._material.transmissionColor=e)}get transmissionColor(){return this._material.transmissionColor}get refractionBackgroundTexture(){return this._material.backgroundRefractionTexture}set refractionBackgroundTexture(e){this._material.backgroundRefractionTexture=e}configureVolume(){this._material.geometryThinWalled=0}set geometryThinWalled(e){this._material.geometryThinWalled=e?1:0}get geometryThinWalled(){return!!this._material.geometryThinWalled}set volumeThicknessTexture(e){this._material.geometryThicknessTexture=e,this._material._useGeometryThicknessFromGreenChannel=!0}set volumeThickness(e){this._material.geometryThickness=e}configureSubsurface(){this._material.geometryThinWalled=1,this._material.subsurfaceScatterAnisotropy=1}set subsurfaceWeight(e){this._material.subsurfaceWeight=e}get subsurfaceWeight(){return this._material.subsurfaceWeight}set subsurfaceWeightTexture(e){this._material.subsurfaceWeightTexture=e}set subsurfaceColor(e){this._material.subsurfaceColor=e}set subsurfaceColorTexture(e){this._material.subsurfaceColorTexture=e}set diffuseTransmissionTint(e){this._diffuseTransmissionTint=e}get diffuseTransmissionTint(){return this._diffuseTransmissionTint}set diffuseTransmissionTintTexture(e){this._diffuseTransmissionTintTexture=e}get subsurfaceRadius(){return this._material.subsurfaceRadius}set subsurfaceRadius(e){this._material.subsurfaceRadius=e}get subsurfaceRadiusScale(){return this._material.subsurfaceRadiusScale}set subsurfaceRadiusScale(e){this._material.subsurfaceRadiusScale=e}set subsurfaceScatterAnisotropy(e){this._material.subsurfaceScatterAnisotropy=e}isTranslucent(){return this.transmissionWeight>0||this.subsurfaceWeight>0}configureFuzz(){}set fuzzWeight(e){this._material.fuzzWeight=e}set fuzzWeightTexture(e){this._material.fuzzWeightTexture=e}set fuzzColor(e){this._material.fuzzColor=e}set fuzzColorTexture(e){this._material.fuzzColorTexture=e}set fuzzRoughness(e){this._material.fuzzRoughness=e}set fuzzRoughnessTexture(e){this._material.fuzzRoughnessTexture=e,this._material._useFuzzRoughnessFromTextureAlpha=!0}set specularRoughnessAnisotropy(e){this._material.specularRoughnessAnisotropy=e}get specularRoughnessAnisotropy(){return this._material.specularRoughnessAnisotropy}set geometryTangentAngle(e){this._material.geometryTangentAngle=e}set geometryTangentTexture(e){this._material.geometryTangentTexture=e,this._material._useSpecularRoughnessAnisotropyFromTangentTexture=!0}get geometryTangentTexture(){return this._material.geometryTangentTexture}configureGltfStyleAnisotropy(e=!0){this._material._useGltfStyleAnisotropy=e}set thinFilmWeight(e){this._material.thinFilmWeight=e}set thinFilmIor(e){this._material.thinFilmIor=e}set thinFilmThicknessMinimum(e){this._material.thinFilmThicknessMin=e/1e3}set thinFilmThicknessMaximum(e){this._material.thinFilmThickness=e/1e3}set thinFilmWeightTexture(e){this._material.thinFilmWeightTexture=e}set thinFilmThicknessTexture(e){this._material.thinFilmThicknessTexture=e,this._material._useThinFilmThicknessFromTextureGreen=!0}set unlit(e){this._material.unlit=e}set geometryOpacity(e){this._material.geometryOpacity=e}get geometryOpacity(){return this._material.geometryOpacity}set geometryNormalTexture(e){this._material.geometryNormalTexture=e}get geometryNormalTexture(){return this._material.geometryNormalTexture}setNormalMapInversions(e,t){}set geometryCoatNormalTexture(e){this._material.geometryCoatNormalTexture=e}get geometryCoatNormalTexture(){return this._material.geometryCoatNormalTexture}set geometryCoatNormalTextureScale(e){this._material.geometryCoatNormalTexture&&(this._material.geometryCoatNormalTexture.level=e)}finalize(){(this._diffuseTransmissionTint&&!this._diffuseTransmissionTint.equals(ge.White())||this._diffuseTransmissionTintTexture)&&(this._material.geometryThinWalled?(this.subsurfaceColor=this._diffuseTransmissionTint,this.subsurfaceColorTexture=this._diffuseTransmissionTintTexture):this._material.coatWeight==0&&(!this.baseColor.equals(ge.White())||this.baseColorTexture)&&(this._material.coatWeight=this.subsurfaceWeight,this._material.coatWeightTexture=this.subsurfaceWeightTexture,this._material.coatColor=this._diffuseTransmissionTint,this._material.coatColorTexture=this._diffuseTransmissionTintTexture,this._material.coatIor=this._material.specularIor,this._material.coatDarkening=0,this._material.coatRoughness=this._material.specularRoughness,this._material.coatRoughnessTexture=this._material.specularRoughnessTexture,this._material.specularRoughness=1,this._material.specularRoughnessTexture=null)),this.transmissionWeight>0&&(this._material.geometryThinWalled||this._material.transmissionDepth===0?(this._material.transmissionColor=this._material.baseColor,this._material.transmissionColorTexture=this._material.baseColorTexture):this._material.coatWeight==0&&(!this.baseColor.equals(ge.White())||this.baseColorTexture!==null)&&(this._material.coatWeight=this.transmissionWeight,this._material.coatWeightTexture=this.transmissionWeightTexture,this._material.coatColor=this.baseColor,this._material.coatColorTexture=this.baseColorTexture,this._material.coatIor=this._material.specularIor,this._material.coatDarkening=0,this._material.coatRoughness=this._material.specularRoughness,this._material.coatRoughnessTexture=this._material.specularRoughnessTexture))}}});var YL,Mr,m6=C(()=>{Gt();Ut();Oa();Bf();YL=class extends xr{constructor(){super(...arguments),this.BRDF_V_HEIGHT_CORRELATED=!1,this.MS_BRDF_ENERGY_CONSERVATION=!1,this.SPHERICAL_HARMONICS=!1,this.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=!1,this.MIX_IBL_RADIANCE_WITH_IRRADIANCE=!0,this.LEGACY_SPECULAR_ENERGY_CONSERVATION=!1,this.BASE_DIFFUSE_MODEL=0,this.DIELECTRIC_SPECULAR_MODEL=0,this.CONDUCTOR_SPECULAR_MODEL=0}},Mr=class n extends Vr{_markAllSubMeshesAsMiscDirty(){this._internalMarkAllSubMeshesAsMiscDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRBRDF",90,new YL,t),this._useEnergyConservation=n.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=n.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=n.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=n.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=n.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=n.DEFAULT_USE_SPHERICAL_HARMONICS,this._useSpecularGlossinessInputEnergyConservation=n.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this.useSpecularGlossinessInputEnergyConservation=n.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this._mixIblRadianceWithIrradiance=n.DEFAULT_MIX_IBL_RADIANCE_WITH_IRRADIANCE,this.mixIblRadianceWithIrradiance=n.DEFAULT_MIX_IBL_RADIANCE_WITH_IRRADIANCE,this._useLegacySpecularEnergyConservation=n.DEFAULT_USE_LEGACY_SPECULAR_ENERGY_CONSERVATION,this.useLegacySpecularEnergyConservation=n.DEFAULT_USE_LEGACY_SPECULAR_ENERGY_CONSERVATION,this._baseDiffuseModel=n.DEFAULT_DIFFUSE_MODEL,this.baseDiffuseModel=n.DEFAULT_DIFFUSE_MODEL,this._dielectricSpecularModel=n.DEFAULT_DIELECTRIC_SPECULAR_MODEL,this.dielectricSpecularModel=n.DEFAULT_DIELECTRIC_SPECULAR_MODEL,this._conductorSpecularModel=n.DEFAULT_CONDUCTOR_SPECULAR_MODEL,this.conductorSpecularModel=n.DEFAULT_CONDUCTOR_SPECULAR_MODEL,this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16],this._enable(!0)}prepareDefines(e){e.BRDF_V_HEIGHT_CORRELATED=this._useSmithVisibilityHeightCorrelated,e.MS_BRDF_ENERGY_CONSERVATION=this._useEnergyConservation&&this._useSmithVisibilityHeightCorrelated,e.SPHERICAL_HARMONICS=this._useSphericalHarmonics,e.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=this._useSpecularGlossinessInputEnergyConservation,e.MIX_IBL_RADIANCE_WITH_IRRADIANCE=this._mixIblRadianceWithIrradiance&&!this._material._disableLighting,e.LEGACY_SPECULAR_ENERGY_CONSERVATION=this._useLegacySpecularEnergyConservation,e.BASE_DIFFUSE_MODEL=this._baseDiffuseModel,e.DIELECTRIC_SPECULAR_MODEL=this._dielectricSpecularModel,e.CONDUCTOR_SPECULAR_MODEL=this._conductorSpecularModel}getClassName(){return"PBRBRDFConfiguration"}};Mr.DEFAULT_USE_ENERGY_CONSERVATION=!0;Mr.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0;Mr.DEFAULT_USE_SPHERICAL_HARMONICS=!0;Mr.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0;Mr.DEFAULT_MIX_IBL_RADIANCE_WITH_IRRADIANCE=!0;Mr.DEFAULT_USE_LEGACY_SPECULAR_ENERGY_CONSERVATION=!0;Mr.DEFAULT_DIFFUSE_MODEL=0;Mr.DEFAULT_DIELECTRIC_SPECULAR_MODEL=0;Mr.DEFAULT_CONDUCTOR_SPECULAR_MODEL=0;P([w(),oe("_markAllSubMeshesAsMiscDirty")],Mr.prototype,"useEnergyConservation",void 0);P([w(),oe("_markAllSubMeshesAsMiscDirty")],Mr.prototype,"useSmithVisibilityHeightCorrelated",void 0);P([w(),oe("_markAllSubMeshesAsMiscDirty")],Mr.prototype,"useSphericalHarmonics",void 0);P([w(),oe("_markAllSubMeshesAsMiscDirty")],Mr.prototype,"useSpecularGlossinessInputEnergyConservation",void 0);P([w(),oe("_markAllSubMeshesAsMiscDirty")],Mr.prototype,"mixIblRadianceWithIrradiance",void 0);P([w(),oe("_markAllSubMeshesAsMiscDirty")],Mr.prototype,"useLegacySpecularEnergyConservation",void 0);P([w("baseDiffuseModel"),oe("_markAllSubMeshesAsMiscDirty")],Mr.prototype,"baseDiffuseModel",void 0);P([w("dielectricSpecularModel"),oe("_markAllSubMeshesAsMiscDirty")],Mr.prototype,"dielectricSpecularModel",void 0);P([w("conductorSpecularModel"),oe("_markAllSubMeshesAsMiscDirty")],Mr.prototype,"conductorSpecularModel",void 0)});var KL,sn,p6=C(()=>{Gt();Ut();zt();Da();Bf();Oa();Un();KL=class extends xr{constructor(){super(...arguments),this.CLEARCOAT=!1,this.CLEARCOAT_DEFAULTIOR=!1,this.CLEARCOAT_TEXTURE=!1,this.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this.CLEARCOAT_TEXTUREDIRECTUV=0,this.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV=0,this.CLEARCOAT_BUMP=!1,this.CLEARCOAT_BUMPDIRECTUV=0,this.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,this.CLEARCOAT_REMAP_F0=!1,this.CLEARCOAT_TINT=!1,this.CLEARCOAT_TINT_TEXTURE=!1,this.CLEARCOAT_TINT_TEXTUREDIRECTUV=0,this.CLEARCOAT_TINT_GAMMATEXTURE=!1}},sn=class n extends Vr{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRClearCoat",100,new KL,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.roughness=0,this._indexOfRefraction=n._DefaultIndexOfRefraction,this.indexOfRefraction=n._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._useRoughnessFromMainTexture=!0,this.useRoughnessFromMainTexture=!0,this._textureRoughness=null,this.textureRoughness=null,this._remapF0OnInterfaceChange=!0,this.remapF0OnInterfaceChange=!0,this._bumpTexture=null,this.bumpTexture=null,this._isTintEnabled=!1,this.isTintEnabled=!1,this.tintColor=ge.White(),this.tintColorAtDistance=1,this.tintThickness=1,this._tintTexture=null,this.tintTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){if(!this._isEnabled)return!0;let r=this._material._disableBumpMap;return!(e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&le.ClearCoatTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._textureRoughness&&le.ClearCoatTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking()||i.getCaps().standardDerivatives&&this._bumpTexture&&le.ClearCoatBumpTextureEnabled&&!r&&!this._bumpTexture.isReady()||this._isTintEnabled&&this._tintTexture&&le.ClearCoatTintTextureEnabled&&!this._tintTexture.isReadyOrNotBlocking()))}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.CLEARCOAT=!0,e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,e.CLEARCOAT_REMAP_F0=this._remapF0OnInterfaceChange,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&le.ClearCoatTextureEnabled?ri(this._texture,e,"CLEARCOAT_TEXTURE"):e.CLEARCOAT_TEXTURE=!1,this._textureRoughness&&le.ClearCoatTextureEnabled?ri(this._textureRoughness,e,"CLEARCOAT_TEXTURE_ROUGHNESS"):e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this._bumpTexture&&le.ClearCoatBumpTextureEnabled?ri(this._bumpTexture,e,"CLEARCOAT_BUMP"):e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_DEFAULTIOR=this._indexOfRefraction===n._DefaultIndexOfRefraction,this._isTintEnabled?(e.CLEARCOAT_TINT=!0,this._tintTexture&&le.ClearCoatTintTextureEnabled?(ri(this._tintTexture,e,"CLEARCOAT_TINT_TEXTURE"),e.CLEARCOAT_TINT_GAMMATEXTURE=this._tintTexture.gammaSpace):e.CLEARCOAT_TINT_TEXTURE=!1):(e.CLEARCOAT_TINT=!1,e.CLEARCOAT_TINT_TEXTURE=!1))):(e.CLEARCOAT=!1,e.CLEARCOAT_TEXTURE=!1,e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_TINT=!1,e.CLEARCOAT_TINT_TEXTURE=!1,e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.CLEARCOAT_DEFAULTIOR=!1,e.CLEARCOAT_TEXTUREDIRECTUV=0,e.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV=0,e.CLEARCOAT_BUMPDIRECTUV=0,e.CLEARCOAT_REMAP_F0=!1,e.CLEARCOAT_TINT_TEXTUREDIRECTUV=0,e.CLEARCOAT_TINT_GAMMATEXTURE=!1)}bindForSubMesh(e,t,i,r){var f,h,d,u,m,p,_,g;if(!this._isEnabled)return;let s=r.materialDefines,a=this._material.isFrozen,o=this._material._disableBumpMap,l=this._material._invertNormalMapX,c=this._material._invertNormalMapY;if(!e.useUbo||!a||!e.isSync){(this._texture||this._textureRoughness)&&le.ClearCoatTextureEnabled&&(e.updateFloat4("vClearCoatInfos",(h=(f=this._texture)==null?void 0:f.coordinatesIndex)!=null?h:0,(u=(d=this._texture)==null?void 0:d.level)!=null?u:0,(p=(m=this._textureRoughness)==null?void 0:m.coordinatesIndex)!=null?p:0,(g=(_=this._textureRoughness)==null?void 0:_.level)!=null?g:0),this._texture&&ni(this._texture,e,"clearCoat"),this._textureRoughness&&!s.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&ni(this._textureRoughness,e,"clearCoatRoughness")),this._bumpTexture&&i.getCaps().standardDerivatives&&le.ClearCoatTextureEnabled&&!o&&(e.updateFloat2("vClearCoatBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level),ni(this._bumpTexture,e,"clearCoatBump"),t._mirroredCameraPosition?e.updateFloat2("vClearCoatTangentSpaceParams",l?1:-1,c?1:-1):e.updateFloat2("vClearCoatTangentSpaceParams",l?-1:1,c?-1:1)),this._tintTexture&&le.ClearCoatTintTextureEnabled&&(e.updateFloat2("vClearCoatTintInfos",this._tintTexture.coordinatesIndex,this._tintTexture.level),ni(this._tintTexture,e,"clearCoatTint")),e.updateFloat2("vClearCoatParams",this.intensity,this.roughness);let v=1-this._indexOfRefraction,x=1+this._indexOfRefraction,A=Math.pow(-v/x,2),S=1/this._indexOfRefraction;e.updateFloat4("vClearCoatRefractionParams",A,S,v,x),this._isTintEnabled&&(e.updateFloat4("vClearCoatTintParams",this.tintColor.r,this.tintColor.g,this.tintColor.b,Math.max(1e-5,this.tintThickness)),e.updateFloat("clearCoatColorAtDistance",Math.max(1e-5,this.tintColorAtDistance)))}t.texturesEnabled&&(this._texture&&le.ClearCoatTextureEnabled&&e.setTexture("clearCoatSampler",this._texture),this._textureRoughness&&!s.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&le.ClearCoatTextureEnabled&&e.setTexture("clearCoatRoughnessSampler",this._textureRoughness),this._bumpTexture&&i.getCaps().standardDerivatives&&le.ClearCoatBumpTextureEnabled&&!o&&e.setTexture("clearCoatBumpSampler",this._bumpTexture),this._isTintEnabled&&this._tintTexture&&le.ClearCoatTintTextureEnabled&&e.setTexture("clearCoatTintSampler",this._tintTexture))}hasTexture(e){return this._texture===e||this._textureRoughness===e||this._bumpTexture===e||this._tintTexture===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._textureRoughness&&e.push(this._textureRoughness),this._bumpTexture&&e.push(this._bumpTexture),this._tintTexture&&e.push(this._tintTexture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._tintTexture&&this._tintTexture.animations&&this._tintTexture.animations.length>0&&e.push(this._tintTexture)}dispose(e){var t,i,r,s;e&&((t=this._texture)==null||t.dispose(),(i=this._textureRoughness)==null||i.dispose(),(r=this._bumpTexture)==null||r.dispose(),(s=this._tintTexture)==null||s.dispose())}getClassName(){return"PBRClearCoatConfiguration"}addFallbacks(e,t,i){return e.CLEARCOAT_BUMP&&t.addFallback(i++,"CLEARCOAT_BUMP"),e.CLEARCOAT_TINT&&t.addFallback(i++,"CLEARCOAT_TINT"),e.CLEARCOAT&&t.addFallback(i++,"CLEARCOAT"),i}getSamplers(e){e.push("clearCoatSampler","clearCoatRoughnessSampler","clearCoatBumpSampler","clearCoatTintSampler")}getUniforms(){return{ubo:[{name:"vClearCoatParams",size:2,type:"vec2"},{name:"vClearCoatRefractionParams",size:4,type:"vec4"},{name:"vClearCoatInfos",size:4,type:"vec4"},{name:"clearCoatMatrix",size:16,type:"mat4"},{name:"clearCoatRoughnessMatrix",size:16,type:"mat4"},{name:"vClearCoatBumpInfos",size:2,type:"vec2"},{name:"vClearCoatTangentSpaceParams",size:2,type:"vec2"},{name:"clearCoatBumpMatrix",size:16,type:"mat4"},{name:"vClearCoatTintParams",size:4,type:"vec4"},{name:"clearCoatColorAtDistance",size:1,type:"float"},{name:"vClearCoatTintInfos",size:2,type:"vec2"},{name:"clearCoatTintMatrix",size:16,type:"mat4"}]}}};sn._DefaultIndexOfRefraction=1.5;P([w(),oe("_markAllSubMeshesAsTexturesDirty")],sn.prototype,"isEnabled",void 0);P([w()],sn.prototype,"intensity",void 0);P([w()],sn.prototype,"roughness",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],sn.prototype,"indexOfRefraction",void 0);P([Bt(),oe("_markAllSubMeshesAsTexturesDirty")],sn.prototype,"texture",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],sn.prototype,"useRoughnessFromMainTexture",void 0);P([Bt(),oe("_markAllSubMeshesAsTexturesDirty")],sn.prototype,"textureRoughness",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],sn.prototype,"remapF0OnInterfaceChange",void 0);P([Bt(),oe("_markAllSubMeshesAsTexturesDirty")],sn.prototype,"bumpTexture",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],sn.prototype,"isTintEnabled",void 0);P([_r()],sn.prototype,"tintColor",void 0);P([w()],sn.prototype,"tintColorAtDistance",void 0);P([w()],sn.prototype,"tintThickness",void 0);P([Bt(),oe("_markAllSubMeshesAsTexturesDirty")],sn.prototype,"tintTexture",void 0)});var jL,Ds,_6=C(()=>{Gt();Ut();Da();Bf();Oa();Un();jL=class extends xr{constructor(){super(...arguments),this.IRIDESCENCE=!1,this.IRIDESCENCE_TEXTURE=!1,this.IRIDESCENCE_TEXTUREDIRECTUV=0,this.IRIDESCENCE_THICKNESS_TEXTURE=!1,this.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0}},Ds=class n extends Vr{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRIridescence",110,new jL,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.minimumThickness=n._DefaultMinimumThickness,this.maximumThickness=n._DefaultMaximumThickness,this.indexOfRefraction=n._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._thicknessTexture=null,this.thicknessTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){return this._isEnabled?!(e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&le.IridescenceTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._thicknessTexture&&le.IridescenceTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())):!0}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.IRIDESCENCE=!0,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&le.IridescenceTextureEnabled?ri(this._texture,e,"IRIDESCENCE_TEXTURE"):e.IRIDESCENCE_TEXTURE=!1,this._thicknessTexture&&le.IridescenceTextureEnabled?ri(this._thicknessTexture,e,"IRIDESCENCE_THICKNESS_TEXTURE"):e.IRIDESCENCE_THICKNESS_TEXTURE=!1)):(e.IRIDESCENCE=!1,e.IRIDESCENCE_TEXTURE=!1,e.IRIDESCENCE_THICKNESS_TEXTURE=!1,e.IRIDESCENCE_TEXTUREDIRECTUV=0,e.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0)}bindForSubMesh(e,t){var r,s,a,o,l,c,f,h;if(!this._isEnabled)return;let i=this._material.isFrozen;(!e.useUbo||!i||!e.isSync)&&((this._texture||this._thicknessTexture)&&le.IridescenceTextureEnabled&&(e.updateFloat4("vIridescenceInfos",(s=(r=this._texture)==null?void 0:r.coordinatesIndex)!=null?s:0,(o=(a=this._texture)==null?void 0:a.level)!=null?o:0,(c=(l=this._thicknessTexture)==null?void 0:l.coordinatesIndex)!=null?c:0,(h=(f=this._thicknessTexture)==null?void 0:f.level)!=null?h:0),this._texture&&ni(this._texture,e,"iridescence"),this._thicknessTexture&&ni(this._thicknessTexture,e,"iridescenceThickness")),e.updateFloat4("vIridescenceParams",this.intensity,this.indexOfRefraction,this.minimumThickness,this.maximumThickness)),t.texturesEnabled&&(this._texture&&le.IridescenceTextureEnabled&&e.setTexture("iridescenceSampler",this._texture),this._thicknessTexture&&le.IridescenceTextureEnabled&&e.setTexture("iridescenceThicknessSampler",this._thicknessTexture))}hasTexture(e){return this._texture===e||this._thicknessTexture===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._thicknessTexture&&e.push(this._thicknessTexture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture)}dispose(e){var t,i;e&&((t=this._texture)==null||t.dispose(),(i=this._thicknessTexture)==null||i.dispose())}getClassName(){return"PBRIridescenceConfiguration"}addFallbacks(e,t,i){return e.IRIDESCENCE&&t.addFallback(i++,"IRIDESCENCE"),i}getSamplers(e){e.push("iridescenceSampler","iridescenceThicknessSampler")}getUniforms(){return{ubo:[{name:"vIridescenceParams",size:4,type:"vec4"},{name:"vIridescenceInfos",size:4,type:"vec4"},{name:"iridescenceMatrix",size:16,type:"mat4"},{name:"iridescenceThicknessMatrix",size:16,type:"mat4"}]}}};Ds._DefaultMinimumThickness=100;Ds._DefaultMaximumThickness=400;Ds._DefaultIndexOfRefraction=1.3;P([w(),oe("_markAllSubMeshesAsTexturesDirty")],Ds.prototype,"isEnabled",void 0);P([w()],Ds.prototype,"intensity",void 0);P([w()],Ds.prototype,"minimumThickness",void 0);P([w()],Ds.prototype,"maximumThickness",void 0);P([w()],Ds.prototype,"indexOfRefraction",void 0);P([Bt(),oe("_markAllSubMeshesAsTexturesDirty")],Ds.prototype,"texture",void 0);P([Bt(),oe("_markAllSubMeshesAsTexturesDirty")],Ds.prototype,"thicknessTexture",void 0)});var qL,Rc,g6=C(()=>{Gt();Ut();Gi();Ve();Da();Bf();Oa();Un();qL=class extends xr{constructor(){super(...arguments),this.ANISOTROPIC=!1,this.ANISOTROPIC_TEXTURE=!1,this.ANISOTROPIC_TEXTUREDIRECTUV=0,this.ANISOTROPIC_LEGACY=!1,this.MAINUV1=!1}},Rc=class extends Vr{set angle(e){this.direction.x=Math.cos(e),this.direction.y=Math.sin(e)}get angle(){return Math.atan2(this.direction.y,this.direction.x)}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markAllSubMeshesAsMiscDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsMiscDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRAnisotropic",110,new qL,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new we(1,0),this._texture=null,this.texture=null,this._legacy=!1,this.legacy=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16]}isReadyForSubMesh(e,t){return this._isEnabled?!(e._areTexturesDirty&&t.texturesEnabled&&this._texture&&le.AnisotropicTextureEnabled&&!this._texture.isReadyOrNotBlocking()):!0}prepareDefinesBeforeAttributes(e,t,i){this._isEnabled?(e.ANISOTROPIC=this._isEnabled,this._isEnabled&&!i.isVerticesDataPresent(L.TangentKind)&&(e._needUVs=!0,e.MAINUV1=!0),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&le.AnisotropicTextureEnabled?ri(this._texture,e,"ANISOTROPIC_TEXTURE"):e.ANISOTROPIC_TEXTURE=!1),e._areMiscDirty&&(e.ANISOTROPIC_LEGACY=this._legacy)):(e.ANISOTROPIC=!1,e.ANISOTROPIC_TEXTURE=!1,e.ANISOTROPIC_TEXTUREDIRECTUV=0,e.ANISOTROPIC_LEGACY=!1)}bindForSubMesh(e,t){if(!this._isEnabled)return;let i=this._material.isFrozen;(!e.useUbo||!i||!e.isSync)&&(this._texture&&le.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),ni(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&&le.AnisotropicTextureEnabled&&e.setTexture("anisotropySampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){e&&this._texture&&this._texture.dispose()}getClassName(){return"PBRAnisotropicConfiguration"}addFallbacks(e,t,i){return e.ANISOTROPIC&&t.addFallback(i++,"ANISOTROPIC"),i}getSamplers(e){e.push("anisotropySampler")}getUniforms(){return{ubo:[{name:"vAnisotropy",size:3,type:"vec3"},{name:"vAnisotropyInfos",size:2,type:"vec2"},{name:"anisotropyMatrix",size:16,type:"mat4"}]}}parse(e,t,i){super.parse(e,t,i),e.legacy===void 0&&(this.legacy=!0)}};P([w(),oe("_markAllSubMeshesAsTexturesDirty")],Rc.prototype,"isEnabled",void 0);P([w()],Rc.prototype,"intensity",void 0);P([tm()],Rc.prototype,"direction",void 0);P([Bt(),oe("_markAllSubMeshesAsTexturesDirty")],Rc.prototype,"texture",void 0);P([w(),oe("_markAllSubMeshesAsMiscDirty")],Rc.prototype,"legacy",void 0)});var ZL,$s,v6=C(()=>{Gt();Ut();zt();Da();Bf();Oa();Un();ZL=class extends xr{constructor(){super(...arguments),this.SHEEN=!1,this.SHEEN_TEXTURE=!1,this.SHEEN_GAMMATEXTURE=!1,this.SHEEN_TEXTURE_ROUGHNESS=!1,this.SHEEN_TEXTUREDIRECTUV=0,this.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0,this.SHEEN_LINKWITHALBEDO=!1,this.SHEEN_ROUGHNESS=!1,this.SHEEN_ALBEDOSCALING=!1,this.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1}},$s=class extends Vr{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"Sheen",120,new ZL,t),this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=ge.White(),this._texture=null,this.texture=null,this._useRoughnessFromMainTexture=!0,this.useRoughnessFromMainTexture=!0,this._roughness=null,this.roughness=null,this._textureRoughness=null,this.textureRoughness=null,this._albedoScaling=!1,this.albedoScaling=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){return this._isEnabled?!(e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&le.SheenTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._textureRoughness&&le.SheenTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking())):!0}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.SHEEN=!0,e.SHEEN_LINKWITHALBEDO=this._linkSheenWithAlbedo,e.SHEEN_ROUGHNESS=this._roughness!==null,e.SHEEN_ALBEDOSCALING=this._albedoScaling,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&le.SheenTextureEnabled?(ri(this._texture,e,"SHEEN_TEXTURE"),e.SHEEN_GAMMATEXTURE=this._texture.gammaSpace):e.SHEEN_TEXTURE=!1,this._textureRoughness&&le.SheenTextureEnabled?ri(this._textureRoughness,e,"SHEEN_TEXTURE_ROUGHNESS"):e.SHEEN_TEXTURE_ROUGHNESS=!1)):(e.SHEEN=!1,e.SHEEN_TEXTURE=!1,e.SHEEN_TEXTURE_ROUGHNESS=!1,e.SHEEN_LINKWITHALBEDO=!1,e.SHEEN_ROUGHNESS=!1,e.SHEEN_ALBEDOSCALING=!1,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.SHEEN_GAMMATEXTURE=!1,e.SHEEN_TEXTUREDIRECTUV=0,e.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0)}bindForSubMesh(e,t,i,r){var o,l,c,f,h,d,u,m;if(!this._isEnabled)return;let s=r.materialDefines,a=this._material.isFrozen;(!e.useUbo||!a||!e.isSync)&&((this._texture||this._textureRoughness)&&le.SheenTextureEnabled&&(e.updateFloat4("vSheenInfos",(l=(o=this._texture)==null?void 0:o.coordinatesIndex)!=null?l:0,(f=(c=this._texture)==null?void 0:c.level)!=null?f:0,(d=(h=this._textureRoughness)==null?void 0:h.coordinatesIndex)!=null?d:0,(m=(u=this._textureRoughness)==null?void 0:u.level)!=null?m:0),this._texture&&ni(this._texture,e,"sheen"),this._textureRoughness&&!s.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&ni(this._textureRoughness,e,"sheenRoughness")),e.updateFloat4("vSheenColor",this.color.r,this.color.g,this.color.b,this.intensity),this._roughness!==null&&e.updateFloat("vSheenRoughness",this._roughness)),t.texturesEnabled&&(this._texture&&le.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture),this._textureRoughness&&!s.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&le.SheenTextureEnabled&&e.setTexture("sheenRoughnessSampler",this._textureRoughness))}hasTexture(e){return this._texture===e||this._textureRoughness===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._textureRoughness&&e.push(this._textureRoughness)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness)}dispose(e){var t,i;e&&((t=this._texture)==null||t.dispose(),(i=this._textureRoughness)==null||i.dispose())}getClassName(){return"PBRSheenConfiguration"}addFallbacks(e,t,i){return e.SHEEN&&t.addFallback(i++,"SHEEN"),i}getSamplers(e){e.push("sheenSampler","sheenRoughnessSampler")}getUniforms(){return{ubo:[{name:"vSheenColor",size:4,type:"vec4"},{name:"vSheenRoughness",size:1,type:"float"},{name:"vSheenInfos",size:4,type:"vec4"},{name:"sheenMatrix",size:16,type:"mat4"},{name:"sheenRoughnessMatrix",size:16,type:"mat4"}]}}};P([w(),oe("_markAllSubMeshesAsTexturesDirty")],$s.prototype,"isEnabled",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],$s.prototype,"linkSheenWithAlbedo",void 0);P([w()],$s.prototype,"intensity",void 0);P([_r()],$s.prototype,"color",void 0);P([Bt(),oe("_markAllSubMeshesAsTexturesDirty")],$s.prototype,"texture",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],$s.prototype,"useRoughnessFromMainTexture",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],$s.prototype,"roughness",void 0);P([Bt(),oe("_markAllSubMeshesAsTexturesDirty")],$s.prototype,"textureRoughness",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],$s.prototype,"albedoScaling",void 0)});var QL,Ai,E6=C(()=>{Gt();Ut();zt();Da();Ve();Bf();Oa();Un();QL=class extends xr{constructor(){super(...arguments),this.SUBSURFACE=!1,this.SS_REFRACTION=!1,this.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=!1,this.SS_TRANSLUCENCY=!1,this.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=!1,this.SS_SCATTERING=!1,this.SS_DISPERSION=!1,this.SS_THICKNESSANDMASK_TEXTURE=!1,this.SS_THICKNESSANDMASK_TEXTUREDIRECTUV=0,this.SS_HAS_THICKNESS=!1,this.SS_REFRACTIONINTENSITY_TEXTURE=!1,this.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV=0,this.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,this.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV=0,this.SS_TRANSLUCENCYCOLOR_TEXTURE=!1,this.SS_TRANSLUCENCYCOLOR_TEXTUREDIRECTUV=0,this.SS_TRANSLUCENCYCOLOR_TEXTURE_GAMMA=!1,this.SS_REFRACTIONMAP_3D=!1,this.SS_REFRACTIONMAP_OPPOSITEZ=!1,this.SS_LODINREFRACTIONALPHA=!1,this.SS_GAMMAREFRACTION=!1,this.SS_RGBDREFRACTION=!1,this.SS_LINEARSPECULARREFRACTION=!1,this.SS_LINKREFRACTIONTOTRANSPARENCY=!1,this.SS_ALBEDOFORREFRACTIONTINT=!1,this.SS_ALBEDOFORTRANSLUCENCYTINT=!1,this.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.SS_USE_THICKNESS_AS_DEPTH=!1,this.SS_USE_GLTF_TEXTURES=!1,this.SS_APPLY_ALBEDO_AFTER_SUBSURFACE=!1,this.SS_TRANSLUCENCY_LEGACY=!1}},Ai=class n extends Vr{get scatteringDiffusionProfile(){return this._scene.subSurfaceConfiguration?this._scene.subSurfaceConfiguration.ssDiffusionProfileColors[this._scatteringDiffusionProfileIndex]:null}set scatteringDiffusionProfile(e){this._scene.enableSubSurfaceForPrePass()&&e&&(this._scatteringDiffusionProfileIndex=this._scene.subSurfaceConfiguration.addDiffusionProfile(e))}get volumeIndexOfRefraction(){return this._volumeIndexOfRefraction>=1?this._volumeIndexOfRefraction:this._indexOfRefraction}set volumeIndexOfRefraction(e){e>=1?this._volumeIndexOfRefraction=e:this._volumeIndexOfRefraction=-1}get legacyTransluceny(){return this.legacyTranslucency}set legacyTransluceny(e){this.legacyTranslucency=e}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markScenePrePassDirty(){this._enable(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled),this._internalMarkAllSubMeshesAsTexturesDirty(),this._internalMarkScenePrePassDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRSubSurface",130,new QL,t),this._isRefractionEnabled=!1,this.isRefractionEnabled=!1,this._isTranslucencyEnabled=!1,this.isTranslucencyEnabled=!1,this._isDispersionEnabled=!1,this.isDispersionEnabled=!1,this._isScatteringEnabled=!1,this.isScatteringEnabled=!1,this._scatteringDiffusionProfileIndex=0,this.refractionIntensity=1,this.translucencyIntensity=1,this._useAlbedoToTintRefraction=!1,this.useAlbedoToTintRefraction=!1,this._useAlbedoToTintTranslucency=!1,this.useAlbedoToTintTranslucency=!1,this._thicknessTexture=null,this.thicknessTexture=null,this._refractionTexture=null,this.refractionTexture=null,this._indexOfRefraction=1.5,this.indexOfRefraction=1.5,this._volumeIndexOfRefraction=-1,this._invertRefractionY=!1,this.invertRefractionY=!1,this._linkRefractionWithTransparency=!1,this.linkRefractionWithTransparency=!1,this.minimumThickness=0,this.maximumThickness=1,this.useThicknessAsDepth=!1,this.tintColor=ge.White(),this.tintColorAtDistance=1,this.dispersion=0,this.diffusionDistance=ge.White(),this._useMaskFromThicknessTexture=!1,this.useMaskFromThicknessTexture=!1,this._refractionIntensityTexture=null,this.refractionIntensityTexture=null,this._translucencyIntensityTexture=null,this.translucencyIntensityTexture=null,this.translucencyColor=null,this._translucencyColorTexture=null,this.translucencyColorTexture=null,this._useGltfStyleTextures=!0,this.useGltfStyleTextures=!0,this.applyAlbedoAfterSubSurface=n.DEFAULT_APPLY_ALBEDO_AFTERSUBSURFACE,this.legacyTranslucency=n.DEFAULT_LEGACY_TRANSLUCENCY,this._scene=e.getScene(),this.registerForExtraEvents=!0,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkScenePrePassDirty=e._dirtyCallbacks[32]}isReadyForSubMesh(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._thicknessTexture&&le.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking()||this._refractionIntensityTexture&&le.RefractionIntensityTextureEnabled&&!this._refractionIntensityTexture.isReadyOrNotBlocking()||this._translucencyColorTexture&&le.TranslucencyColorTextureEnabled&&!this._translucencyColorTexture.isReadyOrNotBlocking()||this._translucencyIntensityTexture&&le.TranslucencyIntensityTextureEnabled&&!this._translucencyIntensityTexture.isReadyOrNotBlocking())return!1;let i=this._getRefractionTexture(t);if(i&&le.RefractionTextureEnabled&&!i.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled){e.SUBSURFACE=!1,e.SS_DISPERSION=!1,e.SS_TRANSLUCENCY=!1,e.SS_SCATTERING=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_THICKNESSANDMASK_TEXTURE=!1,e.SS_THICKNESSANDMASK_TEXTUREDIRECTUV=0,e.SS_HAS_THICKNESS=!1,e.SS_REFRACTIONINTENSITY_TEXTURE=!1,e.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV=0,e.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,e.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV=0,e.SS_REFRACTIONMAP_3D=!1,e.SS_REFRACTIONMAP_OPPOSITEZ=!1,e.SS_LODINREFRACTIONALPHA=!1,e.SS_GAMMAREFRACTION=!1,e.SS_RGBDREFRACTION=!1,e.SS_LINEARSPECULARREFRACTION=!1,e.SS_LINKREFRACTIONTOTRANSPARENCY=!1,e.SS_ALBEDOFORREFRACTIONTINT=!1,e.SS_ALBEDOFORTRANSLUCENCYTINT=!1,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,e.SS_USE_THICKNESS_AS_DEPTH=!1,e.SS_USE_GLTF_TEXTURES=!1,e.SS_TRANSLUCENCYCOLOR_TEXTURE=!1,e.SS_TRANSLUCENCYCOLOR_TEXTUREDIRECTUV=0,e.SS_TRANSLUCENCYCOLOR_TEXTURE_GAMMA=!1,e.SS_APPLY_ALBEDO_AFTER_SUBSURFACE=!1;return}if(e._areTexturesDirty){if(e.SUBSURFACE=!0,e.SS_DISPERSION=this._isDispersionEnabled,e.SS_TRANSLUCENCY=this._isTranslucencyEnabled,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_TRANSLUCENCY_LEGACY=this.legacyTranslucency,e.SS_SCATTERING=this._isScatteringEnabled,e.SS_THICKNESSANDMASK_TEXTURE=!1,e.SS_REFRACTIONINTENSITY_TEXTURE=!1,e.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,e.SS_HAS_THICKNESS=!1,e.SS_USE_GLTF_TEXTURES=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_REFRACTIONMAP_3D=!1,e.SS_GAMMAREFRACTION=!1,e.SS_RGBDREFRACTION=!1,e.SS_LINEARSPECULARREFRACTION=!1,e.SS_REFRACTIONMAP_OPPOSITEZ=!1,e.SS_LODINREFRACTIONALPHA=!1,e.SS_LINKREFRACTIONTOTRANSPARENCY=!1,e.SS_ALBEDOFORREFRACTIONTINT=!1,e.SS_ALBEDOFORTRANSLUCENCYTINT=!1,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,e.SS_USE_THICKNESS_AS_DEPTH=!1,e.SS_TRANSLUCENCYCOLOR_TEXTURE=!1,e.SS_APPLY_ALBEDO_AFTER_SUBSURFACE=this.applyAlbedoAfterSubSurface,e._areTexturesDirty&&t.texturesEnabled&&(this._thicknessTexture&&le.ThicknessTextureEnabled&&ri(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),this._refractionIntensityTexture&&le.RefractionIntensityTextureEnabled&&ri(this._refractionIntensityTexture,e,"SS_REFRACTIONINTENSITY_TEXTURE"),this._translucencyIntensityTexture&&le.TranslucencyIntensityTextureEnabled&&ri(this._translucencyIntensityTexture,e,"SS_TRANSLUCENCYINTENSITY_TEXTURE"),this._translucencyColorTexture&&le.TranslucencyColorTextureEnabled&&(ri(this._translucencyColorTexture,e,"SS_TRANSLUCENCYCOLOR_TEXTURE"),e.SS_TRANSLUCENCYCOLOR_TEXTURE_GAMMA=this._translucencyColorTexture.gammaSpace)),e.SS_HAS_THICKNESS=this.maximumThickness-this.minimumThickness!==0,e.SS_USE_GLTF_TEXTURES=this._useGltfStyleTextures,e.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=this._useMaskFromThicknessTexture&&!this._refractionIntensityTexture,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=this._useMaskFromThicknessTexture&&!this._translucencyIntensityTexture,this._isRefractionEnabled&&t.texturesEnabled){let i=this._getRefractionTexture(t);i&&le.RefractionTextureEnabled&&(e.SS_REFRACTION=!0,e.SS_REFRACTIONMAP_3D=i.isCube,e.SS_GAMMAREFRACTION=i.gammaSpace,e.SS_RGBDREFRACTION=i.isRGBD,e.SS_LINEARSPECULARREFRACTION=i.linearSpecularLOD,e.SS_REFRACTIONMAP_OPPOSITEZ=this._scene.useRightHandedSystem&&i.isCube?!i.invertZ:i.invertZ,e.SS_LODINREFRACTIONALPHA=i.lodLevelInAlpha,e.SS_LINKREFRACTIONTOTRANSPARENCY=this._linkRefractionWithTransparency,e.SS_ALBEDOFORREFRACTIONTINT=this._useAlbedoToTintRefraction,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=i.isCube&&i.boundingBoxSize,e.SS_USE_THICKNESS_AS_DEPTH=this.useThicknessAsDepth)}this._isTranslucencyEnabled&&(e.SS_ALBEDOFORTRANSLUCENCYTINT=this._useAlbedoToTintTranslucency)}}hardBindForSubMesh(e,t,i,r){if(!(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled))if(this.maximumThickness===0&&this.minimumThickness===0)e.updateFloat2("vThicknessParam",0,0);else{r.getRenderingMesh().getWorldMatrix().decompose($.Vector3[0]);let s=Math.max(Math.abs($.Vector3[0].x),Math.abs($.Vector3[0].y),Math.abs($.Vector3[0].z));e.updateFloat2("vThicknessParam",this.minimumThickness*s,(this.maximumThickness-this.minimumThickness)*s)}}bindForSubMesh(e,t,i,r){var f;if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;let s=r.materialDefines,a=this._material.isFrozen,o=this._material.realTimeFiltering,l=s.LODBASEDMICROSFURACE,c=this._getRefractionTexture(t);if(!e.useUbo||!a||!e.isSync){if(this._thicknessTexture&&le.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),ni(this._thicknessTexture,e,"thickness")),this._refractionIntensityTexture&&le.RefractionIntensityTextureEnabled&&s.SS_REFRACTIONINTENSITY_TEXTURE&&(e.updateFloat2("vRefractionIntensityInfos",this._refractionIntensityTexture.coordinatesIndex,this._refractionIntensityTexture.level),ni(this._refractionIntensityTexture,e,"refractionIntensity")),this._translucencyColorTexture&&le.TranslucencyColorTextureEnabled&&s.SS_TRANSLUCENCYCOLOR_TEXTURE&&(e.updateFloat2("vTranslucencyColorInfos",this._translucencyColorTexture.coordinatesIndex,this._translucencyColorTexture.level),ni(this._translucencyColorTexture,e,"translucencyColor")),this._translucencyIntensityTexture&&le.TranslucencyIntensityTextureEnabled&&s.SS_TRANSLUCENCYINTENSITY_TEXTURE&&(e.updateFloat2("vTranslucencyIntensityInfos",this._translucencyIntensityTexture.coordinatesIndex,this._translucencyIntensityTexture.level),ni(this._translucencyIntensityTexture,e,"translucencyIntensity")),c&&le.RefractionTextureEnabled){e.updateMatrix("refractionMatrix",c.getRefractionTextureMatrix());let h=1;c.isCube||c.depth&&(h=c.depth);let d=c.getSize().width,u=this.volumeIndexOfRefraction;if(e.updateFloat4("vRefractionInfos",c.level,1/u,h,this._invertRefractionY?-1:1),e.updateFloat4("vRefractionMicrosurfaceInfos",d,c.lodGenerationScale,c.lodGenerationOffset,1/this.indexOfRefraction),o&&e.updateFloat2("vRefractionFilteringInfo",d,Math.log2(d)),c.boundingBoxSize){let m=c;e.updateVector3("vRefractionPosition",m.boundingBoxPosition),e.updateVector3("vRefractionSize",m.boundingBoxSize)}}this._isScatteringEnabled&&e.updateFloat("scatteringDiffusionProfile",this._scatteringDiffusionProfileIndex),e.updateColor3("vDiffusionDistance",this.diffusionDistance),e.updateFloat4("vTintColor",this.tintColor.r,this.tintColor.g,this.tintColor.b,Math.max(1e-5,this.tintColorAtDistance)),e.updateColor4("vTranslucencyColor",(f=this.translucencyColor)!=null?f:this.tintColor,0),e.updateFloat3("vSubSurfaceIntensity",this.refractionIntensity,this.translucencyIntensity,0),e.updateFloat("dispersion",this.dispersion)}t.texturesEnabled&&(this._thicknessTexture&&le.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),this._refractionIntensityTexture&&le.RefractionIntensityTextureEnabled&&s.SS_REFRACTIONINTENSITY_TEXTURE&&e.setTexture("refractionIntensitySampler",this._refractionIntensityTexture),this._translucencyIntensityTexture&&le.TranslucencyIntensityTextureEnabled&&s.SS_TRANSLUCENCYINTENSITY_TEXTURE&&e.setTexture("translucencyIntensitySampler",this._translucencyIntensityTexture),this._translucencyColorTexture&&le.TranslucencyColorTextureEnabled&&s.SS_TRANSLUCENCYCOLOR_TEXTURE&&e.setTexture("translucencyColorSampler",this._translucencyColorTexture),c&&le.RefractionTextureEnabled&&(l?e.setTexture("refractionSampler",c):(e.setTexture("refractionSampler",c._lodTextureMid||c),e.setTexture("refractionSamplerLow",c._lodTextureLow||c),e.setTexture("refractionSamplerHigh",c._lodTextureHigh||c))))}_getRefractionTexture(e){return this._refractionTexture?this._refractionTexture:this._isRefractionEnabled?e.environmentTexture:null}get disableAlphaBlending(){return this._isRefractionEnabled&&this._linkRefractionWithTransparency}fillRenderTargetTextures(e){le.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&e.push(this._refractionTexture)}hasTexture(e){return this._thicknessTexture===e||this._refractionTexture===e||this._refractionIntensityTexture===e||this._translucencyIntensityTexture===e||this._translucencyColorTexture===e}hasRenderTargetTextures(){return!!(le.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)}getActiveTextures(e){this._thicknessTexture&&e.push(this._thicknessTexture),this._refractionTexture&&e.push(this._refractionTexture),this._refractionIntensityTexture&&e.push(this._refractionIntensityTexture),this._translucencyColorTexture&&e.push(this._translucencyColorTexture),this._translucencyIntensityTexture&&e.push(this._translucencyIntensityTexture)}getAnimatables(e){this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),this._refractionIntensityTexture&&this._refractionIntensityTexture.animations&&this._refractionIntensityTexture.animations.length>0&&e.push(this._refractionIntensityTexture),this._translucencyColorTexture&&this._translucencyColorTexture.animations&&this._translucencyColorTexture.animations.length>0&&e.push(this._translucencyColorTexture),this._translucencyIntensityTexture&&this._translucencyIntensityTexture.animations&&this._translucencyIntensityTexture.animations.length>0&&e.push(this._translucencyIntensityTexture)}dispose(e){e&&(this._thicknessTexture&&this._thicknessTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose(),this._refractionIntensityTexture&&this._refractionIntensityTexture.dispose(),this._translucencyColorTexture&&this._translucencyColorTexture.dispose(),this._translucencyIntensityTexture&&this._translucencyIntensityTexture.dispose())}getClassName(){return"PBRSubSurfaceConfiguration"}addFallbacks(e,t,i){return e.SS_SCATTERING&&t.addFallback(i++,"SS_SCATTERING"),e.SS_TRANSLUCENCY&&t.addFallback(i++,"SS_TRANSLUCENCY"),i}getSamplers(e){e.push("thicknessSampler","refractionIntensitySampler","translucencyIntensitySampler","refractionSampler","refractionSamplerLow","refractionSamplerHigh","translucencyColorSampler")}getUniforms(){return{ubo:[{name:"vRefractionMicrosurfaceInfos",size:4,type:"vec4"},{name:"vRefractionFilteringInfo",size:2,type:"vec2"},{name:"vTranslucencyIntensityInfos",size:2,type:"vec2"},{name:"vRefractionInfos",size:4,type:"vec4"},{name:"refractionMatrix",size:16,type:"mat4"},{name:"vThicknessInfos",size:2,type:"vec2"},{name:"vRefractionIntensityInfos",size:2,type:"vec2"},{name:"thicknessMatrix",size:16,type:"mat4"},{name:"refractionIntensityMatrix",size:16,type:"mat4"},{name:"translucencyIntensityMatrix",size:16,type:"mat4"},{name:"vThicknessParam",size:2,type:"vec2"},{name:"vDiffusionDistance",size:3,type:"vec3"},{name:"vTintColor",size:4,type:"vec4"},{name:"vSubSurfaceIntensity",size:3,type:"vec3"},{name:"vRefractionPosition",size:3,type:"vec3"},{name:"vRefractionSize",size:3,type:"vec3"},{name:"scatteringDiffusionProfile",size:1,type:"float"},{name:"dispersion",size:1,type:"float"},{name:"vTranslucencyColor",size:4,type:"vec4"},{name:"vTranslucencyColorInfos",size:2,type:"vec2"},{name:"translucencyColorMatrix",size:16,type:"mat4"}]}}};Ai.DEFAULT_APPLY_ALBEDO_AFTERSUBSURFACE=!1;Ai.DEFAULT_LEGACY_TRANSLUCENCY=!1;P([w(),oe("_markAllSubMeshesAsTexturesDirty")],Ai.prototype,"isRefractionEnabled",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],Ai.prototype,"isTranslucencyEnabled",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],Ai.prototype,"isDispersionEnabled",void 0);P([w(),oe("_markScenePrePassDirty")],Ai.prototype,"isScatteringEnabled",void 0);P([w()],Ai.prototype,"_scatteringDiffusionProfileIndex",void 0);P([w()],Ai.prototype,"refractionIntensity",void 0);P([w()],Ai.prototype,"translucencyIntensity",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],Ai.prototype,"useAlbedoToTintRefraction",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],Ai.prototype,"useAlbedoToTintTranslucency",void 0);P([Bt(),oe("_markAllSubMeshesAsTexturesDirty")],Ai.prototype,"thicknessTexture",void 0);P([Bt(),oe("_markAllSubMeshesAsTexturesDirty")],Ai.prototype,"refractionTexture",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],Ai.prototype,"indexOfRefraction",void 0);P([w()],Ai.prototype,"_volumeIndexOfRefraction",void 0);P([oe("_markAllSubMeshesAsTexturesDirty")],Ai.prototype,"volumeIndexOfRefraction",null);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],Ai.prototype,"invertRefractionY",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],Ai.prototype,"linkRefractionWithTransparency",void 0);P([w()],Ai.prototype,"minimumThickness",void 0);P([w()],Ai.prototype,"maximumThickness",void 0);P([w()],Ai.prototype,"useThicknessAsDepth",void 0);P([_r()],Ai.prototype,"tintColor",void 0);P([w()],Ai.prototype,"tintColorAtDistance",void 0);P([w()],Ai.prototype,"dispersion",void 0);P([_r()],Ai.prototype,"diffusionDistance",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],Ai.prototype,"useMaskFromThicknessTexture",void 0);P([Bt(),oe("_markAllSubMeshesAsTexturesDirty")],Ai.prototype,"refractionIntensityTexture",void 0);P([Bt(),oe("_markAllSubMeshesAsTexturesDirty")],Ai.prototype,"translucencyIntensityTexture",void 0);P([_r()],Ai.prototype,"translucencyColor",void 0);P([Bt(),oe("_markAllSubMeshesAsTexturesDirty")],Ai.prototype,"translucencyColorTexture",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],Ai.prototype,"useGltfStyleTextures",void 0);P([w()],Ai.prototype,"applyAlbedoAfterSubSurface",void 0);P([w()],Ai.prototype,"legacyTranslucency",void 0)});var S6,xhe,$L=C(()=>{W();ed();Lg();S6="pbrUboDeclaration",xhe=`uniform vAlbedoInfos: vec2f;uniform vBaseWeightInfos: vec2f;uniform vBaseDiffuseRoughnessInfos: vec2f;uniform vAmbientInfos: vec4f;uniform vOpacityInfos: vec2f;uniform vEmissiveInfos: vec2f;uniform vLightmapInfos: vec2f;uniform vReflectivityInfos: vec3f;uniform vMicroSurfaceSamplerInfos: vec2f;uniform vBumpInfos: vec3f;uniform albedoMatrix: mat4x4f;uniform baseWeightMatrix: mat4x4f;uniform baseDiffuseRoughnessMatrix: mat4x4f;uniform ambientMatrix: mat4x4f;uniform opacityMatrix: mat4x4f;uniform emissiveMatrix: mat4x4f;uniform lightmapMatrix: mat4x4f;uniform reflectivityMatrix: mat4x4f;uniform microSurfaceSamplerMatrix: mat4x4f;uniform bumpMatrix: mat4x4f;uniform vTangentSpaceParams: vec2f;uniform vAlbedoColor: vec4f;uniform baseWeight: f32;uniform baseDiffuseRoughness: f32;uniform vLightingIntensity: vec4f;uniform pointSize: f32;uniform vReflectivityColor: vec4f;uniform vEmissiveColor: vec3f;uniform vAmbientColor: vec3f;uniform vDebugMode: vec2f;uniform vMetallicReflectanceFactors: vec4f;uniform vMetallicReflectanceInfos: vec2f;uniform metallicReflectanceMatrix: mat4x4f;uniform vReflectanceInfos: vec2f;uniform reflectanceMatrix: mat4x4f;uniform cameraInfo: vec4f;uniform vReflectionInfos: vec2f;uniform reflectionMatrix: mat4x4f;uniform vReflectionMicrosurfaceInfos: vec3f;uniform vReflectionPosition: vec3f;uniform vReflectionSize: vec3f;uniform vReflectionFilteringInfo: vec2f;uniform vReflectionDominantDirection: vec3f;uniform vReflectionColor: vec3f;uniform vSphericalL00: vec3f;uniform vSphericalL1_1: vec3f;uniform vSphericalL10: vec3f;uniform vSphericalL11: vec3f;uniform vSphericalL2_2: vec3f;uniform vSphericalL2_1: vec3f;uniform vSphericalL20: vec3f;uniform vSphericalL21: vec3f;uniform vSphericalL22: vec3f;uniform vSphericalX: vec3f;uniform vSphericalY: vec3f;uniform vSphericalZ: vec3f;uniform vSphericalXX_ZZ: vec3f;uniform vSphericalYY_ZZ: vec3f;uniform vSphericalZZ: vec3f;uniform vSphericalXY: vec3f;uniform vSphericalYZ: vec3f;uniform vSphericalZX: vec3f; +`;T.ShadersStore[kL]||(T.ShadersStore[kL]=o6);Ahe={name:kL,shader:o6}});var f6={};tt(f6,{OpenPBRMaterial:()=>Ne,OpenPBRMaterialDefines:()=>Kg});var ap,IR,ai,Ti,WL,HL,Kg,zL,Ne,h6=C(()=>{Gt();Vt();SR();zt();q_();Fr();Hi();Vn();Tr();La();qA();Df();ol();_g();Un();ki();ZA();jA();Pa();Pt();QA();$A();d5();Ge();JA();pg();so();Ii();Z5();ap={effect:null,subMesh:null},IR=class n{populateVectorFromLinkedProperties(e){let t=e.dimension[0];for(let i in this.linkedProperties){let r=this.linkedProperties[i],s=r.numComponents;if(tt-s){s==1?te.Error(`Float property ${r.name} has an offset that is too large.`):te.Error(`Vector${s} property ${r.name} won't fit in Vector${t} or has an offset that is too large.`);return}typeof r.value=="number"?n._tmpArray[r.targetUniformComponentOffset]=r.value:r.value.toArray(n._tmpArray,r.targetUniformComponentOffset)}e.fromArray(n._tmpArray)}constructor(e,t){this.linkedProperties={},this.firstLinkedKey="",this.name=e,this.numComponents=t}};IR._tmpArray=[0,0,0,0];ai=class{constructor(e,t,i,r,s=0,a){this.targetUniformComponentNum=4,this.targetUniformComponentOffset=0,this.name=e,this.targetUniformName=i,this.defaultValue=t,this.value=t,this.targetUniformComponentNum=r,this.targetUniformComponentOffset=s,this.requiredDefine=a}get numComponents(){return typeof this.defaultValue=="number"?1:this.defaultValue.dimension[0]}},Ti=class{get samplerName(){return this.samplerPrefix+"Sampler"}get samplerInfoName(){return"v"+this.samplerPrefix.charAt(0).toUpperCase()+this.samplerPrefix.slice(1)+"Infos"}get samplerMatrixName(){return this.samplerPrefix+"Matrix"}constructor(e,t,i){this.value=null,this.samplerPrefix="",this.textureDefine="",this.name=e,this.samplerPrefix=t,this.textureDefine=i}},WL=class extends Ym(Xm(xr)){},HL=class extends h5(WL){},Kg=class extends Hm(HL){constructor(e){super(e),this.NUM_SAMPLES="0",this.REALTIME_FILTERING=!1,this.IBL_CDF_FILTERING=!1,this.LIGHTCOUNT=0,this.VERTEXCOLOR=!1,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.VERTEXALPHA=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHABLEND=!1,this.ALPHA_FROM_BASE_COLOR_TEXTURE=!1,this.ALPHATESTVALUE="0.5",this.PREMULTIPLYALPHA=!1,this.REFLECTIVITY_GAMMA=!1,this.REFLECTIVITYDIRECTUV=0,this.SPECULARTERM=!1,this.LODBASEDMICROSFURACE=!0,this.SPECULAR_ROUGHNESS_FROM_METALNESS_TEXTURE_GREEN=!1,this.BASE_METALNESS_FROM_METALNESS_TEXTURE_BLUE=!1,this.AOSTOREINMETALMAPRED=!1,this.SPECULAR_WEIGHT_IN_ALPHA=!1,this.SPECULAR_WEIGHT_FROM_SPECULAR_COLOR_TEXTURE=!1,this.SPECULAR_ROUGHNESS_ANISOTROPY_FROM_TANGENT_TEXTURE=!1,this.COAT_ROUGHNESS_FROM_GREEN_CHANNEL=!1,this.COAT_ROUGHNESS_ANISOTROPY_FROM_TANGENT_TEXTURE=!1,this.USE_GLTF_STYLE_ANISOTROPY=!1,this.THIN_FILM_THICKNESS_FROM_THIN_FILM_TEXTURE=!1,this.FUZZ_ROUGHNESS_FROM_TEXTURE_ALPHA=!1,this.GEOMETRY_THICKNESS_FROM_GREEN_CHANNEL=!1,this.ENVIRONMENTBRDF=!1,this.ENVIRONMENTBRDF_RGBD=!1,this.FUZZENVIRONMENTBRDF=!1,this.NORMAL=!1,this.TANGENT=!1,this.OBJECTSPACE_NORMALMAP=!1,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.NORMALXYSCALE=!0,this.ANISOTROPIC=!1,this.ANISOTROPIC_OPENPBR=!0,this.ANISOTROPIC_BASE=!1,this.ANISOTROPIC_COAT=!1,this.FUZZ_IBL_SAMPLES=6,this.REFRACTION_HIGH_QUALITY_BLUR=!1,this.FUZZ=!1,this.THIN_FILM=!1,this.IRIDESCENCE=!1,this.DISPERSION=!1,this.SCATTERING=!1,this.USE_IRRADIANCE_TEXTURE_FOR_SCATTERING=!1,this.SSS_SAMPLE_COUNT=16,this.USE_IRRADIANCE_TEXTURE_FOR_SCATTERING_GBUFFER=!1,this.TRANSMISSION_SLAB=!1,this.TRANSMISSION_SLAB_VOLUME=!1,this.SUBSURFACE_SLAB=!1,this.GEOMETRY_THIN_WALLED=!1,this.REFRACTED_BACKGROUND=!1,this.REFRACTED_LIGHTS=!1,this.REFRACTED_ENVIRONMENT=!1,this.REFRACTED_ENVIRONMENT_OPPOSITEZ=!1,this.REFRACTED_ENVIRONMENT_LOCAL_CUBE=!1,this.RADIANCEOCCLUSION=!1,this.HORIZONOCCLUSION=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.NONUNIFORMSCALING=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_POSITION=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.MORPHTARGETS_UV2=!1,this.MORPHTARGETS_COLOR=!1,this.MORPHTARGETTEXTURE_HASPOSITIONS=!1,this.MORPHTARGETTEXTURE_HASNORMALS=!1,this.MORPHTARGETTEXTURE_HASTANGENTS=!1,this.MORPHTARGETTEXTURE_HASUVS=!1,this.MORPHTARGETTEXTURE_HASUV2S=!1,this.MORPHTARGETTEXTURE_HASCOLORS=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.USEPHYSICALLIGHTFALLOFF=!1,this.USEGLTFLIGHTFALLOFF=!1,this.TWOSIDEDLIGHTING=!1,this.MIRRORED=!1,this.SHADOWFLOAT=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.LOGARITHMICDEPTH=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.AREALIGHTSUPPORTED=!0,this.FORCENORMALFORWARD=!1,this.SPECULARAA=!1,this.UNLIT=!1,this.DECAL_AFTER_DETAIL=!1,this.DEBUGMODE=0,this.USE_VERTEX_PULLING=!1,this.VERTEX_PULLING_USE_INDEX_BUFFER=!1,this.VERTEX_PULLING_INDEX_BUFFER_32BITS=!1,this.RIGHT_HANDED=!1,this.CLUSTLIGHT_SLICES=0,this.CLUSTLIGHT_BATCH=0,this.BRDF_V_HEIGHT_CORRELATED=!0,this.MS_BRDF_ENERGY_CONSERVATION=!0,this.SPHERICAL_HARMONICS=!0,this.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=!0,this.MIX_IBL_RADIANCE_WITH_IRRADIANCE=!0,this.LEGACY_SPECULAR_ENERGY_CONSERVATION=!1,this.BASE_DIFFUSE_MODEL=0,this.DIELECTRIC_SPECULAR_MODEL=1,this.CONDUCTOR_SPECULAR_MODEL=1,this.rebuild()}reset(){super.reset(),this.ALPHATESTVALUE="0.5",this.NORMALXYSCALE=!0}},zL=class extends Km(hl){},Ne=class n extends zL{get geometryTangentAngle(){return Math.atan2(this.geometryTangent.y,this.geometryTangent.x)}set geometryTangentAngle(e){this.geometryTangent=new we(Math.cos(e),Math.sin(e))}get geometryCoatTangentAngle(){return Math.atan2(this.geometryCoatTangent.y,this.geometryCoatTangent.x)}set geometryCoatTangentAngle(e){this.geometryCoatTangent=new we(Math.cos(e),Math.sin(e))}get sssQuality(){return this._sssQuality}set sssQuality(e){this._sssQuality!==e&&(this._sssQuality=e,this.markAsDirty(1))}get sssIrradianceTexture(){return this._sssIrradianceTexture}set sssIrradianceTexture(e){this._sssIrradianceTexture!==e&&(this._sssIrradianceTexture=e,this._markAllSubMeshesAsTexturesDirty())}get sssDepthTexture(){return this._sssDepthTexture}set sssDepthTexture(e){this._sssDepthTexture!==e&&(this._sssDepthTexture=e,this._markAllSubMeshesAsTexturesDirty())}get hasTransparency(){return this.subsurfaceWeight>0||this.transmissionWeight>0}get hasScattering(){return this.transmissionWeight>0&&this.transmissionDepth>0&&!this.transmissionScatter.equals(ve.BlackReadOnly)||this.subsurfaceWeight>0}get usePhysicalLightFalloff(){return this._lightFalloff===Ee.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=Ee.LIGHTFALLOFF_PHYSICAL:this._lightFalloff=Ee.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===Ee.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=Ee.LIGHTFALLOFF_GLTF:this._lightFalloff=Ee.LIGHTFALLOFF_STANDARD)}get backgroundRefractionTexture(){return this._backgroundRefractionTexture}set backgroundRefractionTexture(e){this._backgroundRefractionTexture=e,this._markAllSubMeshesAsTexturesDirty()}get refractionHighQualityBlur(){return this._refractionHighQualityBlur}set refractionHighQualityBlur(e){this._refractionHighQualityBlur!==e&&(this._refractionHighQualityBlur=e,this.markAsDirty(1))}get realTimeFiltering(){return this._realTimeFiltering}set realTimeFiltering(e){this._realTimeFiltering=e,this.markAsDirty(1)}get realTimeFilteringQuality(){return this._realTimeFilteringQuality}set realTimeFilteringQuality(e){this._realTimeFilteringQuality=e,this.markAsDirty(1)}get fuzzSampleNumber(){return this._fuzzSampleNumber}set fuzzSampleNumber(e){this._fuzzSampleNumber=e,this.markAsDirty(1)}get canRenderToMRT(){return!0}constructor(e,t,i=!1){var s;super(e,t,void 0,i||n.ForceGLSL),this._baseWeight=new ai("base_weight",1,"vBaseWeight",1),this._baseWeightTexture=new Ti("base_weight","baseWeight","BASE_WEIGHT"),this._baseColor=new ai("base_color",ve.White(),"vBaseColor",4),this._baseColorTexture=new Ti("base_color","baseColor","BASE_COLOR"),this._baseDiffuseRoughness=new ai("base_diffuse_roughness",0,"vBaseDiffuseRoughness",1),this._baseDiffuseRoughnessTexture=new Ti("base_diffuse_roughness","baseDiffuseRoughness","BASE_DIFFUSE_ROUGHNESS"),this._baseMetalness=new ai("base_metalness",0,"vReflectanceInfo",4,0),this._baseMetalnessTexture=new Ti("base_metalness","baseMetalness","BASE_METALNESS"),this._specularWeight=new ai("specular_weight",1,"vReflectanceInfo",4,3),this._specularWeightTexture=new Ti("specular_weight","specularWeight","SPECULAR_WEIGHT"),this._specularColor=new ai("specular_color",ve.White(),"vSpecularColor",4),this._specularColorTexture=new Ti("specular_color","specularColor","SPECULAR_COLOR"),this._specularRoughness=new ai("specular_roughness",.3,"vReflectanceInfo",4,1),this._specularRoughnessTexture=new Ti("specular_roughness","specularRoughness","SPECULAR_ROUGHNESS"),this._specularRoughnessAnisotropy=new ai("specular_roughness_anisotropy",0,"vSpecularAnisotropy",3,2),this._specularRoughnessAnisotropyTexture=new Ti("specular_roughness_anisotropy","specularRoughnessAnisotropy","SPECULAR_ROUGHNESS_ANISOTROPY"),this._specularIor=new ai("specular_ior",1.5,"vReflectanceInfo",4,2),this._transmissionWeight=new ai("transmission_weight",0,"vTransmissionWeight",1),this._transmissionWeightTexture=new Ti("transmission_weight","transmissionWeight","TRANSMISSION_WEIGHT"),this._transmissionColor=new ai("transmission_color",ve.White(),"vTransmissionColor",3,0),this._transmissionColorTexture=new Ti("transmission_color","transmissionColor","TRANSMISSION_COLOR"),this._transmissionDepth=new ai("transmission_depth",0,"vTransmissionDepth",1,0),this._transmissionDepthTexture=new Ti("transmission_depth","transmissionDepth","TRANSMISSION_DEPTH"),this._transmissionScatter=new ai("transmission_scatter",ve.Black(),"vTransmissionScatter",3,0),this._transmissionScatterTexture=new Ti("transmission_scatter","transmissionScatter","TRANSMISSION_SCATTER"),this._transmissionScatterAnisotropy=new ai("transmission_scatter_anisotropy",0,"vTransmissionScatterAnisotropy",1,0),this._transmissionDispersionScale=new ai("transmission_dispersion_scale",0,"vTransmissionDispersionScale",1,0),this._transmissionDispersionScaleTexture=new Ti("transmission_dispersion_scale","transmissionDispersionScale","TRANSMISSION_DISPERSION_SCALE"),this._transmissionDispersionAbbeNumber=new ai("transmission_dispersion_abbe_number",20,"vTransmissionDispersionAbbeNumber",1,0),this._subsurfaceWeight=new ai("subsurface_weight",0,"vSubsurfaceWeight",1,0,"SUBSURFACE_SLAB"),this._subsurfaceWeightTexture=new Ti("subsurface_weight","subsurfaceWeight","SUBSURFACE_WEIGHT"),this._subsurfaceColor=new ai("subsurface_color",new ve(.8,.8,.8),"vSubsurfaceColor",3,0,"SUBSURFACE_SLAB"),this._subsurfaceColorTexture=new Ti("subsurface_color","subsurfaceColor","SUBSURFACE_COLOR"),this._subsurfaceRadius=new ai("subsurface_radius",.1,"vSubsurfaceRadius",1,0,"SUBSURFACE_SLAB"),this._subsurfaceRadiusScale=new ai("subsurface_radius_scale",new ve(1,.5,.25),"vSubsurfaceRadiusScale",3,0,"SUBSURFACE_SLAB"),this._subsurfaceRadiusScaleTexture=new Ti("subsurface_radius_scale","subsurfaceRadiusScale","SUBSURFACE_RADIUS_SCALE"),this._subsurfaceScatterAnisotropy=new ai("subsurface_scatter_anisotropy",0,"vSubsurfaceScatterAnisotropy",1,0,"SUBSURFACE_SLAB"),this._coatWeight=new ai("coat_weight",0,"vCoatWeight",1,0),this._coatWeightTexture=new Ti("coat_weight","coatWeight","COAT_WEIGHT"),this._coatColor=new ai("coat_color",ve.White(),"vCoatColor",3,0),this._coatColorTexture=new Ti("coat_color","coatColor","COAT_COLOR"),this._coatRoughness=new ai("coat_roughness",0,"vCoatRoughness",1,0),this._coatRoughnessTexture=new Ti("coat_roughness","coatRoughness","COAT_ROUGHNESS"),this._coatRoughnessAnisotropy=new ai("coat_roughness_anisotropy",0,"vCoatRoughnessAnisotropy",1),this._coatRoughnessAnisotropyTexture=new Ti("coat_roughness_anisotropy","coatRoughnessAnisotropy","COAT_ROUGHNESS_ANISOTROPY"),this._coatIor=new ai("coat_ior",1.5,"vCoatIor",1,0),this._coatDarkening=new ai("coat_darkening",1,"vCoatDarkening",1,0),this._coatDarkeningTexture=new Ti("coat_darkening","coatDarkening","COAT_DARKENING"),this.useCoatRoughnessFromWeightTexture=!1,this._fuzzWeight=new ai("fuzz_weight",0,"vFuzzWeight",1,0),this._fuzzWeightTexture=new Ti("fuzz_weight","fuzzWeight","FUZZ_WEIGHT"),this._fuzzColor=new ai("fuzz_color",ve.White(),"vFuzzColor",3,0),this._fuzzColorTexture=new Ti("fuzz_color","fuzzColor","FUZZ_COLOR"),this._fuzzRoughness=new ai("fuzz_roughness",.5,"vFuzzRoughness",1,0),this._fuzzRoughnessTexture=new Ti("fuzz_roughness","fuzzRoughness","FUZZ_ROUGHNESS"),this._geometryThinWalled=new ai("geometry_thin_walled",0,"vGeometryThinWalled",1,0),this._geometryNormalTexture=new Ti("geometry_normal","geometryNormal","GEOMETRY_NORMAL"),this._geometryTangent=new ai("geometry_tangent",new we(1,0),"vSpecularAnisotropy",3,0),this._geometryTangentTexture=new Ti("geometry_tangent","geometryTangent","GEOMETRY_TANGENT"),this._geometryCoatNormalTexture=new Ti("geometry_coat_normal","geometryCoatNormal","GEOMETRY_COAT_NORMAL"),this._geometryCoatTangent=new ai("geometry_coat_tangent",new we(1,0),"vGeometryCoatTangent",2,0),this._geometryCoatTangentTexture=new Ti("geometry_coat_tangent","geometryCoatTangent","GEOMETRY_COAT_TANGENT"),this._geometryOpacity=new ai("geometry_opacity",1,"vBaseColor",4,3),this._geometryOpacityTexture=new Ti("geometry_opacity","geometryOpacity","GEOMETRY_OPACITY"),this._geometryThickness=new ai("geometry_thickness",0,"vGeometryThickness",1,0),this._geometryThicknessTexture=new Ti("geometry_thickness","geometryThickness","GEOMETRY_THICKNESS"),this._emissionLuminance=new ai("emission_luminance",1,"vLightingIntensity",4,1),this._emissionColor=new ai("emission_color",ve.Black(),"vEmissionColor",3),this._emissionColorTexture=new Ti("emission_color","emissionColor","EMISSION_COLOR"),this._thinFilmWeight=new ai("thin_film_weight",0,"vThinFilmWeight",1,0),this._thinFilmWeightTexture=new Ti("thin_film_weight","thinFilmWeight","THIN_FILM_WEIGHT"),this._thinFilmThickness=new ai("thin_film_thickness",.5,"vThinFilmThickness",2,0),this._thinFilmThicknessMin=new ai("thin_film_thickness_min",0,"vThinFilmThickness",2,1),this._thinFilmThicknessTexture=new Ti("thin_film_thickness","thinFilmThickness","THIN_FILM_THICKNESS"),this._thinFilmIor=new ai("thin_film_ior",1.4,"vThinFilmIor",1,0),this._ambientOcclusionTexture=new Ti("ambient_occlusion","ambientOcclusion","AMBIENT_OCCLUSION"),this._sssQuality=n.SSS_QUALITY_MEDIUM,this._sssIrradianceTexture=null,this._sssDepthTexture=null,this._uniformsList={},this._uniformsArray=[],this._samplersList={},this._samplerDefines={},this.directIntensity=1,this.environmentIntensity=1,this.useSpecularWeightFromTextureAlpha=!1,this.forceAlphaTest=!1,this.alphaCutOff=.4,this.useAmbientOcclusionFromMetallicTextureRed=!1,this.useAmbientInGrayScale=!1,this.useObjectSpaceNormalMap=!1,this.useParallax=!1,this.useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this.disableLighting=!1,this.forceIrradianceInFragment=!1,this.maxSimultaneousLights=4,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.twoSidedLighting=!1,this.useAlphaFresnel=!1,this.useLinearAlphaFresnel=!1,this.environmentBRDFTexture=null,this.forceNormalForward=!1,this.enableSpecularAntiAliasing=!1,this.useHorizonOcclusion=!0,this.useRadianceOcclusion=!0,this.unlit=!1,this.applyDecalMapAfterDetailMap=!1,this._lightingInfos=new bi(this.directIntensity,1,this.environmentIntensity,1),this._radianceTexture=null,this._useSpecularWeightFromAlpha=!1,this._useSpecularWeightFromSpecularColorTexture=!1,this._useSpecularRoughnessAnisotropyFromTangentTexture=!1,this._useCoatRoughnessAnisotropyFromTangentTexture=!1,this._useCoatRoughnessFromGreenChannel=!1,this._useGltfStyleAnisotropy=!1,this._useFuzzRoughnessFromTextureAlpha=!1,this._useHorizonOcclusion=!0,this._useRadianceOcclusion=!0,this._useAlphaFromBaseColorTexture=!1,this._useAmbientOcclusionFromMetallicTextureRed=!1,this._useRoughnessFromMetallicTextureGreen=!1,this._useMetallicFromMetallicTextureBlue=!1,this._useThinFilmThicknessFromTextureGreen=!1,this._useGeometryThicknessFromGreenChannel=!1,this._lightFalloff=Ee.LIGHTFALLOFF_PHYSICAL,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this._parallaxScaleBias=.05,this._disableLighting=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._alphaCutOff=.4,this._useAlphaFresnel=!1,this._useLinearAlphaFresnel=!1,this._environmentBRDFTexture=null,this._environmentFuzzBRDFTexture=null,this._backgroundRefractionTexture=null,this._refractionHighQualityBlur=!0,this._forceIrradianceInFragment=!1,this._realTimeFiltering=!1,this._realTimeFilteringQuality=8,this._fuzzSampleNumber=4,this._forceNormalForward=!1,this._enableSpecularAntiAliasing=!1,this._renderTargets=new Bi(16),this._unlit=!1,this._applyDecalMapAfterDetailMap=!1,this._debugMode=0,this._shadersLoaded=!1,this._breakShaderLoadedCheck=!1,this._vertexPullingMetadata=null,this.debugMode=0,this.debugLimit=-1,this.debugFactor=1,this._cacheHasRenderTargetTextures=!1,this._transparencyMode=Ee.MATERIAL_OPAQUE,this.getScene()&&!((s=this.getScene())!=null&&s.getEngine().isWebGPU)&&this.getScene().getEngine().webGLVersion<2&&te.Error("OpenPBRMaterial: WebGL 2.0 or above is required for this material."),n._noiseTextures[this.getScene().uniqueId]||(n._noiseTextures[this.getScene().uniqueId]=new ge(_e.GetAssetUrl("https://assets.babylonjs.com/core/blue_noise/blue_noise_rgb.png"),this.getScene(),!1,!0,1),this.getScene().onDisposeObservable.addOnce(()=>{var a;(a=n._noiseTextures[this.getScene().uniqueId])==null||a.dispose(),delete n._noiseTextures[this.getScene().uniqueId]})),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),ce.ReflectionTextureEnabled&&this._radianceTexture&&this._radianceTexture.isRenderTarget&&this._renderTargets.push(this._radianceTexture),ce.RefractionTextureEnabled&&this._backgroundRefractionTexture&&this._backgroundRefractionTexture.isRenderTarget&&this._renderTargets.push(this._backgroundRefractionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=f5(this.getScene()),this._environmentFuzzBRDFTexture=KD(this.getScene()),this.prePassConfiguration=new Cs,this._propertyList={};for(let a of Object.getOwnPropertyNames(this)){let o=this[a];o instanceof ai&&(this._propertyList[a]=o)}Object.keys(this._propertyList).forEach(a=>{let o=this._propertyList[a],l=this._uniformsList[o.targetUniformName];l?l.numComponents!==o.targetUniformComponentNum?te.Error(`Uniform ${o.targetUniformName} already exists of size ${l.numComponents}, but trying to set it to ${o.targetUniformComponentNum}.`):l.requiredDefine!==o.requiredDefine&&(l.requiredDefine=void 0):(l=new IR(o.targetUniformName,o.targetUniformComponentNum),l.requiredDefine=o.requiredDefine,this._uniformsList[o.targetUniformName]=l),l.firstLinkedKey===""&&(l.firstLinkedKey=o.name),l.linkedProperties[o.name]=o}),this._uniformsArray=Object.values(this._uniformsList),this._samplersList={};for(let a of Object.getOwnPropertyNames(this)){let o=this[a];o instanceof Ti&&(this._samplersList[a]=o)}for(let a in this._samplersList){let l=this._samplersList[a].textureDefine;this._samplerDefines[l]={type:"boolean",default:!1},this._samplerDefines[l+"DIRECTUV"]={type:"number",default:0},this._samplerDefines[l+"_GAMMA"]={type:"boolean",default:!1}}this._baseWeight,this._baseWeightTexture,this._baseColor,this._baseColorTexture,this._baseDiffuseRoughness,this._baseDiffuseRoughnessTexture,this._baseMetalness,this._baseMetalnessTexture,this._specularWeight,this._specularWeightTexture,this._specularColor,this._specularColorTexture,this._specularRoughness,this._specularIor,this._specularRoughnessTexture,this._specularRoughnessAnisotropy,this._specularRoughnessAnisotropyTexture,this._transmissionWeight,this._transmissionWeightTexture,this._transmissionColor,this._transmissionColorTexture,this._transmissionDepth,this._transmissionDepthTexture,this._transmissionScatter,this._transmissionScatterTexture,this._transmissionScatterAnisotropy,this._transmissionDispersionScale,this._transmissionDispersionScaleTexture,this._transmissionDispersionAbbeNumber,this._subsurfaceWeight,this._subsurfaceWeightTexture,this._subsurfaceColor,this._subsurfaceColorTexture,this._subsurfaceRadius,this._subsurfaceRadiusScale,this._subsurfaceRadiusScaleTexture,this._subsurfaceScatterAnisotropy,this._coatWeight,this._coatWeightTexture,this._coatColor,this._coatColorTexture,this._coatRoughness,this._coatRoughnessTexture,this._coatRoughnessAnisotropy,this._coatRoughnessAnisotropyTexture,this._coatIor,this._coatDarkening,this._coatDarkeningTexture,this._fuzzWeight,this._fuzzWeightTexture,this._fuzzColor,this._fuzzColorTexture,this._fuzzRoughness,this._fuzzRoughnessTexture,this._geometryThinWalled,this._geometryNormalTexture,this._geometryTangent,this._geometryTangentTexture,this._geometryCoatNormalTexture,this._geometryCoatTangent,this._geometryCoatTangentTexture,this._geometryOpacity,this._geometryOpacityTexture,this._geometryThickness,this._geometryThicknessTexture,this._thinFilmWeight,this._thinFilmWeightTexture,this._thinFilmThickness,this._thinFilmThicknessMin,this._thinFilmThicknessTexture,this._thinFilmIor,this._emissionLuminance,this._emissionColor,this._emissionColorTexture,this._ambientOcclusionTexture}get hasRenderTargetTextures(){return ce.ReflectionTextureEnabled&&this._radianceTexture&&this._radianceTexture.isRenderTarget||ce.RefractionTextureEnabled&&this._backgroundRefractionTexture&&this._backgroundRefractionTexture.isRenderTarget?!0:this._cacheHasRenderTargetTextures}get isPrePassCapable(){return!this.disableDepthWrite}getClassName(){return"OpenPBRMaterial"}get transparencyMode(){return this._transparencyMode}set transparencyMode(e){this._transparencyMode!==e&&(this._transparencyMode=e,this._markAllSubMeshesAsTexturesAndMiscDirty())}_shouldUseAlphaFromBaseColorTexture(){return this._hasAlphaChannel()&&this._transparencyMode!==Ee.MATERIAL_OPAQUE&&!this.geometryOpacityTexture}_hasAlphaChannel(){return this.baseColorTexture!=null&&this.baseColorTexture.hasAlpha&&this._useAlphaFromBaseColorTexture||this.geometryOpacityTexture!=null}clone(e,t=!0,i=""){let r=it.Clone(()=>new n(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return r.id=e,r.name=e,this.stencil.copyTo(r.stencil),this._clonePlugins(r,i),r}serialize(){let e=super.serialize();return e.customType="BABYLON.OpenPBRMaterial",e}static Parse(e,t,i){let r=it.Parse(()=>new n(e.name,t),e,t,i);return e.stencil&&r.stencil.parse(e.stencil,t,i),Ee._ParsePlugins(e,r,t,i),r}forceCompilation(e,t,i){let r={clipPlane:!1,useInstances:!1,...i};this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(4,this._eventInfo),(()=>{if(this._breakShaderLoadedCheck)return;let a=new Kg({...this._eventInfo.defineNames||{},...this._samplerDefines||{}}),o=this._prepareEffect(e,e,a,void 0,void 0,r.useInstances,r.clipPlane);this._onEffectCreatedObservable&&(ap.effect=o,ap.subMesh=null,this._onEffectCreatedObservable.notifyObservers(ap)),o.isReady()?t&&t(this):o.onCompileObservable.add(()=>{t&&t(this)})})()}isReadyForSubMesh(e,t,i){var d;this._uniformBufferLayoutBuilt||this.buildUniformLayout();let r=t._drawWrapper;if(r.effect&&this.isFrozen&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(4,this._eventInfo),t.materialDefines=new Kg({...this._eventInfo.defineNames||{},...this._samplerDefines||{}}));let s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let a=this.getScene(),o=a.getEngine();if(s._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,a.texturesEnabled)){for(let m in this._samplersList){let p=this._samplersList[m];if(p.value&&!p.value.isReadyOrNotBlocking())return!1}let u=this._getRadianceTexture();if(u&&ce.ReflectionTextureEnabled){if(!u.isReadyOrNotBlocking())return!1;if(u.irradianceTexture){if(!u.irradianceTexture.isReadyOrNotBlocking())return!1}else if(!u.sphericalPolynomial&&((d=u.getInternalTexture())!=null&&d._sphericalPolynomialPromise))return!1}if(this._environmentBRDFTexture&&ce.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady()||this._environmentFuzzBRDFTexture&&ce.ReflectionTextureEnabled&&!this._environmentFuzzBRDFTexture.isReady()||this._backgroundRefractionTexture&&ce.RefractionTextureEnabled&&!this._backgroundRefractionTexture.isReadyOrNotBlocking()||n._noiseTextures[a.uniqueId]&&!n._noiseTextures[a.uniqueId].isReady()||this._sssIrradianceTexture&&this._sssDepthTexture&&(!this._sssIrradianceTexture.isReady()||!this._sssDepthTexture.isReady()))return!1}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh||s._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;if(s.AREALIGHTUSED){for(let u=0;u{e.addUniform(t.name,t.numComponents)}),Object.values(this._samplersList).forEach(t=>{e.addUniform(t.samplerInfoName,2),e.addUniform(t.samplerMatrixName,16)}),super.buildUniformLayout()}bindPropertiesForSubMesh(e,t,i,r){if(this.geometryThickness===0)e.updateFloat("vGeometryThickness",0);else{r.getRenderingMesh().getWorldMatrix().decompose($.Vector3[0]);let s=Math.max(Math.abs($.Vector3[0].x),Math.abs($.Vector3[0].y),Math.abs($.Vector3[0].z));e.updateFloat("vGeometryThickness",this.geometryThickness*s)}}bindForSubMesh(e,t,i){var h;let r=this.getScene(),s=i.materialDefines;if(!s)return;let a=i.effect;if(!a)return;this._activeEffect=a,t.getMeshUniformBuffer().bindToEffect(a,"Mesh"),t.transferToEffect(e);let o=r.getEngine();this._uniformBuffer.bindToEffect(a,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,r,t,e,this.isFrozen),Hn.Bind(o.currentRenderPassId,this._activeEffect,t,e,this);let l=r.activeCamera;l?this._uniformBuffer.updateFloat4("cameraInfo",l.minZ,l.maxZ,0,0):this._uniformBuffer.updateFloat4("cameraInfo",0,0,0,0),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),s.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));let c=this._mustRebind(r,a,i,t.visibility);Rs(t,this._activeEffect,this.prePassConfiguration),this._vertexPullingMetadata&&Of(this._activeEffect,this._vertexPullingMetadata);let f=this._uniformBuffer;if(c){this.bindViewProjection(a);let d=this._getRadianceTexture();if(!f.useUbo||!this.isFrozen||!f.isSync||i._drawWrapper._forceRebindOnNextCall){if(r.texturesEnabled){for(let m in this._samplersList){let p=this._samplersList[m];p.value&&(f.updateFloat2(p.samplerInfoName,p.value.coordinatesIndex,p.value.level),si(p.value,f,p.samplerPrefix))}(this.geometryNormalTexture||this.geometryCoatNormalTexture)&&(r._mirroredCameraPosition?f.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):f.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),vm(r,s,f,ve.White(),d,this.realTimeFiltering,!0,!0,!0,!0,!0)}this.pointsCloud&&f.updateFloat("pointSize",this.pointSize);let u=this._uniformsArray;for(let m=0,p=u.length;m0&&e.push(i.value)}return this._radianceTexture&&this._radianceTexture.animations&&this._radianceTexture.animations.length>0&&e.push(this._radianceTexture),e}getActiveTextures(){let e=super.getActiveTextures();for(let t in this._samplersList){let i=this._samplersList[t];i.value&&e.push(i.value)}return this._radianceTexture&&e.push(this._radianceTexture),e}hasTexture(e){if(super.hasTexture(e))return!0;for(let t in this._samplersList)if(this._samplersList[t].value===e)return!0;return this._radianceTexture===e}setPrePassRenderer(){return!1}dispose(e,t){var i,r;if(this._breakShaderLoadedCheck=!0,t){this._environmentBRDFTexture&&this.getScene().openPBREnvironmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),this._environmentFuzzBRDFTexture&&this.getScene().environmentFuzzBRDFTexture!==this._environmentFuzzBRDFTexture&&this._environmentFuzzBRDFTexture.dispose(),this._backgroundRefractionTexture=null;for(let s in this._samplersList)(i=this._samplersList[s].value)==null||i.dispose();(r=this._radianceTexture)==null||r.dispose()}this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}_getRadianceTexture(){return this._radianceTexture?this._radianceTexture:this.getScene().environmentTexture}_prepareEffect(e,t,i,r=null,s=null,a=null,o=null){if(this._prepareDefines(e,t,i,a,o),!i.isDirty)return null;i.markAsProcessed();let c=this.getScene().getEngine(),f=new Wn,h=0;i.USESPHERICALINVERTEX&&f.addFallback(h++,"USESPHERICALINVERTEX"),i.FOG&&f.addFallback(h,"FOG"),i.SPECULARAA&&f.addFallback(h,"SPECULARAA"),i.POINTSIZE&&f.addFallback(h,"POINTSIZE"),i.LOGARITHMICDEPTH&&f.addFallback(h,"LOGARITHMICDEPTH"),i.PARALLAX&&f.addFallback(h,"PARALLAX"),i.PARALLAX_RHS&&f.addFallback(h,"PARALLAX_RHS"),i.PARALLAXOCCLUSION&&f.addFallback(h++,"PARALLAXOCCLUSION"),i.ENVIRONMENTBRDF&&f.addFallback(h++,"ENVIRONMENTBRDF"),i.TANGENT&&f.addFallback(h++,"TANGENT"),h=xm(i,f,this._maxSimultaneousLights,h),i.SPECULARTERM&&f.addFallback(h++,"SPECULARTERM"),i.USESPHERICALFROMREFLECTIONMAP&&f.addFallback(h++,"USESPHERICALFROMREFLECTIONMAP"),i.USEIRRADIANCEMAP&&f.addFallback(h++,"USEIRRADIANCEMAP"),i.NORMAL&&f.addFallback(h++,"NORMAL"),i.VERTEXCOLOR&&f.addFallback(h++,"VERTEXCOLOR"),i.MORPHTARGETS&&f.addFallback(h++,"MORPHTARGETS"),i.MULTIVIEW&&f.addFallback(0,"MULTIVIEW");let d=[L.PositionKind];i.NORMAL&&d.push(L.NormalKind),i.TANGENT&&d.push(L.TangentKind);for(let S=1;S<=6;++S)i["UV"+S]&&d.push(`uv${S===1?"":S}`);i.VERTEXCOLOR&&d.push(L.ColorKind),Tm(d,e,i,f),Am(d,i),Qh(d,e,i),Em(d,e,i);let u="openpbr",m=["world","view","viewProjection","projection","vEyePosition","inverseProjection","renderTargetSize","vLightsType","visibility","vFogInfos","vFogColor","pointSize","mBones","normalMatrix","vLightingIntensity","logarithmicDepthConstant","vTangentSpaceParams","boneTextureInfo","vDebugMode","morphTargetTextureInfo","morphTargetTextureIndices","cameraInfo","backgroundRefractionMatrix","vBackgroundRefractionInfos"];for(let S in this._uniformsList)m.push(S);let p=["environmentBrdfSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler","areaLightsLTC1Sampler","areaLightsLTC2Sampler"];i.FUZZENVIRONMENTBRDF&&p.push("environmentFuzzBrdfSampler"),i.REFRACTED_BACKGROUND&&p.push("backgroundRefractionSampler"),(i.ANISOTROPIC||i.FUZZ||i.REFRACTED_BACKGROUND||i.USE_IRRADIANCE_TEXTURE_FOR_SCATTERING)&&p.push("blueNoiseSampler"),i.USE_IRRADIANCE_TEXTURE_FOR_SCATTERING&&(p.push("sceneIrradianceSampler"),p.push("sceneDepthSampler"));for(let S in this._samplersList){let E=this._samplersList[S];p.push(E.samplerName),m.push(E.samplerInfoName),m.push(E.samplerMatrixName)}Rf(m,p,!0);let _=["Material","Scene","Mesh"],g={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:i.NUM_MORPH_INFLUENCERS};if(this._eventInfo.fallbacks=f,this._eventInfo.fallbackRank=h,this._eventInfo.defines=i,this._eventInfo.uniforms=m,this._eventInfo.attributes=d,this._eventInfo.samplers=p,this._eventInfo.uniformBuffersNames=_,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=g,this._callbackPluginEventGeneric(128,this._eventInfo),Hn.AddUniformsAndSamplers(m,p),Cs.AddUniforms(m),Cs.AddSamplers(p),wn(m),this._useVertexPulling){let S=t==null?void 0:t.geometry;S&&(this._vertexPullingMetadata=Lf(S),this._vertexPullingMetadata&&this._vertexPullingMetadata.forEach((E,R)=>{m.push(`vp_${R}_info`)}))}else this._vertexPullingMetadata=null;kt&&(kt.PrepareUniforms(m,i),kt.PrepareSamplers(p,i)),Lm({uniformsNames:m,uniformBuffersNames:_,samplers:p,defines:i,maxSimultaneousLights:this._maxSimultaneousLights,shaderLanguage:this._shaderLanguage});let v={};this.customShaderNameResolve&&(u=this.customShaderNameResolve(u,m,_,p,i,d,v));let x=i.toString(),A=c.createEffect(u,{attributes:d,uniformsNames:m,uniformBuffersNames:_,samplers:p,defines:x,fallbacks:f,onCompiled:r,onError:s,indexParameters:g,processFinalCode:v.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:i.PREPASS,shaderLanguage:this._shaderLanguage,extraInitializationsAsync:this._shadersLoaded?void 0:async()=>{this.shaderLanguage===1?await Promise.all([Promise.resolve().then(()=>(nY(),rY)),Promise.resolve().then(()=>(t8(),e8))]):await Promise.all([Promise.resolve().then(()=>(h8(),f8)),Promise.resolve().then(()=>(c6(),l6))]),this._shadersLoaded=!0}},c);return this._eventInfo.customCode=void 0,A}_prepareDefines(e,t,i,r=null,s=null){var h;let a=t.hasThinInstances,o=this.getScene(),l=o.getEngine();Im(o,e,i,!0,this._maxSimultaneousLights,this._disableLighting),i._needNormals=!0,ym(o,i);let c=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(Dm(o,i,this.canRenderToMRT&&!c),Pm(o,i,c),Hn.PrepareDefines(l.currentRenderPassId,e,i),i._areTexturesDirty){i._needUVs=!1;for(let d=1;d<=6;++d)i["MAINUV"+d]=!1;if(o.texturesEnabled){for(let m in this._samplersList){let p=this._samplersList[m];p.value?(ni(p.value,i,p.textureDefine),i[p.textureDefine+"_GAMMA"]=p.value.gammaSpace):i[p.textureDefine]=!1}let d=this._getRadianceTexture(),u=this._forceIrradianceInFragment||this.realTimeFiltering||this._twoSidedLighting||l.getCaps().maxVaryingVectors<=8||this._baseDiffuseRoughnessTexture!=null;if(xf(o,d,i,this.realTimeFiltering,this.realTimeFilteringQuality,!u),this._baseMetalnessTexture&&(i.AOSTOREINMETALMAPRED=this._useAmbientOcclusionFromMetallicTextureRed),i.SPECULAR_WEIGHT_IN_ALPHA=this._useSpecularWeightFromAlpha,i.SPECULAR_WEIGHT_FROM_SPECULAR_COLOR_TEXTURE=this._useSpecularWeightFromSpecularColorTexture,i.SPECULAR_ROUGHNESS_ANISOTROPY_FROM_TANGENT_TEXTURE=this._useSpecularRoughnessAnisotropyFromTangentTexture,i.COAT_ROUGHNESS_ANISOTROPY_FROM_TANGENT_TEXTURE=this._useCoatRoughnessAnisotropyFromTangentTexture,i.COAT_ROUGHNESS_FROM_GREEN_CHANNEL=this._useCoatRoughnessFromGreenChannel,i.SPECULAR_ROUGHNESS_FROM_METALNESS_TEXTURE_GREEN=this._useRoughnessFromMetallicTextureGreen,i.FUZZ_ROUGHNESS_FROM_TEXTURE_ALPHA=this._useFuzzRoughnessFromTextureAlpha,i.BASE_METALNESS_FROM_METALNESS_TEXTURE_BLUE=this._useMetallicFromMetallicTextureBlue,i.THIN_FILM_THICKNESS_FROM_THIN_FILM_TEXTURE=this._useThinFilmThicknessFromTextureGreen,i.GEOMETRY_THICKNESS_FROM_GREEN_CHANNEL=this._useGeometryThicknessFromGreenChannel,this.geometryNormalTexture?(this._useParallax&&this.baseColorTexture&&ce.DiffuseTextureEnabled?(i.PARALLAX=!0,i.PARALLAX_RHS=o.useRightHandedSystem,i.PARALLAXOCCLUSION=!!this._useParallaxOcclusion):i.PARALLAX=!1,i.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap):(i.PARALLAX=!1,i.PARALLAX_RHS=!1,i.PARALLAXOCCLUSION=!1,i.OBJECTSPACE_NORMALMAP=!1),this._environmentBRDFTexture&&ce.ReflectionTextureEnabled?(i.ENVIRONMENTBRDF=!0,i.ENVIRONMENTBRDF_RGBD=this._environmentBRDFTexture.isRGBD):(i.ENVIRONMENTBRDF=!1,i.ENVIRONMENTBRDF_RGBD=!1),this._environmentFuzzBRDFTexture?i.FUZZENVIRONMENTBRDF=!0:i.FUZZENVIRONMENTBRDF=!1,this.hasTransparency){i.REFRACTED_BACKGROUND=!!this._backgroundRefractionTexture&&ce.RefractionTextureEnabled,i.REFRACTION_HIGH_QUALITY_BLUR=this._refractionHighQualityBlur,i.REFRACTED_LIGHTS=!0;let m=this._getRadianceTexture();m?(i.REFRACTED_ENVIRONMENT=ce.RefractionTextureEnabled,i.REFRACTED_ENVIRONMENT_OPPOSITEZ=this.getScene().useRightHandedSystem?!m.invertZ:m.invertZ,i.REFRACTED_ENVIRONMENT_LOCAL_CUBE=m.isCube&&m.boundingBoxSize):i.REFRACTED_ENVIRONMENT=!1}else i.REFRACTED_BACKGROUND=!1,i.REFRACTED_LIGHTS=!1,i.REFRACTED_ENVIRONMENT=!1;this._shouldUseAlphaFromBaseColorTexture()?i.ALPHA_FROM_BASE_COLOR_TEXTURE=!0:i.ALPHA_FROM_BASE_COLOR_TEXTURE=!1}this._lightFalloff===Ee.LIGHTFALLOFF_STANDARD?(i.USEPHYSICALLIGHTFALLOFF=!1,i.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===Ee.LIGHTFALLOFF_GLTF?(i.USEPHYSICALLIGHTFALLOFF=!1,i.USEGLTFLIGHTFALLOFF=!0):(i.USEPHYSICALLIGHTFALLOFF=!0,i.USEGLTFLIGHTFALLOFF=!1),!this.backFaceCulling&&this._twoSidedLighting?i.TWOSIDEDLIGHTING=!0:i.TWOSIDEDLIGHTING=!1,i.MIRRORED=!!o._mirroredCameraPosition,i.SPECULARAA=l.getCaps().standardDerivatives&&this._enableSpecularAntiAliasing}(i._areTexturesDirty||i._areMiscDirty)&&(i.ALPHATESTVALUE=`${this._alphaCutOff}${this._alphaCutOff%1===0?".":""}`,i.PREMULTIPLYALPHA=this.alphaMode===7||this.alphaMode===8,i.ALPHABLEND=this.needAlphaBlendingForMesh(e)),i._areImageProcessingDirty&&this._imageProcessingConfiguration&&this._imageProcessingConfiguration.prepareDefines(i),i.FORCENORMALFORWARD=this._forceNormalForward,i.RADIANCEOCCLUSION=this._useRadianceOcclusion,i.HORIZONOCCLUSION=this._useHorizonOcclusion,(this.specularRoughnessAnisotropy>0||this.coatRoughnessAnisotropy>0)&&n._noiseTextures[o.uniqueId]&&ce.ReflectionTextureEnabled?(i.ANISOTROPIC=!0,e.isVerticesDataPresent(L.TangentKind)||(i._needUVs=!0,i.MAINUV1=!0),this._useGltfStyleAnisotropy&&(i.USE_GLTF_STYLE_ANISOTROPY=!0),i.ANISOTROPIC_BASE=this.specularRoughnessAnisotropy>0,i.ANISOTROPIC_COAT=this.coatRoughnessAnisotropy>0):(i.ANISOTROPIC=!1,i.USE_GLTF_STYLE_ANISOTROPY=!1,i.ANISOTROPIC_BASE=!1,i.ANISOTROPIC_COAT=!1),i.THIN_FILM=this.thinFilmWeight>0,i.IRIDESCENCE=this.thinFilmWeight>0,i.DISPERSION=this.transmissionDispersionScale>0,i.SCATTERING=this.hasScattering;let f=[8,16,32];if(i.SSS_SAMPLE_COUNT=(h=f[this._sssQuality])!=null?h:16,i.TRANSMISSION_SLAB=this.transmissionWeight>0,i.TRANSMISSION_SLAB_VOLUME=this.transmissionWeight>0&&this.transmissionDepth>0,i.SUBSURFACE_SLAB=this.subsurfaceWeight>0,!i.PREPASS&&(i.SUBSURFACE_SLAB||i.TRANSMISSION_SLAB_VOLUME)){let d=!1;if(!this.sssIrradianceTexture&&o.geometryBufferRenderer){let u=o.geometryBufferRenderer.getTextureIndex(ns.IRRADIANCE_TEXTURE_TYPE);this.sssIrradianceTexture=o.geometryBufferRenderer.getGBuffer().textures[u],d=!0}if(!this.sssDepthTexture&&o.geometryBufferRenderer){let u=o.geometryBufferRenderer.getTextureIndex(ns.SCREENSPACE_DEPTH_TEXTURE_TYPE);this.sssDepthTexture=o.geometryBufferRenderer.getGBuffer().textures[u],d=!0}this.sssIrradianceTexture&&this.sssDepthTexture&&(i.USE_IRRADIANCE_TEXTURE_FOR_SCATTERING=!0,d&&(i.USE_IRRADIANCE_TEXTURE_FOR_SCATTERING_GBUFFER=!0))}i.FUZZ=this.fuzzWeight>0&&ce.ReflectionTextureEnabled,i.GEOMETRY_THIN_WALLED=this.geometryThinWalled!=0,i.FUZZ?(e.isVerticesDataPresent(L.TangentKind)||(i._needUVs=!0,i.MAINUV1=!0),this._environmentFuzzBRDFTexture=KD(this.getScene()),i.FUZZ_IBL_SAMPLES=this.fuzzSampleNumber):(this._environmentFuzzBRDFTexture=null,i.FUZZENVIRONMENTBRDF=!1,i.FUZZ_IBL_SAMPLES=0),i._areMiscDirty&&(Rm(e,o,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this.needAlphaTestingForMesh(e),i,this._applyDecalMapAfterDetailMap,this._useVertexPulling,t,this._isVertexOutputInvariant),i.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent(L.NormalKind),i.DEBUGMODE=this._debugMode),Mm(o,l,this,i,!!r,s,a),this._eventInfo.defines=i,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),Cm(e,i,!0,!0,!0,this._transparencyMode!==Ee.MATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}};Ne.SSS_QUALITY_LOW=0;Ne.SSS_QUALITY_MEDIUM=1;Ne.SSS_QUALITY_HIGH=2;Ne._noiseTextures={};Ne.ForceGLSL=!1;P([ut("_markAllSubMeshesAsTexturesDirty","baseWeight")],Ne.prototype,"_baseWeight",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","baseWeightTexture")],Ne.prototype,"_baseWeightTexture",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","baseColor")],Ne.prototype,"_baseColor",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","baseColorTexture")],Ne.prototype,"_baseColorTexture",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","baseDiffuseRoughness")],Ne.prototype,"_baseDiffuseRoughness",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","baseDiffuseRoughnessTexture")],Ne.prototype,"_baseDiffuseRoughnessTexture",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","baseMetalness")],Ne.prototype,"_baseMetalness",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","baseMetalnessTexture")],Ne.prototype,"_baseMetalnessTexture",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","specularWeight")],Ne.prototype,"_specularWeight",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","specularWeightTexture")],Ne.prototype,"_specularWeightTexture",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","specularColor")],Ne.prototype,"_specularColor",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","specularColorTexture")],Ne.prototype,"_specularColorTexture",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","specularRoughness")],Ne.prototype,"_specularRoughness",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","specularRoughnessTexture")],Ne.prototype,"_specularRoughnessTexture",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","specularRoughnessAnisotropy")],Ne.prototype,"_specularRoughnessAnisotropy",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","specularRoughnessAnisotropyTexture")],Ne.prototype,"_specularRoughnessAnisotropyTexture",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","specularIor")],Ne.prototype,"_specularIor",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","transmissionWeight")],Ne.prototype,"_transmissionWeight",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","transmissionWeightTexture")],Ne.prototype,"_transmissionWeightTexture",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","transmissionColor")],Ne.prototype,"_transmissionColor",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","transmissionColorTexture")],Ne.prototype,"_transmissionColorTexture",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","transmissionDepth")],Ne.prototype,"_transmissionDepth",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","transmissionDepthTexture")],Ne.prototype,"_transmissionDepthTexture",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","transmissionScatter")],Ne.prototype,"_transmissionScatter",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","transmissionScatterTexture")],Ne.prototype,"_transmissionScatterTexture",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","transmissionScatterAnisotropy")],Ne.prototype,"_transmissionScatterAnisotropy",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","transmissionDispersionScale")],Ne.prototype,"_transmissionDispersionScale",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","transmissionDispersionScaleTexture")],Ne.prototype,"_transmissionDispersionScaleTexture",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","transmissionDispersionAbbeNumber")],Ne.prototype,"_transmissionDispersionAbbeNumber",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","subsurfaceWeight")],Ne.prototype,"_subsurfaceWeight",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","subsurfaceWeightTexture")],Ne.prototype,"_subsurfaceWeightTexture",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","subsurfaceColor")],Ne.prototype,"_subsurfaceColor",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","subsurfaceColorTexture")],Ne.prototype,"_subsurfaceColorTexture",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","subsurfaceRadius")],Ne.prototype,"_subsurfaceRadius",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","subsurfaceRadiusScale")],Ne.prototype,"_subsurfaceRadiusScale",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","subsurfaceRadiusScaleTexture")],Ne.prototype,"_subsurfaceRadiusScaleTexture",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","subsurfaceScatterAnisotropy")],Ne.prototype,"_subsurfaceScatterAnisotropy",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","coatWeight")],Ne.prototype,"_coatWeight",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","coatWeightTexture")],Ne.prototype,"_coatWeightTexture",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","coatColor")],Ne.prototype,"_coatColor",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","coatColorTexture")],Ne.prototype,"_coatColorTexture",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","coatRoughness")],Ne.prototype,"_coatRoughness",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","coatRoughnessTexture")],Ne.prototype,"_coatRoughnessTexture",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","coatRoughnessAnisotropy")],Ne.prototype,"_coatRoughnessAnisotropy",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","coatRoughnessAnisotropyTexture")],Ne.prototype,"_coatRoughnessAnisotropyTexture",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","coatIor")],Ne.prototype,"_coatIor",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","coatDarkening")],Ne.prototype,"_coatDarkening",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","coatDarkeningTexture")],Ne.prototype,"_coatDarkeningTexture",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","fuzzWeight")],Ne.prototype,"_fuzzWeight",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","fuzzWeightTexture")],Ne.prototype,"_fuzzWeightTexture",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","fuzzColor")],Ne.prototype,"_fuzzColor",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","fuzzColorTexture")],Ne.prototype,"_fuzzColorTexture",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","fuzzRoughness")],Ne.prototype,"_fuzzRoughness",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","fuzzRoughnessTexture")],Ne.prototype,"_fuzzRoughnessTexture",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","geometryThinWalled")],Ne.prototype,"_geometryThinWalled",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","geometryNormalTexture")],Ne.prototype,"_geometryNormalTexture",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","geometryTangent")],Ne.prototype,"_geometryTangent",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","geometryTangentTexture")],Ne.prototype,"_geometryTangentTexture",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","geometryCoatNormalTexture")],Ne.prototype,"_geometryCoatNormalTexture",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","geometryCoatTangent")],Ne.prototype,"_geometryCoatTangent",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","geometryCoatTangentTexture")],Ne.prototype,"_geometryCoatTangentTexture",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","geometryOpacity")],Ne.prototype,"_geometryOpacity",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","geometryOpacityTexture")],Ne.prototype,"_geometryOpacityTexture",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","geometryThickness")],Ne.prototype,"_geometryThickness",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","geometryThicknessTexture")],Ne.prototype,"_geometryThicknessTexture",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","emissionLuminance")],Ne.prototype,"_emissionLuminance",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","emissionColor")],Ne.prototype,"_emissionColor",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","emissionColorTexture")],Ne.prototype,"_emissionColorTexture",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","thinFilmWeight")],Ne.prototype,"_thinFilmWeight",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","thinFilmWeightTexture")],Ne.prototype,"_thinFilmWeightTexture",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","thinFilmThickness")],Ne.prototype,"_thinFilmThickness",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","thinFilmThicknessMin")],Ne.prototype,"_thinFilmThicknessMin",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","thinFilmThicknessTexture")],Ne.prototype,"_thinFilmThicknessTexture",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","thinFilmIor")],Ne.prototype,"_thinFilmIor",void 0);P([ut("_markAllSubMeshesAsTexturesDirty","ambientOcclusionTexture")],Ne.prototype,"_ambientOcclusionTexture",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"directIntensity",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"environmentIntensity",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"useSpecularWeightFromTextureAlpha",void 0);P([w(),le("_markAllSubMeshesAsTexturesAndMiscDirty")],Ne.prototype,"forceAlphaTest",void 0);P([w(),le("_markAllSubMeshesAsTexturesAndMiscDirty")],Ne.prototype,"alphaCutOff",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"useAmbientInGrayScale",void 0);P([w()],Ne.prototype,"usePhysicalLightFalloff",null);P([w()],Ne.prototype,"useGLTFLightFalloff",null);P([w(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"useObjectSpaceNormalMap",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"useParallax",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"useParallaxOcclusion",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"parallaxScaleBias",void 0);P([w(),le("_markAllSubMeshesAsLightsDirty")],Ne.prototype,"disableLighting",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"forceIrradianceInFragment",void 0);P([w(),le("_markAllSubMeshesAsLightsDirty")],Ne.prototype,"maxSimultaneousLights",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"invertNormalMapX",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"invertNormalMapY",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"twoSidedLighting",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"useAlphaFresnel",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"useLinearAlphaFresnel",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"environmentBRDFTexture",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"forceNormalForward",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"enableSpecularAntiAliasing",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"useHorizonOcclusion",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],Ne.prototype,"useRadianceOcclusion",void 0);P([w(),le("_markAllSubMeshesAsMiscDirty")],Ne.prototype,"unlit",void 0);P([w(),le("_markAllSubMeshesAsMiscDirty")],Ne.prototype,"applyDecalMapAfterDetailMap",void 0);P([le("_markAllSubMeshesAsMiscDirty")],Ne.prototype,"debugMode",void 0);P([w()],Ne.prototype,"transparencyMode",null);Ft("BABYLON.OpenPBRMaterial",Ne)});var d6={};tt(d6,{OpenPBRMaterialLoadingAdapter:()=>XL});var XL,u6=C(()=>{zt();XL=class{constructor(e){this._diffuseTransmissionTint=ve.White(),this._diffuseTransmissionTintTexture=null,this._material=e}get material(){return this._material}get isUnlit(){return this._material.unlit}set isUnlit(e){this._material.unlit=e}set backFaceCulling(e){this._material.backFaceCulling=e}get backFaceCulling(){return this._material.backFaceCulling}set twoSidedLighting(e){this._material.twoSidedLighting=e}get twoSidedLighting(){return this._material.twoSidedLighting}set alphaCutOff(e){}get alphaCutOff(){return .5}set useAlphaFromBaseColorTexture(e){this._material._useAlphaFromBaseColorTexture=e}get useAlphaFromBaseColorTexture(){return!1}get transparencyAsAlphaCoverage(){return!1}set transparencyAsAlphaCoverage(e){}set baseColor(e){this._material.baseColor=e}get baseColor(){return this._material.baseColor}set baseColorTexture(e){this._material.baseColorTexture=e}get baseColorTexture(){return this._material.baseColorTexture}set baseDiffuseRoughness(e){this._material.baseDiffuseRoughness=e}get baseDiffuseRoughness(){return this._material.baseDiffuseRoughness}set baseDiffuseRoughnessTexture(e){this._material.baseDiffuseRoughnessTexture=e}get baseDiffuseRoughnessTexture(){return this._material.baseDiffuseRoughnessTexture}set baseMetalness(e){this._material.baseMetalness=e}get baseMetalness(){return this._material.baseMetalness}set baseMetalnessTexture(e){this._material.baseMetalnessTexture=e}get baseMetalnessTexture(){return this._material.baseMetalnessTexture}set useRoughnessFromMetallicTextureGreen(e){this._material._useRoughnessFromMetallicTextureGreen=e}set useMetallicFromMetallicTextureBlue(e){this._material._useMetallicFromMetallicTextureBlue=e}enableSpecularEdgeColor(e=!1){}set specularWeight(e){this._material.specularWeight=e}get specularWeight(){return this._material.specularWeight}set specularWeightTexture(e){this._material.specularColorTexture===e?(this._material.specularWeightTexture=null,this._material._useSpecularWeightFromSpecularColorTexture=!0,this._material._useSpecularWeightFromAlpha=!0):this._material.specularWeightTexture=e}get specularWeightTexture(){return this._material.specularWeightTexture}set specularColor(e){this._material.specularColor=e}get specularColor(){return this._material.specularColor}set specularColorTexture(e){this._material.specularColorTexture=e,this._material.specularWeightTexture===this._material.specularColorTexture&&(this._material.specularWeightTexture=null,this._material._useSpecularWeightFromSpecularColorTexture=!0,this._material._useSpecularWeightFromAlpha=!0)}get specularColorTexture(){return this._material.specularColorTexture}set specularRoughness(e){this._material.specularRoughness=e}get specularRoughness(){return this._material.specularRoughness}set specularRoughnessTexture(e){this._material.specularRoughnessTexture=e}get specularRoughnessTexture(){return this._material.specularRoughnessTexture}set specularIor(e){this._material.specularIor=e}get specularIor(){return this._material.specularIor}set emissionColor(e){this._material.emissionColor=e}get emissionColor(){return this._material.emissionColor}set emissionLuminance(e){this._material.emissionLuminance=e}get emissionLuminance(){return this._material.emissionLuminance}set emissionColorTexture(e){this._material.emissionColorTexture=e}get emissionColorTexture(){return this._material.emissionColorTexture}set ambientOcclusionTexture(e){this._material.ambientOcclusionTexture=e}get ambientOcclusionTexture(){return this._material.ambientOcclusionTexture}set ambientOcclusionTextureStrength(e){let t=this._material.ambientOcclusionTexture;t&&(t.level=e)}get ambientOcclusionTextureStrength(){var t;let e=this._material.ambientOcclusionTexture;return(t=e==null?void 0:e.level)!=null?t:1}configureCoat(){}set coatWeight(e){this._material.coatWeight=e}get coatWeight(){return this._material.coatWeight}set coatWeightTexture(e){this._material.coatWeightTexture=e}get coatWeightTexture(){return this._material.coatWeightTexture}set coatColor(e){this._material.coatColor=e}set coatColorTexture(e){this._material.coatColorTexture=e}set coatRoughness(e){this._material.coatRoughness=e}get coatRoughness(){return this._material.coatRoughness}set coatRoughnessTexture(e){this._material.coatRoughnessTexture=e,e&&(this._material._useCoatRoughnessFromGreenChannel=!0)}get coatRoughnessTexture(){return this._material.coatRoughnessTexture}set coatIor(e){this._material.coatIor=e}set coatDarkening(e){this._material.coatDarkening=e}set coatDarkeningTexture(e){this._material.coatDarkeningTexture=e}set coatRoughnessAnisotropy(e){this._material.coatRoughnessAnisotropy=e}get coatRoughnessAnisotropy(){return this._material.coatRoughnessAnisotropy}set geometryCoatTangentAngle(e){this._material.geometryCoatTangentAngle=e}set geometryCoatTangentTexture(e){this._material.geometryCoatTangentTexture=e,e&&(this._material._useCoatRoughnessAnisotropyFromTangentTexture=!0)}get geometryCoatTangentTexture(){return this._material.geometryCoatTangentTexture}configureTransmission(){this._material.geometryThinWalled=1,this._material.transmissionDepth=0}set transmissionWeight(e){this._material.transmissionWeight=e}set transmissionWeightTexture(e){this._material.transmissionWeightTexture=e}get transmissionWeight(){return this._material.transmissionWeight}set transmissionScatter(e){this._material.transmissionScatter=e}get transmissionScatter(){return this._material.transmissionScatter}set transmissionScatterTexture(e){this._material.transmissionScatterTexture=e}get transmissionScatterTexture(){return this._material.transmissionScatterTexture}set transmissionScatterAnisotropy(e){this._material.transmissionScatterAnisotropy=e}set transmissionDispersionAbbeNumber(e){this._material.transmissionDispersionAbbeNumber=e}set transmissionDispersionScale(e){this._material.transmissionDispersionScale=e}set transmissionDepth(e){e!==Number.MAX_VALUE||this._material.transmissionDepth!==0?this._material.transmissionDepth=e:this._material.transmissionDepth=0}get transmissionDepth(){return this._material.transmissionDepth}set transmissionColor(e){e.equals(ve.White())||(this._material.transmissionColor=e)}get transmissionColor(){return this._material.transmissionColor}get refractionBackgroundTexture(){return this._material.backgroundRefractionTexture}set refractionBackgroundTexture(e){this._material.backgroundRefractionTexture=e}configureVolume(){this._material.geometryThinWalled=0}set geometryThinWalled(e){this._material.geometryThinWalled=e?1:0}get geometryThinWalled(){return!!this._material.geometryThinWalled}set volumeThicknessTexture(e){this._material.geometryThicknessTexture=e,this._material._useGeometryThicknessFromGreenChannel=!0}set volumeThickness(e){this._material.geometryThickness=e}configureSubsurface(){this._material.geometryThinWalled=1,this._material.subsurfaceScatterAnisotropy=1}set subsurfaceWeight(e){this._material.subsurfaceWeight=e}get subsurfaceWeight(){return this._material.subsurfaceWeight}set subsurfaceWeightTexture(e){this._material.subsurfaceWeightTexture=e}set subsurfaceColor(e){this._material.subsurfaceColor=e}set subsurfaceColorTexture(e){this._material.subsurfaceColorTexture=e}set diffuseTransmissionTint(e){this._diffuseTransmissionTint=e}get diffuseTransmissionTint(){return this._diffuseTransmissionTint}set diffuseTransmissionTintTexture(e){this._diffuseTransmissionTintTexture=e}get subsurfaceRadius(){return this._material.subsurfaceRadius}set subsurfaceRadius(e){this._material.subsurfaceRadius=e}get subsurfaceRadiusScale(){return this._material.subsurfaceRadiusScale}set subsurfaceRadiusScale(e){this._material.subsurfaceRadiusScale=e}set subsurfaceScatterAnisotropy(e){this._material.subsurfaceScatterAnisotropy=e}isTranslucent(){return this.transmissionWeight>0||this.subsurfaceWeight>0}configureFuzz(){}set fuzzWeight(e){this._material.fuzzWeight=e}set fuzzWeightTexture(e){this._material.fuzzWeightTexture=e}set fuzzColor(e){this._material.fuzzColor=e}set fuzzColorTexture(e){this._material.fuzzColorTexture=e}set fuzzRoughness(e){this._material.fuzzRoughness=e}set fuzzRoughnessTexture(e){this._material.fuzzRoughnessTexture=e,this._material._useFuzzRoughnessFromTextureAlpha=!0}set specularRoughnessAnisotropy(e){this._material.specularRoughnessAnisotropy=e}get specularRoughnessAnisotropy(){return this._material.specularRoughnessAnisotropy}set geometryTangentAngle(e){this._material.geometryTangentAngle=e}set geometryTangentTexture(e){this._material.geometryTangentTexture=e,this._material._useSpecularRoughnessAnisotropyFromTangentTexture=!0}get geometryTangentTexture(){return this._material.geometryTangentTexture}configureGltfStyleAnisotropy(e=!0){this._material._useGltfStyleAnisotropy=e}set thinFilmWeight(e){this._material.thinFilmWeight=e}set thinFilmIor(e){this._material.thinFilmIor=e}set thinFilmThicknessMinimum(e){this._material.thinFilmThicknessMin=e/1e3}set thinFilmThicknessMaximum(e){this._material.thinFilmThickness=e/1e3}set thinFilmWeightTexture(e){this._material.thinFilmWeightTexture=e}set thinFilmThicknessTexture(e){this._material.thinFilmThicknessTexture=e,this._material._useThinFilmThicknessFromTextureGreen=!0}set unlit(e){this._material.unlit=e}set geometryOpacity(e){this._material.geometryOpacity=e}get geometryOpacity(){return this._material.geometryOpacity}set geometryNormalTexture(e){this._material.geometryNormalTexture=e}get geometryNormalTexture(){return this._material.geometryNormalTexture}setNormalMapInversions(e,t){}set geometryCoatNormalTexture(e){this._material.geometryCoatNormalTexture=e}get geometryCoatNormalTexture(){return this._material.geometryCoatNormalTexture}set geometryCoatNormalTextureScale(e){this._material.geometryCoatNormalTexture&&(this._material.geometryCoatNormalTexture.level=e)}finalize(){(this._diffuseTransmissionTint&&!this._diffuseTransmissionTint.equals(ve.White())||this._diffuseTransmissionTintTexture)&&(this._material.geometryThinWalled?(this.subsurfaceColor=this._diffuseTransmissionTint,this.subsurfaceColorTexture=this._diffuseTransmissionTintTexture):this._material.coatWeight==0&&(!this.baseColor.equals(ve.White())||this.baseColorTexture)&&(this._material.coatWeight=this.subsurfaceWeight,this._material.coatWeightTexture=this.subsurfaceWeightTexture,this._material.coatColor=this._diffuseTransmissionTint,this._material.coatColorTexture=this._diffuseTransmissionTintTexture,this._material.coatIor=this._material.specularIor,this._material.coatDarkening=0,this._material.coatRoughness=this._material.specularRoughness,this._material.coatRoughnessTexture=this._material.specularRoughnessTexture,this._material.specularRoughness=1,this._material.specularRoughnessTexture=null)),this.transmissionWeight>0&&(this._material.geometryThinWalled||this._material.transmissionDepth===0?(this._material.transmissionColor=this._material.baseColor,this._material.transmissionColorTexture=this._material.baseColorTexture):this._material.coatWeight==0&&(!this.baseColor.equals(ve.White())||this.baseColorTexture!==null)&&(this._material.coatWeight=this.transmissionWeight,this._material.coatWeightTexture=this.transmissionWeightTexture,this._material.coatColor=this.baseColor,this._material.coatColorTexture=this.baseColorTexture,this._material.coatIor=this._material.specularIor,this._material.coatDarkening=0,this._material.coatRoughness=this._material.specularRoughness,this._material.coatRoughnessTexture=this._material.specularRoughnessTexture))}}});var YL,Mr,m6=C(()=>{Gt();Vt();La();Ff();YL=class extends xr{constructor(){super(...arguments),this.BRDF_V_HEIGHT_CORRELATED=!1,this.MS_BRDF_ENERGY_CONSERVATION=!1,this.SPHERICAL_HARMONICS=!1,this.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=!1,this.MIX_IBL_RADIANCE_WITH_IRRADIANCE=!0,this.LEGACY_SPECULAR_ENERGY_CONSERVATION=!1,this.BASE_DIFFUSE_MODEL=0,this.DIELECTRIC_SPECULAR_MODEL=0,this.CONDUCTOR_SPECULAR_MODEL=0}},Mr=class n extends Vr{_markAllSubMeshesAsMiscDirty(){this._internalMarkAllSubMeshesAsMiscDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRBRDF",90,new YL,t),this._useEnergyConservation=n.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=n.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=n.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=n.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=n.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=n.DEFAULT_USE_SPHERICAL_HARMONICS,this._useSpecularGlossinessInputEnergyConservation=n.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this.useSpecularGlossinessInputEnergyConservation=n.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this._mixIblRadianceWithIrradiance=n.DEFAULT_MIX_IBL_RADIANCE_WITH_IRRADIANCE,this.mixIblRadianceWithIrradiance=n.DEFAULT_MIX_IBL_RADIANCE_WITH_IRRADIANCE,this._useLegacySpecularEnergyConservation=n.DEFAULT_USE_LEGACY_SPECULAR_ENERGY_CONSERVATION,this.useLegacySpecularEnergyConservation=n.DEFAULT_USE_LEGACY_SPECULAR_ENERGY_CONSERVATION,this._baseDiffuseModel=n.DEFAULT_DIFFUSE_MODEL,this.baseDiffuseModel=n.DEFAULT_DIFFUSE_MODEL,this._dielectricSpecularModel=n.DEFAULT_DIELECTRIC_SPECULAR_MODEL,this.dielectricSpecularModel=n.DEFAULT_DIELECTRIC_SPECULAR_MODEL,this._conductorSpecularModel=n.DEFAULT_CONDUCTOR_SPECULAR_MODEL,this.conductorSpecularModel=n.DEFAULT_CONDUCTOR_SPECULAR_MODEL,this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16],this._enable(!0)}prepareDefines(e){e.BRDF_V_HEIGHT_CORRELATED=this._useSmithVisibilityHeightCorrelated,e.MS_BRDF_ENERGY_CONSERVATION=this._useEnergyConservation&&this._useSmithVisibilityHeightCorrelated,e.SPHERICAL_HARMONICS=this._useSphericalHarmonics,e.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=this._useSpecularGlossinessInputEnergyConservation,e.MIX_IBL_RADIANCE_WITH_IRRADIANCE=this._mixIblRadianceWithIrradiance&&!this._material._disableLighting,e.LEGACY_SPECULAR_ENERGY_CONSERVATION=this._useLegacySpecularEnergyConservation,e.BASE_DIFFUSE_MODEL=this._baseDiffuseModel,e.DIELECTRIC_SPECULAR_MODEL=this._dielectricSpecularModel,e.CONDUCTOR_SPECULAR_MODEL=this._conductorSpecularModel}getClassName(){return"PBRBRDFConfiguration"}};Mr.DEFAULT_USE_ENERGY_CONSERVATION=!0;Mr.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0;Mr.DEFAULT_USE_SPHERICAL_HARMONICS=!0;Mr.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0;Mr.DEFAULT_MIX_IBL_RADIANCE_WITH_IRRADIANCE=!0;Mr.DEFAULT_USE_LEGACY_SPECULAR_ENERGY_CONSERVATION=!0;Mr.DEFAULT_DIFFUSE_MODEL=0;Mr.DEFAULT_DIELECTRIC_SPECULAR_MODEL=0;Mr.DEFAULT_CONDUCTOR_SPECULAR_MODEL=0;P([w(),le("_markAllSubMeshesAsMiscDirty")],Mr.prototype,"useEnergyConservation",void 0);P([w(),le("_markAllSubMeshesAsMiscDirty")],Mr.prototype,"useSmithVisibilityHeightCorrelated",void 0);P([w(),le("_markAllSubMeshesAsMiscDirty")],Mr.prototype,"useSphericalHarmonics",void 0);P([w(),le("_markAllSubMeshesAsMiscDirty")],Mr.prototype,"useSpecularGlossinessInputEnergyConservation",void 0);P([w(),le("_markAllSubMeshesAsMiscDirty")],Mr.prototype,"mixIblRadianceWithIrradiance",void 0);P([w(),le("_markAllSubMeshesAsMiscDirty")],Mr.prototype,"useLegacySpecularEnergyConservation",void 0);P([w("baseDiffuseModel"),le("_markAllSubMeshesAsMiscDirty")],Mr.prototype,"baseDiffuseModel",void 0);P([w("dielectricSpecularModel"),le("_markAllSubMeshesAsMiscDirty")],Mr.prototype,"dielectricSpecularModel",void 0);P([w("conductorSpecularModel"),le("_markAllSubMeshesAsMiscDirty")],Mr.prototype,"conductorSpecularModel",void 0)});var KL,sn,p6=C(()=>{Gt();Vt();zt();Pa();Ff();La();Un();KL=class extends xr{constructor(){super(...arguments),this.CLEARCOAT=!1,this.CLEARCOAT_DEFAULTIOR=!1,this.CLEARCOAT_TEXTURE=!1,this.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this.CLEARCOAT_TEXTUREDIRECTUV=0,this.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV=0,this.CLEARCOAT_BUMP=!1,this.CLEARCOAT_BUMPDIRECTUV=0,this.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,this.CLEARCOAT_REMAP_F0=!1,this.CLEARCOAT_TINT=!1,this.CLEARCOAT_TINT_TEXTURE=!1,this.CLEARCOAT_TINT_TEXTUREDIRECTUV=0,this.CLEARCOAT_TINT_GAMMATEXTURE=!1}},sn=class n extends Vr{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRClearCoat",100,new KL,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.roughness=0,this._indexOfRefraction=n._DefaultIndexOfRefraction,this.indexOfRefraction=n._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._useRoughnessFromMainTexture=!0,this.useRoughnessFromMainTexture=!0,this._textureRoughness=null,this.textureRoughness=null,this._remapF0OnInterfaceChange=!0,this.remapF0OnInterfaceChange=!0,this._bumpTexture=null,this.bumpTexture=null,this._isTintEnabled=!1,this.isTintEnabled=!1,this.tintColor=ve.White(),this.tintColorAtDistance=1,this.tintThickness=1,this._tintTexture=null,this.tintTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){if(!this._isEnabled)return!0;let r=this._material._disableBumpMap;return!(e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&ce.ClearCoatTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._textureRoughness&&ce.ClearCoatTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking()||i.getCaps().standardDerivatives&&this._bumpTexture&&ce.ClearCoatBumpTextureEnabled&&!r&&!this._bumpTexture.isReady()||this._isTintEnabled&&this._tintTexture&&ce.ClearCoatTintTextureEnabled&&!this._tintTexture.isReadyOrNotBlocking()))}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.CLEARCOAT=!0,e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,e.CLEARCOAT_REMAP_F0=this._remapF0OnInterfaceChange,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&ce.ClearCoatTextureEnabled?ni(this._texture,e,"CLEARCOAT_TEXTURE"):e.CLEARCOAT_TEXTURE=!1,this._textureRoughness&&ce.ClearCoatTextureEnabled?ni(this._textureRoughness,e,"CLEARCOAT_TEXTURE_ROUGHNESS"):e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this._bumpTexture&&ce.ClearCoatBumpTextureEnabled?ni(this._bumpTexture,e,"CLEARCOAT_BUMP"):e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_DEFAULTIOR=this._indexOfRefraction===n._DefaultIndexOfRefraction,this._isTintEnabled?(e.CLEARCOAT_TINT=!0,this._tintTexture&&ce.ClearCoatTintTextureEnabled?(ni(this._tintTexture,e,"CLEARCOAT_TINT_TEXTURE"),e.CLEARCOAT_TINT_GAMMATEXTURE=this._tintTexture.gammaSpace):e.CLEARCOAT_TINT_TEXTURE=!1):(e.CLEARCOAT_TINT=!1,e.CLEARCOAT_TINT_TEXTURE=!1))):(e.CLEARCOAT=!1,e.CLEARCOAT_TEXTURE=!1,e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_TINT=!1,e.CLEARCOAT_TINT_TEXTURE=!1,e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.CLEARCOAT_DEFAULTIOR=!1,e.CLEARCOAT_TEXTUREDIRECTUV=0,e.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV=0,e.CLEARCOAT_BUMPDIRECTUV=0,e.CLEARCOAT_REMAP_F0=!1,e.CLEARCOAT_TINT_TEXTUREDIRECTUV=0,e.CLEARCOAT_TINT_GAMMATEXTURE=!1)}bindForSubMesh(e,t,i,r){var f,h,d,u,m,p,_,g;if(!this._isEnabled)return;let s=r.materialDefines,a=this._material.isFrozen,o=this._material._disableBumpMap,l=this._material._invertNormalMapX,c=this._material._invertNormalMapY;if(!e.useUbo||!a||!e.isSync){(this._texture||this._textureRoughness)&&ce.ClearCoatTextureEnabled&&(e.updateFloat4("vClearCoatInfos",(h=(f=this._texture)==null?void 0:f.coordinatesIndex)!=null?h:0,(u=(d=this._texture)==null?void 0:d.level)!=null?u:0,(p=(m=this._textureRoughness)==null?void 0:m.coordinatesIndex)!=null?p:0,(g=(_=this._textureRoughness)==null?void 0:_.level)!=null?g:0),this._texture&&si(this._texture,e,"clearCoat"),this._textureRoughness&&!s.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&si(this._textureRoughness,e,"clearCoatRoughness")),this._bumpTexture&&i.getCaps().standardDerivatives&&ce.ClearCoatTextureEnabled&&!o&&(e.updateFloat2("vClearCoatBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level),si(this._bumpTexture,e,"clearCoatBump"),t._mirroredCameraPosition?e.updateFloat2("vClearCoatTangentSpaceParams",l?1:-1,c?1:-1):e.updateFloat2("vClearCoatTangentSpaceParams",l?-1:1,c?-1:1)),this._tintTexture&&ce.ClearCoatTintTextureEnabled&&(e.updateFloat2("vClearCoatTintInfos",this._tintTexture.coordinatesIndex,this._tintTexture.level),si(this._tintTexture,e,"clearCoatTint")),e.updateFloat2("vClearCoatParams",this.intensity,this.roughness);let v=1-this._indexOfRefraction,x=1+this._indexOfRefraction,A=Math.pow(-v/x,2),S=1/this._indexOfRefraction;e.updateFloat4("vClearCoatRefractionParams",A,S,v,x),this._isTintEnabled&&(e.updateFloat4("vClearCoatTintParams",this.tintColor.r,this.tintColor.g,this.tintColor.b,Math.max(1e-5,this.tintThickness)),e.updateFloat("clearCoatColorAtDistance",Math.max(1e-5,this.tintColorAtDistance)))}t.texturesEnabled&&(this._texture&&ce.ClearCoatTextureEnabled&&e.setTexture("clearCoatSampler",this._texture),this._textureRoughness&&!s.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&ce.ClearCoatTextureEnabled&&e.setTexture("clearCoatRoughnessSampler",this._textureRoughness),this._bumpTexture&&i.getCaps().standardDerivatives&&ce.ClearCoatBumpTextureEnabled&&!o&&e.setTexture("clearCoatBumpSampler",this._bumpTexture),this._isTintEnabled&&this._tintTexture&&ce.ClearCoatTintTextureEnabled&&e.setTexture("clearCoatTintSampler",this._tintTexture))}hasTexture(e){return this._texture===e||this._textureRoughness===e||this._bumpTexture===e||this._tintTexture===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._textureRoughness&&e.push(this._textureRoughness),this._bumpTexture&&e.push(this._bumpTexture),this._tintTexture&&e.push(this._tintTexture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._tintTexture&&this._tintTexture.animations&&this._tintTexture.animations.length>0&&e.push(this._tintTexture)}dispose(e){var t,i,r,s;e&&((t=this._texture)==null||t.dispose(),(i=this._textureRoughness)==null||i.dispose(),(r=this._bumpTexture)==null||r.dispose(),(s=this._tintTexture)==null||s.dispose())}getClassName(){return"PBRClearCoatConfiguration"}addFallbacks(e,t,i){return e.CLEARCOAT_BUMP&&t.addFallback(i++,"CLEARCOAT_BUMP"),e.CLEARCOAT_TINT&&t.addFallback(i++,"CLEARCOAT_TINT"),e.CLEARCOAT&&t.addFallback(i++,"CLEARCOAT"),i}getSamplers(e){e.push("clearCoatSampler","clearCoatRoughnessSampler","clearCoatBumpSampler","clearCoatTintSampler")}getUniforms(){return{ubo:[{name:"vClearCoatParams",size:2,type:"vec2"},{name:"vClearCoatRefractionParams",size:4,type:"vec4"},{name:"vClearCoatInfos",size:4,type:"vec4"},{name:"clearCoatMatrix",size:16,type:"mat4"},{name:"clearCoatRoughnessMatrix",size:16,type:"mat4"},{name:"vClearCoatBumpInfos",size:2,type:"vec2"},{name:"vClearCoatTangentSpaceParams",size:2,type:"vec2"},{name:"clearCoatBumpMatrix",size:16,type:"mat4"},{name:"vClearCoatTintParams",size:4,type:"vec4"},{name:"clearCoatColorAtDistance",size:1,type:"float"},{name:"vClearCoatTintInfos",size:2,type:"vec2"},{name:"clearCoatTintMatrix",size:16,type:"mat4"}]}}};sn._DefaultIndexOfRefraction=1.5;P([w(),le("_markAllSubMeshesAsTexturesDirty")],sn.prototype,"isEnabled",void 0);P([w()],sn.prototype,"intensity",void 0);P([w()],sn.prototype,"roughness",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],sn.prototype,"indexOfRefraction",void 0);P([Ut(),le("_markAllSubMeshesAsTexturesDirty")],sn.prototype,"texture",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],sn.prototype,"useRoughnessFromMainTexture",void 0);P([Ut(),le("_markAllSubMeshesAsTexturesDirty")],sn.prototype,"textureRoughness",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],sn.prototype,"remapF0OnInterfaceChange",void 0);P([Ut(),le("_markAllSubMeshesAsTexturesDirty")],sn.prototype,"bumpTexture",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],sn.prototype,"isTintEnabled",void 0);P([gr()],sn.prototype,"tintColor",void 0);P([w()],sn.prototype,"tintColorAtDistance",void 0);P([w()],sn.prototype,"tintThickness",void 0);P([Ut(),le("_markAllSubMeshesAsTexturesDirty")],sn.prototype,"tintTexture",void 0)});var jL,Ps,_6=C(()=>{Gt();Vt();Pa();Ff();La();Un();jL=class extends xr{constructor(){super(...arguments),this.IRIDESCENCE=!1,this.IRIDESCENCE_TEXTURE=!1,this.IRIDESCENCE_TEXTUREDIRECTUV=0,this.IRIDESCENCE_THICKNESS_TEXTURE=!1,this.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0}},Ps=class n extends Vr{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRIridescence",110,new jL,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.minimumThickness=n._DefaultMinimumThickness,this.maximumThickness=n._DefaultMaximumThickness,this.indexOfRefraction=n._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._thicknessTexture=null,this.thicknessTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){return this._isEnabled?!(e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&ce.IridescenceTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._thicknessTexture&&ce.IridescenceTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())):!0}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.IRIDESCENCE=!0,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&ce.IridescenceTextureEnabled?ni(this._texture,e,"IRIDESCENCE_TEXTURE"):e.IRIDESCENCE_TEXTURE=!1,this._thicknessTexture&&ce.IridescenceTextureEnabled?ni(this._thicknessTexture,e,"IRIDESCENCE_THICKNESS_TEXTURE"):e.IRIDESCENCE_THICKNESS_TEXTURE=!1)):(e.IRIDESCENCE=!1,e.IRIDESCENCE_TEXTURE=!1,e.IRIDESCENCE_THICKNESS_TEXTURE=!1,e.IRIDESCENCE_TEXTUREDIRECTUV=0,e.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0)}bindForSubMesh(e,t){var r,s,a,o,l,c,f,h;if(!this._isEnabled)return;let i=this._material.isFrozen;(!e.useUbo||!i||!e.isSync)&&((this._texture||this._thicknessTexture)&&ce.IridescenceTextureEnabled&&(e.updateFloat4("vIridescenceInfos",(s=(r=this._texture)==null?void 0:r.coordinatesIndex)!=null?s:0,(o=(a=this._texture)==null?void 0:a.level)!=null?o:0,(c=(l=this._thicknessTexture)==null?void 0:l.coordinatesIndex)!=null?c:0,(h=(f=this._thicknessTexture)==null?void 0:f.level)!=null?h:0),this._texture&&si(this._texture,e,"iridescence"),this._thicknessTexture&&si(this._thicknessTexture,e,"iridescenceThickness")),e.updateFloat4("vIridescenceParams",this.intensity,this.indexOfRefraction,this.minimumThickness,this.maximumThickness)),t.texturesEnabled&&(this._texture&&ce.IridescenceTextureEnabled&&e.setTexture("iridescenceSampler",this._texture),this._thicknessTexture&&ce.IridescenceTextureEnabled&&e.setTexture("iridescenceThicknessSampler",this._thicknessTexture))}hasTexture(e){return this._texture===e||this._thicknessTexture===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._thicknessTexture&&e.push(this._thicknessTexture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture)}dispose(e){var t,i;e&&((t=this._texture)==null||t.dispose(),(i=this._thicknessTexture)==null||i.dispose())}getClassName(){return"PBRIridescenceConfiguration"}addFallbacks(e,t,i){return e.IRIDESCENCE&&t.addFallback(i++,"IRIDESCENCE"),i}getSamplers(e){e.push("iridescenceSampler","iridescenceThicknessSampler")}getUniforms(){return{ubo:[{name:"vIridescenceParams",size:4,type:"vec4"},{name:"vIridescenceInfos",size:4,type:"vec4"},{name:"iridescenceMatrix",size:16,type:"mat4"},{name:"iridescenceThicknessMatrix",size:16,type:"mat4"}]}}};Ps._DefaultMinimumThickness=100;Ps._DefaultMaximumThickness=400;Ps._DefaultIndexOfRefraction=1.3;P([w(),le("_markAllSubMeshesAsTexturesDirty")],Ps.prototype,"isEnabled",void 0);P([w()],Ps.prototype,"intensity",void 0);P([w()],Ps.prototype,"minimumThickness",void 0);P([w()],Ps.prototype,"maximumThickness",void 0);P([w()],Ps.prototype,"indexOfRefraction",void 0);P([Ut(),le("_markAllSubMeshesAsTexturesDirty")],Ps.prototype,"texture",void 0);P([Ut(),le("_markAllSubMeshesAsTexturesDirty")],Ps.prototype,"thicknessTexture",void 0)});var qL,xc,g6=C(()=>{Gt();Vt();ki();Ge();Pa();Ff();La();Un();qL=class extends xr{constructor(){super(...arguments),this.ANISOTROPIC=!1,this.ANISOTROPIC_TEXTURE=!1,this.ANISOTROPIC_TEXTUREDIRECTUV=0,this.ANISOTROPIC_LEGACY=!1,this.MAINUV1=!1}},xc=class extends Vr{set angle(e){this.direction.x=Math.cos(e),this.direction.y=Math.sin(e)}get angle(){return Math.atan2(this.direction.y,this.direction.x)}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markAllSubMeshesAsMiscDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsMiscDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRAnisotropic",110,new qL,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new we(1,0),this._texture=null,this.texture=null,this._legacy=!1,this.legacy=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16]}isReadyForSubMesh(e,t){return this._isEnabled?!(e._areTexturesDirty&&t.texturesEnabled&&this._texture&&ce.AnisotropicTextureEnabled&&!this._texture.isReadyOrNotBlocking()):!0}prepareDefinesBeforeAttributes(e,t,i){this._isEnabled?(e.ANISOTROPIC=this._isEnabled,this._isEnabled&&!i.isVerticesDataPresent(L.TangentKind)&&(e._needUVs=!0,e.MAINUV1=!0),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&ce.AnisotropicTextureEnabled?ni(this._texture,e,"ANISOTROPIC_TEXTURE"):e.ANISOTROPIC_TEXTURE=!1),e._areMiscDirty&&(e.ANISOTROPIC_LEGACY=this._legacy)):(e.ANISOTROPIC=!1,e.ANISOTROPIC_TEXTURE=!1,e.ANISOTROPIC_TEXTUREDIRECTUV=0,e.ANISOTROPIC_LEGACY=!1)}bindForSubMesh(e,t){if(!this._isEnabled)return;let i=this._material.isFrozen;(!e.useUbo||!i||!e.isSync)&&(this._texture&&ce.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),si(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&&ce.AnisotropicTextureEnabled&&e.setTexture("anisotropySampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){e&&this._texture&&this._texture.dispose()}getClassName(){return"PBRAnisotropicConfiguration"}addFallbacks(e,t,i){return e.ANISOTROPIC&&t.addFallback(i++,"ANISOTROPIC"),i}getSamplers(e){e.push("anisotropySampler")}getUniforms(){return{ubo:[{name:"vAnisotropy",size:3,type:"vec3"},{name:"vAnisotropyInfos",size:2,type:"vec2"},{name:"anisotropyMatrix",size:16,type:"mat4"}]}}parse(e,t,i){super.parse(e,t,i),e.legacy===void 0&&(this.legacy=!0)}};P([w(),le("_markAllSubMeshesAsTexturesDirty")],xc.prototype,"isEnabled",void 0);P([w()],xc.prototype,"intensity",void 0);P([em()],xc.prototype,"direction",void 0);P([Ut(),le("_markAllSubMeshesAsTexturesDirty")],xc.prototype,"texture",void 0);P([w(),le("_markAllSubMeshesAsMiscDirty")],xc.prototype,"legacy",void 0)});var ZL,Qs,v6=C(()=>{Gt();Vt();zt();Pa();Ff();La();Un();ZL=class extends xr{constructor(){super(...arguments),this.SHEEN=!1,this.SHEEN_TEXTURE=!1,this.SHEEN_GAMMATEXTURE=!1,this.SHEEN_TEXTURE_ROUGHNESS=!1,this.SHEEN_TEXTUREDIRECTUV=0,this.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0,this.SHEEN_LINKWITHALBEDO=!1,this.SHEEN_ROUGHNESS=!1,this.SHEEN_ALBEDOSCALING=!1,this.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1}},Qs=class extends Vr{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"Sheen",120,new ZL,t),this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=ve.White(),this._texture=null,this.texture=null,this._useRoughnessFromMainTexture=!0,this.useRoughnessFromMainTexture=!0,this._roughness=null,this.roughness=null,this._textureRoughness=null,this.textureRoughness=null,this._albedoScaling=!1,this.albedoScaling=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){return this._isEnabled?!(e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&ce.SheenTextureEnabled&&!this._texture.isReadyOrNotBlocking()||this._textureRoughness&&ce.SheenTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking())):!0}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.SHEEN=!0,e.SHEEN_LINKWITHALBEDO=this._linkSheenWithAlbedo,e.SHEEN_ROUGHNESS=this._roughness!==null,e.SHEEN_ALBEDOSCALING=this._albedoScaling,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&ce.SheenTextureEnabled?(ni(this._texture,e,"SHEEN_TEXTURE"),e.SHEEN_GAMMATEXTURE=this._texture.gammaSpace):e.SHEEN_TEXTURE=!1,this._textureRoughness&&ce.SheenTextureEnabled?ni(this._textureRoughness,e,"SHEEN_TEXTURE_ROUGHNESS"):e.SHEEN_TEXTURE_ROUGHNESS=!1)):(e.SHEEN=!1,e.SHEEN_TEXTURE=!1,e.SHEEN_TEXTURE_ROUGHNESS=!1,e.SHEEN_LINKWITHALBEDO=!1,e.SHEEN_ROUGHNESS=!1,e.SHEEN_ALBEDOSCALING=!1,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.SHEEN_GAMMATEXTURE=!1,e.SHEEN_TEXTUREDIRECTUV=0,e.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0)}bindForSubMesh(e,t,i,r){var o,l,c,f,h,d,u,m;if(!this._isEnabled)return;let s=r.materialDefines,a=this._material.isFrozen;(!e.useUbo||!a||!e.isSync)&&((this._texture||this._textureRoughness)&&ce.SheenTextureEnabled&&(e.updateFloat4("vSheenInfos",(l=(o=this._texture)==null?void 0:o.coordinatesIndex)!=null?l:0,(f=(c=this._texture)==null?void 0:c.level)!=null?f:0,(d=(h=this._textureRoughness)==null?void 0:h.coordinatesIndex)!=null?d:0,(m=(u=this._textureRoughness)==null?void 0:u.level)!=null?m:0),this._texture&&si(this._texture,e,"sheen"),this._textureRoughness&&!s.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&si(this._textureRoughness,e,"sheenRoughness")),e.updateFloat4("vSheenColor",this.color.r,this.color.g,this.color.b,this.intensity),this._roughness!==null&&e.updateFloat("vSheenRoughness",this._roughness)),t.texturesEnabled&&(this._texture&&ce.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture),this._textureRoughness&&!s.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&ce.SheenTextureEnabled&&e.setTexture("sheenRoughnessSampler",this._textureRoughness))}hasTexture(e){return this._texture===e||this._textureRoughness===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._textureRoughness&&e.push(this._textureRoughness)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness)}dispose(e){var t,i;e&&((t=this._texture)==null||t.dispose(),(i=this._textureRoughness)==null||i.dispose())}getClassName(){return"PBRSheenConfiguration"}addFallbacks(e,t,i){return e.SHEEN&&t.addFallback(i++,"SHEEN"),i}getSamplers(e){e.push("sheenSampler","sheenRoughnessSampler")}getUniforms(){return{ubo:[{name:"vSheenColor",size:4,type:"vec4"},{name:"vSheenRoughness",size:1,type:"float"},{name:"vSheenInfos",size:4,type:"vec4"},{name:"sheenMatrix",size:16,type:"mat4"},{name:"sheenRoughnessMatrix",size:16,type:"mat4"}]}}};P([w(),le("_markAllSubMeshesAsTexturesDirty")],Qs.prototype,"isEnabled",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],Qs.prototype,"linkSheenWithAlbedo",void 0);P([w()],Qs.prototype,"intensity",void 0);P([gr()],Qs.prototype,"color",void 0);P([Ut(),le("_markAllSubMeshesAsTexturesDirty")],Qs.prototype,"texture",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],Qs.prototype,"useRoughnessFromMainTexture",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],Qs.prototype,"roughness",void 0);P([Ut(),le("_markAllSubMeshesAsTexturesDirty")],Qs.prototype,"textureRoughness",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],Qs.prototype,"albedoScaling",void 0)});var QL,Ai,E6=C(()=>{Gt();Vt();zt();Pa();Ge();Ff();La();Un();QL=class extends xr{constructor(){super(...arguments),this.SUBSURFACE=!1,this.SS_REFRACTION=!1,this.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=!1,this.SS_TRANSLUCENCY=!1,this.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=!1,this.SS_SCATTERING=!1,this.SS_DISPERSION=!1,this.SS_THICKNESSANDMASK_TEXTURE=!1,this.SS_THICKNESSANDMASK_TEXTUREDIRECTUV=0,this.SS_HAS_THICKNESS=!1,this.SS_REFRACTIONINTENSITY_TEXTURE=!1,this.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV=0,this.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,this.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV=0,this.SS_TRANSLUCENCYCOLOR_TEXTURE=!1,this.SS_TRANSLUCENCYCOLOR_TEXTUREDIRECTUV=0,this.SS_TRANSLUCENCYCOLOR_TEXTURE_GAMMA=!1,this.SS_REFRACTIONMAP_3D=!1,this.SS_REFRACTIONMAP_OPPOSITEZ=!1,this.SS_LODINREFRACTIONALPHA=!1,this.SS_GAMMAREFRACTION=!1,this.SS_RGBDREFRACTION=!1,this.SS_LINEARSPECULARREFRACTION=!1,this.SS_LINKREFRACTIONTOTRANSPARENCY=!1,this.SS_ALBEDOFORREFRACTIONTINT=!1,this.SS_ALBEDOFORTRANSLUCENCYTINT=!1,this.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.SS_USE_THICKNESS_AS_DEPTH=!1,this.SS_USE_GLTF_TEXTURES=!1,this.SS_APPLY_ALBEDO_AFTER_SUBSURFACE=!1,this.SS_TRANSLUCENCY_LEGACY=!1}},Ai=class n extends Vr{get scatteringDiffusionProfile(){return this._scene.subSurfaceConfiguration?this._scene.subSurfaceConfiguration.ssDiffusionProfileColors[this._scatteringDiffusionProfileIndex]:null}set scatteringDiffusionProfile(e){this._scene.enableSubSurfaceForPrePass()&&e&&(this._scatteringDiffusionProfileIndex=this._scene.subSurfaceConfiguration.addDiffusionProfile(e))}get volumeIndexOfRefraction(){return this._volumeIndexOfRefraction>=1?this._volumeIndexOfRefraction:this._indexOfRefraction}set volumeIndexOfRefraction(e){e>=1?this._volumeIndexOfRefraction=e:this._volumeIndexOfRefraction=-1}get legacyTransluceny(){return this.legacyTranslucency}set legacyTransluceny(e){this.legacyTranslucency=e}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markScenePrePassDirty(){this._enable(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled),this._internalMarkAllSubMeshesAsTexturesDirty(),this._internalMarkScenePrePassDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRSubSurface",130,new QL,t),this._isRefractionEnabled=!1,this.isRefractionEnabled=!1,this._isTranslucencyEnabled=!1,this.isTranslucencyEnabled=!1,this._isDispersionEnabled=!1,this.isDispersionEnabled=!1,this._isScatteringEnabled=!1,this.isScatteringEnabled=!1,this._scatteringDiffusionProfileIndex=0,this.refractionIntensity=1,this.translucencyIntensity=1,this._useAlbedoToTintRefraction=!1,this.useAlbedoToTintRefraction=!1,this._useAlbedoToTintTranslucency=!1,this.useAlbedoToTintTranslucency=!1,this._thicknessTexture=null,this.thicknessTexture=null,this._refractionTexture=null,this.refractionTexture=null,this._indexOfRefraction=1.5,this.indexOfRefraction=1.5,this._volumeIndexOfRefraction=-1,this._invertRefractionY=!1,this.invertRefractionY=!1,this._linkRefractionWithTransparency=!1,this.linkRefractionWithTransparency=!1,this.minimumThickness=0,this.maximumThickness=1,this.useThicknessAsDepth=!1,this.tintColor=ve.White(),this.tintColorAtDistance=1,this.dispersion=0,this.diffusionDistance=ve.White(),this._useMaskFromThicknessTexture=!1,this.useMaskFromThicknessTexture=!1,this._refractionIntensityTexture=null,this.refractionIntensityTexture=null,this._translucencyIntensityTexture=null,this.translucencyIntensityTexture=null,this.translucencyColor=null,this._translucencyColorTexture=null,this.translucencyColorTexture=null,this._useGltfStyleTextures=!0,this.useGltfStyleTextures=!0,this.applyAlbedoAfterSubSurface=n.DEFAULT_APPLY_ALBEDO_AFTERSUBSURFACE,this.legacyTranslucency=n.DEFAULT_LEGACY_TRANSLUCENCY,this._scene=e.getScene(),this.registerForExtraEvents=!0,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkScenePrePassDirty=e._dirtyCallbacks[32]}isReadyForSubMesh(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._thicknessTexture&&ce.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking()||this._refractionIntensityTexture&&ce.RefractionIntensityTextureEnabled&&!this._refractionIntensityTexture.isReadyOrNotBlocking()||this._translucencyColorTexture&&ce.TranslucencyColorTextureEnabled&&!this._translucencyColorTexture.isReadyOrNotBlocking()||this._translucencyIntensityTexture&&ce.TranslucencyIntensityTextureEnabled&&!this._translucencyIntensityTexture.isReadyOrNotBlocking())return!1;let i=this._getRefractionTexture(t);if(i&&ce.RefractionTextureEnabled&&!i.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled){e.SUBSURFACE=!1,e.SS_DISPERSION=!1,e.SS_TRANSLUCENCY=!1,e.SS_SCATTERING=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_THICKNESSANDMASK_TEXTURE=!1,e.SS_THICKNESSANDMASK_TEXTUREDIRECTUV=0,e.SS_HAS_THICKNESS=!1,e.SS_REFRACTIONINTENSITY_TEXTURE=!1,e.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV=0,e.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,e.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV=0,e.SS_REFRACTIONMAP_3D=!1,e.SS_REFRACTIONMAP_OPPOSITEZ=!1,e.SS_LODINREFRACTIONALPHA=!1,e.SS_GAMMAREFRACTION=!1,e.SS_RGBDREFRACTION=!1,e.SS_LINEARSPECULARREFRACTION=!1,e.SS_LINKREFRACTIONTOTRANSPARENCY=!1,e.SS_ALBEDOFORREFRACTIONTINT=!1,e.SS_ALBEDOFORTRANSLUCENCYTINT=!1,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,e.SS_USE_THICKNESS_AS_DEPTH=!1,e.SS_USE_GLTF_TEXTURES=!1,e.SS_TRANSLUCENCYCOLOR_TEXTURE=!1,e.SS_TRANSLUCENCYCOLOR_TEXTUREDIRECTUV=0,e.SS_TRANSLUCENCYCOLOR_TEXTURE_GAMMA=!1,e.SS_APPLY_ALBEDO_AFTER_SUBSURFACE=!1;return}if(e._areTexturesDirty){if(e.SUBSURFACE=!0,e.SS_DISPERSION=this._isDispersionEnabled,e.SS_TRANSLUCENCY=this._isTranslucencyEnabled,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_TRANSLUCENCY_LEGACY=this.legacyTranslucency,e.SS_SCATTERING=this._isScatteringEnabled,e.SS_THICKNESSANDMASK_TEXTURE=!1,e.SS_REFRACTIONINTENSITY_TEXTURE=!1,e.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,e.SS_HAS_THICKNESS=!1,e.SS_USE_GLTF_TEXTURES=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_REFRACTIONMAP_3D=!1,e.SS_GAMMAREFRACTION=!1,e.SS_RGBDREFRACTION=!1,e.SS_LINEARSPECULARREFRACTION=!1,e.SS_REFRACTIONMAP_OPPOSITEZ=!1,e.SS_LODINREFRACTIONALPHA=!1,e.SS_LINKREFRACTIONTOTRANSPARENCY=!1,e.SS_ALBEDOFORREFRACTIONTINT=!1,e.SS_ALBEDOFORTRANSLUCENCYTINT=!1,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,e.SS_USE_THICKNESS_AS_DEPTH=!1,e.SS_TRANSLUCENCYCOLOR_TEXTURE=!1,e.SS_APPLY_ALBEDO_AFTER_SUBSURFACE=this.applyAlbedoAfterSubSurface,e._areTexturesDirty&&t.texturesEnabled&&(this._thicknessTexture&&ce.ThicknessTextureEnabled&&ni(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),this._refractionIntensityTexture&&ce.RefractionIntensityTextureEnabled&&ni(this._refractionIntensityTexture,e,"SS_REFRACTIONINTENSITY_TEXTURE"),this._translucencyIntensityTexture&&ce.TranslucencyIntensityTextureEnabled&&ni(this._translucencyIntensityTexture,e,"SS_TRANSLUCENCYINTENSITY_TEXTURE"),this._translucencyColorTexture&&ce.TranslucencyColorTextureEnabled&&(ni(this._translucencyColorTexture,e,"SS_TRANSLUCENCYCOLOR_TEXTURE"),e.SS_TRANSLUCENCYCOLOR_TEXTURE_GAMMA=this._translucencyColorTexture.gammaSpace)),e.SS_HAS_THICKNESS=this.maximumThickness-this.minimumThickness!==0,e.SS_USE_GLTF_TEXTURES=this._useGltfStyleTextures,e.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=this._useMaskFromThicknessTexture&&!this._refractionIntensityTexture,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=this._useMaskFromThicknessTexture&&!this._translucencyIntensityTexture,this._isRefractionEnabled&&t.texturesEnabled){let i=this._getRefractionTexture(t);i&&ce.RefractionTextureEnabled&&(e.SS_REFRACTION=!0,e.SS_REFRACTIONMAP_3D=i.isCube,e.SS_GAMMAREFRACTION=i.gammaSpace,e.SS_RGBDREFRACTION=i.isRGBD,e.SS_LINEARSPECULARREFRACTION=i.linearSpecularLOD,e.SS_REFRACTIONMAP_OPPOSITEZ=this._scene.useRightHandedSystem&&i.isCube?!i.invertZ:i.invertZ,e.SS_LODINREFRACTIONALPHA=i.lodLevelInAlpha,e.SS_LINKREFRACTIONTOTRANSPARENCY=this._linkRefractionWithTransparency,e.SS_ALBEDOFORREFRACTIONTINT=this._useAlbedoToTintRefraction,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=i.isCube&&i.boundingBoxSize,e.SS_USE_THICKNESS_AS_DEPTH=this.useThicknessAsDepth)}this._isTranslucencyEnabled&&(e.SS_ALBEDOFORTRANSLUCENCYTINT=this._useAlbedoToTintTranslucency)}}hardBindForSubMesh(e,t,i,r){if(!(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled))if(this.maximumThickness===0&&this.minimumThickness===0)e.updateFloat2("vThicknessParam",0,0);else{r.getRenderingMesh().getWorldMatrix().decompose($.Vector3[0]);let s=Math.max(Math.abs($.Vector3[0].x),Math.abs($.Vector3[0].y),Math.abs($.Vector3[0].z));e.updateFloat2("vThicknessParam",this.minimumThickness*s,(this.maximumThickness-this.minimumThickness)*s)}}bindForSubMesh(e,t,i,r){var f;if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;let s=r.materialDefines,a=this._material.isFrozen,o=this._material.realTimeFiltering,l=s.LODBASEDMICROSFURACE,c=this._getRefractionTexture(t);if(!e.useUbo||!a||!e.isSync){if(this._thicknessTexture&&ce.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),si(this._thicknessTexture,e,"thickness")),this._refractionIntensityTexture&&ce.RefractionIntensityTextureEnabled&&s.SS_REFRACTIONINTENSITY_TEXTURE&&(e.updateFloat2("vRefractionIntensityInfos",this._refractionIntensityTexture.coordinatesIndex,this._refractionIntensityTexture.level),si(this._refractionIntensityTexture,e,"refractionIntensity")),this._translucencyColorTexture&&ce.TranslucencyColorTextureEnabled&&s.SS_TRANSLUCENCYCOLOR_TEXTURE&&(e.updateFloat2("vTranslucencyColorInfos",this._translucencyColorTexture.coordinatesIndex,this._translucencyColorTexture.level),si(this._translucencyColorTexture,e,"translucencyColor")),this._translucencyIntensityTexture&&ce.TranslucencyIntensityTextureEnabled&&s.SS_TRANSLUCENCYINTENSITY_TEXTURE&&(e.updateFloat2("vTranslucencyIntensityInfos",this._translucencyIntensityTexture.coordinatesIndex,this._translucencyIntensityTexture.level),si(this._translucencyIntensityTexture,e,"translucencyIntensity")),c&&ce.RefractionTextureEnabled){e.updateMatrix("refractionMatrix",c.getRefractionTextureMatrix());let h=1;c.isCube||c.depth&&(h=c.depth);let d=c.getSize().width,u=this.volumeIndexOfRefraction;if(e.updateFloat4("vRefractionInfos",c.level,1/u,h,this._invertRefractionY?-1:1),e.updateFloat4("vRefractionMicrosurfaceInfos",d,c.lodGenerationScale,c.lodGenerationOffset,1/this.indexOfRefraction),o&&e.updateFloat2("vRefractionFilteringInfo",d,Math.log2(d)),c.boundingBoxSize){let m=c;e.updateVector3("vRefractionPosition",m.boundingBoxPosition),e.updateVector3("vRefractionSize",m.boundingBoxSize)}}this._isScatteringEnabled&&e.updateFloat("scatteringDiffusionProfile",this._scatteringDiffusionProfileIndex),e.updateColor3("vDiffusionDistance",this.diffusionDistance),e.updateFloat4("vTintColor",this.tintColor.r,this.tintColor.g,this.tintColor.b,Math.max(1e-5,this.tintColorAtDistance)),e.updateColor4("vTranslucencyColor",(f=this.translucencyColor)!=null?f:this.tintColor,0),e.updateFloat3("vSubSurfaceIntensity",this.refractionIntensity,this.translucencyIntensity,0),e.updateFloat("dispersion",this.dispersion)}t.texturesEnabled&&(this._thicknessTexture&&ce.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),this._refractionIntensityTexture&&ce.RefractionIntensityTextureEnabled&&s.SS_REFRACTIONINTENSITY_TEXTURE&&e.setTexture("refractionIntensitySampler",this._refractionIntensityTexture),this._translucencyIntensityTexture&&ce.TranslucencyIntensityTextureEnabled&&s.SS_TRANSLUCENCYINTENSITY_TEXTURE&&e.setTexture("translucencyIntensitySampler",this._translucencyIntensityTexture),this._translucencyColorTexture&&ce.TranslucencyColorTextureEnabled&&s.SS_TRANSLUCENCYCOLOR_TEXTURE&&e.setTexture("translucencyColorSampler",this._translucencyColorTexture),c&&ce.RefractionTextureEnabled&&(l?e.setTexture("refractionSampler",c):(e.setTexture("refractionSampler",c._lodTextureMid||c),e.setTexture("refractionSamplerLow",c._lodTextureLow||c),e.setTexture("refractionSamplerHigh",c._lodTextureHigh||c))))}_getRefractionTexture(e){return this._refractionTexture?this._refractionTexture:this._isRefractionEnabled?e.environmentTexture:null}get disableAlphaBlending(){return this._isRefractionEnabled&&this._linkRefractionWithTransparency}fillRenderTargetTextures(e){ce.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&e.push(this._refractionTexture)}hasTexture(e){return this._thicknessTexture===e||this._refractionTexture===e||this._refractionIntensityTexture===e||this._translucencyIntensityTexture===e||this._translucencyColorTexture===e}hasRenderTargetTextures(){return!!(ce.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)}getActiveTextures(e){this._thicknessTexture&&e.push(this._thicknessTexture),this._refractionTexture&&e.push(this._refractionTexture),this._refractionIntensityTexture&&e.push(this._refractionIntensityTexture),this._translucencyColorTexture&&e.push(this._translucencyColorTexture),this._translucencyIntensityTexture&&e.push(this._translucencyIntensityTexture)}getAnimatables(e){this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),this._refractionIntensityTexture&&this._refractionIntensityTexture.animations&&this._refractionIntensityTexture.animations.length>0&&e.push(this._refractionIntensityTexture),this._translucencyColorTexture&&this._translucencyColorTexture.animations&&this._translucencyColorTexture.animations.length>0&&e.push(this._translucencyColorTexture),this._translucencyIntensityTexture&&this._translucencyIntensityTexture.animations&&this._translucencyIntensityTexture.animations.length>0&&e.push(this._translucencyIntensityTexture)}dispose(e){e&&(this._thicknessTexture&&this._thicknessTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose(),this._refractionIntensityTexture&&this._refractionIntensityTexture.dispose(),this._translucencyColorTexture&&this._translucencyColorTexture.dispose(),this._translucencyIntensityTexture&&this._translucencyIntensityTexture.dispose())}getClassName(){return"PBRSubSurfaceConfiguration"}addFallbacks(e,t,i){return e.SS_SCATTERING&&t.addFallback(i++,"SS_SCATTERING"),e.SS_TRANSLUCENCY&&t.addFallback(i++,"SS_TRANSLUCENCY"),i}getSamplers(e){e.push("thicknessSampler","refractionIntensitySampler","translucencyIntensitySampler","refractionSampler","refractionSamplerLow","refractionSamplerHigh","translucencyColorSampler")}getUniforms(){return{ubo:[{name:"vRefractionMicrosurfaceInfos",size:4,type:"vec4"},{name:"vRefractionFilteringInfo",size:2,type:"vec2"},{name:"vTranslucencyIntensityInfos",size:2,type:"vec2"},{name:"vRefractionInfos",size:4,type:"vec4"},{name:"refractionMatrix",size:16,type:"mat4"},{name:"vThicknessInfos",size:2,type:"vec2"},{name:"vRefractionIntensityInfos",size:2,type:"vec2"},{name:"thicknessMatrix",size:16,type:"mat4"},{name:"refractionIntensityMatrix",size:16,type:"mat4"},{name:"translucencyIntensityMatrix",size:16,type:"mat4"},{name:"vThicknessParam",size:2,type:"vec2"},{name:"vDiffusionDistance",size:3,type:"vec3"},{name:"vTintColor",size:4,type:"vec4"},{name:"vSubSurfaceIntensity",size:3,type:"vec3"},{name:"vRefractionPosition",size:3,type:"vec3"},{name:"vRefractionSize",size:3,type:"vec3"},{name:"scatteringDiffusionProfile",size:1,type:"float"},{name:"dispersion",size:1,type:"float"},{name:"vTranslucencyColor",size:4,type:"vec4"},{name:"vTranslucencyColorInfos",size:2,type:"vec2"},{name:"translucencyColorMatrix",size:16,type:"mat4"}]}}};Ai.DEFAULT_APPLY_ALBEDO_AFTERSUBSURFACE=!1;Ai.DEFAULT_LEGACY_TRANSLUCENCY=!1;P([w(),le("_markAllSubMeshesAsTexturesDirty")],Ai.prototype,"isRefractionEnabled",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],Ai.prototype,"isTranslucencyEnabled",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],Ai.prototype,"isDispersionEnabled",void 0);P([w(),le("_markScenePrePassDirty")],Ai.prototype,"isScatteringEnabled",void 0);P([w()],Ai.prototype,"_scatteringDiffusionProfileIndex",void 0);P([w()],Ai.prototype,"refractionIntensity",void 0);P([w()],Ai.prototype,"translucencyIntensity",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],Ai.prototype,"useAlbedoToTintRefraction",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],Ai.prototype,"useAlbedoToTintTranslucency",void 0);P([Ut(),le("_markAllSubMeshesAsTexturesDirty")],Ai.prototype,"thicknessTexture",void 0);P([Ut(),le("_markAllSubMeshesAsTexturesDirty")],Ai.prototype,"refractionTexture",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],Ai.prototype,"indexOfRefraction",void 0);P([w()],Ai.prototype,"_volumeIndexOfRefraction",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],Ai.prototype,"volumeIndexOfRefraction",null);P([w(),le("_markAllSubMeshesAsTexturesDirty")],Ai.prototype,"invertRefractionY",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],Ai.prototype,"linkRefractionWithTransparency",void 0);P([w()],Ai.prototype,"minimumThickness",void 0);P([w()],Ai.prototype,"maximumThickness",void 0);P([w()],Ai.prototype,"useThicknessAsDepth",void 0);P([gr()],Ai.prototype,"tintColor",void 0);P([w()],Ai.prototype,"tintColorAtDistance",void 0);P([w()],Ai.prototype,"dispersion",void 0);P([gr()],Ai.prototype,"diffusionDistance",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],Ai.prototype,"useMaskFromThicknessTexture",void 0);P([Ut(),le("_markAllSubMeshesAsTexturesDirty")],Ai.prototype,"refractionIntensityTexture",void 0);P([Ut(),le("_markAllSubMeshesAsTexturesDirty")],Ai.prototype,"translucencyIntensityTexture",void 0);P([gr()],Ai.prototype,"translucencyColor",void 0);P([Ut(),le("_markAllSubMeshesAsTexturesDirty")],Ai.prototype,"translucencyColorTexture",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],Ai.prototype,"useGltfStyleTextures",void 0);P([w()],Ai.prototype,"applyAlbedoAfterSubSurface",void 0);P([w()],Ai.prototype,"legacyTranslucency",void 0)});var S6,xhe,$L=C(()=>{k();ed();Lg();S6="pbrUboDeclaration",xhe=`uniform vAlbedoInfos: vec2f;uniform vBaseWeightInfos: vec2f;uniform vBaseDiffuseRoughnessInfos: vec2f;uniform vAmbientInfos: vec4f;uniform vOpacityInfos: vec2f;uniform vEmissiveInfos: vec2f;uniform vLightmapInfos: vec2f;uniform vReflectivityInfos: vec3f;uniform vMicroSurfaceSamplerInfos: vec2f;uniform vBumpInfos: vec3f;uniform albedoMatrix: mat4x4f;uniform baseWeightMatrix: mat4x4f;uniform baseDiffuseRoughnessMatrix: mat4x4f;uniform ambientMatrix: mat4x4f;uniform opacityMatrix: mat4x4f;uniform emissiveMatrix: mat4x4f;uniform lightmapMatrix: mat4x4f;uniform reflectivityMatrix: mat4x4f;uniform microSurfaceSamplerMatrix: mat4x4f;uniform bumpMatrix: mat4x4f;uniform vTangentSpaceParams: vec2f;uniform vAlbedoColor: vec4f;uniform baseWeight: f32;uniform baseDiffuseRoughness: f32;uniform vLightingIntensity: vec4f;uniform pointSize: f32;uniform vReflectivityColor: vec4f;uniform vEmissiveColor: vec3f;uniform vAmbientColor: vec3f;uniform vDebugMode: vec2f;uniform vMetallicReflectanceFactors: vec4f;uniform vMetallicReflectanceInfos: vec2f;uniform metallicReflectanceMatrix: mat4x4f;uniform vReflectanceInfos: vec2f;uniform reflectanceMatrix: mat4x4f;uniform cameraInfo: vec4f;uniform vReflectionInfos: vec2f;uniform reflectionMatrix: mat4x4f;uniform vReflectionMicrosurfaceInfos: vec3f;uniform vReflectionPosition: vec3f;uniform vReflectionSize: vec3f;uniform vReflectionFilteringInfo: vec2f;uniform vReflectionDominantDirection: vec3f;uniform vReflectionColor: vec3f;uniform vSphericalL00: vec3f;uniform vSphericalL1_1: vec3f;uniform vSphericalL10: vec3f;uniform vSphericalL11: vec3f;uniform vSphericalL2_2: vec3f;uniform vSphericalL2_1: vec3f;uniform vSphericalL20: vec3f;uniform vSphericalL21: vec3f;uniform vSphericalL22: vec3f;uniform vSphericalX: vec3f;uniform vSphericalY: vec3f;uniform vSphericalZ: vec3f;uniform vSphericalXX_ZZ: vec3f;uniform vSphericalYY_ZZ: vec3f;uniform vSphericalZZ: vec3f;uniform vSphericalXY: vec3f;uniform vSphericalYZ: vec3f;uniform vSphericalZX: vec3f; #define ADDITIONAL_UBO_DECLARATION #include #include -`;T.IncludesShadersStoreWGSL[S6]||(T.IncludesShadersStoreWGSL[S6]=xhe)});var A6={};tt(A6,{pbrVertexShaderWGSL:()=>Rhe});var JL,T6,Rhe,x6=C(()=>{W();$L();JA();qm();Ca();ap();rc();nc();wf();ex();tx();sp();bP();sc();gg();ix();Uf();Vf();td();rx();nx();Gf();kf();ac();oc();lc();sx();ax();ox();lx();cc();vg();cx();Eg();fx();JL="pbrVertexShader",T6=`#define PBR_VERTEX_SHADER +`;T.IncludesShadersStoreWGSL[S6]||(T.IncludesShadersStoreWGSL[S6]=xhe)});var A6={};tt(A6,{pbrVertexShaderWGSL:()=>Rhe});var JL,T6,Rhe,x6=C(()=>{k();$L();ex();jm();Ma();sp();ic();rc();Nf();tx();ix();np();bP();nc();gg();rx();Bf();Uf();td();nx();sx();Vf();Gf();sc();ac();oc();ax();ox();lx();cx();lc();vg();fx();Eg();hx();JL="pbrVertexShader",T6=`#define PBR_VERTEX_SHADER #include #define CUSTOM_VERTEX_BEGIN #ifndef USE_VERTEX_PULLING @@ -17773,7 +17773,7 @@ vertexOutputs.vMainUV2=uv2Updated; #include #include #define CUSTOM_VERTEX_MAIN_END -}`;T.ShadersStoreWGSL[JL]||(T.ShadersStoreWGSL[JL]=T6);Rhe={name:JL,shader:T6}});var R6,bhe,b6=C(()=>{W();R6="samplerFragmentAlternateDeclaration",bhe=`#ifdef _DEFINENAME_ +}`;T.ShadersStoreWGSL[JL]||(T.ShadersStoreWGSL[JL]=T6);Rhe={name:JL,shader:T6}});var R6,bhe,b6=C(()=>{k();R6="samplerFragmentAlternateDeclaration",bhe=`#ifdef _DEFINENAME_ #if _DEFINENAME_DIRECTUV==1 #define v_VARYINGNAME_UV vMainUV1 #elif _DEFINENAME_DIRECTUV==2 @@ -17790,7 +17790,7 @@ vertexOutputs.vMainUV2=uv2Updated; varying v_VARYINGNAME_UV: vec2f; #endif #endif -`;T.IncludesShadersStoreWGSL[R6]||(T.IncludesShadersStoreWGSL[R6]=bhe)});var I6,Ihe,M6=C(()=>{W();id();b6();xR();I6="pbrFragmentSamplersDeclaration",Ihe=`#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo) +`;T.IncludesShadersStoreWGSL[R6]||(T.IncludesShadersStoreWGSL[R6]=bhe)});var I6,Ihe,M6=C(()=>{k();id();b6();RR();I6="pbrFragmentSamplersDeclaration",Ihe=`#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo) #include(_DEFINENAME_,BASE_WEIGHT,_VARYINGNAME_,BaseWeight,_SAMPLERNAME_,baseWeight) #include(_DEFINENAME_,BASE_DIFFUSE_ROUGHNESS,_VARYINGNAME_,BaseDiffuseRoughness,_SAMPLERNAME_,baseDiffuseRoughness) #include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient) @@ -17853,7 +17853,7 @@ var refractionLowSamplerSampler: sampler;var refractionLowSampler: texture_2d; #endif -`;T.IncludesShadersStoreWGSL[I6]||(T.IncludesShadersStoreWGSL[I6]=Ihe)});var C6,Mhe,y6=C(()=>{W();yP();C6="pbrBlockAlbedoOpacity",Mhe=`struct albedoOpacityOutParams +`;T.IncludesShadersStoreWGSL[I6]||(T.IncludesShadersStoreWGSL[I6]=Ihe)});var C6,Mhe,y6=C(()=>{k();yP();C6="pbrBlockAlbedoOpacity",Mhe=`struct albedoOpacityOutParams {surfaceAlbedo: vec3f, alpha: f32}; #define pbr_inline @@ -17932,7 +17932,7 @@ alpha=1.0; #endif #endif outParams.surfaceAlbedo=surfaceAlbedo;outParams.alpha=alpha;return outParams;} -`;T.IncludesShadersStoreWGSL[C6]||(T.IncludesShadersStoreWGSL[C6]=Mhe)});var P6,Che,D6=C(()=>{W();P6="pbrBlockReflectivity",Che=`struct reflectivityOutParams +`;T.IncludesShadersStoreWGSL[C6]||(T.IncludesShadersStoreWGSL[C6]=Mhe)});var P6,Che,D6=C(()=>{k();P6="pbrBlockReflectivity",Che=`struct reflectivityOutParams {microSurface: f32, roughness: f32, diffuseRoughness: f32, @@ -18092,7 +18092,7 @@ microSurface=saturate(microSurface);var roughness: f32=1.-microSurface;var diffu diffuseRoughness*=baseDiffuseRoughnessTexture*baseDiffuseRoughnessInfos.y; #endif outParams.microSurface=microSurface;outParams.roughness=roughness;outParams.diffuseRoughness=diffuseRoughness;return outParams;} -`;T.IncludesShadersStoreWGSL[P6]||(T.IncludesShadersStoreWGSL[P6]=Che)});var L6,yhe,O6=C(()=>{W();L6="pbrBlockAmbientOcclusion",yhe=`struct ambientOcclusionOutParams +`;T.IncludesShadersStoreWGSL[P6]||(T.IncludesShadersStoreWGSL[P6]=Che)});var L6,yhe,O6=C(()=>{k();L6="pbrBlockAmbientOcclusion",yhe=`struct ambientOcclusionOutParams {ambientOcclusionColor: vec3f, #if DEBUGMODE>0 && defined(AMBIENT) ambientOcclusionColorMap: vec3f @@ -18118,7 +18118,7 @@ outParams.ambientOcclusionColorMap=ambientOcclusionColorMap; #endif #endif outParams.ambientOcclusionColor=ambientOcclusionColor;return outParams;} -`;T.IncludesShadersStoreWGSL[L6]||(T.IncludesShadersStoreWGSL[L6]=yhe)});var N6,Phe,w6=C(()=>{W();N6="pbrBlockAlphaFresnel",Phe=`#ifdef ALPHAFRESNEL +`;T.IncludesShadersStoreWGSL[L6]||(T.IncludesShadersStoreWGSL[L6]=yhe)});var N6,Phe,w6=C(()=>{k();N6="pbrBlockAlphaFresnel",Phe=`#ifdef ALPHAFRESNEL #if defined(ALPHATEST) || defined(ALPHABLEND) struct alphaFresnelOutParams {alpha: f32};fn faceforward(N: vec3,I: vec3,Nref: vec3)->vec3 {return select(N,-N,dot(Nref,I)>0.0);} @@ -18145,7 +18145,7 @@ outParams.alpha=1.0; return outParams;} #endif #endif -`;T.IncludesShadersStoreWGSL[N6]||(T.IncludesShadersStoreWGSL[N6]=Phe)});var F6,Dhe,B6=C(()=>{W();F6="pbrBlockAnisotropic",Dhe=`#ifdef ANISOTROPIC +`;T.IncludesShadersStoreWGSL[N6]||(T.IncludesShadersStoreWGSL[N6]=Phe)});var F6,Dhe,B6=C(()=>{k();F6="pbrBlockAnisotropic",Dhe=`#ifdef ANISOTROPIC struct anisotropicOutParams {anisotropy: f32, anisotropicTangent: vec3f, @@ -18182,7 +18182,7 @@ anisotropyDirection=vec3f(mat2x2f(anisotropyDirection.x,anisotropyDirection.y,-a #endif var anisoTBN: mat3x3f= mat3x3f(normalize(TBN[0]),normalize(TBN[1]),normalize(TBN[2]));var anisotropicTangent: vec3f=normalize(anisoTBN*anisotropyDirection);var anisotropicBitangent: vec3f=normalize(cross(anisoTBN[2],anisotropicTangent));outParams.anisotropy=anisotropy;outParams.anisotropicTangent=anisotropicTangent;outParams.anisotropicBitangent=anisotropicBitangent;outParams.anisotropicNormal=getAnisotropicBentNormals(anisotropicTangent,anisotropicBitangent,normalW,viewDirectionW,anisotropy,roughness);return outParams;} #endif -`;T.IncludesShadersStoreWGSL[F6]||(T.IncludesShadersStoreWGSL[F6]=Dhe)});var U6,Lhe,V6=C(()=>{W();U6="pbrBlockReflection",Lhe=`#ifdef REFLECTION +`;T.IncludesShadersStoreWGSL[F6]||(T.IncludesShadersStoreWGSL[F6]=Dhe)});var U6,Lhe,V6=C(()=>{k();U6="pbrBlockReflection",Lhe=`#ifdef REFLECTION struct reflectionOutParams {environmentRadiance: vec4f ,environmentIrradiance: vec3f @@ -18492,7 +18492,7 @@ outParams.environmentRadiance=environmentRadiance; #endif outParams.environmentIrradiance=environmentIrradiance;outParams.reflectionCoords=reflectionCoords;return outParams;} #endif -`;T.IncludesShadersStoreWGSL[U6]||(T.IncludesShadersStoreWGSL[U6]=Lhe)});var G6,Ohe,k6=C(()=>{W();G6="pbrBlockSheen",Ohe=`#ifdef SHEEN +`;T.IncludesShadersStoreWGSL[U6]||(T.IncludesShadersStoreWGSL[U6]=Lhe)});var G6,Ohe,k6=C(()=>{k();G6="pbrBlockSheen",Ohe=`#ifdef SHEEN struct sheenOutParams {sheenIntensity: f32 ,sheenColor: vec3f @@ -18678,7 +18678,7 @@ outParams.sheenAlbedoScaling=1.0-sheenIntensity*max(max(sheenColor.r,sheenColor. #endif outParams.sheenIntensity=sheenIntensity;outParams.sheenColor=sheenColor;outParams.sheenRoughness=sheenRoughness;return outParams;} #endif -`;T.IncludesShadersStoreWGSL[G6]||(T.IncludesShadersStoreWGSL[G6]=Ohe)});var W6,Nhe,H6=C(()=>{W();W6="pbrBlockClearcoat",Nhe=`struct clearcoatOutParams +`;T.IncludesShadersStoreWGSL[G6]||(T.IncludesShadersStoreWGSL[G6]=Ohe)});var W6,Nhe,H6=C(()=>{k();W6="pbrBlockClearcoat",Nhe=`struct clearcoatOutParams {specularEnvironmentR0: vec3f, conservationFactor: f32, clearCoatNormalW: vec3f, @@ -18931,7 +18931,7 @@ outParams.energyConservationFactorClearCoat=getEnergyConservationFactor(outParam #endif return outParams;} #endif -`;T.IncludesShadersStoreWGSL[W6]||(T.IncludesShadersStoreWGSL[W6]=Nhe)});var z6,whe,X6=C(()=>{W();z6="pbrBlockIridescence",whe=`struct iridescenceOutParams +`;T.IncludesShadersStoreWGSL[W6]||(T.IncludesShadersStoreWGSL[W6]=Nhe)});var z6,whe,X6=C(()=>{k();z6="pbrBlockIridescence",whe=`struct iridescenceOutParams {iridescenceIntensity: f32, iridescenceIOR: f32, iridescenceThickness: f32, @@ -18972,7 +18972,7 @@ topIor=mix(1.0,uniforms.vClearCoatRefractionParams.w-1.,clearCoatIntensity);view #endif var iridescenceFresnel: vec3f=evalIridescence(topIor,iridescenceIOR,viewAngle,iridescenceThickness,specularEnvironmentR0);outParams.specularEnvironmentR0=mix(specularEnvironmentR0,iridescenceFresnel,iridescenceIntensity);outParams.iridescenceIntensity=iridescenceIntensity;outParams.iridescenceThickness=iridescenceThickness;outParams.iridescenceIOR=iridescenceIOR;return outParams;} #endif -`;T.IncludesShadersStoreWGSL[z6]||(T.IncludesShadersStoreWGSL[z6]=whe)});var Y6,Fhe,K6=C(()=>{W();Y6="pbrBlockSubSurface",Fhe=`struct subSurfaceOutParams +`;T.IncludesShadersStoreWGSL[z6]||(T.IncludesShadersStoreWGSL[z6]=whe)});var Y6,Fhe,K6=C(()=>{k();Y6="pbrBlockSubSurface",Fhe=`struct subSurfaceOutParams {specularEnvironmentReflectance: vec3f, #ifdef SS_REFRACTION finalRefraction: vec3f, @@ -19394,7 +19394,7 @@ outParams.refractionIrradiance=refractionIrradiance; #endif return outParams;} #endif -`;T.IncludesShadersStoreWGSL[Y6]||(T.IncludesShadersStoreWGSL[Y6]=Fhe)});var j6,Bhe,q6=C(()=>{W();j6="pbrBlockNormalFinal",Bhe=`#if defined(FORCENORMALFORWARD) && defined(NORMAL) +`;T.IncludesShadersStoreWGSL[Y6]||(T.IncludesShadersStoreWGSL[Y6]=Fhe)});var j6,Bhe,q6=C(()=>{k();j6="pbrBlockNormalFinal",Bhe=`#if defined(FORCENORMALFORWARD) && defined(NORMAL) var faceNormal: vec3f=normalize(cross(dpdx(fragmentInputs.vPositionW),dpdy(fragmentInputs.vPositionW)))*scene.vEyePosition.w; #if defined(TWOSIDEDLIGHTING) faceNormal=select(-faceNormal,faceNormal,fragmentInputs.frontFacing); @@ -19408,7 +19408,7 @@ normalW=select(normalW,-normalW,fragmentInputs.frontFacing); normalW=select(-normalW,normalW,fragmentInputs.frontFacing); #endif #endif -`;T.IncludesShadersStoreWGSL[j6]||(T.IncludesShadersStoreWGSL[j6]=Bhe)});var Z6,Uhe,Q6=C(()=>{W();Z6="pbrBlockLightmapInit",Uhe=`#ifdef LIGHTMAP +`;T.IncludesShadersStoreWGSL[j6]||(T.IncludesShadersStoreWGSL[j6]=Bhe)});var Z6,Uhe,Q6=C(()=>{k();Z6="pbrBlockLightmapInit",Uhe=`#ifdef LIGHTMAP var lightmapColor: vec4f=textureSample(lightmapSampler,lightmapSamplerSampler,fragmentInputs.vLightmapUV+uvOffset); #ifdef RGBDLIGHTMAP lightmapColor=vec4f(fromRGBD(lightmapColor),lightmapColor.a); @@ -19418,7 +19418,7 @@ lightmapColor=vec4f(toLinearSpaceVec3(lightmapColor.rgb),lightmapColor.a); #endif lightmapColor=vec4f(lightmapColor.rgb*uniforms.vLightmapInfos.y,lightmapColor.a); #endif -`;T.IncludesShadersStoreWGSL[Z6]||(T.IncludesShadersStoreWGSL[Z6]=Uhe)});var $6,Vhe,J6=C(()=>{W();$6="pbrBlockGeometryInfo",Vhe=`var NdotVUnclamped: f32=dot(normalW,viewDirectionW);var NdotV: f32=absEps(NdotVUnclamped);var alphaG: f32=convertRoughnessToAverageSlope(roughness);var AARoughnessFactors: vec2f=getAARoughnessFactors(normalW.xyz); +`;T.IncludesShadersStoreWGSL[Z6]||(T.IncludesShadersStoreWGSL[Z6]=Uhe)});var $6,Vhe,J6=C(()=>{k();$6="pbrBlockGeometryInfo",Vhe=`var NdotVUnclamped: f32=dot(normalW,viewDirectionW);var NdotV: f32=absEps(NdotVUnclamped);var alphaG: f32=convertRoughnessToAverageSlope(roughness);var AARoughnessFactors: vec2f=getAARoughnessFactors(normalW.xyz); #ifdef SPECULARAA alphaG+=AARoughnessFactors.y; #endif @@ -19442,7 +19442,7 @@ var eho: f32=environmentHorizonOcclusion(-viewDirectionW,normalW,geometricNormal #endif #endif #endif -`;T.IncludesShadersStoreWGSL[$6]||(T.IncludesShadersStoreWGSL[$6]=Vhe)});var e7,Ghe,t7=C(()=>{W();e7="pbrBlockReflectance",Ghe=`#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +`;T.IncludesShadersStoreWGSL[$6]||(T.IncludesShadersStoreWGSL[$6]=Vhe)});var e7,Ghe,t7=C(()=>{k();e7="pbrBlockReflectance",Ghe=`#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) var baseSpecularEnvironmentReflectance: vec3f=getReflectanceFromBRDFWithEnvLookup(vec3f(reflectanceF0),vec3f(reflectivityOut.reflectanceF90),environmentBrdf); #if (CONDUCTOR_SPECULAR_MODEL==CONDUCTOR_SPECULAR_MODEL_OPENPBR) let metalEnvironmentReflectance: vec3f=vec3f(reflectivityOut.specularWeight)*getF82Specular(NdotV,clearcoatOut.specularEnvironmentR0,reflectivityOut.colorReflectanceF90,reflectivityOut.roughness);let dielectricEnvironmentReflectance=getReflectanceFromBRDFWithEnvLookup(reflectivityOut.dielectricColorF0,reflectivityOut.colorReflectanceF90,environmentBrdf);var colorSpecularEnvironmentReflectance: vec3f=mix(dielectricEnvironmentReflectance,metalEnvironmentReflectance,reflectivityOut.metallic); @@ -19468,7 +19468,7 @@ colorSpecularEnvironmentReflectance*=clearcoatOut.conservationFactor; colorSpecularEnvironmentReflectance*=clearcoatOut.absorption; #endif #endif -`;T.IncludesShadersStoreWGSL[e7]||(T.IncludesShadersStoreWGSL[e7]=Ghe)});var i7,khe,r7=C(()=>{W();i7="pbrBlockDirectLighting",khe=`var diffuseBase: vec3f=vec3f(0.,0.,0.); +`;T.IncludesShadersStoreWGSL[e7]||(T.IncludesShadersStoreWGSL[e7]=Ghe)});var i7,khe,r7=C(()=>{k();i7="pbrBlockDirectLighting",khe=`var diffuseBase: vec3f=vec3f(0.,0.,0.); #ifdef SS_TRANSLUCENCY var diffuseTransmissionBase: vec3f=vec3f(0.,0.,0.); #endif @@ -19489,7 +19489,7 @@ var aggShadow: f32=0.;var numLights: f32=0.; #if defined(CLEARCOAT) && defined(CLEARCOAT_TINT) var absorption: vec3f=vec3f(0.); #endif -`;T.IncludesShadersStoreWGSL[i7]||(T.IncludesShadersStoreWGSL[i7]=khe)});var n7,Whe,s7=C(()=>{W();n7="pbrBlockFinalLitComponents",Whe=`aggShadow=aggShadow/numLights; +`;T.IncludesShadersStoreWGSL[i7]||(T.IncludesShadersStoreWGSL[i7]=khe)});var n7,Whe,s7=C(()=>{k();n7="pbrBlockFinalLitComponents",Whe=`aggShadow=aggShadow/numLights; #if defined(ENVIRONMENTBRDF) #ifdef MS_BRDF_ENERGY_CONSERVATION var baseSpecularEnergyConservationFactor: vec3f=getEnergyConservationFactor(vec3f(reflectanceF0),environmentBrdf);var coloredEnergyConservationFactor: vec3f=getEnergyConservationFactor(clearcoatOut.specularEnvironmentR0,environmentBrdf); @@ -19595,7 +19595,7 @@ luminanceOverAlpha+=getLuminance(finalClearCoatScaled); alpha=saturate(alpha+luminanceOverAlpha*luminanceOverAlpha); #endif #endif -`;T.IncludesShadersStoreWGSL[n7]||(T.IncludesShadersStoreWGSL[n7]=Whe)});var a7,Hhe,o7=C(()=>{W();a7="pbrBlockFinalUnlitComponents",Hhe=`var finalDiffuse: vec3f=diffuseBase;finalDiffuse*=surfaceAlbedo; +`;T.IncludesShadersStoreWGSL[n7]||(T.IncludesShadersStoreWGSL[n7]=Whe)});var a7,Hhe,o7=C(()=>{k();a7="pbrBlockFinalUnlitComponents",Hhe=`var finalDiffuse: vec3f=diffuseBase;finalDiffuse*=surfaceAlbedo; #if defined(SS_REFRACTION) && !defined(UNLIT) && !defined(LEGACY_SPECULAR_ENERGY_CONSERVATION) finalDiffuse*=subSurfaceOut.refractionOpacity; #endif @@ -19619,7 +19619,7 @@ var ambientOcclusionForDirectDiffuse: vec3f=mix( vec3f(1.),aoOut.ambientOcclusio var ambientOcclusionForDirectDiffuse: vec3f=aoOut.ambientOcclusionColor; #endif finalAmbient*=aoOut.ambientOcclusionColor;finalDiffuse*=ambientOcclusionForDirectDiffuse; -`;T.IncludesShadersStoreWGSL[a7]||(T.IncludesShadersStoreWGSL[a7]=Hhe)});var l7,zhe,c7=C(()=>{W();l7="pbrBlockFinalColorComposition",zhe=`var finalColor: vec4f= vec4f( +`;T.IncludesShadersStoreWGSL[a7]||(T.IncludesShadersStoreWGSL[a7]=Hhe)});var l7,zhe,c7=C(()=>{k();l7="pbrBlockFinalColorComposition",zhe=`var finalColor: vec4f= vec4f( #ifndef UNLIT #ifdef REFLECTION finalIrradiance + @@ -19661,7 +19661,7 @@ finalColor=vec4f(finalColor.rgb+lightmapColor.rgb,finalColor.a); finalColor=vec4f(finalColor.rgb+finalEmissive,finalColor.a); #define CUSTOM_FRAGMENT_BEFORE_FOG finalColor=max(finalColor,vec4f(0.0)); -`;T.IncludesShadersStoreWGSL[l7]||(T.IncludesShadersStoreWGSL[l7]=zhe)});var f7,Xhe,h7=C(()=>{W();f7="pbrBlockPrePass",Xhe=`#if SCENE_MRT_COUNT>0 +`;T.IncludesShadersStoreWGSL[l7]||(T.IncludesShadersStoreWGSL[l7]=zhe)});var f7,Xhe,h7=C(()=>{k();f7="pbrBlockPrePass",Xhe=`#if SCENE_MRT_COUNT>0 var writeGeometryInfo: f32=select(0.0,1.0,finalColor.a>ALPHATESTVALUE);var fragData: array,SCENE_MRT_COUNT>; #ifdef PREPASS_POSITION fragData[PREPASS_POSITION_INDEX]= vec4f(fragmentInputs.vPositionW,writeGeometryInfo); @@ -19767,7 +19767,7 @@ fragmentOutputs.fragData6=fragData[6]; fragmentOutputs.fragData7=fragData[7]; #endif #endif -`;T.IncludesShadersStoreWGSL[f7]||(T.IncludesShadersStoreWGSL[f7]=Xhe)});var u7={};tt(u7,{pbrPixelShaderWGSL:()=>Yhe});var eO,d7,Yhe,m7=C(()=>{W();hx();dx();$L();pL();ux();M6();px();fc();td();Sg();Ca();_L();gL();vL();_x();mx();sp();EL();SL();ap();TL();xL();RR();gx();vx();Og();y6();D6();O6();w6();B6();V6();k6();H6();X6();K6();hc();RL();Ex();q6();Sx();Q6();J6();AL();t7();r7();PP();s7();o7();c7();Tx();Tg();bL();h7();Ax();IL();eO="pbrPixelShader",d7=`#define PBR_FRAGMENT_SHADER +`;T.IncludesShadersStoreWGSL[f7]||(T.IncludesShadersStoreWGSL[f7]=Xhe)});var u7={};tt(u7,{pbrPixelShaderWGSL:()=>Yhe});var eO,d7,Yhe,m7=C(()=>{k();dx();ux();$L();pL();mx();M6();_x();cc();td();Sg();Ma();_L();gL();vL();gx();px();np();EL();SL();sp();TL();xL();bR();vx();Ex();Og();y6();D6();O6();w6();B6();V6();k6();H6();X6();K6();fc();RL();Sx();q6();Tx();Q6();J6();AL();t7();r7();PP();s7();o7();c7();Ax();Tg();bL();h7();xx();IL();eO="pbrPixelShader",d7=`#define PBR_FRAGMENT_SHADER #define CUSTOM_FRAGMENT_BEGIN #include[SCENE_MRT_COUNT] #include @@ -20331,7 +20331,7 @@ if (fragDepth==nearestDepth) {fragmentOutputs.frontColor=vec4f(fragmentOutputs.f #include #define CUSTOM_FRAGMENT_MAIN_END } -`;T.ShadersStoreWGSL[eO]||(T.ShadersStoreWGSL[eO]=d7);Yhe={name:eO,shader:d7}});var p7,Khe,_7=C(()=>{W();xx();p7="pbrVertexDeclaration",Khe=`uniform mat4 view;uniform mat4 viewProjection;uniform vec4 vEyePosition; +`;T.ShadersStoreWGSL[eO]||(T.ShadersStoreWGSL[eO]=d7);Yhe={name:eO,shader:d7}});var p7,Khe,_7=C(()=>{k();Rx();p7="pbrVertexDeclaration",Khe=`uniform mat4 view;uniform mat4 viewProjection;uniform vec4 vEyePosition; #ifdef MULTIVIEW mat4 viewProjectionR; #endif @@ -20456,12 +20456,12 @@ uniform vec4 vDetailInfos;uniform mat4 detailMatrix; #endif #include #define ADDITIONAL_VERTEX_DECLARATION -`;T.IncludesShadersStore[p7]||(T.IncludesShadersStore[p7]=Khe)});var g7,jhe,tO=C(()=>{W();rd();Ng();g7="pbrUboDeclaration",jhe=`layout(std140,column_major) uniform;uniform Material {vec2 vAlbedoInfos;vec2 vBaseWeightInfos;vec2 vBaseDiffuseRoughnessInfos;vec4 vAmbientInfos;vec2 vOpacityInfos;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec3 vReflectivityInfos;vec2 vMicroSurfaceSamplerInfos;vec3 vBumpInfos;mat4 albedoMatrix;mat4 baseWeightMatrix;mat4 baseDiffuseRoughnessMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 reflectivityMatrix;mat4 microSurfaceSamplerMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;vec4 vAlbedoColor;float baseWeight;float baseDiffuseRoughness;vec4 vLightingIntensity;float pointSize;vec4 vReflectivityColor;vec3 vEmissiveColor;vec3 vAmbientColor;vec2 vDebugMode;vec4 vMetallicReflectanceFactors;vec2 vMetallicReflectanceInfos;mat4 metallicReflectanceMatrix;vec2 vReflectanceInfos;mat4 reflectanceMatrix;vec4 cameraInfo;vec2 vReflectionInfos;mat4 reflectionMatrix;vec3 vReflectionMicrosurfaceInfos;vec3 vReflectionPosition;vec3 vReflectionSize;vec2 vReflectionFilteringInfo;vec3 vReflectionDominantDirection;vec3 vReflectionColor;vec3 vSphericalL00;vec3 vSphericalL1_1;vec3 vSphericalL10;vec3 vSphericalL11;vec3 vSphericalL2_2;vec3 vSphericalL2_1;vec3 vSphericalL20;vec3 vSphericalL21;vec3 vSphericalL22;vec3 vSphericalX;vec3 vSphericalY;vec3 vSphericalZ;vec3 vSphericalXX_ZZ;vec3 vSphericalYY_ZZ;vec3 vSphericalZZ;vec3 vSphericalXY;vec3 vSphericalYZ;vec3 vSphericalZX; +`;T.IncludesShadersStore[p7]||(T.IncludesShadersStore[p7]=Khe)});var g7,jhe,tO=C(()=>{k();rd();Ng();g7="pbrUboDeclaration",jhe=`layout(std140,column_major) uniform;uniform Material {vec2 vAlbedoInfos;vec2 vBaseWeightInfos;vec2 vBaseDiffuseRoughnessInfos;vec4 vAmbientInfos;vec2 vOpacityInfos;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec3 vReflectivityInfos;vec2 vMicroSurfaceSamplerInfos;vec3 vBumpInfos;mat4 albedoMatrix;mat4 baseWeightMatrix;mat4 baseDiffuseRoughnessMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 reflectivityMatrix;mat4 microSurfaceSamplerMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;vec4 vAlbedoColor;float baseWeight;float baseDiffuseRoughness;vec4 vLightingIntensity;float pointSize;vec4 vReflectivityColor;vec3 vEmissiveColor;vec3 vAmbientColor;vec2 vDebugMode;vec4 vMetallicReflectanceFactors;vec2 vMetallicReflectanceInfos;mat4 metallicReflectanceMatrix;vec2 vReflectanceInfos;mat4 reflectanceMatrix;vec4 cameraInfo;vec2 vReflectionInfos;mat4 reflectionMatrix;vec3 vReflectionMicrosurfaceInfos;vec3 vReflectionPosition;vec3 vReflectionSize;vec2 vReflectionFilteringInfo;vec3 vReflectionDominantDirection;vec3 vReflectionColor;vec3 vSphericalL00;vec3 vSphericalL1_1;vec3 vSphericalL10;vec3 vSphericalL11;vec3 vSphericalL2_2;vec3 vSphericalL2_1;vec3 vSphericalL20;vec3 vSphericalL21;vec3 vSphericalL22;vec3 vSphericalX;vec3 vSphericalY;vec3 vSphericalZ;vec3 vSphericalXX_ZZ;vec3 vSphericalYY_ZZ;vec3 vSphericalZZ;vec3 vSphericalXY;vec3 vSphericalYZ;vec3 vSphericalZX; #define ADDITIONAL_UBO_DECLARATION }; #include #include -`;T.IncludesShadersStore[g7]||(T.IncludesShadersStore[g7]=jhe)});var E7={};tt(E7,{pbrVertexShader:()=>qhe});var iO,v7,qhe,S7=C(()=>{W();_7();tO();Rx();Zm();ya();rp();dc();uc();Ff();bx();Ix();np();OP();mc();Ag();Mx();Cx();Wf();Hf();nd();zf();Xf();pc();_c();gc();yx();Px();Dx();Lx();vc();xg();Ox();Rg();Nx();iO="pbrVertexShader",v7=`#define PBR_VERTEX_SHADER +`;T.IncludesShadersStore[g7]||(T.IncludesShadersStore[g7]=jhe)});var E7={};tt(E7,{pbrVertexShader:()=>qhe});var iO,v7,qhe,S7=C(()=>{k();_7();tO();bx();qm();Ca();ip();hc();dc();wf();Ix();Mx();rp();OP();uc();Ag();Cx();yx();kf();Wf();nd();Hf();zf();mc();pc();_c();Px();Dx();Lx();Ox();gc();xg();Nx();Rg();wx();iO="pbrVertexShader",v7=`#define PBR_VERTEX_SHADER #define CUSTOM_VERTEX_EXTENSION precision highp float; #include<__decl__pbrVertex> @@ -20692,7 +20692,7 @@ gl_PointSize=pointSize; #include #define CUSTOM_VERTEX_MAIN_END } -`;T.ShadersStore[iO]||(T.ShadersStore[iO]=v7);qhe={name:iO,shader:v7}});var T7,Zhe,A7=C(()=>{W();wx();T7="pbrFragmentDeclaration",Zhe=`uniform vec4 vEyePosition;uniform vec3 vReflectionColor;uniform vec4 vAlbedoColor;uniform float baseWeight;uniform float baseDiffuseRoughness;uniform vec4 vLightingIntensity;uniform vec4 vReflectivityColor;uniform vec4 vMetallicReflectanceFactors;uniform vec3 vEmissiveColor;uniform float visibility;uniform vec3 vAmbientColor; +`;T.ShadersStore[iO]||(T.ShadersStore[iO]=v7);qhe={name:iO,shader:v7}});var T7,Zhe,A7=C(()=>{k();Fx();T7="pbrFragmentDeclaration",Zhe=`uniform vec4 vEyePosition;uniform vec3 vReflectionColor;uniform vec4 vAlbedoColor;uniform float baseWeight;uniform float baseDiffuseRoughness;uniform vec4 vLightingIntensity;uniform vec4 vReflectivityColor;uniform vec4 vMetallicReflectanceFactors;uniform vec3 vEmissiveColor;uniform float visibility;uniform vec3 vAmbientColor; #ifdef ALBEDO uniform vec2 vAlbedoInfos; #endif @@ -20840,7 +20840,7 @@ uniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;unifo #endif #endif #define ADDITIONAL_FRAGMENT_DECLARATION -`;T.IncludesShadersStore[T7]||(T.IncludesShadersStore[T7]=Zhe)});var x7,Qhe,R7=C(()=>{W();x7="samplerFragmentAlternateDeclaration",Qhe=`#ifdef _DEFINENAME_ +`;T.IncludesShadersStore[T7]||(T.IncludesShadersStore[T7]=Zhe)});var x7,Qhe,R7=C(()=>{k();x7="samplerFragmentAlternateDeclaration",Qhe=`#ifdef _DEFINENAME_ #if _DEFINENAME_DIRECTUV==1 #define v_VARYINGNAME_UV vMainUV1 #elif _DEFINENAME_DIRECTUV==2 @@ -20857,7 +20857,7 @@ uniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;unifo varying vec2 v_VARYINGNAME_UV; #endif #endif -`;T.IncludesShadersStore[x7]||(T.IncludesShadersStore[x7]=Qhe)});var b7,$he,I7=C(()=>{W();sd();R7();TR();b7="pbrFragmentSamplersDeclaration",$he=`#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo) +`;T.IncludesShadersStore[x7]||(T.IncludesShadersStore[x7]=Qhe)});var b7,$he,I7=C(()=>{k();sd();R7();AR();b7="pbrFragmentSamplersDeclaration",$he=`#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo) #include(_DEFINENAME_,BASE_WEIGHT,_VARYINGNAME_,BaseWeight,_SAMPLERNAME_,baseWeight) #include(_DEFINENAME_,BASE_DIFFUSE_ROUGHNESS,_VARYINGNAME_,BaseDiffuseRoughness,_SAMPLERNAME_,baseDiffuseRoughness) #include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient) @@ -20924,7 +20924,7 @@ uniform sampler2D refractionSamplerLow;uniform sampler2D refractionSamplerHigh; #ifdef IBL_CDF_FILTERING uniform sampler2D icdfSampler; #endif -`;T.IncludesShadersStore[b7]||(T.IncludesShadersStore[b7]=$he)});var M7,Jhe,C7=C(()=>{W();UP();M7="pbrBlockAlbedoOpacity",Jhe=`struct albedoOpacityOutParams +`;T.IncludesShadersStore[b7]||(T.IncludesShadersStore[b7]=$he)});var M7,Jhe,C7=C(()=>{k();UP();M7="pbrBlockAlbedoOpacity",Jhe=`struct albedoOpacityOutParams {vec3 surfaceAlbedo;float alpha;}; #define pbr_inline albedoOpacityOutParams albedoOpacityBlock( @@ -21003,7 +21003,7 @@ alpha=1.0; #endif #endif outParams.surfaceAlbedo=surfaceAlbedo;outParams.alpha=alpha;return outParams;} -`;T.IncludesShadersStore[M7]||(T.IncludesShadersStore[M7]=Jhe)});var y7,ede,P7=C(()=>{W();y7="pbrBlockReflectivity",ede=`struct reflectivityOutParams +`;T.IncludesShadersStore[M7]||(T.IncludesShadersStore[M7]=Jhe)});var y7,ede,P7=C(()=>{k();y7="pbrBlockReflectivity",ede=`struct reflectivityOutParams {float microSurface;float roughness;float diffuseRoughness;float reflectanceF0;vec3 reflectanceF90;vec3 colorReflectanceF0;vec3 colorReflectanceF90; #ifdef METALLICWORKFLOW vec3 surfaceAlbedo;float metallic;float specularWeight;vec3 dielectricColorF0; @@ -21150,7 +21150,7 @@ microSurface=saturate(microSurface);float roughness=1.-microSurface;float diffus diffuseRoughness*=baseDiffuseRoughnessTexture*baseDiffuseRoughnessInfos.y; #endif outParams.microSurface=microSurface;outParams.roughness=roughness;outParams.diffuseRoughness=diffuseRoughness;return outParams;} -`;T.IncludesShadersStore[y7]||(T.IncludesShadersStore[y7]=ede)});var D7,tde,L7=C(()=>{W();D7="pbrBlockAmbientOcclusion",tde=`struct ambientOcclusionOutParams +`;T.IncludesShadersStore[y7]||(T.IncludesShadersStore[y7]=ede)});var D7,tde,L7=C(()=>{k();D7="pbrBlockAmbientOcclusion",tde=`struct ambientOcclusionOutParams {vec3 ambientOcclusionColor; #if DEBUGMODE>0 && defined(AMBIENT) vec3 ambientOcclusionColorMap; @@ -21173,7 +21173,7 @@ outParams.ambientOcclusionColorMap=ambientOcclusionColorMap; #endif #endif outParams.ambientOcclusionColor=ambientOcclusionColor;return outParams;} -`;T.IncludesShadersStore[D7]||(T.IncludesShadersStore[D7]=tde)});var O7,ide,N7=C(()=>{W();O7="pbrBlockAlphaFresnel",ide=`#ifdef ALPHAFRESNEL +`;T.IncludesShadersStore[D7]||(T.IncludesShadersStore[D7]=tde)});var O7,ide,N7=C(()=>{k();O7="pbrBlockAlphaFresnel",ide=`#ifdef ALPHAFRESNEL #if defined(ALPHATEST) || defined(ALPHABLEND) struct alphaFresnelOutParams {float alpha;}; @@ -21201,7 +21201,7 @@ outParams.alpha=1.0; return outParams;} #endif #endif -`;T.IncludesShadersStore[O7]||(T.IncludesShadersStore[O7]=ide)});var w7,rde,F7=C(()=>{W();w7="pbrBlockAnisotropic",rde=`#ifdef ANISOTROPIC +`;T.IncludesShadersStore[O7]||(T.IncludesShadersStore[O7]=ide)});var w7,rde,F7=C(()=>{k();w7="pbrBlockAnisotropic",rde=`#ifdef ANISOTROPIC struct anisotropicOutParams {float anisotropy;vec3 anisotropicTangent;vec3 anisotropicBitangent;vec3 anisotropicNormal; #if DEBUGMODE>0 && defined(ANISOTROPIC_TEXTURE) @@ -21234,7 +21234,7 @@ anisotropyDirection.xy=mat2(anisotropyDirection.x,anisotropyDirection.y,-anisotr #endif mat3 anisoTBN=mat3(normalize(TBN[0]),normalize(TBN[1]),normalize(TBN[2]));vec3 anisotropicTangent=normalize(anisoTBN*anisotropyDirection);vec3 anisotropicBitangent=normalize(cross(anisoTBN[2],anisotropicTangent));outParams.anisotropy=anisotropy;outParams.anisotropicTangent=anisotropicTangent;outParams.anisotropicBitangent=anisotropicBitangent;outParams.anisotropicNormal=getAnisotropicBentNormals(anisotropicTangent,anisotropicBitangent,normalW,viewDirectionW,anisotropy,roughness);return outParams;} #endif -`;T.IncludesShadersStore[w7]||(T.IncludesShadersStore[w7]=rde)});var B7,nde,U7=C(()=>{W();B7="pbrBlockReflection",nde=`#ifdef REFLECTION +`;T.IncludesShadersStore[w7]||(T.IncludesShadersStore[w7]=rde)});var B7,nde,U7=C(()=>{k();B7="pbrBlockReflection",nde=`#ifdef REFLECTION struct reflectionOutParams {vec4 environmentRadiance;vec3 environmentIrradiance; #ifdef REFLECTIONMAP_3D @@ -21519,7 +21519,7 @@ outParams.environmentRadiance=environmentRadiance; #endif outParams.environmentIrradiance=environmentIrradiance;outParams.reflectionCoords=reflectionCoords;return outParams;} #endif -`;T.IncludesShadersStore[B7]||(T.IncludesShadersStore[B7]=nde)});var V7,sde,G7=C(()=>{W();V7="pbrBlockSheen",sde=`#ifdef SHEEN +`;T.IncludesShadersStore[B7]||(T.IncludesShadersStore[B7]=nde)});var V7,sde,G7=C(()=>{k();V7="pbrBlockSheen",sde=`#ifdef SHEEN struct sheenOutParams {float sheenIntensity;vec3 sheenColor;float sheenRoughness; #ifdef SHEEN_LINKWITHALBEDO @@ -21696,7 +21696,7 @@ outParams.sheenAlbedoScaling=1.0-sheenIntensity*max(max(sheenColor.r,sheenColor. #endif outParams.sheenIntensity=sheenIntensity;outParams.sheenColor=sheenColor;outParams.sheenRoughness=sheenRoughness;return outParams;} #endif -`;T.IncludesShadersStore[V7]||(T.IncludesShadersStore[V7]=sde)});var k7,ade,W7=C(()=>{W();k7="pbrBlockClearcoat",ade=`struct clearcoatOutParams +`;T.IncludesShadersStore[V7]||(T.IncludesShadersStore[V7]=sde)});var k7,ade,W7=C(()=>{k();k7="pbrBlockClearcoat",ade=`struct clearcoatOutParams {vec3 specularEnvironmentR0;float conservationFactor;vec3 clearCoatNormalW;vec2 clearCoatAARoughnessFactors;float clearCoatIntensity;float clearCoatRoughness; #ifdef REFLECTION vec3 finalClearCoatRadianceScaled; @@ -21933,7 +21933,7 @@ outParams.energyConservationFactorClearCoat=getEnergyConservationFactor(outParam #endif return outParams;} #endif -`;T.IncludesShadersStore[k7]||(T.IncludesShadersStore[k7]=ade)});var H7,ode,z7=C(()=>{W();H7="pbrBlockIridescence",ode=`struct iridescenceOutParams +`;T.IncludesShadersStore[k7]||(T.IncludesShadersStore[k7]=ade)});var H7,ode,z7=C(()=>{k();H7="pbrBlockIridescence",ode=`struct iridescenceOutParams {float iridescenceIntensity;float iridescenceIOR;float iridescenceThickness;vec3 specularEnvironmentR0;}; #ifdef IRIDESCENCE #define pbr_inline @@ -21973,7 +21973,7 @@ topIor=mix(1.0,vClearCoatRefractionParams.w-1.,clearCoatIntensity);viewAngle=sqr #endif vec3 iridescenceFresnel=evalIridescence(topIor,iridescenceIOR,viewAngle,iridescenceThickness,specularEnvironmentR0);outParams.specularEnvironmentR0=mix(specularEnvironmentR0,iridescenceFresnel,iridescenceIntensity);outParams.iridescenceIntensity=iridescenceIntensity;outParams.iridescenceThickness=iridescenceThickness;outParams.iridescenceIOR=iridescenceIOR;return outParams;} #endif -`;T.IncludesShadersStore[H7]||(T.IncludesShadersStore[H7]=ode)});var X7,lde,Y7=C(()=>{W();X7="pbrBlockSubSurface",lde=`struct subSurfaceOutParams +`;T.IncludesShadersStore[H7]||(T.IncludesShadersStore[H7]=ode)});var X7,lde,Y7=C(()=>{k();X7="pbrBlockSubSurface",lde=`struct subSurfaceOutParams {vec3 specularEnvironmentReflectance; #ifdef SS_REFRACTION vec3 finalRefraction;vec3 surfaceAlbedo; @@ -22370,11 +22370,11 @@ outParams.refractionIrradiance=refractionIrradiance.rgb; #endif return outParams;} #endif -`;T.IncludesShadersStore[X7]||(T.IncludesShadersStore[X7]=lde)});var K7,cde,rO=C(()=>{W();K7="pbrBlockReflectance0",cde=`float reflectanceF0=reflectivityOut.reflectanceF0;vec3 specularEnvironmentR0=reflectivityOut.colorReflectanceF0;vec3 specularEnvironmentR90=reflectivityOut.colorReflectanceF90; +`;T.IncludesShadersStore[X7]||(T.IncludesShadersStore[X7]=lde)});var K7,cde,rO=C(()=>{k();K7="pbrBlockReflectance0",cde=`float reflectanceF0=reflectivityOut.reflectanceF0;vec3 specularEnvironmentR0=reflectivityOut.colorReflectanceF0;vec3 specularEnvironmentR90=reflectivityOut.colorReflectanceF90; #ifdef ALPHAFRESNEL float reflectance90=fresnelGrazingReflectance(reflectanceF0);specularEnvironmentR90=specularEnvironmentR90*reflectance90; #endif -`;T.IncludesShadersStore[K7]||(T.IncludesShadersStore[K7]=cde)});var j7,fde,q7=C(()=>{W();BP();rO();j7="pbrClusteredLightingFunctions",fde=`#if defined(CLUSTLIGHT_BATCH) && CLUSTLIGHT_BATCH>0 +`;T.IncludesShadersStore[K7]||(T.IncludesShadersStore[K7]=cde)});var j7,fde,q7=C(()=>{k();BP();rO();j7="pbrClusteredLightingFunctions",fde=`#if defined(CLUSTLIGHT_BATCH) && CLUSTLIGHT_BATCH>0 #include #define inline lightingInfo computeClusteredLighting( @@ -22487,7 +22487,7 @@ result.sheen+=info.sheen; batchOffset+=CLUSTLIGHT_BATCH;} return result;} #endif -`;T.IncludesShadersStore[j7]||(T.IncludesShadersStore[j7]=fde)});var Z7,hde,Q7=C(()=>{W();Z7="pbrBlockNormalFinal",hde=`#if defined(FORCENORMALFORWARD) && defined(NORMAL) +`;T.IncludesShadersStore[j7]||(T.IncludesShadersStore[j7]=fde)});var Z7,hde,Q7=C(()=>{k();Z7="pbrBlockNormalFinal",hde=`#if defined(FORCENORMALFORWARD) && defined(NORMAL) vec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w; #if defined(TWOSIDEDLIGHTING) faceNormal=gl_FrontFacing ? faceNormal : -faceNormal; @@ -22501,7 +22501,7 @@ normalW=gl_FrontFacing ? -normalW : normalW; normalW=gl_FrontFacing ? normalW : -normalW; #endif #endif -`;T.IncludesShadersStore[Z7]||(T.IncludesShadersStore[Z7]=hde)});var $7,dde,J7=C(()=>{W();$7="pbrBlockLightmapInit",dde=`#ifdef LIGHTMAP +`;T.IncludesShadersStore[Z7]||(T.IncludesShadersStore[Z7]=hde)});var $7,dde,J7=C(()=>{k();$7="pbrBlockLightmapInit",dde=`#ifdef LIGHTMAP vec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset); #ifdef RGBDLIGHTMAP lightmapColor.rgb=fromRGBD(lightmapColor); @@ -22511,7 +22511,7 @@ lightmapColor.rgb=toLinearSpace(lightmapColor.rgb); #endif lightmapColor.rgb*=vLightmapInfos.y; #endif -`;T.IncludesShadersStore[$7]||(T.IncludesShadersStore[$7]=dde)});var e9,ude,t9=C(()=>{W();e9="pbrBlockGeometryInfo",ude=`float NdotVUnclamped=dot(normalW,viewDirectionW);float NdotV=absEps(NdotVUnclamped);float alphaG=convertRoughnessToAverageSlope(roughness);vec2 AARoughnessFactors=getAARoughnessFactors(normalW.xyz); +`;T.IncludesShadersStore[$7]||(T.IncludesShadersStore[$7]=dde)});var e9,ude,t9=C(()=>{k();e9="pbrBlockGeometryInfo",ude=`float NdotVUnclamped=dot(normalW,viewDirectionW);float NdotV=absEps(NdotVUnclamped);float alphaG=convertRoughnessToAverageSlope(roughness);vec2 AARoughnessFactors=getAARoughnessFactors(normalW.xyz); #ifdef SPECULARAA alphaG+=AARoughnessFactors.y; #endif @@ -22535,7 +22535,7 @@ float eho=environmentHorizonOcclusion(-viewDirectionW,normalW,geometricNormalW); #endif #endif #endif -`;T.IncludesShadersStore[e9]||(T.IncludesShadersStore[e9]=ude)});var i9,mde,r9=C(()=>{W();i9="pbrBlockReflectance",mde=`#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +`;T.IncludesShadersStore[e9]||(T.IncludesShadersStore[e9]=ude)});var i9,mde,r9=C(()=>{k();i9="pbrBlockReflectance",mde=`#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) vec3 baseSpecularEnvironmentReflectance=getReflectanceFromBRDFLookup(vec3(reflectanceF0),reflectivityOut.reflectanceF90,environmentBrdf); #if (CONDUCTOR_SPECULAR_MODEL==CONDUCTOR_SPECULAR_MODEL_OPENPBR) vec3 metalEnvironmentReflectance=reflectivityOut.specularWeight*getF82Specular(NdotV,clearcoatOut.specularEnvironmentR0,reflectivityOut.colorReflectanceF90,reflectivityOut.roughness);vec3 dielectricEnvironmentReflectance=getReflectanceFromBRDFLookup(reflectivityOut.dielectricColorF0,reflectivityOut.colorReflectanceF90,environmentBrdf);vec3 colorSpecularEnvironmentReflectance=mix(dielectricEnvironmentReflectance,metalEnvironmentReflectance,reflectivityOut.metallic); @@ -22561,7 +22561,7 @@ colorSpecularEnvironmentReflectance*=clearcoatOut.conservationFactor; colorSpecularEnvironmentReflectance*=clearcoatOut.absorption; #endif #endif -`;T.IncludesShadersStore[i9]||(T.IncludesShadersStore[i9]=mde)});var n9,pde,s9=C(()=>{W();n9="pbrBlockDirectLighting",pde=`vec3 diffuseBase=vec3(0.,0.,0.); +`;T.IncludesShadersStore[i9]||(T.IncludesShadersStore[i9]=mde)});var n9,pde,s9=C(()=>{k();n9="pbrBlockDirectLighting",pde=`vec3 diffuseBase=vec3(0.,0.,0.); #ifdef SS_TRANSLUCENCY vec3 diffuseTransmissionBase=vec3(0.,0.,0.); #endif @@ -22582,7 +22582,7 @@ float aggShadow=0.;float numLights=0.; #if defined(CLEARCOAT) && defined(CLEARCOAT_TINT) vec3 absorption=vec3(0.); #endif -`;T.IncludesShadersStore[n9]||(T.IncludesShadersStore[n9]=pde)});var a9,_de,o9=C(()=>{W();a9="pbrBlockFinalLitComponents",_de=`aggShadow=aggShadow/numLights; +`;T.IncludesShadersStore[n9]||(T.IncludesShadersStore[n9]=pde)});var a9,_de,o9=C(()=>{k();a9="pbrBlockFinalLitComponents",_de=`aggShadow=aggShadow/numLights; #if defined(ENVIRONMENTBRDF) #ifdef MS_BRDF_ENERGY_CONSERVATION vec3 baseSpecularEnergyConservationFactor=getEnergyConservationFactor(vec3(reflectanceF0),environmentBrdf);vec3 coloredEnergyConservationFactor=getEnergyConservationFactor(clearcoatOut.specularEnvironmentR0,environmentBrdf); @@ -22688,7 +22688,7 @@ luminanceOverAlpha+=getLuminance(finalClearCoatScaled); alpha=saturate(alpha+luminanceOverAlpha*luminanceOverAlpha); #endif #endif -`;T.IncludesShadersStore[a9]||(T.IncludesShadersStore[a9]=_de)});var l9,gde,c9=C(()=>{W();l9="pbrBlockFinalUnlitComponents",gde=`vec3 finalDiffuse=diffuseBase;finalDiffuse*=surfaceAlbedo; +`;T.IncludesShadersStore[a9]||(T.IncludesShadersStore[a9]=_de)});var l9,gde,c9=C(()=>{k();l9="pbrBlockFinalUnlitComponents",gde=`vec3 finalDiffuse=diffuseBase;finalDiffuse*=surfaceAlbedo; #if defined(SS_REFRACTION) && !defined(UNLIT) && !defined(LEGACY_SPECULAR_ENERGY_CONSERVATION) finalDiffuse*=subSurfaceOut.refractionOpacity; #endif @@ -22712,7 +22712,7 @@ vec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),aoOut.ambientOcclusionColor,v vec3 ambientOcclusionForDirectDiffuse=aoOut.ambientOcclusionColor; #endif finalAmbient*=aoOut.ambientOcclusionColor;finalDiffuse*=ambientOcclusionForDirectDiffuse; -`;T.IncludesShadersStore[l9]||(T.IncludesShadersStore[l9]=gde)});var f9,vde,h9=C(()=>{W();f9="pbrBlockFinalColorComposition",vde=`vec4 finalColor=vec4( +`;T.IncludesShadersStore[l9]||(T.IncludesShadersStore[l9]=gde)});var f9,vde,h9=C(()=>{k();f9="pbrBlockFinalColorComposition",vde=`vec4 finalColor=vec4( #ifndef UNLIT #ifdef REFLECTION finalIrradiance + @@ -22754,7 +22754,7 @@ finalColor.rgb+=lightmapColor.rgb; finalColor.rgb+=finalEmissive; #define CUSTOM_FRAGMENT_BEFORE_FOG finalColor=max(finalColor,0.0); -`;T.IncludesShadersStore[f9]||(T.IncludesShadersStore[f9]=vde)});var d9,Ede,u9=C(()=>{W();d9="pbrBlockPrePass",Ede=`#if SCENE_MRT_COUNT>0 +`;T.IncludesShadersStore[f9]||(T.IncludesShadersStore[f9]=vde)});var d9,Ede,u9=C(()=>{k();d9="pbrBlockPrePass",Ede=`#if SCENE_MRT_COUNT>0 float writeGeometryInfo=finalColor.a>ALPHATESTVALUE ? 1.0 : 0.0; #ifdef PREPASS_POSITION gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo); @@ -22836,7 +22836,7 @@ gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4( 0.0,0.0,0.0,1.0 )*writeGeometryInf #endif #endif #endif -`;T.IncludesShadersStore[d9]||(T.IncludesShadersStore[d9]=Ede)});var p9={};tt(p9,{pbrPixelShader:()=>Sde});var nO,m9,Sde,_9=C(()=>{W();Fx();Bx();A7();tO();PL();Ux();Vx();I7();kx();Ec();nd();bg();ya();DL();LL();OL();Wx();Gx();np();NL();wL();rp();FL();BL();AR();Hx();zx();wg();C7();P7();L7();N7();F7();U7();G7();W7();z7();Y7();q7();Sc();UL();Xx();Q7();Yx();J7();t9();rO();r9();s9();VP();o9();c9();h9();Kx();Ig();VL();u9();jx();GL();nO="pbrPixelShader",m9=`#define PBR_FRAGMENT_SHADER +`;T.IncludesShadersStore[d9]||(T.IncludesShadersStore[d9]=Ede)});var p9={};tt(p9,{pbrPixelShader:()=>Sde});var nO,m9,Sde,_9=C(()=>{k();Bx();Ux();A7();tO();PL();Vx();Gx();I7();Wx();vc();nd();bg();Ca();DL();LL();OL();Hx();kx();rp();NL();wL();ip();FL();BL();xR();zx();Xx();wg();C7();P7();L7();N7();F7();U7();G7();W7();z7();Y7();q7();Ec();UL();Yx();Q7();Kx();J7();t9();rO();r9();s9();VP();o9();c9();h9();jx();Ig();VL();u9();qx();GL();nO="pbrPixelShader",m9=`#define PBR_FRAGMENT_SHADER #define CUSTOM_FRAGMENT_EXTENSION #if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) #extension GL_OES_standard_derivatives : enable @@ -23399,23 +23399,23 @@ if (fragDepth==nearestDepth) {frontColor.rgb+=finalColor.rgb*finalColor.a*alphaM #include #define CUSTOM_FRAGMENT_MAIN_END } -`;T.ShadersStore[nO]||(T.ShadersStore[nO]=m9);Sde={name:nO,shader:m9}});var lp,sO,IR,aO,vr,g9=C(()=>{Gt();Ut();yt();so();ER();xs();Ve();Gi();m6();KA();zt();jA();q_();Vn();Oa();pg();Da();NC();Lf();p6();_6();g6();v6();E6();xP();ol();_g();Un();qA();ZA();QA();$A();lp={effect:null,subMesh:null},sO=class extends Km(Ym(xr)){},IR=class extends zm(sO){constructor(e){super(e),this.PBR=!0,this.NUM_SAMPLES="0",this.REALTIME_FILTERING=!1,this.IBL_CDF_FILTERING=!1,this.ALBEDO=!1,this.GAMMAALBEDO=!1,this.ALBEDODIRECTUV=0,this.VERTEXCOLOR=!1,this.BASE_WEIGHT=!1,this.BASE_WEIGHTDIRECTUV=0,this.BASE_DIFFUSE_ROUGHNESS=!1,this.BASE_DIFFUSE_ROUGHNESSDIRECTUV=0,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.AMBIENTINGRAYSCALE=!1,this.OPACITY=!1,this.VERTEXALPHA=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHABLEND=!1,this.ALPHAFROMALBEDO=!1,this.ALPHATESTVALUE="0.5",this.SPECULAROVERALPHA=!1,this.RADIANCEOVERALPHA=!1,this.ALPHAFRESNEL=!1,this.LINEARALPHAFRESNEL=!1,this.PREMULTIPLYALPHA=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.GAMMAEMISSIVE=!1,this.REFLECTIVITY=!1,this.REFLECTIVITY_GAMMA=!1,this.REFLECTIVITYDIRECTUV=0,this.SPECULARTERM=!1,this.MICROSURFACEFROMREFLECTIVITYMAP=!1,this.MICROSURFACEAUTOMATIC=!1,this.LODBASEDMICROSFURACE=!1,this.MICROSURFACEMAP=!1,this.MICROSURFACEMAPDIRECTUV=0,this.METALLICWORKFLOW=!1,this.ROUGHNESSSTOREINMETALMAPALPHA=!1,this.ROUGHNESSSTOREINMETALMAPGREEN=!1,this.METALLNESSSTOREINMETALMAPBLUE=!1,this.AOSTOREINMETALMAPRED=!1,this.METALLIC_REFLECTANCE=!1,this.METALLIC_REFLECTANCE_GAMMA=!1,this.METALLIC_REFLECTANCEDIRECTUV=0,this.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=!1,this.REFLECTANCE=!1,this.REFLECTANCE_GAMMA=!1,this.REFLECTANCEDIRECTUV=0,this.ENVIRONMENTBRDF=!1,this.ENVIRONMENTBRDF_RGBD=!1,this.NORMAL=!1,this.TANGENT=!1,this.BUMP=!1,this.BUMPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.NORMALXYSCALE=!0,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.USELIGHTMAPASSHADOWMAP=!1,this.GAMMALIGHTMAP=!1,this.RGBDLIGHTMAP=!1,this.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.INVERTCUBICMAP=!1,this.USESPHERICALFROMREFLECTIONMAP=!1,this.USEIRRADIANCEMAP=!1,this.USE_IRRADIANCE_DOMINANT_DIRECTION=!1,this.USESPHERICALINVERTEX=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1,this.LINEARSPECULARREFLECTION=!1,this.RADIANCEOCCLUSION=!1,this.HORIZONOCCLUSION=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.NONUNIFORMSCALING=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_POSITION=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.MORPHTARGETS_UV2=!1,this.MORPHTARGETS_COLOR=!1,this.MORPHTARGETTEXTURE_HASPOSITIONS=!1,this.MORPHTARGETTEXTURE_HASNORMALS=!1,this.MORPHTARGETTEXTURE_HASTANGENTS=!1,this.MORPHTARGETTEXTURE_HASUVS=!1,this.MORPHTARGETTEXTURE_HASUV2S=!1,this.MORPHTARGETTEXTURE_HASCOLORS=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.USEPHYSICALLIGHTFALLOFF=!1,this.USEGLTFLIGHTFALLOFF=!1,this.TWOSIDEDLIGHTING=!1,this.MIRRORED=!1,this.SHADOWFLOAT=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.LOGARITHMICDEPTH=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.AREALIGHTSUPPORTED=!0,this.FORCENORMALFORWARD=!1,this.SPECULARAA=!1,this.UNLIT=!1,this.DECAL_AFTER_DETAIL=!1,this.DEBUGMODE=0,this.USE_VERTEX_PULLING=!1,this.VERTEX_PULLING_USE_INDEX_BUFFER=!1,this.VERTEX_PULLING_INDEX_BUFFER_32BITS=!1,this.RIGHT_HANDED=!1,this.CLUSTLIGHT_SLICES=0,this.CLUSTLIGHT_BATCH=0,this.rebuild()}reset(){super.reset(),this.ALPHATESTVALUE="0.5",this.PBR=!0,this.NORMALXYSCALE=!0}},aO=class extends jm(hl){},vr=class n extends aO{get realTimeFiltering(){return this._realTimeFiltering}set realTimeFiltering(e){this._realTimeFiltering=e,this.markAsDirty(1)}get realTimeFilteringQuality(){return this._realTimeFilteringQuality}set realTimeFilteringQuality(e){this._realTimeFilteringQuality=e,this.markAsDirty(1)}get canRenderToMRT(){return!0}constructor(e,t,i=!1){super(e,t,void 0,i||n.ForceGLSL),this._directIntensity=1,this._emissiveIntensity=1,this._environmentIntensity=1,this._specularIntensity=1,this._lightingInfos=new Ri(this._directIntensity,this._emissiveIntensity,this._environmentIntensity,this._specularIntensity),this._disableBumpMap=!1,this._albedoTexture=null,this._baseWeightTexture=null,this._baseDiffuseRoughnessTexture=null,this._ambientTexture=null,this._ambientTextureStrength=1,this._ambientTextureImpactOnAnalyticalLights=n.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._reflectivityTexture=null,this._metallicTexture=null,this._metallic=null,this._roughness=null,this._metallicF0Factor=1,this._metallicReflectanceColor=ge.White(),this._useOnlyMetallicFromMetallicReflectanceTexture=!1,this._metallicReflectanceTexture=null,this._reflectanceTexture=null,this._microSurfaceTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._ambientColor=new ge(0,0,0),this._albedoColor=new ge(1,1,1),this._baseWeight=1,this._baseDiffuseRoughness=null,this._reflectivityColor=new ge(1,1,1),this._reflectionColor=new ge(1,1,1),this._emissiveColor=new ge(0,0,0),this._microSurface=.9,this._useLightmapAsShadowmap=!1,this._useHorizonOcclusion=!0,this._useRadianceOcclusion=!0,this._useAlphaFromAlbedoTexture=!1,this._useSpecularOverAlpha=!0,this._useMicroSurfaceFromReflectivityMapAlpha=!1,this._useRoughnessFromMetallicTextureAlpha=!0,this._useRoughnessFromMetallicTextureGreen=!1,this._useMetallnessFromMetallicTextureBlue=!1,this._useAmbientOcclusionFromMetallicTextureRed=!1,this._useAmbientInGrayScale=!1,this._useAutoMicroSurfaceFromReflectivityMap=!1,this._lightFalloff=n.LIGHTFALLOFF_PHYSICAL,this._useRadianceOverAlpha=!0,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this._parallaxScaleBias=.05,this._disableLighting=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._alphaCutOff=.4,this._useAlphaFresnel=!1,this._useLinearAlphaFresnel=!1,this._environmentBRDFTexture=null,this._forceIrradianceInFragment=!1,this._realTimeFiltering=!1,this._realTimeFilteringQuality=8,this._forceNormalForward=!1,this._enableSpecularAntiAliasing=!1,this._renderTargets=new wi(16),this._globalAmbientColor=new ge(0,0,0),this._unlit=!1,this._applyDecalMapAfterDetailMap=!1,this._debugMode=0,this._shadersLoaded=!1,this._breakShaderLoadedCheck=!1,this._vertexPullingMetadata=null,this.debugMode=0,this.debugLimit=-1,this.debugFactor=1,this._cacheHasRenderTargetTextures=!1,this.brdf=new Mr(this),this.clearCoat=new sn(this),this.iridescence=new Ds(this),this.anisotropy=new Rc(this),this.sheen=new $s(this),this.subSurface=new Ai(this),this.detailMap=new Na(this),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),le.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=vR(this.getScene()),this.prePassConfiguration=new ys}get hasRenderTargetTextures(){return le.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget?!0:this._cacheHasRenderTargetTextures}get isPrePassCapable(){return!this.disableDepthWrite}getClassName(){return"PBRBaseMaterial"}get _disableAlphaBlending(){var e;return this._transparencyMode===n.PBRMATERIAL_OPAQUE||this._transparencyMode===n.PBRMATERIAL_ALPHATEST||((e=this.subSurface)==null?void 0:e.disableAlphaBlending)}needAlphaBlending(){return this._hasTransparencyMode?this._transparencyModeIsBlend:this._disableAlphaBlending?!1:this.alpha<1||this._opacityTexture!=null||this._shouldUseAlphaFromAlbedoTexture()}needAlphaTesting(){var e;return this._hasTransparencyMode?this._transparencyModeIsTest:(e=this.subSurface)!=null&&e.disableAlphaBlending?!1:this._hasAlphaChannel()&&(this._transparencyMode==null||this._transparencyMode===n.PBRMATERIAL_ALPHATEST)}_shouldUseAlphaFromAlbedoTexture(){return this._albedoTexture!=null&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==n.PBRMATERIAL_OPAQUE}_hasAlphaChannel(){return this._albedoTexture!=null&&this._albedoTexture.hasAlpha||this._opacityTexture!=null}getAlphaTestTexture(){return this._albedoTexture}isReadyForSubMesh(e,t,i){var d;this._uniformBufferLayoutBuilt||this.buildUniformLayout();let r=t._drawWrapper;if(r.effect&&this.isFrozen&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(4,this._eventInfo),t.materialDefines=new IR(this._eventInfo.defineNames));let s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let a=this.getScene(),o=a.getEngine();if(s._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,a.texturesEnabled)){if(this._albedoTexture&&le.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking()||this._baseWeightTexture&&le.BaseWeightTextureEnabled&&!this._baseWeightTexture.isReadyOrNotBlocking()||this._baseDiffuseRoughnessTexture&&le.BaseDiffuseRoughnessTextureEnabled&&!this._baseDiffuseRoughnessTexture.isReadyOrNotBlocking()||this._ambientTexture&&le.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking()||this._opacityTexture&&le.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;let u=this._getReflectionTexture();if(u&&le.ReflectionTextureEnabled){if(!u.isReadyOrNotBlocking())return!1;if(u.irradianceTexture){if(!u.irradianceTexture.isReadyOrNotBlocking())return!1}else if(!u.sphericalPolynomial&&((d=u.getInternalTexture())!=null&&d._sphericalPolynomialPromise))return!1}if(this._lightmapTexture&&le.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking()||this._emissiveTexture&&le.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(le.SpecularTextureEnabled){if(this._metallicTexture){if(!this._metallicTexture.isReadyOrNotBlocking())return!1}else if(this._reflectivityTexture&&!this._reflectivityTexture.isReadyOrNotBlocking())return!1;if(this._metallicReflectanceTexture&&!this._metallicReflectanceTexture.isReadyOrNotBlocking()||this._reflectanceTexture&&!this._reflectanceTexture.isReadyOrNotBlocking()||this._microSurfaceTexture&&!this._microSurfaceTexture.isReadyOrNotBlocking())return!1}if(o.getCaps().standardDerivatives&&this._bumpTexture&&le.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady()||this._environmentBRDFTexture&&le.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady())return!1}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh||s._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;if(s.AREALIGHTUSED||s.CLUSTLIGHT_BATCH){for(let u=0;u{m.push(`vp_${R}_info`)}))}else this._vertexPullingMetadata=null;kt&&(kt.PrepareUniforms(m,i),kt.PrepareSamplers(p,i)),Om({uniformsNames:m,uniformBuffersNames:_,samplers:p,defines:i,maxSimultaneousLights:this._maxSimultaneousLights,shaderLanguage:this._shaderLanguage});let v={};this.customShaderNameResolve&&(u=this.customShaderNameResolve(u,m,_,p,i,d,v));let x=i.toString(),A=c.createEffect(u,{attributes:d,uniformsNames:m,uniformBuffersNames:_,samplers:p,defines:x,fallbacks:f,onCompiled:r,onError:s,indexParameters:g,processFinalCode:v.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:i.PREPASS,shaderLanguage:this._shaderLanguage,extraInitializationsAsync:this._shadersLoaded?void 0:async()=>{this.shaderLanguage===1?await Promise.all([Promise.resolve().then(()=>(x6(),A6)),Promise.resolve().then(()=>(m7(),u7))]):await Promise.all([Promise.resolve().then(()=>(S7(),E7)),Promise.resolve().then(()=>(_9(),p9))]),this._shadersLoaded=!0}},c);return this._eventInfo.customCode=void 0,A}_prepareDefines(e,t,i,r=null,s=null){let a=t.hasThinInstances,o=this.getScene(),l=o.getEngine();Mm(o,e,i,!0,this._maxSimultaneousLights,this._disableLighting),i._needNormals=!0,Pm(o,i);let c=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(Lm(o,i,this.canRenderToMRT&&!c),Dm(o,i,c),Hn.PrepareDefines(l.currentRenderPassId,e,i),i.METALLICWORKFLOW=this.isMetallicWorkflow(),i._areTexturesDirty){i._needUVs=!1;for(let f=1;f<=6;++f)i["MAINUV"+f]=!1;if(o.texturesEnabled){i.ALBEDODIRECTUV=0,i.BASE_WEIGHTDIRECTUV=0,i.BASE_DIFFUSE_ROUGHNESSDIRECTUV=0,i.AMBIENTDIRECTUV=0,i.OPACITYDIRECTUV=0,i.EMISSIVEDIRECTUV=0,i.REFLECTIVITYDIRECTUV=0,i.MICROSURFACEMAPDIRECTUV=0,i.METALLIC_REFLECTANCEDIRECTUV=0,i.REFLECTANCEDIRECTUV=0,i.BUMPDIRECTUV=0,i.LIGHTMAPDIRECTUV=0,l.getCaps().textureLOD&&(i.LODBASEDMICROSFURACE=!0),this._albedoTexture&&le.DiffuseTextureEnabled?(ri(this._albedoTexture,i,"ALBEDO"),i.GAMMAALBEDO=this._albedoTexture.gammaSpace):i.ALBEDO=!1,this._baseWeightTexture&&le.BaseWeightTextureEnabled?ri(this._baseWeightTexture,i,"BASE_WEIGHT"):i.BASE_WEIGHT=!1,this._baseDiffuseRoughnessTexture&&le.BaseDiffuseRoughnessTextureEnabled?ri(this._baseDiffuseRoughnessTexture,i,"BASE_DIFFUSE_ROUGHNESS"):i.BASE_DIFFUSE_ROUGHNESS=!1,this._ambientTexture&&le.AmbientTextureEnabled?(ri(this._ambientTexture,i,"AMBIENT"),i.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):i.AMBIENT=!1,this._opacityTexture&&le.OpacityTextureEnabled?(ri(this._opacityTexture,i,"OPACITY"),i.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):i.OPACITY=!1;let f=this._getReflectionTexture(),h=this._forceIrradianceInFragment||this.realTimeFiltering||this._twoSidedLighting||l.getCaps().maxVaryingVectors<=8||this._baseDiffuseRoughnessTexture!=null;Rf(o,f,i,this.realTimeFiltering,this.realTimeFilteringQuality,!h),this._lightmapTexture&&le.LightmapTextureEnabled?(ri(this._lightmapTexture,i,"LIGHTMAP"),i.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,i.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace,i.RGBDLIGHTMAP=this._lightmapTexture.isRGBD):i.LIGHTMAP=!1,this._emissiveTexture&&le.EmissiveTextureEnabled?(ri(this._emissiveTexture,i,"EMISSIVE"),i.GAMMAEMISSIVE=this._emissiveTexture.gammaSpace):i.EMISSIVE=!1,le.SpecularTextureEnabled?(this._metallicTexture?(ri(this._metallicTexture,i,"REFLECTIVITY"),i.ROUGHNESSSTOREINMETALMAPALPHA=this._useRoughnessFromMetallicTextureAlpha,i.ROUGHNESSSTOREINMETALMAPGREEN=!this._useRoughnessFromMetallicTextureAlpha&&this._useRoughnessFromMetallicTextureGreen,i.METALLNESSSTOREINMETALMAPBLUE=this._useMetallnessFromMetallicTextureBlue,i.AOSTOREINMETALMAPRED=this._useAmbientOcclusionFromMetallicTextureRed,i.REFLECTIVITY_GAMMA=!1):this._reflectivityTexture?(ri(this._reflectivityTexture,i,"REFLECTIVITY"),i.MICROSURFACEFROMREFLECTIVITYMAP=this._useMicroSurfaceFromReflectivityMapAlpha,i.MICROSURFACEAUTOMATIC=this._useAutoMicroSurfaceFromReflectivityMap,i.REFLECTIVITY_GAMMA=this._reflectivityTexture.gammaSpace):i.REFLECTIVITY=!1,this._metallicReflectanceTexture||this._reflectanceTexture?(i.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=this._useOnlyMetallicFromMetallicReflectanceTexture,this._metallicReflectanceTexture?(ri(this._metallicReflectanceTexture,i,"METALLIC_REFLECTANCE"),i.METALLIC_REFLECTANCE_GAMMA=this._metallicReflectanceTexture.gammaSpace):i.METALLIC_REFLECTANCE=!1,this._reflectanceTexture&&(!this._metallicReflectanceTexture||this._metallicReflectanceTexture&&this._useOnlyMetallicFromMetallicReflectanceTexture)?(ri(this._reflectanceTexture,i,"REFLECTANCE"),i.REFLECTANCE_GAMMA=this._reflectanceTexture.gammaSpace):i.REFLECTANCE=!1):(i.METALLIC_REFLECTANCE=!1,i.REFLECTANCE=!1),this._microSurfaceTexture?ri(this._microSurfaceTexture,i,"MICROSURFACEMAP"):i.MICROSURFACEMAP=!1):(i.REFLECTIVITY=!1,i.MICROSURFACEMAP=!1),l.getCaps().standardDerivatives&&this._bumpTexture&&le.BumpTextureEnabled&&!this._disableBumpMap?(ri(this._bumpTexture,i,"BUMP"),this._useParallax&&this._albedoTexture&&le.DiffuseTextureEnabled?(i.PARALLAX=!0,i.PARALLAX_RHS=o.useRightHandedSystem,i.PARALLAXOCCLUSION=!!this._useParallaxOcclusion):i.PARALLAX=!1,i.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap):(i.BUMP=!1,i.PARALLAX=!1,i.PARALLAX_RHS=!1,i.PARALLAXOCCLUSION=!1,i.OBJECTSPACE_NORMALMAP=!1),this._environmentBRDFTexture&&le.ReflectionTextureEnabled?(i.ENVIRONMENTBRDF=!0,i.ENVIRONMENTBRDF_RGBD=this._environmentBRDFTexture.isRGBD):(i.ENVIRONMENTBRDF=!1,i.ENVIRONMENTBRDF_RGBD=!1),this._shouldUseAlphaFromAlbedoTexture()?i.ALPHAFROMALBEDO=!0:i.ALPHAFROMALBEDO=!1}i.SPECULAROVERALPHA=this._useSpecularOverAlpha,this._lightFalloff===n.LIGHTFALLOFF_STANDARD?(i.USEPHYSICALLIGHTFALLOFF=!1,i.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===n.LIGHTFALLOFF_GLTF?(i.USEPHYSICALLIGHTFALLOFF=!1,i.USEGLTFLIGHTFALLOFF=!0):(i.USEPHYSICALLIGHTFALLOFF=!0,i.USEGLTFLIGHTFALLOFF=!1),i.RADIANCEOVERALPHA=this._useRadianceOverAlpha,!this.backFaceCulling&&this._twoSidedLighting?i.TWOSIDEDLIGHTING=!0:i.TWOSIDEDLIGHTING=!1,i.MIRRORED=!!o._mirroredCameraPosition,i.SPECULARAA=l.getCaps().standardDerivatives&&this._enableSpecularAntiAliasing}(i._areTexturesDirty||i._areMiscDirty)&&(i.ALPHATESTVALUE=`${this._alphaCutOff}${this._alphaCutOff%1===0?".":""}`,i.PREMULTIPLYALPHA=this.alphaMode===7||this.alphaMode===8,i.ALPHABLEND=this.needAlphaBlendingForMesh(e),i.ALPHAFRESNEL=this._useAlphaFresnel||this._useLinearAlphaFresnel,i.LINEARALPHAFRESNEL=this._useLinearAlphaFresnel),i._areImageProcessingDirty&&this._imageProcessingConfiguration&&this._imageProcessingConfiguration.prepareDefines(i),i.FORCENORMALFORWARD=this._forceNormalForward,i.RADIANCEOCCLUSION=this._useRadianceOcclusion,i.HORIZONOCCLUSION=this._useHorizonOcclusion,i._areMiscDirty&&(bm(e,o,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this.needAlphaTestingForMesh(e),i,this._applyDecalMapAfterDetailMap,this._useVertexPulling,t,this._isVertexOutputInvariant),i.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent(L.NormalKind),i.DEBUGMODE=this._debugMode),Cm(o,l,this,i,!!r,s,a),this._eventInfo.defines=i,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),ym(e,i,!0,!0,!0,this._transparencyMode!==n.PBRMATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}forceCompilation(e,t,i){let r={clipPlane:!1,useInstances:!1,...i};this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(4,this._eventInfo),(()=>{if(this._breakShaderLoadedCheck)return;let a=new IR(this._eventInfo.defineNames),o=this._prepareEffect(e,e,a,void 0,void 0,r.useInstances,r.clipPlane);this._onEffectCreatedObservable&&(lp.effect=o,lp.subMesh=null,this._onEffectCreatedObservable.notifyObservers(lp)),o.isReady()?t&&t(this):o.onCompileObservable.add(()=>{t&&t(this)})})()}buildUniformLayout(){let e=this._uniformBuffer;e.addUniform("vAlbedoInfos",2),e.addUniform("vBaseWeightInfos",2),e.addUniform("vBaseDiffuseRoughnessInfos",2),e.addUniform("vAmbientInfos",4),e.addUniform("vOpacityInfos",2),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vReflectivityInfos",3),e.addUniform("vMicroSurfaceSamplerInfos",2),e.addUniform("vBumpInfos",3),e.addUniform("albedoMatrix",16),e.addUniform("baseWeightMatrix",16),e.addUniform("baseDiffuseRoughnessMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("reflectivityMatrix",16),e.addUniform("microSurfaceSamplerMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("vAlbedoColor",4),e.addUniform("baseWeight",1),e.addUniform("baseDiffuseRoughness",1),e.addUniform("vLightingIntensity",4),e.addUniform("pointSize",1),e.addUniform("vReflectivityColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vAmbientColor",3),e.addUniform("vDebugMode",2),e.addUniform("vMetallicReflectanceFactors",4),e.addUniform("vMetallicReflectanceInfos",2),e.addUniform("metallicReflectanceMatrix",16),e.addUniform("vReflectanceInfos",2),e.addUniform("reflectanceMatrix",16),e.addUniform("cameraInfo",4),Nm(e,!0,!0,!0,!0,!0),super.buildUniformLayout()}bindForSubMesh(e,t,i){var d,u,m,p;let r=this.getScene(),s=i.materialDefines;if(!s)return;let a=i.effect;if(!a)return;this._activeEffect=a,t.getMeshUniformBuffer().bindToEffect(a,"Mesh"),t.transferToEffect(e);let o=r.getEngine();this._uniformBuffer.bindToEffect(a,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,r,t,e,this.isFrozen),Hn.Bind(o.currentRenderPassId,this._activeEffect,t,e,this);let l=r.activeCamera;l?this._uniformBuffer.updateFloat4("cameraInfo",l.minZ,l.maxZ,0,0):this._uniformBuffer.updateFloat4("cameraInfo",0,0,0,0),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),s.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));let c=this._mustRebind(r,a,i,t.visibility);bs(t,this._activeEffect,this.prePassConfiguration),this._vertexPullingMetadata&&Nf(this._activeEffect,this._vertexPullingMetadata);let f=null,h=this._uniformBuffer;if(c){if(this.bindViewProjection(a),f=this._getReflectionTexture(),!h.useUbo||!this.isFrozen||!h.isSync||i._drawWrapper._forceRebindOnNextCall){if(r.texturesEnabled&&(this._albedoTexture&&le.DiffuseTextureEnabled&&(h.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),ni(this._albedoTexture,h,"albedo")),this._baseWeightTexture&&le.BaseWeightTextureEnabled&&(h.updateFloat2("vBaseWeightInfos",this._baseWeightTexture.coordinatesIndex,this._baseWeightTexture.level),ni(this._baseWeightTexture,h,"baseWeight")),this._baseDiffuseRoughnessTexture&&le.BaseDiffuseRoughnessTextureEnabled&&(h.updateFloat2("vBaseDiffuseRoughnessInfos",this._baseDiffuseRoughnessTexture.coordinatesIndex,this._baseDiffuseRoughnessTexture.level),ni(this._baseDiffuseRoughnessTexture,h,"baseDiffuseRoughness")),this._ambientTexture&&le.AmbientTextureEnabled&&(h.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),ni(this._ambientTexture,h,"ambient")),this._opacityTexture&&le.OpacityTextureEnabled&&(h.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),ni(this._opacityTexture,h,"opacity")),this._emissiveTexture&&le.EmissiveTextureEnabled&&(h.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),ni(this._emissiveTexture,h,"emissive")),this._lightmapTexture&&le.LightmapTextureEnabled&&(h.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),ni(this._lightmapTexture,h,"lightmap")),le.SpecularTextureEnabled&&(this._metallicTexture?(h.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),ni(this._metallicTexture,h,"reflectivity")):this._reflectivityTexture&&(h.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),ni(this._reflectivityTexture,h,"reflectivity")),this._metallicReflectanceTexture&&(h.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),ni(this._metallicReflectanceTexture,h,"metallicReflectance")),this._reflectanceTexture&&s.REFLECTANCE&&(h.updateFloat2("vReflectanceInfos",this._reflectanceTexture.coordinatesIndex,this._reflectanceTexture.level),ni(this._reflectanceTexture,h,"reflectance")),this._microSurfaceTexture&&(h.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),ni(this._microSurfaceTexture,h,"microSurfaceSampler"))),this._bumpTexture&&o.getCaps().standardDerivatives&&le.BumpTextureEnabled&&!this._disableBumpMap&&(h.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),ni(this._bumpTexture,h,"bump"),r._mirroredCameraPosition?h.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):h.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),Em(r,s,h,this._reflectionColor,f,this.realTimeFiltering,!0,!0,!0,!0,!0)),this.pointsCloud&&h.updateFloat("pointSize",this.pointSize),s.METALLICWORKFLOW){En.Color4[0].r=this._metallic===void 0||this._metallic===null?1:this._metallic,En.Color4[0].g=this._roughness===void 0||this._roughness===null?1:this._roughness;let _=(u=(d=this.subSurface)==null?void 0:d._indexOfRefraction)!=null?u:1.5,g=1;En.Color4[0].b=_;let v=Math.pow((_-g)/(_+g),2);En.Color4[0].a=v,h.updateDirectColor4("vReflectivityColor",En.Color4[0]),h.updateColor4("vMetallicReflectanceFactors",this._metallicReflectanceColor,this._metallicF0Factor)}else h.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);h.updateColor3("vEmissiveColor",le.EmissiveTextureEnabled?this._emissiveColor:ge.BlackReadOnly),!s.SS_REFRACTION&&((m=this.subSurface)!=null&&m._linkRefractionWithTransparency)?h.updateColor4("vAlbedoColor",this._albedoColor,1):h.updateColor4("vAlbedoColor",this._albedoColor,this.alpha),h.updateFloat("baseWeight",this._baseWeight),h.updateFloat("baseDiffuseRoughness",this._baseDiffuseRoughness||0),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity*r.environmentIntensity,this._lightingInfos.w=this._specularIntensity,h.updateVector4("vLightingIntensity",this._lightingInfos),r.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor),h.updateColor3("vAmbientColor",this._globalAmbientColor),h.updateFloat2("vDebugMode",this.debugLimit,this.debugFactor)}r.texturesEnabled&&(this._albedoTexture&&le.DiffuseTextureEnabled&&h.setTexture("albedoSampler",this._albedoTexture),this._baseWeightTexture&&le.BaseWeightTextureEnabled&&h.setTexture("baseWeightSampler",this._baseWeightTexture),this._baseDiffuseRoughnessTexture&&le.BaseDiffuseRoughnessTextureEnabled&&h.setTexture("baseDiffuseRoughnessSampler",this._baseDiffuseRoughnessTexture),this._ambientTexture&&le.AmbientTextureEnabled&&h.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&le.OpacityTextureEnabled&&h.setTexture("opacitySampler",this._opacityTexture),DA(r,s,h,f,this.realTimeFiltering),s.ENVIRONMENTBRDF&&h.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&le.EmissiveTextureEnabled&&h.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&le.LightmapTextureEnabled&&h.setTexture("lightmapSampler",this._lightmapTexture),le.SpecularTextureEnabled&&(this._metallicTexture?h.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&h.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&h.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._reflectanceTexture&&s.REFLECTANCE&&h.setTexture("reflectanceSampler",this._reflectanceTexture),this._microSurfaceTexture&&h.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&o.getCaps().standardDerivatives&&le.BumpTextureEnabled&&!this._disableBumpMap&&h.setTexture("bumpSampler",this._bumpTexture)),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(a),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),Fn(this._activeEffect,this,r),this.bindEyePosition(a)}else r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(c||!this.isFrozen)&&(r.lightsEnabled&&!this._disableLighting&&Tm(r,t,this._activeEffect,s,this._maxSimultaneousLights),(r.fogEnabled&&t.applyFog&&r.fogMode!==$t.FOGMODE_NONE||f||this.subSurface.refractionTexture||t.receiveShadows||s.PREPASS||s.CLUSTLIGHT_BATCH)&&this.bindView(a),Af(r,t,this._activeEffect,!0),s.NUM_MORPH_INFLUENCERS&&Bn(t,this._activeEffect),s.BAKED_VERTEX_ANIMATION_TEXTURE&&((p=t.bakedVertexAnimationManager)==null||p.bind(a,s.INSTANCES)),this._imageProcessingConfiguration.bind(this._activeEffect),Tf(s,this._activeEffect,r)),this._afterBind(t,this._activeEffect,i),h.update()}getAnimatables(){let e=super.getAnimatables();return this._albedoTexture&&this._albedoTexture.animations&&this._albedoTexture.animations.length>0&&e.push(this._albedoTexture),this._baseWeightTexture&&this._baseWeightTexture.animations&&this._baseWeightTexture.animations.length>0&&e.push(this._baseWeightTexture),this._baseDiffuseRoughnessTexture&&this._baseDiffuseRoughnessTexture.animations&&this._baseDiffuseRoughnessTexture.animations.length>0&&e.push(this._baseDiffuseRoughnessTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._metallicTexture&&this._metallicTexture.animations&&this._metallicTexture.animations.length>0?e.push(this._metallicTexture):this._reflectivityTexture&&this._reflectivityTexture.animations&&this._reflectivityTexture.animations.length>0&&e.push(this._reflectivityTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._metallicReflectanceTexture&&this._metallicReflectanceTexture.animations&&this._metallicReflectanceTexture.animations.length>0&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&this._reflectanceTexture.animations&&this._reflectanceTexture.animations.length>0&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&this._microSurfaceTexture.animations&&this._microSurfaceTexture.animations.length>0&&e.push(this._microSurfaceTexture),e}_getReflectionTexture(){return this._reflectionTexture?this._reflectionTexture:this.getScene().environmentTexture}getActiveTextures(){let e=super.getActiveTextures();return this._albedoTexture&&e.push(this._albedoTexture),this._baseWeightTexture&&e.push(this._baseWeightTexture),this._baseDiffuseRoughnessTexture&&e.push(this._baseDiffuseRoughnessTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._reflectivityTexture&&e.push(this._reflectivityTexture),this._metallicTexture&&e.push(this._metallicTexture),this._metallicReflectanceTexture&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&e.push(this._microSurfaceTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),e}hasTexture(e){return!!(super.hasTexture(e)||this._albedoTexture===e||this._baseWeightTexture===e||this._baseDiffuseRoughnessTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._reflectivityTexture===e||this._metallicTexture===e||this._metallicReflectanceTexture===e||this._reflectanceTexture===e||this._microSurfaceTexture===e||this._bumpTexture===e||this._lightmapTexture===e)}setPrePassRenderer(){var t;if(!((t=this.subSurface)!=null&&t.isScatteringEnabled))return!1;let e=this.getScene().enableSubSurfaceForPrePass();return e&&(e.enabled=!0),!0}dispose(e,t){var i,r,s,a,o,l,c,f,h,d,u,m,p,_;this._breakShaderLoadedCheck=!0,t&&(this._environmentBRDFTexture&&this.getScene().environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),(i=this._albedoTexture)==null||i.dispose(),(r=this._baseWeightTexture)==null||r.dispose(),(s=this._baseDiffuseRoughnessTexture)==null||s.dispose(),(a=this._ambientTexture)==null||a.dispose(),(o=this._opacityTexture)==null||o.dispose(),(l=this._reflectionTexture)==null||l.dispose(),(c=this._emissiveTexture)==null||c.dispose(),(f=this._metallicTexture)==null||f.dispose(),(h=this._reflectivityTexture)==null||h.dispose(),(d=this._bumpTexture)==null||d.dispose(),(u=this._lightmapTexture)==null||u.dispose(),(m=this._metallicReflectanceTexture)==null||m.dispose(),(p=this._reflectanceTexture)==null||p.dispose(),(_=this._microSurfaceTexture)==null||_.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}};vr.PBRMATERIAL_OPAQUE=Ee.MATERIAL_OPAQUE;vr.PBRMATERIAL_ALPHATEST=Ee.MATERIAL_ALPHATEST;vr.PBRMATERIAL_ALPHABLEND=Ee.MATERIAL_ALPHABLEND;vr.PBRMATERIAL_ALPHATESTANDBLEND=Ee.MATERIAL_ALPHATESTANDBLEND;vr.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0;vr.LIGHTFALLOFF_PHYSICAL=0;vr.LIGHTFALLOFF_GLTF=1;vr.LIGHTFALLOFF_STANDARD=2;vr.ForceGLSL=!1;P([oe("_markAllSubMeshesAsMiscDirty")],vr.prototype,"debugMode",void 0)});var v9={};tt(v9,{PBRMaterial:()=>ht});var ht,E9=C(()=>{Gt();Ut();ER();zt();g9();Hi();Vn();Tr();ht=class n extends vr{get refractionTexture(){return this.subSurface.refractionTexture}set refractionTexture(e){this.subSurface.refractionTexture=e,e?this.subSurface.isRefractionEnabled=!0:this.subSurface.linkRefractionWithTransparency||(this.subSurface.isRefractionEnabled=!1)}get indexOfRefraction(){return this.subSurface.indexOfRefraction}set indexOfRefraction(e){this.subSurface.indexOfRefraction=e}get invertRefractionY(){return this.subSurface.invertRefractionY}set invertRefractionY(e){this.subSurface.invertRefractionY=e}get linkRefractionWithTransparency(){return this.subSurface.linkRefractionWithTransparency}set linkRefractionWithTransparency(e){this.subSurface.linkRefractionWithTransparency=e,e&&(this.subSurface.isRefractionEnabled=!0)}get usePhysicalLightFalloff(){return this._lightFalloff===vr.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=vr.LIGHTFALLOFF_PHYSICAL:this._lightFalloff=vr.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===vr.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=vr.LIGHTFALLOFF_GLTF:this._lightFalloff=vr.LIGHTFALLOFF_STANDARD)}constructor(e,t,i=!1){super(e,t,i),this.directIntensity=1,this.emissiveIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.disableBumpMap=!1,this.ambientTextureStrength=1,this.ambientTextureImpactOnAnalyticalLights=n.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this.metallicF0Factor=1,this.metallicReflectanceColor=ge.White(),this.useOnlyMetallicFromMetallicReflectanceTexture=!1,this.ambientColor=new ge(0,0,0),this.albedoColor=new ge(1,1,1),this.baseWeight=1,this.reflectivityColor=new ge(1,1,1),this.reflectionColor=new ge(1,1,1),this.emissiveColor=new ge(0,0,0),this.microSurface=1,this.useLightmapAsShadowmap=!1,this.useAlphaFromAlbedoTexture=!1,this.forceAlphaTest=!1,this.alphaCutOff=.4,this.useSpecularOverAlpha=!0,this.useMicroSurfaceFromReflectivityMapAlpha=!1,this.useRoughnessFromMetallicTextureAlpha=!0,this.useRoughnessFromMetallicTextureGreen=!1,this.useMetallnessFromMetallicTextureBlue=!1,this.useAmbientOcclusionFromMetallicTextureRed=!1,this.useAmbientInGrayScale=!1,this.useAutoMicroSurfaceFromReflectivityMap=!1,this.useRadianceOverAlpha=!0,this.useObjectSpaceNormalMap=!1,this.useParallax=!1,this.useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this.disableLighting=!1,this.forceIrradianceInFragment=!1,this.maxSimultaneousLights=4,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.twoSidedLighting=!1,this.useAlphaFresnel=!1,this.useLinearAlphaFresnel=!1,this.environmentBRDFTexture=null,this.forceNormalForward=!1,this.enableSpecularAntiAliasing=!1,this.useHorizonOcclusion=!0,this.useRadianceOcclusion=!0,this.unlit=!1,this.applyDecalMapAfterDetailMap=!1,this._environmentBRDFTexture=vR(this.getScene())}getClassName(){return"PBRMaterial"}clone(e,t=!0,i=""){let r=it.Clone(()=>new n(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return r.id=e,r.name=e,this.stencil.copyTo(r.stencil),this._clonePlugins(r,i),r}serialize(){let e=super.serialize();return e.customType="BABYLON.PBRMaterial",e}static Parse(e,t,i){let r=it.Parse(()=>new n(e.name,t),e,t,i);return e.stencil&&r.stencil.parse(e.stencil,t,i),Ee._ParsePlugins(e,r,t,i),e.clearCoat&&r.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&r.anisotropy.parse(e.anisotropy,t,i),e.brdf&&r.brdf.parse(e.brdf,t,i),e.sheen&&r.sheen.parse(e.sheen,t,i),e.subSurface&&r.subSurface.parse(e.subSurface,t,i),e.iridescence&&r.iridescence.parse(e.iridescence,t,i),r}};ht.PBRMATERIAL_OPAQUE=vr.PBRMATERIAL_OPAQUE;ht.PBRMATERIAL_ALPHATEST=vr.PBRMATERIAL_ALPHATEST;ht.PBRMATERIAL_ALPHABLEND=vr.PBRMATERIAL_ALPHABLEND;ht.PBRMATERIAL_ALPHATESTANDBLEND=vr.PBRMATERIAL_ALPHATESTANDBLEND;ht.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=vr.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;P([w(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"directIntensity",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"emissiveIntensity",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"environmentIntensity",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"specularIntensity",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"disableBumpMap",void 0);P([Bt(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"albedoTexture",void 0);P([Bt(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"baseWeightTexture",void 0);P([Bt(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"baseDiffuseRoughnessTexture",void 0);P([Bt(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"ambientTexture",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"ambientTextureStrength",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"ambientTextureImpactOnAnalyticalLights",void 0);P([Bt(),oe("_markAllSubMeshesAsTexturesAndMiscDirty")],ht.prototype,"opacityTexture",void 0);P([Bt(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"reflectionTexture",void 0);P([Bt(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"emissiveTexture",void 0);P([Bt(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"reflectivityTexture",void 0);P([Bt(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"metallicTexture",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"metallic",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"roughness",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"metallicF0Factor",void 0);P([_r(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"metallicReflectanceColor",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"useOnlyMetallicFromMetallicReflectanceTexture",void 0);P([Bt(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"metallicReflectanceTexture",void 0);P([Bt(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"reflectanceTexture",void 0);P([Bt(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"microSurfaceTexture",void 0);P([Bt(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"bumpTexture",void 0);P([Bt(),oe("_markAllSubMeshesAsTexturesDirty",null)],ht.prototype,"lightmapTexture",void 0);P([_r("ambient"),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"ambientColor",void 0);P([_r("albedo"),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"albedoColor",void 0);P([w("baseWeight"),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"baseWeight",void 0);P([w("baseDiffuseRoughness"),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"baseDiffuseRoughness",void 0);P([_r("reflectivity"),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"reflectivityColor",void 0);P([_r("reflection"),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"reflectionColor",void 0);P([_r("emissive"),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"emissiveColor",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"microSurface",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"useLightmapAsShadowmap",void 0);P([w(),oe("_markAllSubMeshesAsTexturesAndMiscDirty")],ht.prototype,"useAlphaFromAlbedoTexture",void 0);P([w(),oe("_markAllSubMeshesAsTexturesAndMiscDirty")],ht.prototype,"forceAlphaTest",void 0);P([w(),oe("_markAllSubMeshesAsTexturesAndMiscDirty")],ht.prototype,"alphaCutOff",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"useSpecularOverAlpha",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"useRoughnessFromMetallicTextureAlpha",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"useRoughnessFromMetallicTextureGreen",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"useMetallnessFromMetallicTextureBlue",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"useAmbientInGrayScale",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0);P([w()],ht.prototype,"usePhysicalLightFalloff",null);P([w()],ht.prototype,"useGLTFLightFalloff",null);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"useRadianceOverAlpha",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"useObjectSpaceNormalMap",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"useParallax",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"useParallaxOcclusion",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"parallaxScaleBias",void 0);P([w(),oe("_markAllSubMeshesAsLightsDirty")],ht.prototype,"disableLighting",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"forceIrradianceInFragment",void 0);P([w(),oe("_markAllSubMeshesAsLightsDirty")],ht.prototype,"maxSimultaneousLights",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"invertNormalMapX",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"invertNormalMapY",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"twoSidedLighting",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"useAlphaFresnel",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"useLinearAlphaFresnel",void 0);P([oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"environmentBRDFTexture",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"forceNormalForward",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"enableSpecularAntiAliasing",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"useHorizonOcclusion",void 0);P([w(),oe("_markAllSubMeshesAsTexturesDirty")],ht.prototype,"useRadianceOcclusion",void 0);P([w(),oe("_markAllSubMeshesAsMiscDirty")],ht.prototype,"unlit",void 0);P([w(),oe("_markAllSubMeshesAsMiscDirty")],ht.prototype,"applyDecalMapAfterDetailMap",void 0);wt("BABYLON.PBRMaterial",ht)});var S9={};tt(S9,{PBRMaterialLoadingAdapter:()=>oO});var oO,T9=C(()=>{zt();GD();Ve();oO=class{constructor(e){this._material=e,this._material.enableSpecularAntiAliasing=!0}get material(){return this._material}get isUnlit(){return this._material.unlit}set isUnlit(e){this._material.unlit=e}set backFaceCulling(e){this._material.backFaceCulling=e}get backFaceCulling(){return this._material.backFaceCulling}set twoSidedLighting(e){this._material.twoSidedLighting=e}get twoSidedLighting(){return this._material.twoSidedLighting}set alphaCutOff(e){this._material.alphaCutOff=e}get alphaCutOff(){return this._material.alphaCutOff}set useAlphaFromBaseColorTexture(e){this._material.useAlphaFromAlbedoTexture=e}get useAlphaFromBaseColorTexture(){return this._material.useAlphaFromAlbedoTexture}get transparencyAsAlphaCoverage(){return this._material.useRadianceOverAlpha||this._material.useSpecularOverAlpha}set transparencyAsAlphaCoverage(e){this._material.useRadianceOverAlpha=!e,this._material.useSpecularOverAlpha=!e}set baseColor(e){this._material.albedoColor=e}get baseColor(){return this._material.albedoColor}set baseColorTexture(e){this._material.albedoTexture=e}get baseColorTexture(){return this._material.albedoTexture}set baseDiffuseRoughness(e){this._material.baseDiffuseRoughness=e,e>0&&(this._material.brdf.baseDiffuseModel=H.MATERIAL_DIFFUSE_MODEL_E_OREN_NAYAR)}get baseDiffuseRoughness(){var e;return(e=this._material.baseDiffuseRoughness)!=null?e:0}set baseDiffuseRoughnessTexture(e){this._material.baseDiffuseRoughnessTexture=e}get baseDiffuseRoughnessTexture(){return this._material.baseDiffuseRoughnessTexture}set baseMetalness(e){this._material.metallic=e}get baseMetalness(){var e;return(e=this._material.metallic)!=null?e:1}set baseMetalnessTexture(e){this._material.metallicTexture=e}get baseMetalnessTexture(){return this._material.metallicTexture}set useRoughnessFromMetallicTextureGreen(e){this._material.useRoughnessFromMetallicTextureGreen=e,this._material.useRoughnessFromMetallicTextureAlpha=!e}set useMetallicFromMetallicTextureBlue(e){this._material.useMetallnessFromMetallicTextureBlue=e}enableSpecularEdgeColor(e=!1){e&&(this._material.brdf.dielectricSpecularModel=H.MATERIAL_DIELECTRIC_SPECULAR_MODEL_OPENPBR,this._material.brdf.conductorSpecularModel=H.MATERIAL_CONDUCTOR_SPECULAR_MODEL_OPENPBR)}set specularWeight(e){this._material.metallicF0Factor=e}get specularWeight(){var e;return(e=this._material.metallicF0Factor)!=null?e:1}set specularWeightTexture(e){e?(this._material.metallicReflectanceTexture=e,this._material.useOnlyMetallicFromMetallicReflectanceTexture=!0):(this._material.metallicReflectanceTexture=null,this._material.useOnlyMetallicFromMetallicReflectanceTexture=!1)}get specularWeightTexture(){return this._material.metallicReflectanceTexture}set specularColor(e){this._material.metallicReflectanceColor=e}get specularColor(){return this._material.metallicReflectanceColor}set specularColorTexture(e){this._material.reflectanceTexture=e}get specularColorTexture(){return this._material.reflectanceTexture}set specularRoughness(e){this._material.roughness=e}get specularRoughness(){var e;return(e=this._material.roughness)!=null?e:1}set specularRoughnessTexture(e){this.baseMetalnessTexture||(this._material.metallicTexture=e)}get specularRoughnessTexture(){return this._material.metallicTexture}set specularIor(e){this._material.indexOfRefraction=e}get specularIor(){return this._material.indexOfRefraction}set emissionColor(e){this._material.emissiveColor=e}get emissionColor(){return this._material.emissiveColor}set emissionLuminance(e){this._material.emissiveIntensity=e}get emissionLuminance(){return this._material.emissiveIntensity}set emissionColorTexture(e){this._material.emissiveTexture=e}get emissionColorTexture(){return this._material.emissiveTexture}set ambientOcclusionTexture(e){this._material.ambientTexture=e,e&&(this._material.useAmbientInGrayScale=!0)}get ambientOcclusionTexture(){return this._material.ambientTexture}set ambientOcclusionTextureStrength(e){this._material.ambientTextureStrength=e}get ambientOcclusionTextureStrength(){var e;return(e=this._material.ambientTextureStrength)!=null?e:1}configureCoat(){this._material.clearCoat.isEnabled=!0,this._material.clearCoat.useRoughnessFromMainTexture=!1,this._material.clearCoat.remapF0OnInterfaceChange=!1}set coatWeight(e){this._material.clearCoat.isEnabled=!0,this._material.clearCoat.intensity=e}get coatWeight(){return this._material.clearCoat.intensity}set coatWeightTexture(e){this._material.clearCoat.isEnabled=!0,this._material.clearCoat.texture=e}get coatWeightTexture(){return this._material.clearCoat.texture}set coatColor(e){this._material.clearCoat.isTintEnabled=e!=ge.White(),this._material.clearCoat.tintColor=e}set coatColorTexture(e){this._material.clearCoat.tintTexture=e}set coatRoughness(e){this._material.clearCoat.isEnabled=!0,this._material.clearCoat.roughness=e}get coatRoughness(){var e;return(e=this._material.clearCoat.roughness)!=null?e:0}set coatRoughnessTexture(e){this._material.clearCoat.isEnabled=!0,this._material.clearCoat.useRoughnessFromMainTexture=!1,this._material.clearCoat.textureRoughness=e}get coatRoughnessTexture(){return this._material.clearCoat.textureRoughness}set coatIor(e){this._material.clearCoat.indexOfRefraction=e}set coatDarkening(e){}set coatDarkeningTexture(e){}set coatRoughnessAnisotropy(e){}get coatRoughnessAnisotropy(){return 0}set geometryCoatTangentAngle(e){}set geometryCoatTangentTexture(e){}get geometryCoatTangentTexture(){return null}set transmissionWeight(e){this._material.subSurface.isRefractionEnabled=e>0,this._material.subSurface.refractionIntensity=e}get transmissionWeight(){return this._material.subSurface.isRefractionEnabled?this._material.subSurface.refractionIntensity:0}set transmissionWeightTexture(e){this._material.subSurface.isRefractionEnabled=!0,this._material.subSurface.refractionIntensityTexture=e,this._material.subSurface.useGltfStyleTextures=!0}set transmissionDepth(e){this.transmissionWeight>0?this._material.subSurface.tintColorAtDistance=e:this.subsurfaceWeight>0&&this._material.subSurface.diffusionDistance.multiplyInPlace(new ge(e,e,e))}get transmissionDepth(){return this.transmissionWeight>0?this._material.subSurface.tintColorAtDistance:0}set transmissionColor(e){this.transmissionWeight>0?this._material.subSurface.tintColor=e:this.subsurfaceWeight>0&&this._material.subSurface.diffusionDistance.multiplyInPlace(e)}get transmissionColor(){return this.transmissionWeight>0?this._material.subSurface.tintColor:this.subsurfaceWeight>0?this._material.subSurface.diffusionDistance:new ge(0,0,0)}set transmissionScatter(e){this._material.subSurface.diffusionDistance=e}get transmissionScatter(){return this._material.subSurface.diffusionDistance}set transmissionScatterTexture(e){}set transmissionScatterAnisotropy(e){}set transmissionDispersionAbbeNumber(e){}set transmissionDispersionScale(e){e>0?(this._material.subSurface.isDispersionEnabled=!0,this._material.subSurface.dispersion=20/e):(this._material.subSurface.isDispersionEnabled=!1,this._material.subSurface.dispersion=0)}get refractionBackgroundTexture(){return this._material.subSurface.refractionTexture}set refractionBackgroundTexture(e){this._material.subSurface.refractionTexture=e}configureTransmission(){this._material.subSurface.volumeIndexOfRefraction=1,this._material.subSurface.useAlbedoToTintRefraction=!0,this._material.subSurface.minimumThickness=0,this._material.subSurface.maximumThickness=0}configureVolume(){}set geometryThinWalled(e){}get geometryThinWalled(){return!0}set volumeThicknessTexture(e){this._material.subSurface.thicknessTexture=e,this._material.subSurface.useGltfStyleTextures=!0}set volumeThickness(e){this._material.subSurface.minimumThickness=0,this._material.subSurface.maximumThickness=e,this._material.subSurface.useThicknessAsDepth=!0,e>0&&(this._material.subSurface.volumeIndexOfRefraction=this._material.indexOfRefraction)}configureSubsurface(){this._material.subSurface.useGltfStyleTextures=!0,this._material.subSurface.volumeIndexOfRefraction=1,this._material.subSurface.minimumThickness=0,this._material.subSurface.maximumThickness=0,this._material.subSurface.useAlbedoToTintTranslucency=!1}set subsurfaceWeight(e){this._material.subSurface.isTranslucencyEnabled=e>0,this._material.subSurface.translucencyIntensity=e}get subsurfaceWeight(){return this._material.subSurface.isTranslucencyEnabled?this._material.subSurface.translucencyIntensity:0}set subsurfaceWeightTexture(e){this._material.subSurface.translucencyIntensityTexture=e}set subsurfaceColor(e){let t=new b(-Math.log(this.transmissionColor.r),-Math.log(this.transmissionColor.g),-Math.log(this.transmissionColor.b));t.scaleInPlace(1/Math.max(this.transmissionDepth,.001));let i=t,r=Math.max(i.x,Math.max(i.y,i.z)),s=r>0?1/r:1;this._material.subSurface.diffusionDistance=new ge(Math.exp(-i.x*s),Math.exp(-i.y*s),Math.exp(-i.z*s))}set subsurfaceColorTexture(e){}set diffuseTransmissionTint(e){this._material.subSurface.tintColor=e}get diffuseTransmissionTint(){return this._material.subSurface.tintColor}set diffuseTransmissionTintTexture(e){this._material.subSurface.translucencyColorTexture=e}get subsurfaceRadius(){return 1}set subsurfaceRadius(e){}get subsurfaceRadiusScale(){var e;return(e=this._material.subSurface.scatteringDiffusionProfile)!=null?e:ge.White()}set subsurfaceRadiusScale(e){this._material.subSurface.scatteringDiffusionProfile=e}set subsurfaceScatterAnisotropy(e){}isTranslucent(){return this.transmissionWeight>0||this.subsurfaceWeight>0}configureFuzz(){this._material.sheen.isEnabled=!0,this._material.sheen.useRoughnessFromMainTexture=!1,this._material.sheen.albedoScaling=!0}set fuzzWeight(e){this._material.sheen.isEnabled=!0,this._material.sheen.intensity=e}set fuzzWeightTexture(e){this._material.sheen.texture||(this._material.sheen.texture=e)}set fuzzColor(e){this._material.sheen.isEnabled=!0,this._material.sheen.color=e}set fuzzColorTexture(e){this._material.sheen.texture=e}set fuzzRoughness(e){this._material.sheen.isEnabled=!0,this._material.sheen.roughness=e}set fuzzRoughnessTexture(e){this._material.sheen.isEnabled=!0,this._material.sheen.textureRoughness=e}set specularRoughnessAnisotropy(e){this._material.anisotropy.isEnabled=!0,this._material.anisotropy.intensity=e}get specularRoughnessAnisotropy(){return this._material.anisotropy.intensity}set geometryTangentAngle(e){this._material.anisotropy.isEnabled=!0,this._material.anisotropy.angle=e}set geometryTangentTexture(e){this._material.anisotropy.isEnabled=!0,this._material.anisotropy.texture=e}get geometryTangentTexture(){return this._material.anisotropy.texture}configureGltfStyleAnisotropy(e=!0){}set thinFilmWeight(e){this._material.iridescence.isEnabled=e>0,this._material.iridescence.intensity=e}set thinFilmIor(e){this._material.iridescence.indexOfRefraction=e}set thinFilmThicknessMinimum(e){this._material.iridescence.minimumThickness=e}set thinFilmThicknessMaximum(e){this._material.iridescence.maximumThickness=e}set thinFilmWeightTexture(e){this._material.iridescence.texture=e}set thinFilmThicknessTexture(e){this._material.iridescence.thicknessTexture=e}set unlit(e){this._material.unlit=e}set geometryOpacity(e){this._material.alpha=e}get geometryOpacity(){return this._material.alpha}set geometryNormalTexture(e){this._material.bumpTexture=e,this._material.forceIrradianceInFragment=!0}get geometryNormalTexture(){return this._material.bumpTexture}setNormalMapInversions(e,t){this._material.invertNormalMapX=e,this._material.invertNormalMapY=t}set geometryCoatNormalTexture(e){this._material.clearCoat.isEnabled=!0,this._material.clearCoat.bumpTexture=e}get geometryCoatNormalTexture(){return this._material.clearCoat.bumpTexture}set geometryCoatNormalTextureScale(e){this._material.clearCoat.bumpTexture&&(this._material.clearCoat.bumpTexture.level=e)}}});function xde(n){if(n.min&&n.max){let e=n.min,t=n.max,i=$.Vector3[0].copyFromFloats(e[0],e[1],e[2]),r=$.Vector3[1].copyFromFloats(t[0],t[1],t[2]);if(n.normalized&&n.componentType!==5126){let s=1;switch(n.componentType){case 5120:s=127;break;case 5121:s=255;break;case 5122:s=32767;break;case 5123:s=65535;break}let a=1/s;i.scaleInPlace(a),r.scaleInPlace(a)}return new un(i,r)}return null}var Tde,Ade,Kt,MR,A9=C(()=>{UX();Ve();zt();bi();sl();XX();hR();KX();Vn();Fr();qh();Gi();CA();gm();Ii();BD();qX();FD();Hl();yt();pm();VD();kD();JX();nm();e5();Tde=new zg(()=>Promise.resolve().then(()=>(s5(),n5))),Ade=new zg(()=>Promise.resolve().then(()=>(c5(),l5))),Kt=class{static Get(e,t,i){if(!t||i==null||!t[i])throw new Error(`${e}: Failed to find index (${i})`);return t[i]}static TryGet(e,t){return!e||t==null||!e[t]?null:e[t]}static Assign(e){if(e)for(let t=0;tt.dispose&&t.dispose()),this._extensions.length=0;for(let t of Array.from(this._materialAdapters))(e=t.finalize)==null||e.call(t);this._materialAdapters.clear(),this._gltf=null,this._bin=null,this._babylonScene=null,this._rootBabylonMesh=null,this._defaultBabylonMaterialData={},this._postSceneLoadActions.length=0,this._parent.dispose()}}async importMeshAsync(e,t,i,r,s,a,o=""){return await Promise.resolve().then(async()=>{this._babylonScene=t,this._assetContainer=i,this._loadData(r);let l=null;if(e){let c={};if(this._gltf.nodes)for(let h of this._gltf.nodes)h.name&&(c[h.name]=h.index);l=(e instanceof Array?e:[e]).map(h=>{let d=c[h];if(d===void 0)throw new Error(`Failed to find node '${h}'`);return d})}return await this._loadAsync(s,o,l,()=>({meshes:this._getMeshes(),particleSystems:[],skeletons:this._getSkeletons(),animationGroups:this._getAnimationGroups(),lights:this._babylonLights,transformNodes:this._getTransformNodes(),geometries:this._getGeometries(),spriteManagers:[]}))})}async loadAsync(e,t,i,r,s=""){return this._babylonScene=e,this._loadData(t),await this._loadAsync(i,s,null,()=>{})}async _loadAsync(e,t,i,r){return await Promise.resolve().then(async()=>{this._rootUrl=e,this._uniqueRootUrl=!e.startsWith("file:")&&t?e:`${e}${Date.now()}/`,this._fileName=t,this._allMaterialsDirtyRequired=!1,await this._loadExtensionsAsync(),!this.parent.skipMaterials&&this._pbrMaterialImpl==null&&(this.parent.useOpenPBR||this.isExtensionUsed("KHR_materials_openpbr")?this._pbrMaterialImpl={materialClass:(await Promise.resolve().then(()=>(h6(),f6))).OpenPBRMaterial,adapterClass:(await Promise.resolve().then(()=>(u6(),d6))).OpenPBRMaterialLoadingAdapter}:this._pbrMaterialImpl={materialClass:(await Promise.resolve().then(()=>(E9(),v9))).PBRMaterial,adapterClass:(await Promise.resolve().then(()=>(T9(),S9))).PBRMaterialLoadingAdapter});let s=`${ns[ns.LOADING]} => ${ns[ns.READY]}`,a=`${ns[ns.LOADING]} => ${ns[ns.COMPLETE]}`;this._parent._startPerformanceCounter(s),this._parent._startPerformanceCounter(a),this._parent._setState(ns.LOADING),this._extensionsOnLoading();let o=new Array,l=this._babylonScene.blockMaterialDirtyMechanism;if(this._babylonScene.blockMaterialDirtyMechanism=!0,!this.parent.loadOnlyMaterials){if(i)o.push(this.loadSceneAsync("/nodes",{nodes:i,index:-1}));else if(this._gltf.scene!=null||this._gltf.scenes&&this._gltf.scenes[0]){let f=Kt.Get("/scene",this._gltf.scenes,this._gltf.scene||0);o.push(this.loadSceneAsync(`/scenes/${f.index}`,f))}}if(!this.parent.skipMaterials&&this.parent.loadAllMaterials&&this._gltf.materials)for(let f=0;f{}))}return this._allMaterialsDirtyRequired?this._babylonScene.blockMaterialDirtyMechanism=l:this._babylonScene._forceBlockMaterialDirtyMechanism(l),this._parent.compileMaterials&&o.push(this._compileMaterialsAsync()),this._parent.compileShadowGenerators&&o.push(this._compileShadowGeneratorsAsync()),await Promise.all(o).then(()=>{this._rootBabylonMesh&&this._rootBabylonMesh!==this._parent.customRootNode&&this._rootBabylonMesh.setEnabled(!0);for(let f of this._babylonScene.materials){let h=f;h.maxSimultaneousLights!==void 0&&(h.maxSimultaneousLights=Math.max(h.maxSimultaneousLights,this._babylonScene.lights.length))}return this._extensionsOnReady(),this._parent._setState(ns.READY),this._skipStartAnimationStep||this._startAnimations(),r()}).then(f=>(this._parent._endPerformanceCounter(s),pe.SetImmediate(()=>{this._disposed||Promise.all(this._completePromises).then(()=>{this._parent._endPerformanceCounter(a),this._parent._setState(ns.COMPLETE),this._parent.onCompleteObservable.notifyObservers(void 0),this._parent.onCompleteObservable.clear(),this.dispose()},h=>{this._parent.onErrorObservable.notifyObservers(h),this._parent.onErrorObservable.clear(),this.dispose()})}),f))}).catch(s=>{throw this._disposed||(this._parent.onErrorObservable.notifyObservers(s),this._parent.onErrorObservable.clear(),this.dispose()),s})}_loadData(e){if(this._gltf=e.json,this._setupData(),e.bin){let t=this._gltf.buffers;if(t&&t[0]&&!t[0].uri){let i=t[0];(i.byteLengthe.bin.byteLength)&&te.Warn(`Binary buffer length (${i.byteLength}) from JSON does not match chunk length (${e.bin.byteLength})`),this._bin=e.bin}else te.Warn("Unexpected BIN chunk")}}_setupData(){if(Kt.Assign(this._gltf.accessors),Kt.Assign(this._gltf.animations),Kt.Assign(this._gltf.buffers),Kt.Assign(this._gltf.bufferViews),Kt.Assign(this._gltf.cameras),Kt.Assign(this._gltf.images),Kt.Assign(this._gltf.materials),Kt.Assign(this._gltf.meshes),Kt.Assign(this._gltf.nodes),Kt.Assign(this._gltf.samplers),Kt.Assign(this._gltf.scenes),Kt.Assign(this._gltf.skins),Kt.Assign(this._gltf.textures),this._gltf.nodes){let e={};for(let i of this._gltf.nodes)if(i.children)for(let r of i.children)e[r]=i.index;let t=this._createRootNode();for(let i of this._gltf.nodes){let r=e[i.index];i.parent=r===void 0?t:this._gltf.nodes[r]}}}async _loadExtensionsAsync(){var t;let e=[];if(ZX.forEach((i,r)=>{var s;((s=this.parent.extensionOptions[r])==null?void 0:s.enabled)===!1?i.isGLTFExtension&&this.isExtensionUsed(r)&&te.Warn(`Extension ${r} is used but has been explicitly disabled.`):(!i.isGLTFExtension||this.isExtensionUsed(r))&&e.push((async()=>{let a=await i.factory(this);return a.name!==r&&te.Warn(`The name of the glTF loader extension instance does not match the registered name: ${a.name} !== ${r}`),this._parent.onExtensionLoadedObservable.notifyObservers(a),a})())}),this._extensions.push(...await Promise.all(e)),this._extensions.sort((i,r)=>(i.order||Number.MAX_VALUE)-(r.order||Number.MAX_VALUE)),this._parent.onExtensionLoadedObservable.clear(),this._gltf.extensionsRequired){for(let i of this._gltf.extensionsRequired)if(!this._extensions.some(s=>s.name===i&&s.enabled))throw((t=this.parent.extensionOptions[i])==null?void 0:t.enabled)===!1?new Error(`Required extension ${i} is disabled`):new Error(`Required extension ${i} is not available`)}}_createRootNode(){if(this._parent.customRootNode!==void 0)return this._rootBabylonMesh=this._parent.customRootNode,{_babylonTransformNode:this._rootBabylonMesh===null?void 0:this._rootBabylonMesh,index:-1};this._babylonScene._blockEntityCollection=!!this._assetContainer;let e=new Z("__root__",this._babylonScene);this._rootBabylonMesh=e,this._rootBabylonMesh._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._rootBabylonMesh.setEnabled(!1);let t={_babylonTransformNode:this._rootBabylonMesh,index:-1};switch(this._parent.coordinateSystemMode){case tp.AUTO:{this._babylonScene.useRightHandedSystem||(t.rotation=[0,1,0,0],t.scale=[1,1,-1],n._LoadTransform(t,this._rootBabylonMesh));break}case tp.FORCE_RIGHT_HANDED:{this._babylonScene.useRightHandedSystem=!0;break}default:throw new Error(`Invalid coordinate system mode (${this._parent.coordinateSystemMode})`)}return this._parent.onMeshLoadedObservable.notifyObservers(e),t}loadSceneAsync(e,t){let i=this._extensionsLoadSceneAsync(e,t);if(i)return i;let r=new Array;if(this.logOpen(`${e} ${t.name||""}`),t.nodes)for(let s of t.nodes){let a=Kt.Get(`${e}/nodes/${s}`,this._gltf.nodes,s);r.push(this.loadNodeAsync(`/nodes/${a.index}`,a,o=>{o.parent=this._rootBabylonMesh}))}for(let s of this._postSceneLoadActions)s();return r.push(this._loadAnimationsAsync()),this.logClose(),Promise.all(r).then(()=>{})}_forEachPrimitive(e,t){if(e._primitiveBabylonMeshes)for(let i of e._primitiveBabylonMeshes)t(i)}_getGeometries(){let e=[],t=this._gltf.nodes;if(t)for(let i of t)this._forEachPrimitive(i,r=>{let s=r.geometry;s&&e.indexOf(s)===-1&&e.push(s)});return e}_getMeshes(){let e=[];this._rootBabylonMesh instanceof gr&&e.push(this._rootBabylonMesh);let t=this._gltf.nodes;if(t)for(let i of t)this._forEachPrimitive(i,r=>{e.push(r)});return e}_getTransformNodes(){let e=[],t=this._gltf.nodes;if(t)for(let i of t)i._babylonTransformNode&&i._babylonTransformNode.getClassName()==="TransformNode"&&e.push(i._babylonTransformNode),i._babylonTransformNodeForSkin&&e.push(i._babylonTransformNodeForSkin);return e}_getSkeletons(){let e=[],t=this._gltf.skins;if(t)for(let i of t)i._data&&e.push(i._data.babylonSkeleton);return e}_getAnimationGroups(){let e=[],t=this._gltf.animations;if(t)for(let i of t)i._babylonAnimationGroup&&e.push(i._babylonAnimationGroup);return e}_startAnimations(){switch(this._parent.animationStartMode){case ld.NONE:break;case ld.FIRST:{let e=this._getAnimationGroups();e.length!==0&&e[0].start(!0);break}case ld.ALL:{let e=this._getAnimationGroups();for(let t of e)t.start(!0);break}default:{te.Error(`Invalid animation start mode (${this._parent.animationStartMode})`);return}}}loadNodeAsync(e,t,i=()=>{}){let r=this._extensionsLoadNodeAsync(e,t,i);if(r)return r;if(t._babylonTransformNode)throw new Error(`${e}: Invalid recursive node hierarchy`);let s=new Array;this.logOpen(`${e} ${t.name||""}`);let a=c=>{if(n.AddPointerMetadata(c,e),n._LoadTransform(t,c),t.camera!=null){let f=Kt.Get(`${e}/camera`,this._gltf.cameras,t.camera);s.push(this.loadCameraAsync(`/cameras/${f.index}`,f,h=>{h.parent=c,this._babylonScene.useRightHandedSystem||(c.scaling.x=-1)}))}if(t.children)for(let f of t.children){let h=Kt.Get(`${e}/children/${f}`,this._gltf.nodes,f);s.push(this.loadNodeAsync(`/nodes/${h.index}`,h,d=>{d.parent=c}))}i(c)},o=t.mesh!=null,l=this._parent.loadSkins&&t.skin!=null;if(!o||l){let c=t.name||`node${t.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;let f=new Jt(c,this._babylonScene);f._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t.mesh==null?t._babylonTransformNode=f:t._babylonTransformNodeForSkin=f,a(f)}if(o)if(l){let c=Kt.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);s.push(this._loadMeshAsync(`/meshes/${c.index}`,t,c,f=>{let h=t._babylonTransformNodeForSkin;f.metadata=WD(h.metadata,f.metadata||{});let d=Kt.Get(`${e}/skin`,this._gltf.skins,t.skin);s.push(this._loadSkinAsync(`/skins/${d.index}`,t,d,u=>{this._forEachPrimitive(t,m=>{m.skeleton=u}),this._postSceneLoadActions.push(()=>{if(d.skeleton!=null){let m=Kt.Get(`/skins/${d.index}/skeleton`,this._gltf.nodes,d.skeleton).parent;t.index===m.index?f.parent=h.parent:f.parent=m._babylonTransformNode}else f.parent=this._rootBabylonMesh;this._parent.onSkinLoadedObservable.notifyObservers({node:h,skinnedNode:f})})}))}))}else{let c=Kt.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);s.push(this._loadMeshAsync(`/meshes/${c.index}`,t,c,a))}return this.logClose(),Promise.all(s).then(()=>(this._forEachPrimitive(t,c=>{let f=c;!f.isAnInstance&&f.geometry&&f.geometry.useBoundingInfoFromGeometry?c._updateBoundingInfo():c.refreshBoundingInfo(!0,!0)}),t._babylonTransformNode))}_loadMeshAsync(e,t,i,r){let s=i.primitives;if(!s||!s.length)throw new Error(`${e}: Primitives are missing`);s[0].index==null&&Kt.Assign(s);let a=new Array;this.logOpen(`${e} ${i.name||""}`);let o=t.name||`node${t.index}`;if(s.length===1){let l=i.primitives[0];a.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${l.index}`,o,t,i,l,c=>{t._babylonTransformNode=c,t._primitiveBabylonMeshes=[c]}))}else{this._babylonScene._blockEntityCollection=!!this._assetContainer,t._babylonTransformNode=new Jt(o,this._babylonScene),t._babylonTransformNode._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._primitiveBabylonMeshes=[];for(let l of s)a.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${l.index}`,`${o}_primitive${l.index}`,t,i,l,c=>{c.parent=t._babylonTransformNode,t._primitiveBabylonMeshes.push(c)}))}return r(t._babylonTransformNode),this.logClose(),Promise.all(a).then(()=>t._babylonTransformNode)}_loadMeshPrimitiveAsync(e,t,i,r,s,a){let o=this._extensionsLoadMeshPrimitiveAsync(e,t,i,r,s,a);if(o)return o;this.logOpen(`${e}`);let l=this._disableInstancedMesh===0&&this._parent.createInstances&&i.skin==null&&!r.primitives[0].targets,c,f;if(l&&s._instanceData)this._babylonScene._blockEntityCollection=!!this._assetContainer,c=s._instanceData.babylonSourceMesh.createInstance(t),c._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,f=s._instanceData.promise;else{let h=new Array;this._babylonScene._blockEntityCollection=!!this._assetContainer;let d=new Z(t,this._babylonScene);if(d._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,d.sideOrientation=this._babylonScene.useRightHandedSystem?Ee.CounterClockWiseSideOrientation:Ee.ClockWiseSideOrientation,this._createMorphTargets(e,i,r,s,d),h.push(this._loadVertexDataAsync(e,s,d).then(async u=>await this._loadMorphTargetsAsync(e,s,d,u).then(()=>{this._disposed||(this._babylonScene._blockEntityCollection=!!this._assetContainer,u.applyToMesh(d),u._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1)}))),!this.parent.skipMaterials){let u=n._GetDrawMode(e,s.mode);if(s.material==null){let m=this._defaultBabylonMaterialData[u];m||(m=this._createDefaultMaterial("__GLTFLoader._default",u),this._parent.onMaterialLoadedObservable.notifyObservers(m),this._defaultBabylonMaterialData[u]=m),d.material=m}else{let m=Kt.Get(`${e}/material`,this._gltf.materials,s.material);h.push(this._loadMaterialAsync(`/materials/${m.index}`,m,d,u,p=>{d.material=p}))}}f=Promise.all(h),l&&(s._instanceData={babylonSourceMesh:d,promise:f}),c=d}return n.AddPointerMetadata(c,e),this._parent.onMeshLoadedObservable.notifyObservers(c),a(c),this.logClose(),f.then(()=>c)}_loadVertexDataAsync(e,t,i){let r=this._extensionsLoadVertexDataAsync(e,t,i);if(r)return r;let s=t.attributes;if(!s)throw new Error(`${e}: Attributes are missing`);let a=new Array,o=new mn(i.name,this._babylonScene);if(t.indices==null)i.isUnIndexed=!0;else{let c=Kt.Get(`${e}/indices`,this._gltf.accessors,t.indices);a.push(this._loadIndicesAccessorAsync(`/accessors/${c.index}`,c).then(f=>{o.setIndices(f)}))}let l=(c,f,h)=>{if(s[c]==null)return;i._delayInfo=i._delayInfo||[],i._delayInfo.indexOf(f)===-1&&i._delayInfo.push(f);let d=Kt.Get(`${e}/attributes/${c}`,this._gltf.accessors,s[c]);a.push(this._loadVertexAccessorAsync(`/accessors/${d.index}`,d,f).then(u=>{if(u.getKind()===L.PositionKind&&!this.parent.alwaysComputeBoundingBox&&!i.skeleton){let m=xde(d);m&&(o._boundingInfo=m,o.useBoundingInfoFromGeometry=!0)}o.setVerticesBuffer(u,d.count)})),f==L.MatricesIndicesExtraKind&&(i.numBoneInfluencers=8),h&&h(d)};return l("POSITION",L.PositionKind),l("NORMAL",L.NormalKind),l("TANGENT",L.TangentKind),l("TEXCOORD_0",L.UVKind),l("TEXCOORD_1",L.UV2Kind),l("TEXCOORD_2",L.UV3Kind),l("TEXCOORD_3",L.UV4Kind),l("TEXCOORD_4",L.UV5Kind),l("TEXCOORD_5",L.UV6Kind),l("JOINTS_0",L.MatricesIndicesKind),l("WEIGHTS_0",L.MatricesWeightsKind),l("JOINTS_1",L.MatricesIndicesExtraKind),l("WEIGHTS_1",L.MatricesWeightsExtraKind),l("COLOR_0",L.ColorKind,c=>{c.type==="VEC4"&&(i.hasVertexAlpha=!0)}),Promise.all(a).then(()=>o)}_createMorphTargets(e,t,i,r,s){if(!r.targets||!this._parent.loadMorphTargets)return;if(t._numMorphTargets==null)t._numMorphTargets=r.targets.length;else if(r.targets.length!==t._numMorphTargets)throw new Error(`${e}: Primitives do not have the same number of targets`);let a=i.extras?i.extras.targetNames:null;this._babylonScene._blockEntityCollection=!!this._assetContainer,s.morphTargetManager=new dd(this._babylonScene),s.morphTargetManager._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,s.morphTargetManager.areUpdatesFrozen=!0;for(let o=0;o{a.areUpdatesFrozen=!1})}async _loadMorphTargetVertexDataAsync(e,t,i,r){let s=new Array,a=(o,l,c)=>{if(i[o]==null)return;let f=t.getVertexBuffer(l);if(!f)return;let h=Kt.Get(`${e}/${o}`,this._gltf.accessors,i[o]);s.push(this._loadFloatAccessorAsync(`/accessors/${h.index}`,h).then(d=>{c(f,d)}))};return a("POSITION",L.PositionKind,(o,l)=>{let c=new Float32Array(l.length);o.forEach(l.length,(f,h)=>{c[h]=l[h]+f}),r.setPositions(c)}),a("NORMAL",L.NormalKind,(o,l)=>{let c=new Float32Array(l.length);o.forEach(c.length,(f,h)=>{c[h]=l[h]+f}),r.setNormals(c)}),a("TANGENT",L.TangentKind,(o,l)=>{let c=new Float32Array(l.length/3*4),f=0;o.forEach(l.length/3*4,(h,d)=>{(d+1)%4!==0&&(c[f]=l[f]+h,f++)}),r.setTangents(c)}),a("TEXCOORD_0",L.UVKind,(o,l)=>{let c=new Float32Array(l.length);o.forEach(l.length,(f,h)=>{c[h]=l[h]+f}),r.setUVs(c)}),a("TEXCOORD_1",L.UV2Kind,(o,l)=>{let c=new Float32Array(l.length);o.forEach(l.length,(f,h)=>{c[h]=l[h]+f}),r.setUV2s(c)}),a("COLOR_0",L.ColorKind,(o,l)=>{let c=null,f=o.getSize();if(f===3){c=new Float32Array(l.length/3*4),o.forEach(l.length,(h,d)=>{let u=Math.floor(d/3),m=d%3;c[4*u+m]=l[3*u+m]+h});for(let h=0;h{c[d]=l[d]+h});else throw new Error(`${e}: Invalid number of components (${f}) for COLOR_0 attribute`);r.setColors(c)}),await Promise.all(s).then(()=>{})}static _LoadTransform(e,t){if(e.skin!=null)return;let i=b.Zero(),r=Ye.Identity(),s=b.One();e.matrix?j.FromArray(e.matrix).decompose(s,r,i):(e.translation&&(i=b.FromArray(e.translation)),e.rotation&&(r=Ye.FromArray(e.rotation)),e.scale&&(s=b.FromArray(e.scale))),t.position=i,t.rotationQuaternion=r,t.scaling=s}_loadSkinAsync(e,t,i,r){if(!this._parent.loadSkins)return Promise.resolve();let s=this._extensionsLoadSkinAsync(e,t,i);if(s)return s;if(i._data)return r(i._data.babylonSkeleton),i._data.promise;let a=`skeleton${i.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;let o=new dR(i.name||a,a,this._babylonScene);o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._loadBones(e,i,o);let l=this._loadSkinInverseBindMatricesDataAsync(e,i).then(c=>{this._updateBoneMatrices(o,c)});return i._data={babylonSkeleton:o,promise:l},r(o),l}_loadBones(e,t,i){if(t.skeleton==null||this._parent.alwaysComputeSkeletonRootNode){let s=this._findSkeletonRootNode(`${e}/joints`,t.joints);if(s)if(t.skeleton===void 0)t.skeleton=s.index;else{let a=(l,c)=>{for(;c.parent;c=c.parent)if(c.parent===l)return!0;return!1},o=Kt.Get(`${e}/skeleton`,this._gltf.nodes,t.skeleton);o!==s&&!a(o,s)&&(te.Warn(`${e}/skeleton: Overriding with nearest common ancestor as skeleton node is not a common root`),t.skeleton=s.index)}else te.Warn(`${e}: Failed to find common root`)}let r={};for(let s of t.joints){let a=Kt.Get(`${e}/joints/${s}`,this._gltf.nodes,s);this._loadBone(a,t,i,r)}}_findSkeletonRootNode(e,t){if(t.length===0)return null;let i={};for(let s of t){let a=[],o=Kt.Get(`${e}/${s}`,this._gltf.nodes,s);for(;o.index!==-1;)a.unshift(o),o=o.parent;i[s]=a}let r=null;for(let s=0;;++s){let a=i[t[0]];if(s>=a.length)return r;let o=a[s];for(let l=1;l=a.length||o!==a[s])return r;r=o}}_loadBone(e,t,i,r){e._isJoint=!0;let s=r[e.index];if(s)return s;let a=null;e.index!==t.skeleton&&(e.parent&&e.parent.index!==-1?a=this._loadBone(e.parent,t,i,r):t.skeleton!==void 0&&te.Warn(`/skins/${t.index}/skeleton: Skeleton node is not a common root`));let o=t.joints.indexOf(e.index);return s=new Fa(e.name||`joint${e.index}`,i,a,this._getNodeMatrix(e),null,null,o),r[e.index]=s,this._postSceneLoadActions.push(()=>{s.linkTransformNode(e._babylonTransformNode)}),s}_loadSkinInverseBindMatricesDataAsync(e,t){if(t.inverseBindMatrices==null)return Promise.resolve(null);let i=Kt.Get(`${e}/inverseBindMatrices`,this._gltf.accessors,t.inverseBindMatrices);return this._loadFloatAccessorAsync(`/accessors/${i.index}`,i)}_updateBoneMatrices(e,t){for(let i of e.bones){let r=j.Identity(),s=i._index;t&&s!==-1&&(j.FromArrayToRef(t,s*16,r),r.invertToRef(r));let a=i.getParent();a&&r.multiplyToRef(a.getAbsoluteInverseBindMatrix(),r),i.updateMatrix(r,!1,!1),i._updateAbsoluteBindMatrices(void 0,!1)}}_getNodeMatrix(e){return e.matrix?j.FromArray(e.matrix):j.Compose(e.scale?b.FromArray(e.scale):b.One(),e.rotation?Ye.FromArray(e.rotation):Ye.Identity(),e.translation?b.FromArray(e.translation):b.Zero())}loadCameraAsync(e,t,i=()=>{}){let r=this._extensionsLoadCameraAsync(e,t,i);if(r)return r;let s=new Array;this.logOpen(`${e} ${t.name||""}`),this._babylonScene._blockEntityCollection=!!this._assetContainer;let a=new xc(t.name||`camera${t.index}`,b.Zero(),this._babylonScene,!1);switch(a._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._babylonCamera=a,a.setTarget(new b(0,0,-1)),t.type){case"perspective":{let o=t.perspective;if(!o)throw new Error(`${e}: Camera perspective properties are missing`);a.fov=o.yfov,a.minZ=o.znear,a.maxZ=o.zfar||0;break}case"orthographic":{if(!t.orthographic)throw new Error(`${e}: Camera orthographic properties are missing`);a.mode=ut.ORTHOGRAPHIC_CAMERA,a.orthoLeft=-t.orthographic.xmag,a.orthoRight=t.orthographic.xmag,a.orthoBottom=-t.orthographic.ymag,a.orthoTop=t.orthographic.ymag,a.minZ=t.orthographic.znear,a.maxZ=t.orthographic.zfar;break}default:throw new Error(`${e}: Invalid camera type (${t.type})`)}return n.AddPointerMetadata(a,e),this._parent.onCameraLoadedObservable.notifyObservers(a),i(a),this.logClose(),Promise.all(s).then(()=>a)}_loadAnimationsAsync(){this._parent._startPerformanceCounter("Load animations");let e=this._gltf.animations;if(!e)return Promise.resolve();let t=new Array;for(let i=0;i{s.targetedAnimations.length===0&&s.dispose()}))}return Promise.all(t).then(()=>{this._parent._endPerformanceCounter("Load animations")})}loadAnimationAsync(e,t){this._parent._startPerformanceCounter("Load animation");let i=this._extensionsLoadAnimationAsync(e,t);return i||Tde.value.then(({AnimationGroup:r})=>{this._babylonScene._blockEntityCollection=!!this._assetContainer;let s=new r(t.name||`animation${t.index}`,this._babylonScene);s._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._babylonAnimationGroup=s;let a=new Array;Kt.Assign(t.channels),Kt.Assign(t.samplers);for(let o of t.channels)a.push(this._loadAnimationChannelAsync(`${e}/channels/${o.index}`,e,t,o,(l,c)=>{l.animations=l.animations||[],l.animations.push(c),s.addTargetedAnimation(c,l)}));return this._parent._endPerformanceCounter("Load animation"),Promise.all(a).then(()=>(s.normalize(0),s))})}_loadAnimationChannelAsync(e,t,i,r,s){let a=this._extensionsLoadAnimationChannelAsync(e,t,i,r,s);if(a)return a;if(r.target.node==null)return Promise.resolve();let o=Kt.Get(`${e}/target/node`,this._gltf.nodes,r.target.node),l=r.target.path,c=l==="weights";return c&&!o._numMorphTargets||!c&&!o._babylonTransformNode||!this._parent.loadNodeAnimations&&!c&&!o._isJoint?Promise.resolve():Ade.value.then(()=>{var d,u,m,p;let f;switch(l){case"translation":{f=(d=Wg("/nodes/{}/translation"))==null?void 0:d.interpolation;break}case"rotation":{f=(u=Wg("/nodes/{}/rotation"))==null?void 0:u.interpolation;break}case"scale":{f=(m=Wg("/nodes/{}/scale"))==null?void 0:m.interpolation;break}case"weights":{f=(p=Wg("/nodes/{}/weights"))==null?void 0:p.interpolation;break}default:throw new Error(`${e}/target/path: Invalid value (${r.target.path})`)}if(!f)throw new Error(`${e}/target/path: Could not find interpolation properties for target path (${r.target.path})`);let h={object:o,info:f};return this._loadAnimationChannelFromTargetInfoAsync(e,t,i,r,h,s)})}_loadAnimationChannelFromTargetInfoAsync(e,t,i,r,s,a){let o=this.parent.targetFps,l=1/o,c=Kt.Get(`${e}/sampler`,i.samplers,r.sampler);return this._loadAnimationSamplerAsync(`${t}/samplers/${r.sampler}`,c).then(f=>{let h=0,d=s.object,u=s.info;for(let m of u){let p=m.getStride(d),_=f.input,g=f.output,v=new Array(_.length),x=0;switch(f.interpolation){case"STEP":{for(let A=0;A<_.length;A++){let S=m.getValue(d,g,x,1);x+=p,v[A]={frame:_[A]*o,value:S,interpolation:1}}break}case"CUBICSPLINE":{for(let A=0;A<_.length;A++){let S=m.getValue(d,g,x,l);x+=p;let E=m.getValue(d,g,x,1);x+=p;let R=m.getValue(d,g,x,l);x+=p,v[A]={frame:_[A]*o,inTangent:S,value:E,outTangent:R}}break}case"LINEAR":{for(let A=0;A<_.length;A++){let S=m.getValue(d,g,x,1);x+=p,v[A]={frame:_[A]*o,value:S}}break}}if(x>0){let A=`${i.name||`animation${i.index}`}_channel${r.index}_${h}`,S=m.buildAnimations(d,A,o,v);for(let E of S)h++,a(E.babylonAnimatable,E.babylonAnimation)}}})}_loadAnimationSamplerAsync(e,t){if(t._data)return t._data;let i=t.interpolation||"LINEAR";switch(i){case"STEP":case"LINEAR":case"CUBICSPLINE":break;default:throw new Error(`${e}/interpolation: Invalid value (${t.interpolation})`)}let r=Kt.Get(`${e}/input`,this._gltf.accessors,t.input),s=Kt.Get(`${e}/output`,this._gltf.accessors,t.output);return t._data=Promise.all([this._loadFloatAccessorAsync(`/accessors/${r.index}`,r),this._loadFloatAccessorAsync(`/accessors/${s.index}`,s)]).then(([a,o])=>({input:a,interpolation:i,output:o})),t._data}loadBufferAsync(e,t,i,r){let s=this._extensionsLoadBufferAsync(e,t,i,r);if(s)return s;if(!t._data)if(t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{if(!this._bin)throw new Error(`${e}: Uri is missing or the binary glTF is missing its binary chunk`);t._data=this._bin.readAsync(0,t.byteLength)}return t._data.then(a=>{try{return new Uint8Array(a.buffer,a.byteOffset+i,r)}catch(o){throw new Error(`${e}: ${o.message}`,{cause:o})}})}loadBufferViewAsync(e,t){let i=this._extensionsLoadBufferViewAsync(e,t);if(i)return i;if(t._data)return t._data;let r=Kt.Get(`${e}/buffer`,this._gltf.buffers,t.buffer);return t._data=this.loadBufferAsync(`/buffers/${r.index}`,r,t.byteOffset||0,t.byteLength),t._data}_loadAccessorAsync(e,t,i){if(t._data)return t._data;let r=n._GetNumComponents(e,t.type),s=r*L.GetTypeByteLength(t.componentType),a=r*t.count;if(t.bufferView==null)t._data=Promise.resolve(new i(a));else{let o=Kt.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${o.index}`,o).then(l=>{if(t.componentType===5126&&!t.normalized&&(!o.byteStride||o.byteStride===s))return n._GetTypedArray(e,t.componentType,l,t.byteOffset,a);{let c=new i(a);return L.ForEach(l,t.byteOffset||0,o.byteStride||s,r,t.componentType,c.length,t.normalized||!1,(f,h)=>{c[h]=f}),c}})}if(t.sparse){let o=t.sparse;t._data=t._data.then(l=>{let c=l,f=Kt.Get(`${e}/sparse/indices/bufferView`,this._gltf.bufferViews,o.indices.bufferView),h=Kt.Get(`${e}/sparse/values/bufferView`,this._gltf.bufferViews,o.values.bufferView);return Promise.all([this.loadBufferViewAsync(`/bufferViews/${f.index}`,f),this.loadBufferViewAsync(`/bufferViews/${h.index}`,h)]).then(([d,u])=>{let m=n._GetTypedArray(`${e}/sparse/indices`,o.indices.componentType,d,o.indices.byteOffset,o.count),p=r*o.count,_;if(t.componentType===5126&&!t.normalized)_=n._GetTypedArray(`${e}/sparse/values`,t.componentType,u,o.values.byteOffset,p);else{let v=n._GetTypedArray(`${e}/sparse/values`,t.componentType,u,o.values.byteOffset,p);_=new i(p),L.ForEach(v,0,s,r,t.componentType,_.length,t.normalized||!1,(x,A)=>{_[A]=x})}let g=0;for(let v=0;vn._GetTypedArray(e,t.componentType,r,t.byteOffset,t.count))}return t._data}_loadVertexBufferViewAsync(e){if(e._babylonBuffer)return e._babylonBuffer;let t=this._babylonScene.getEngine();return e._babylonBuffer=this.loadBufferViewAsync(`/bufferViews/${e.index}`,e).then(i=>new ro(t,i,!1)),e._babylonBuffer}_loadVertexAccessorAsync(e,t,i){var s;if((s=t._babylonVertexBuffer)!=null&&s[i])return t._babylonVertexBuffer[i];t._babylonVertexBuffer||(t._babylonVertexBuffer={});let r=this._babylonScene.getEngine();if(t.sparse||t.bufferView==null)t._babylonVertexBuffer[i]=this._loadFloatAccessorAsync(e,t).then(a=>new L(r,a,i,!1));else{let a=Kt.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._babylonVertexBuffer[i]=this._loadVertexBufferViewAsync(a).then(o=>{let l=n._GetNumComponents(e,t.type);return new L(r,o,i,!1,void 0,a.byteStride,void 0,t.byteOffset,l,t.componentType,t.normalized,!0,void 0,!0)})}return t._babylonVertexBuffer[i]}_loadMaterialMetallicRoughnessPropertiesAsync(e,t,i){let r=new Array,s=this._getOrCreateMaterialAdapter(i);return t&&(t.baseColorFactor?(s.baseColor=ge.FromArray(t.baseColorFactor),s.geometryOpacity=t.baseColorFactor[3]):s.baseColor=ge.White(),s.baseMetalness=t.metallicFactor==null?1:t.metallicFactor,s.specularRoughness=t.roughnessFactor==null?1:t.roughnessFactor,t.baseColorTexture&&r.push(this.loadTextureInfoAsync(`${e}/baseColorTexture`,t.baseColorTexture,a=>{a.name=`${i.name} (Base Color)`,s.baseColorTexture=a})),t.metallicRoughnessTexture&&(t.metallicRoughnessTexture.nonColorData=!0,r.push(this.loadTextureInfoAsync(`${e}/metallicRoughnessTexture`,t.metallicRoughnessTexture,a=>{a.name=`${i.name} (Metallic Roughness)`,s.baseMetalnessTexture=a,s.specularRoughnessTexture=a})),s.useRoughnessFromMetallicTextureGreen=!0,s.useMetallicFromMetallicTextureBlue=!0)),Promise.all(r).then(()=>{})}_loadMaterialAsync(e,t,i,r,s=()=>{}){let a=this._extensionsLoadMaterialAsync(e,t,i,r,s);if(a)return a;t._data=t._data||{};let o=t._data[r];if(!o){this.logOpen(`${e} ${t.name||""}`);let l=this.createMaterial(e,t,r);o={babylonMaterial:l,babylonMeshes:[],promise:this.loadMaterialPropertiesAsync(e,t,l)},t._data[r]=o,n.AddPointerMetadata(l,e),this._parent.onMaterialLoadedObservable.notifyObservers(l),this.logClose()}return i&&(o.babylonMeshes.push(i),i.onDisposeObservable.addOnce(()=>{let l=o.babylonMeshes.indexOf(i);l!==-1&&o.babylonMeshes.splice(l,1)})),s(o.babylonMaterial),o.promise.then(()=>o.babylonMaterial)}_createDefaultMaterial(e,t){if(!this._pbrMaterialImpl)throw new Error("PBR Material class not loaded");this._babylonScene._blockEntityCollection=!!this._assetContainer;let i=new this._pbrMaterialImpl.materialClass(e,this._babylonScene);i._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,i.fillMode=t,i.transparencyMode=this._pbrMaterialImpl.materialClass.MATERIAL_OPAQUE;let r=this._getOrCreateMaterialAdapter(i);return r.transparencyAsAlphaCoverage=this._parent.transparencyAsCoverage,r.baseMetalness=1,r.specularRoughness=1,i}createMaterial(e,t,i){let r=this._extensionsCreateMaterial(e,t,i);if(r)return r;let s=t.name||`material${t.index}`;return this._createDefaultMaterial(s,i)}loadMaterialPropertiesAsync(e,t,i){let r=this._extensionsLoadMaterialPropertiesAsync(e,t,i);if(r)return r;let s=new Array;return s.push(this.loadMaterialBasePropertiesAsync(e,t,i)),t.pbrMetallicRoughness&&s.push(this._loadMaterialMetallicRoughnessPropertiesAsync(`${e}/pbrMetallicRoughness`,t.pbrMetallicRoughness,i)),this.loadMaterialAlphaProperties(e,t,i),Promise.all(s).then(()=>{})}loadMaterialBasePropertiesAsync(e,t,i){let r=new Array,s=this._getOrCreateMaterialAdapter(i);s.emissionColor=t.emissiveFactor?ge.FromArray(t.emissiveFactor):new ge(0,0,0),t.doubleSided&&(s.backFaceCulling=!1,s.twoSidedLighting=!0),t.normalTexture&&(t.normalTexture.nonColorData=!0,r.push(this.loadTextureInfoAsync(`${e}/normalTexture`,t.normalTexture,c=>{var f;c.name=`${i.name} (Normal)`,s.geometryNormalTexture=c,((f=t.normalTexture)==null?void 0:f.scale)!=null&&(c.level=t.normalTexture.scale)})),s.setNormalMapInversions(!this._babylonScene.useRightHandedSystem,this._babylonScene.useRightHandedSystem));let a,o=1,l;return t.occlusionTexture&&(t.occlusionTexture.nonColorData=!0,r.push(this.loadTextureInfoAsync(`${e}/occlusionTexture`,t.occlusionTexture,c=>{c.name=`${i.name} (Occlusion)`,a=c})),t.occlusionTexture.strength!=null&&(o=t.occlusionTexture.strength)),t.emissiveTexture&&r.push(this.loadTextureInfoAsync(`${e}/emissiveTexture`,t.emissiveTexture,c=>{c.name=`${i.name} (Emissive)`,l=c})),Promise.all(r).then(()=>{a&&(s.ambientOcclusionTexture=a,s.ambientOcclusionTextureStrength=o),l&&(s.emissionColorTexture=l)})}loadMaterialAlphaProperties(e,t,i){if(!this._pbrMaterialImpl)throw new Error(`${e}: Material type not supported`);let r=this._getOrCreateMaterialAdapter(i),s=r.baseColorTexture;switch(t.alphaMode||"OPAQUE"){case"OPAQUE":{i.transparencyMode=this._pbrMaterialImpl.materialClass.MATERIAL_OPAQUE,i.alpha=1;break}case"MASK":{i.transparencyMode=this._pbrMaterialImpl.materialClass.MATERIAL_ALPHATEST,r.alphaCutOff=t.alphaCutoff==null?.5:t.alphaCutoff,s&&(s.hasAlpha=!0);break}case"BLEND":{i.transparencyMode=this._pbrMaterialImpl.materialClass.MATERIAL_ALPHABLEND,s&&(s.hasAlpha=!0,r.useAlphaFromBaseColorTexture=!0);break}default:throw new Error(`${e}/alphaMode: Invalid value (${t.alphaMode})`)}}loadTextureInfoAsync(e,t,i=()=>{}){let r=this._extensionsLoadTextureInfoAsync(e,t,i);if(r)return r;if(this.logOpen(`${e}`),t.texCoord>=6)throw new Error(`${e}/texCoord: Invalid value (${t.texCoord})`);let s=Kt.Get(`${e}/index`,this._gltf.textures,t.index);s._textureInfo=t;let a=this._loadTextureAsync(`/textures/${t.index}`,s,o=>{o.coordinatesIndex=t.texCoord||0,n.AddPointerMetadata(o,e),this._parent.onTextureLoadedObservable.notifyObservers(o),i(o)});return this.logClose(),a}_loadTextureAsync(e,t,i=()=>{}){let r=this._extensionsLoadTextureAsync(e,t,i);if(r)return r;this.logOpen(`${e} ${t.name||""}`);let s=t.sampler==null?n.DefaultSampler:Kt.Get(`${e}/sampler`,this._gltf.samplers,t.sampler),a=Kt.Get(`${e}/source`,this._gltf.images,t.source),o=this._createTextureAsync(e,s,a,i,void 0,!t._textureInfo.nonColorData);return this.logClose(),o}_createTextureAsync(e,t,i,r=()=>{},s,a){var m,p;let o=this._loadSampler(`/samplers/${t.index}`,t),l=new Array,c=new cR;this._babylonScene._blockEntityCollection=!!this._assetContainer;let f={noMipmap:o.noMipMaps,invertY:!1,samplingMode:o.samplingMode,onLoad:()=>{this._disposed||c.resolve()},onError:(_,g)=>{this._disposed||c.reject(new Error(`${e}: ${g&&g.message?g.message:_||"Failed to load texture"}`))},mimeType:(p=i.mimeType)!=null?p:F2((m=i.uri)!=null?m:""),loaderOptions:s,useSRGBBuffer:!!a&&this._parent.useSRGBBuffers},h=new _e(null,this._babylonScene,f);h._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,l.push(c.promise);let d=i.uri&&!hf(i.uri)?i.uri:void 0,u=d!=null?d:`${this._fileName}#image${i.index}`;if(l.push(this.loadImageAsync(`/images/${i.index}`,i).then(_=>{let g=`data:${this._uniqueRootUrl}${u}`;h.updateURL(g,_);let v=h.getInternalTexture();v&&(v.label=i.name)})),h.wrapU=o.wrapU,h.wrapV=o.wrapV,r(h),this._parent.useGltfTextureNames){let _=i.name||d||`image${i.index}`;h.name=_}return Promise.all(l).then(()=>h)}_loadSampler(e,t){return t._data||(t._data={noMipMaps:t.minFilter===9728||t.minFilter===9729,samplingMode:n._GetTextureSamplingMode(e,t),wrapU:n._GetTextureWrapMode(`${e}/wrapS`,t.wrapS),wrapV:n._GetTextureWrapMode(`${e}/wrapT`,t.wrapT)}),t._data}loadImageAsync(e,t){if(!t._data){if(this.logOpen(`${e} ${t.name||""}`),t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{let i=Kt.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${i.index}`,i)}this.logClose()}return t._data}loadUriAsync(e,t,i){let r=this._extensionsLoadUriAsync(e,t,i);if(r)return r;if(!n._ValidateUri(i))throw new Error(`${e}: '${i}' is invalid`);if(hf(i)){let s=new Uint8Array(df(i));return this.log(`${e}: Decoded ${i.substring(0,64)}... (${s.length} bytes)`),Promise.resolve(s)}return this.log(`${e}: Loading ${i}`),this._parent.preprocessUrlAsync(this._rootUrl+i).then(s=>new Promise((a,o)=>{this._parent._loadFile(this._babylonScene,s,l=>{this._disposed||(this.log(`${e}: Loaded ${i} (${l.byteLength} bytes)`),a(new Uint8Array(l)))},!0,l=>{o(new sm(`${e}: Failed to load '${i}'${l?": "+l.status+" "+l.statusText:""}`,l))})}))}static AddPointerMetadata(e,t){e.metadata=e.metadata||{};let i=e._internalMetadata=e._internalMetadata||{},r=i.gltf=i.gltf||{};(r.pointers=r.pointers||[]).push(t)}static _GetTextureWrapMode(e,t){switch(t=t==null?10497:t,t){case 33071:return _e.CLAMP_ADDRESSMODE;case 33648:return _e.MIRROR_ADDRESSMODE;case 10497:return _e.WRAP_ADDRESSMODE;default:return te.Warn(`${e}: Invalid value (${t})`),_e.WRAP_ADDRESSMODE}}static _GetTextureSamplingMode(e,t){let i=t.magFilter==null?9729:t.magFilter,r=t.minFilter==null?9987:t.minFilter;if(i===9729)switch(r){case 9728:return _e.LINEAR_NEAREST;case 9729:return _e.LINEAR_LINEAR;case 9984:return _e.LINEAR_NEAREST_MIPNEAREST;case 9985:return _e.LINEAR_LINEAR_MIPNEAREST;case 9986:return _e.LINEAR_NEAREST_MIPLINEAR;case 9987:return _e.LINEAR_LINEAR_MIPLINEAR;default:return te.Warn(`${e}/minFilter: Invalid value (${r})`),_e.LINEAR_LINEAR_MIPLINEAR}else switch(i!==9728&&te.Warn(`${e}/magFilter: Invalid value (${i})`),r){case 9728:return _e.NEAREST_NEAREST;case 9729:return _e.NEAREST_LINEAR;case 9984:return _e.NEAREST_NEAREST_MIPNEAREST;case 9985:return _e.NEAREST_LINEAR_MIPNEAREST;case 9986:return _e.NEAREST_NEAREST_MIPLINEAR;case 9987:return _e.NEAREST_LINEAR_MIPLINEAR;default:return te.Warn(`${e}/minFilter: Invalid value (${r})`),_e.NEAREST_NEAREST_MIPNEAREST}}static _GetTypedArrayConstructor(e,t){try{return UM(t)}catch(i){throw new Error(`${e}: ${i.message}`,{cause:i})}}static _GetTypedArray(e,t,i,r,s){let a=i.buffer;r=i.byteOffset+(r||0);let o=n._GetTypedArrayConstructor(`${e}/componentType`,t),l=L.GetTypeByteLength(t);return r%l!==0?(te.Warn(`${e}: Copying buffer as byte offset (${r}) is not a multiple of component type byte length (${l})`),new o(a.slice(r,r+s*l),0)):new o(a,r,s)}static _GetNumComponents(e,t){switch(t){case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3;case"VEC4":return 4;case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16}throw new Error(`${e}: Invalid type (${t})`)}static _ValidateUri(e){return pe.IsBase64(e)||e.indexOf("..")===-1}static _GetDrawMode(e,t){switch(t==null&&(t=4),t){case 0:return Ee.PointListDrawMode;case 1:return Ee.LineListDrawMode;case 2:return Ee.LineLoopDrawMode;case 3:return Ee.LineStripDrawMode;case 4:return Ee.TriangleFillMode;case 5:return Ee.TriangleStripDrawMode;case 6:return Ee.TriangleFanDrawMode}throw new Error(`${e}: Invalid mesh primitive mode (${t})`)}_compileMaterialsAsync(){this._parent._startPerformanceCounter("Compile materials");let e=new Array;if(this._gltf.materials){for(let t of this._gltf.materials)if(t._data)for(let i in t._data){let r=t._data[i];for(let s of r.babylonMeshes){s.computeWorldMatrix(!0);let a=r.babylonMaterial;e.push(a.forceCompilationAsync(s)),e.push(a.forceCompilationAsync(s,{useInstances:!0})),this._parent.useClipPlane&&(e.push(a.forceCompilationAsync(s,{clipPlane:!0})),e.push(a.forceCompilationAsync(s,{clipPlane:!0,useInstances:!0})))}}}return Promise.all(e).then(()=>{this._parent._endPerformanceCounter("Compile materials")})}_compileShadowGeneratorsAsync(){this._parent._startPerformanceCounter("Compile shadow generators");let e=new Array,t=this._babylonScene.lights;for(let i of t){let r=i.getShadowGenerator();r&&e.push(r.forceCompilationAsync())}return Promise.all(e).then(()=>{this._parent._endPerformanceCounter("Compile shadow generators")})}_forEachExtensions(e){for(let t of this._extensions)t.enabled&&e(t)}_applyExtensions(e,t,i){for(let r of this._extensions)if(r.enabled){let s=`${r.name}.${t}`,a=e;a._activeLoaderExtensionFunctions=a._activeLoaderExtensionFunctions||{};let o=a._activeLoaderExtensionFunctions;if(!o[s]){o[s]=!0;try{let l=i(r);if(l)return l}finally{delete o[s]}}}return null}_extensionsOnLoading(){this._forEachExtensions(e=>e.onLoading&&e.onLoading())}_extensionsOnReady(){this._forEachExtensions(e=>e.onReady&&e.onReady())}_extensionsLoadSceneAsync(e,t){return this._applyExtensions(t,"loadScene",i=>i.loadSceneAsync&&i.loadSceneAsync(e,t))}_extensionsLoadNodeAsync(e,t,i){return this._applyExtensions(t,"loadNode",r=>r.loadNodeAsync&&r.loadNodeAsync(e,t,i))}_extensionsLoadCameraAsync(e,t,i){return this._applyExtensions(t,"loadCamera",r=>r.loadCameraAsync&&r.loadCameraAsync(e,t,i))}_extensionsLoadVertexDataAsync(e,t,i){return this._applyExtensions(t,"loadVertexData",r=>r._loadVertexDataAsync&&r._loadVertexDataAsync(e,t,i))}_extensionsLoadMeshPrimitiveAsync(e,t,i,r,s,a){return this._applyExtensions(s,"loadMeshPrimitive",o=>o._loadMeshPrimitiveAsync&&o._loadMeshPrimitiveAsync(e,t,i,r,s,a))}_extensionsLoadMaterialAsync(e,t,i,r,s){return this._applyExtensions(t,"loadMaterial",a=>a._loadMaterialAsync&&a._loadMaterialAsync(e,t,i,r,s))}_extensionsCreateMaterial(e,t,i){return this._applyExtensions(t,"createMaterial",r=>r.createMaterial&&r.createMaterial(e,t,i))}_extensionsLoadMaterialPropertiesAsync(e,t,i){return this._applyExtensions(t,"loadMaterialProperties",r=>r.loadMaterialPropertiesAsync&&r.loadMaterialPropertiesAsync(e,t,i))}_extensionsLoadTextureInfoAsync(e,t,i){return this._applyExtensions(t,"loadTextureInfo",r=>r.loadTextureInfoAsync&&r.loadTextureInfoAsync(e,t,i))}_extensionsLoadTextureAsync(e,t,i){return this._applyExtensions(t,"loadTexture",r=>r._loadTextureAsync&&r._loadTextureAsync(e,t,i))}_extensionsLoadAnimationAsync(e,t){return this._applyExtensions(t,"loadAnimation",i=>i.loadAnimationAsync&&i.loadAnimationAsync(e,t))}_extensionsLoadAnimationChannelAsync(e,t,i,r,s){return this._applyExtensions(i,"loadAnimationChannel",a=>a._loadAnimationChannelAsync&&a._loadAnimationChannelAsync(e,t,i,r,s))}_extensionsLoadSkinAsync(e,t,i){return this._applyExtensions(i,"loadSkin",r=>r._loadSkinAsync&&r._loadSkinAsync(e,t,i))}_extensionsLoadUriAsync(e,t,i){return this._applyExtensions(t,"loadUri",r=>r._loadUriAsync&&r._loadUriAsync(e,t,i))}_extensionsLoadBufferViewAsync(e,t){return this._applyExtensions(t,"loadBufferView",i=>i.loadBufferViewAsync&&i.loadBufferViewAsync(e,t))}_extensionsLoadBufferAsync(e,t,i,r){return this._applyExtensions(t,"loadBuffer",s=>s.loadBufferAsync&&s.loadBufferAsync(e,t,i,r))}static LoadExtensionAsync(e,t,i,r){if(!t.extensions)return null;let a=t.extensions[i];return a?r(`${e}/extensions/${i}`,a):null}static LoadExtraAsync(e,t,i,r){if(!t.extras)return null;let a=t.extras[i];return a?r(`${e}/extras/${i}`,a):null}isExtensionUsed(e){return!!this._gltf.extensionsUsed&&this._gltf.extensionsUsed.indexOf(e)!==-1}logOpen(e){this._parent._logOpen(e)}logClose(){this._parent._logClose()}log(e){this._parent._log(e)}startPerformanceCounter(e){this._parent._startPerformanceCounter(e)}endPerformanceCounter(e){this._parent._endPerformanceCounter(e)}};MR.DefaultSampler={index:-1};jf._CreateGLTF2Loader=n=>new MR(n)});var cO,lO,x9=C(()=>{VD();cO="ExtrasAsMetadata",lO=class{_assignExtras(e,t){if(t.extras&&Object.keys(t.extras).length>0){let i=e.metadata=e.metadata||{},r=i.gltf=i.gltf||{};r.extras=t.extras}}constructor(e){this.name=cO,this.enabled=!0,this._loader=e}dispose(){this._loader=null}loadNodeAsync(e,t,i){return this._loader.loadNodeAsync(e,t,r=>{this._assignExtras(r,t),i(r)})}loadCameraAsync(e,t,i){return this._loader.loadCameraAsync(e,t,r=>{this._assignExtras(r,t),i(r)})}createMaterial(e,t,i){let r=this._loader.createMaterial(e,t,i);return this._assignExtras(r,t),r}loadAnimationAsync(e,t){return this._loader.loadAnimationAsync(e,t).then(i=>(this._assignExtras(i,t),i))}};kg(cO);mR(cO,!1,n=>new lO(n))});var CR,R9=C(()=>{CR={name:"obj",extensions:".obj"}});var ud,b9=C(()=>{zt();Fr();Tc();ud=class n{constructor(){this.materials=[]}parseMTL(e,t,i,r){if(t instanceof ArrayBuffer)return;let s=t.split(` -`),a=/\s+/,o,l=null;for(let c=0;c=0?f.substring(0,h):f;d=d.toLowerCase();let u=h>=0?f.substring(h+1).trim():"";if(d==="newmtl")l&&this.materials.push(l),e._blockEntityCollection=!!r,l=new Ge(u,e),l._parentContainer=r,e._blockEntityCollection=!1;else if(d==="kd"&&l)o=u.split(a,3).map(parseFloat),l.diffuseColor=ge.FromArray(o);else if(d==="ka"&&l)o=u.split(a,3).map(parseFloat),l.ambientColor=ge.FromArray(o);else if(d==="ks"&&l)o=u.split(a,3).map(parseFloat),l.specularColor=ge.FromArray(o);else if(d==="ke"&&l)o=u.split(a,3).map(parseFloat),l.emissiveColor=ge.FromArray(o);else if(d==="ns"&&l)l.specularPower=parseFloat(u);else if(d==="d"&&l)l.alpha=parseFloat(u);else if(d==="map_ka"&&l)l.ambientTexture=n._GetTexture(i,u,e);else if(d==="map_kd"&&l)l.diffuseTexture=n._GetTexture(i,u,e);else if(d==="map_ks"&&l)l.specularTexture=n._GetTexture(i,u,e);else if(d!=="map_ns")if(d==="map_bump"&&l){let m=u.split(a),p=m.indexOf("-bm"),_=null;p>=0&&(_=m[p+1],m.splice(p,2)),l.bumpTexture=n._GetTexture(i,m.join(" "),e),l.bumpTexture&&_!==null&&(l.bumpTexture.level=parseFloat(_))}else d==="map_d"&&l&&(l.opacityTexture=n._GetTexture(i,u,e))}l&&this.materials.push(l)}static _GetTexture(e,t,i){if(!t)return null;let r=e;if(e==="file:"){let s=t.lastIndexOf("\\");s===-1&&(s=t.lastIndexOf("/")),s>-1?r+=t.substring(s+1):r+=t}else r+=t;return new _e(r,i,!1,n.INVERT_TEXTURE_Y)}};ud.INVERT_TEXTURE_Y=!0});var Kr,I9=C(()=>{Gi();Tc();zt();Ve();CA();Ii();hr();yt();Kr=class n{constructor(e,t,i){this._positions=[],this._normals=[],this._uvs=[],this._colors=[],this._extColors=[],this._meshesFromObj=[],this._indicesForBabylon=[],this._wrappedPositionForBabylon=[],this._wrappedUvsForBabylon=[],this._wrappedColorsForBabylon=[],this._wrappedNormalsForBabylon=[],this._tuplePosNorm=[],this._curPositionInIndices=0,this._hasMeshes=!1,this._unwrappedPositionsForBabylon=[],this._unwrappedColorsForBabylon=[],this._unwrappedNormalsForBabylon=[],this._unwrappedUVForBabylon=[],this._triangles=[],this._materialNameFromObj="",this._objMeshName="",this._increment=1,this._isFirstMaterial=!0,this._grayColor=new lt(.5,.5,.5,1),this._hasLineData=!1,this._materialToUse=e,this._babylonMeshesArray=t,this._loadingOptions=i}_isInArray(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[]});let i=e[t[0]].normals.indexOf(t[1]);return i===-1?-1:e[t[0]].idx[i]}_isInArrayUV(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[],uv:[]});let i=e[t[0]].normals.indexOf(t[1]);return i!=1&&t[2]===e[t[0]].uv[i]?e[t[0]].idx[i]:-1}_setData(e){var i,r;(i=e.indiceUvsFromObj)!=null||(e.indiceUvsFromObj=-1),(r=e.indiceNormalFromObj)!=null||(e.indiceNormalFromObj=-1);let t;this._loadingOptions.optimizeWithUV?t=this._isInArrayUV(this._tuplePosNorm,[e.indicePositionFromObj,e.indiceNormalFromObj,e.indiceUvsFromObj]):t=this._isInArray(this._tuplePosNorm,[e.indicePositionFromObj,e.indiceNormalFromObj]),t===-1?(this._indicesForBabylon.push(this._wrappedPositionForBabylon.length),this._wrappedPositionForBabylon.push(e.positionVectorFromOBJ),e.textureVectorFromOBJ!==void 0&&this._wrappedUvsForBabylon.push(e.textureVectorFromOBJ),e.normalsVectorFromOBJ!==void 0&&this._wrappedNormalsForBabylon.push(e.normalsVectorFromOBJ),e.positionColorsFromOBJ!==void 0&&this._wrappedColorsForBabylon.push(e.positionColorsFromOBJ),this._tuplePosNorm[e.indicePositionFromObj].normals.push(e.indiceNormalFromObj),this._tuplePosNorm[e.indicePositionFromObj].idx.push(this._curPositionInIndices++),this._loadingOptions.optimizeWithUV&&this._tuplePosNorm[e.indicePositionFromObj].uv.push(e.indiceUvsFromObj)):this._indicesForBabylon.push(t)}_unwrapData(){try{for(let e=0;e0&&(this._handledMesh=this._meshesFromObj[this._meshesFromObj.length-1],this._unwrapData(),this._loadingOptions.useLegacyBehavior&&this._indicesForBabylon.reverse(),this._handledMesh.indices=this._indicesForBabylon.slice(),this._handledMesh.positions=this._unwrappedPositionsForBabylon.slice(),this._unwrappedNormalsForBabylon.length&&(this._handledMesh.normals=this._unwrappedNormalsForBabylon.slice()),this._unwrappedUVForBabylon.length&&(this._handledMesh.uvs=this._unwrappedUVForBabylon.slice()),this._unwrappedColorsForBabylon.length&&(this._handledMesh.colors=this._unwrappedColorsForBabylon.slice()),this._handledMesh.hasLines=this._hasLineData,this._indicesForBabylon.length=0,this._unwrappedPositionsForBabylon.length=0,this._unwrappedColorsForBabylon.length=0,this._unwrappedNormalsForBabylon.length=0,this._unwrappedUVForBabylon.length=0,this._hasLineData=!1)}_optimizeNormals(e){let t=e.getVerticesData(L.PositionKind),i=e.getVerticesData(L.NormalKind),r={};if(!t||!i)return;for(let a=0;athis._triangles.push(d[0],d[u],d[u+1]),this._handednessSign=1):i.useRightHandedSystem?(this._pushTriangle=(d,u)=>this._triangles.push(d[0],d[u+1],d[u]),this._handednessSign=1):(this._pushTriangle=(d,u)=>this._triangles.push(d[0],d[u],d[u+1]),this._handednessSign=-1);let a=t.split(` -`),o=[],l=[];o.push(l);for(let d=0;d=7){let p=parseFloat(m[4]),_=parseFloat(m[5]),g=parseFloat(m[6]);this._colors.push(new lt(p>1?p/255:p,_>1?_/255:_,g>1?g/255:g,m.length===7||m[7]===void 0?1:parseFloat(m[7])))}else this._colors.push(this._grayColor)}else if((m=n.NormalPattern.exec(u))!==null)this._normals.push(new b(parseFloat(m[1]),parseFloat(m[2]),parseFloat(m[3])));else if((m=n.UVPattern.exec(u))!==null)this._uvs.push(new we(parseFloat(m[1])*this._loadingOptions.UVScaling.x,parseFloat(m[2])*this._loadingOptions.UVScaling.y));else if((m=n.FacePattern3.exec(u))!==null)this._setDataForCurrentFaceWithPattern3(m[1].trim().split(" "),1);else if((m=n.FacePattern4.exec(u))!==null)this._setDataForCurrentFaceWithPattern4(m[1].trim().split(" "),1);else if((m=n.FacePattern5.exec(u))!==null)this._setDataForCurrentFaceWithPattern5(m[1].trim().split(" "),1);else if((m=n.FacePattern2.exec(u))!==null)this._setDataForCurrentFaceWithPattern2(m[1].trim().split(" "),1);else if((m=n.FacePattern1.exec(u))!==null)this._setDataForCurrentFaceWithPattern1(m[1].trim().split(" "),1);else if((m=n.LinePattern1.exec(u))!==null)this._setDataForCurrentFaceWithPattern1(m[1].trim().split(" "),0),this._hasLineData=!0;else if((m=n.LinePattern2.exec(u))!==null)this._setDataForCurrentFaceWithPattern2(m[1].trim().split(" "),0),this._hasLineData=!0;else if(m=n._GetZbrushMRGB(u,!this._loadingOptions.importVertexColors))for(let p of m)this._extColors.push(p);else if((m=n.LinePattern3.exec(u))!==null)this._setDataForCurrentFaceWithPattern3(m[1].trim().split(" "),0),this._hasLineData=!0;else if(n.GroupDescriptor.test(u)||n.ObjectDescriptor.test(u)){let p={name:u.substring(2).trim(),indices:null,positions:null,normals:null,uvs:null,colors:null,materialName:this._materialNameFromObj,isObject:n.ObjectDescriptor.test(u)};this._addPreviousObjMesh(),this._meshesFromObj.push(p),this._hasMeshes=!0,this._isFirstMaterial=!0,this._increment=1}else if(n.UseMtlDescriptor.test(u)){if(this._materialNameFromObj=u.substring(7).trim(),!this._isFirstMaterial||!this._hasMeshes){this._addPreviousObjMesh();let p={name:(this._objMeshName||"mesh")+"_mm"+this._increment.toString(),indices:null,positions:null,normals:null,uvs:null,colors:null,materialName:this._materialNameFromObj,isObject:!1};this._increment++,this._meshesFromObj.push(p),this._hasMeshes=!0}this._hasMeshes&&this._isFirstMaterial&&(this._meshesFromObj[this._meshesFromObj.length-1].materialName=this._materialNameFromObj,this._isFirstMaterial=!1)}else n.MtlLibGroupDescriptor.test(u)?s(u.substring(7).trim()):n.SmoothDescriptor.test(u)||te.Log("Unhandled expression at line : "+u)}if(this._hasMeshes&&(this._handledMesh=this._meshesFromObj[this._meshesFromObj.length-1],this._loadingOptions.useLegacyBehavior&&this._indicesForBabylon.reverse(),this._unwrapData(),this._handledMesh.indices=this._indicesForBabylon,this._handledMesh.positions=this._unwrappedPositionsForBabylon,this._unwrappedNormalsForBabylon.length&&(this._handledMesh.normals=this._unwrappedNormalsForBabylon),this._unwrappedUVForBabylon.length&&(this._handledMesh.uvs=this._unwrappedUVForBabylon),this._unwrappedColorsForBabylon.length&&(this._handledMesh.colors=this._unwrappedColorsForBabylon),this._handledMesh.hasLines=this._hasLineData),!this._hasMeshes){let d=null;if(this._indicesForBabylon.length)this._loadingOptions.useLegacyBehavior&&this._indicesForBabylon.reverse(),this._unwrapData();else{for(let u of this._positions)this._unwrappedPositionsForBabylon.push(u.x,u.y,u.z);if(this._normals.length)for(let u of this._normals)this._unwrappedNormalsForBabylon.push(u.x,u.y,u.z);if(this._uvs.length)for(let u of this._uvs)this._unwrappedUVForBabylon.push(u.x,u.y);if(this._extColors.length)for(let u of this._extColors)this._unwrappedColorsForBabylon.push(u.r,u.g,u.b,u.a);else if(this._colors.length)for(let u of this._colors)this._unwrappedColorsForBabylon.push(u.r,u.g,u.b,u.a);this._materialNameFromObj||(d=new Ge(mn.RandomId(),i),d.pointsCloud=!0,this._materialNameFromObj=d.name,this._normals.length||(d.disableLighting=!0,d.emissiveColor=ge.White()))}this._meshesFromObj.push({name:mn.RandomId(),indices:this._indicesForBabylon,positions:this._unwrappedPositionsForBabylon,colors:this._unwrappedColorsForBabylon,normals:this._unwrappedNormalsForBabylon,uvs:this._unwrappedUVForBabylon,materialName:this._materialNameFromObj,directMaterial:d,isObject:!0,hasLines:this._hasLineData})}for(let d=0;d=0;--p)if(this._meshesFromObj[p].isObject&&this._meshesFromObj[p]._babylonMesh){u.parent=this._meshesFromObj[p]._babylonMesh;break}}if(this._materialToUse.push(this._meshesFromObj[d].materialName),this._handledMesh.hasLines&&((f=u._internalMetadata)!=null||(u._internalMetadata={}),u._internalMetadata._isLine=!0),((h=this._handledMesh.positions)==null?void 0:h.length)===0){this._babylonMeshesArray.push(u);continue}let m=new Me;if(m.indices=this._handledMesh.indices,m.positions=this._handledMesh.positions,this._loadingOptions.computeNormals||!this._handledMesh.normals){let p=new Array;Me.ComputeNormals(this._handledMesh.positions,this._handledMesh.indices,p),m.normals=p}else m.normals=this._handledMesh.normals;this._handledMesh.uvs&&(m.uvs=this._handledMesh.uvs),this._handledMesh.colors&&(m.colors=this._handledMesh.colors),m.applyToMesh(u),this._loadingOptions.invertY&&(u.scaling.y*=-1),this._loadingOptions.optimizeNormals&&this._optimizeNormals(u),this._babylonMeshesArray.push(u),this._handledMesh.directMaterial&&(u.material=this._handledMesh.directMaterial)}}};Kr.ObjectDescriptor=/^o/;Kr.GroupDescriptor=/^g/;Kr.MtlLibGroupDescriptor=/^mtllib /;Kr.UseMtlDescriptor=/^usemtl /;Kr.SmoothDescriptor=/^s /;Kr.VertexPattern=/^v(\s+[\d|.|+|\-|e|E]+){3,7}/;Kr.NormalPattern=/^vn(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/;Kr.UVPattern=/^vt(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/;Kr.FacePattern1=/^f\s+(([\d]{1,}[\s]?){3,})+/;Kr.FacePattern2=/^f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;Kr.FacePattern3=/^f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;Kr.FacePattern4=/^f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;Kr.FacePattern5=/^f\s+(((-[\d]{1,}\/-[\d]{1,}\/-[\d]{1,}[\s]?){3,})+)/;Kr.LinePattern1=/^l\s+(([\d]{1,}[\s]?){2,})+/;Kr.LinePattern2=/^l\s+((([\d]{1,}\/[\d]{1,}[\s]?){2,})+)/;Kr.LinePattern3=/^l\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){2,})+)/});var M9={};tt(M9,{OBJFileLoader:()=>Js});var Js,fO=C(()=>{Ve();bi();Jm();Ug();R9();b9();I9();Tc();Js=class n{static get INVERT_TEXTURE_Y(){return ud.INVERT_TEXTURE_Y}static set INVERT_TEXTURE_Y(e){ud.INVERT_TEXTURE_Y=e}constructor(e){this.name=CR.name,this.extensions=CR.extensions,this._assetContainer=null,this._loadingOptions={...n._DefaultLoadingOptions,...e!=null?e:{}}}static get _DefaultLoadingOptions(){return{computeNormals:n.COMPUTE_NORMALS,optimizeNormals:n.OPTIMIZE_NORMALS,importVertexColors:n.IMPORT_VERTEX_COLORS,invertY:n.INVERT_Y,invertTextureY:n.INVERT_TEXTURE_Y,UVScaling:n.UV_SCALING,materialLoadingFailsSilently:n.MATERIAL_LOADING_FAILS_SILENTLY,optimizeWithUV:n.OPTIMIZE_WITH_UV,skipMaterials:n.SKIP_MATERIALS,useLegacyBehavior:n.USE_LEGACY_BEHAVIOR}}_loadMTL(e,t,i,r){let s=t+e;pe.LoadFile(s,i,void 0,void 0,!1,(a,o)=>{r(s,o)})}createPlugin(e){return new n(e[CR.name])}canDirectLoad(){return!1}importMeshAsync(e,t,i,r){return this._parseSolidAsync(e,t,i,r).then(s=>({meshes:s,particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]}))}loadAsync(e,t,i){return this.importMeshAsync(null,e,t,i).then(()=>{})}loadAssetContainerAsync(e,t,i){let r=new ul(e);return this._assetContainer=r,this.importMeshAsync(null,e,t,i).then(s=>(s.meshes.forEach(a=>r.meshes.push(a)),s.meshes.forEach(a=>{let o=a.material;o&&r.materials.indexOf(o)==-1&&(r.materials.push(o),o.getActiveTextures().forEach(c=>{r.textures.indexOf(c)==-1&&r.textures.push(c)}))}),this._assetContainer=null,r)).catch(s=>{throw this._assetContainer=null,s})}_parseSolidAsync(e,t,i,r){let s="",a=new ud,o=[],l=[];i=i.replace(/#.*$/gm,"").trim(),new Kr(o,l,this._loadingOptions).parse(e,i,t,this._assetContainer,h=>{s=h});let f=[];return s!==""&&!this._loadingOptions.skipMaterials&&f.push(new Promise((h,d)=>{this._loadMTL(s,r,u=>{try{a.parseMTL(t,u,r,this._assetContainer);for(let m=0;m-1;)_.push(g),p=g+1;if(g===-1&&_.length===0)a.materials[m].dispose();else for(let v=0;v<_.length;v++){let x=l[_[v]],A=a.materials[m];x.material=A,x.getTotalIndices()||(A.pointsCloud=!0)}}h()}catch(m){pe.Warn(`Error processing MTL file: '${s}'`),this._loadingOptions.materialLoadingFailsSilently?h():d(m)}},(u,m)=>{pe.Warn(`Error downloading MTL file: '${s}'`),this._loadingOptions.materialLoadingFailsSilently?h():d(m)})})),Promise.all(f).then(()=>{let h=d=>{var u,m;return!!((m=(u=d._internalMetadata)==null?void 0:u._isLine)!=null&&m)};return l.forEach(d=>{var u,m;if(h(d)){let p=(u=d.material)!=null?u:new Ge(d.name+"_line",t);p.getBindedMeshes().filter(g=>!h(g)).length>0&&(p=(m=p.clone(p.name+"_line"))!=null?m:p),p.wireframe=!0,d.material=p,d._internalMetadata&&(d._internalMetadata._isLine=void 0)}}),l})}};Js.OPTIMIZE_WITH_UV=!0;Js.INVERT_Y=!1;Js.IMPORT_VERTEX_COLORS=!1;Js.COMPUTE_NORMALS=!1;Js.OPTIMIZE_NORMALS=!1;Js.UV_SCALING=new we(1,1);Js.SKIP_MATERIALS=!1;Js.MATERIAL_LOADING_FAILS_SILENTLY=!0;Js.USE_LEGACY_BEHAVIOR=!1;Kf(new Js)});function Rde(n){let e=n.trim();return/^https?:\/\//i.test(e)||/^wss?:\/\//i.test(e)||/^\/\//.test(e)}function hO(n,e){if(Rde(n))throw new Error(`[AI3D] Babylon ${e} is limited to local vault resources. Refused remote URL: ${n}`);return n}function yR(n){throw new Error(`[AI3D] Babylon script loading is disabled in this plugin build. Refused script URL: ${n}`)}function y9(){if(C9)return;let n=i=>hO(i,"asset loading"),e=i=>hO(i,"script loading"),t=()=>-1;pe.PreprocessUrl=n,pe.ScriptPreprocessUrl=e,pe.DefaultRetryStrategy=t,pe.LoadScript=(i,r,s)=>{try{e(i),yR(i)}catch(a){s==null||s(a instanceof Error?a.message:String(a),a);return}r==null||r()},pe.LoadScriptAsync=async i=>{e(i),yR(i)},pe.LoadBabylonScript=(i,r,s)=>{try{yR(i)}catch(a){s==null||s(a instanceof Error?a.message:String(a),a);return}r()},pe.LoadBabylonScriptAsync=async i=>{yR(i)},Vi.PreprocessUrl=n,Vi.ScriptPreprocessUrl=e,Vi.DefaultRetryStrategy=t,Ir.CustomRequestModifiers.push((i,r)=>hO(r,"request")),C9=!0}var C9,P9=C(()=>{"use strict";Hl();bi();Bh();C9=!1});function PR(n,e){if(e.byteLength<84)throw new Error(`STL buffer too small: ${e.byteLength} bytes (need 84+)`);if(e.byteLength>=6){let p=new TextDecoder().decode(new Uint8Array(e,0,6));if(p==="solid "||p===`solid -`){let _=new TextDecoder().decode(new Uint8Array(e,0,Math.min(e.byteLength,800)));if(_.includes("facet")||_.includes("endsolid"))throw new Error("ASCII STL detected \u2014 only binary STL is supported. Convert to binary STL first.")}}let t=new DataView(e),i=t.getUint32(80,!0);if(i===0)throw new Error("STL file contains 0 triangles");let r=84+i*50;if(e.byteLength>0&31)/31,N=(v>>5&31)/31,F=(v>>10&31)/31,U=p*12;l[U+0]=V,l[U+1]=N,l[U+2]=F,l[U+3]=1,l[U+4]=V,l[U+5]=N,l[U+6]=F,l[U+7]=1,l[U+8]=V,l[U+9]=N,l[U+10]=F,l[U+11]=1}let x=a[_+3]-a[_+0],A=a[_+4]-a[_+1],S=a[_+5]-a[_+2],E=a[_+6]-a[_+0],R=a[_+7]-a[_+1],I=a[_+8]-a[_+2],y=A*I-S*R,M=S*E-x*I,D=x*R-A*E,O=Math.sqrt(y*y+M*M+D*D);O>1e-8?(y/=O,M/=O,D/=O):(y=0,M=0,D=1,f++),o[_+0]=y,o[_+1]=M,o[_+2]=D,o[_+3]=y,o[_+4]=M,o[_+5]=D,o[_+6]=y,o[_+7]=M,o[_+8]=D,c[g+0]=_/3+0,c[g+1]=_/3+1,c[g+2]=_/3+2}f>0&&console.warn(`[AI3D STL] ${f} degenerate triangles with zero-area normals`);let d=new Me;d.positions=a,d.normals=o,d.indices=c,l&&(d.colors=l);let u=new Z("stl-model",n);d.applyToMesh(u);let m=new Ge("stl-mat",n);return m.backFaceCulling=!1,m.specularColor=new ge(.3,.3,.3),m.specularPower=32,l?(m.diffuseColor=new ge(1,1,1),m.emissiveColor=new ge(.05,.05,.05),m.vertexColorEnabled=!0):(m.diffuseColor=new ge(.85,.85,.85),m.emissiveColor=new ge(.1,.1,.1)),u.material=m,u}function D9(n,e){return PR(n,e)}function L9(n){n(bde)}var bde,dO=C(()=>{"use strict";Ii();Ug();hr();Tc();zt();bde={name:"stl",extensions:".stl",importMeshAsync(n,e,t){return Promise.resolve().then(()=>({meshes:[PR(e,t)],particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]}))},loadAsync(n,e){return Promise.resolve().then(()=>{PR(n,e)})},loadAssetContainerAsync(n,e){return Promise.resolve().then(()=>{let t=PR(n,e),i=new ul(n);return i.meshes.push(t),t.material&&i.materials.push(t.material),i})},canDirectLoad(){return!1},rewriteRootURL(n){return n}}});function Ide(n){let e=n.split(` -`),t=[],i="binary_little_endian",r=null;for(let s of e){let a=s.trim();if(a==="end_header")break;if(a==="ply"||a===""||a.startsWith("comment"))continue;let o=a.split(/\s+/),l=o[0];l==="format"?i=o[1]:l==="element"?(r={name:o[1],count:parseInt(o[2],10),properties:[]},t.push(r)):l==="property"&&r&&(o[1]==="list"?r.properties.push({name:o[4],type:"list",isList:!0,countType:o[2],itemType:o[3]}):r.properties.push({name:o[2],type:o[1],isList:!1}))}return{format:i,elements:t}}function cp(n){switch(n){case"uchar":case"uint8":return 1;case"char":case"int8":return 1;case"ushort":case"uint16":return 2;case"short":case"int16":return 2;case"uint":case"uint32":return 4;case"int":case"int32":return 4;case"float":case"float32":return 4;case"double":case"float64":return 8;default:return 4}}function DR(n,e,t,i){switch(t){case"uchar":case"uint8":return n.getUint8(e);case"char":case"int8":return n.getInt8(e);case"ushort":case"uint16":return n.getUint16(e,i);case"short":case"int16":return n.getInt16(e,i);case"uint":case"uint32":return n.getUint32(e,i);case"int":case"int32":return n.getInt32(e,i);case"float":case"float32":return n.getFloat32(e,i);case"double":case"float64":return n.getFloat64(e,i);default:return 0}}function Mde(n,e,t,i){let r=i,s=new DataView(n),a=[],o=[],l=[],c=e.elements.find(h=>h.name==="vertex"),f=e.elements.find(h=>h.name==="face");if(c){let h=c.properties.some(u=>u.name==="x"),d=c.properties.some(u=>u.name==="red"||u.name==="r");for(let u=0;ud.name==="vertex"),c=e.elements.find(d=>d.name==="face"),f=0;if(l){let d=l.properties.some(p=>p.name==="x"),u=l.properties.some(p=>p.name==="red"||p.name==="r"),m=l.properties.filter(p=>!p.isList);for(let p=0;p0){c.indices=o.indices;let d=new Array(l.length).fill(0),u=o.indices,m=l.length-3;for(let p=0;pm||g>m||v>m)continue;let x=l[_],A=l[_+1],S=l[_+2],E=l[g]-x,R=l[g+1]-A,I=l[g+2]-S,y=l[v]-x,M=l[v+1]-A,D=l[v+2]-S,O=R*D-I*M,V=I*y-E*D,N=E*M-R*y;d[_]+=O,d[_+1]+=V,d[_+2]+=N,d[g]+=O,d[g+1]+=V,d[g+2]+=N,d[v]+=O,d[v+1]+=V,d[v+2]+=N}for(let p=0;p0&&(d[p]/=_,d[p+1]/=_,d[p+2]/=_)}c.normals=d}else{let d=o.positions.length/3,u=[];for(let m=0;m=3&&u.push(0,1,2),c.indices=u}let f=new Z("ply-model",n);c.applyToMesh(f);let h=new Ge("ply-mat",n);return h.backFaceCulling=!1,o.colors.length>0?(c.colors=o.colors,c.applyToMesh(f),h.diffuseColor=new ge(1,1,1),h.vertexColorEnabled=!0):h.diffuseColor=new ge(.7,.7,.7),f.material=h,f}function O9(n,e){return LR(n,e)}function N9(n){n(yde)}var yde,uO=C(()=>{"use strict";Ii();Ug();hr();Tc();zt();yde={name:"ply",extensions:".ply",importMeshAsync(n,e,t){return Promise.resolve().then(()=>({meshes:[LR(e,t)],particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]}))},loadAsync(n,e){return Promise.resolve().then(()=>{LR(n,e)})},loadAssetContainerAsync(n,e){return Promise.resolve().then(()=>{let t=LR(n,e),i=new ul(n);return i.meshes.push(t),t.material&&i.materials.push(t.material),i})},canDirectLoad(){return!1},rewriteRootURL(n){return n}}});async function jg(){w9||(y9(),L9(Kf),N9(Kf),w9=!0)}var w9,qg=C(()=>{"use strict";FD();A9();x9();fO();Jm();P9();dO();uO();w9=!1});function Zg(n){return Math.floor(n.getTotalIndices()/3)}function md(n){return n.getTotalVertices()}function pd(n,e=[]){let t=[n,...e,...n.getChildMeshes(!0)],i=new Set;return t.filter(r=>!r||i.has(r)||r.isDisposed()?!1:(i.add(r),md(r)>0||r.getTotalIndices()>0))}function F9(n){let e=Array.from(n),t=new Set(e);return e.filter(i=>{let r=i.parent;return!r||!t.has(r)})}function mO(n){n.computeWorldMatrix(!0);let e=n.getBoundingInfo().boundingBox;return I_(Ht(e.minimumWorld),Ht(e.maximumWorld))}function fp(n){let e=null;for(let t of n)!t||t.isDisposed()||(e=Z1(e,mO(t)));return e}function OR(n,e=[]){var t;return(t=fp(pd(n,e)))!=null?t:mO(n)}function NR(n,e,t,i={}){return GS({rootName:n,boundingSize:Wr(e),meshes:t.map(r=>({triangleCount:Zg(r),vertexCount:md(r),materialKeys:r.material?[r.material.name]:[]})),splatCount:i.splatCount,resourceWarnings:i.resourceWarnings})}function B9(n){var t,i;let e=mO(n);return Ih({name:n.name||`mesh-${n.uniqueId}`,triangleCount:Zg(n),vertexCount:md(n),materialName:(i=(t=n.material)==null?void 0:t.name)!=null?i:null,boundingSize:Wr(e),center:fn(e)})}var wR=C(()=>{"use strict";rf();Fs();C_()});function Qf(n){return qr(n)}function U9(n,e,t,i=[]){jS(new FR(n,i),e,t)}function pO(n,e=[]){qS(new FR(n,e))}var FR,V9=C(()=>{"use strict";Ve();rf();Fs();sM();wR();FR=class{constructor(e,t=[]){this.rootMesh=e,this.loadedMeshes=t}getParts(){return pd(this.rootMesh,this.loadedMeshes)}getRootCenter(){return fn(OR(this.rootMesh,this.loadedMeshes))}getPartPosition(e){return Ht(e.position)}getPartCenter(e){return Ht(e.getBoundingInfo().boundingBox.centerWorld)}setPartPosition(e,t){e.position=new b(t.x,t.y,t.z)}getPartState(e){let t=e.metadata;return t!=null&&t._previewExplodeState?{originalPosition:Qf(t._previewExplodeState.originalPosition),originalCenter:Qf(t._previewExplodeState.originalCenter)}:t!=null&&t._originalPos&&(t!=null&&t._originalCenter)?{originalPosition:Qf(t._originalPos),originalCenter:Qf(t._originalCenter)}:null}setPartState(e,t){(!e.metadata||typeof e.metadata!="object")&&(e.metadata={});let i=e.metadata;i._previewExplodeState={originalPosition:Qf(t.originalPosition),originalCenter:Qf(t.originalCenter)},i._originalPos=Qf(t.originalPosition),i._originalCenter=Qf(t.originalCenter)}}});var BR={};tt(BR,{glowBlurPostProcessPixelShaderWGSL:()=>Pde});var _O,G9,Pde,UR=C(()=>{W();_O="glowBlurPostProcessPixelShader",G9=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform screenSize: vec2f;uniform direction: vec2f;uniform blurWidth: f32;fn getLuminance(color: vec3f)->f32 +`;T.ShadersStore[nO]||(T.ShadersStore[nO]=m9);Sde={name:nO,shader:m9}});var op,sO,MR,aO,Er,g9=C(()=>{Gt();Vt();Pt();so();SR();As();Ge();ki();m6();jA();zt();qA();q_();Vn();La();pg();Pa();NC();Df();p6();_6();g6();v6();E6();xP();ol();_g();Un();ZA();QA();$A();JA();op={effect:null,subMesh:null},sO=class extends Ym(Xm(xr)){},MR=class extends Hm(sO){constructor(e){super(e),this.PBR=!0,this.NUM_SAMPLES="0",this.REALTIME_FILTERING=!1,this.IBL_CDF_FILTERING=!1,this.ALBEDO=!1,this.GAMMAALBEDO=!1,this.ALBEDODIRECTUV=0,this.VERTEXCOLOR=!1,this.BASE_WEIGHT=!1,this.BASE_WEIGHTDIRECTUV=0,this.BASE_DIFFUSE_ROUGHNESS=!1,this.BASE_DIFFUSE_ROUGHNESSDIRECTUV=0,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.AMBIENTINGRAYSCALE=!1,this.OPACITY=!1,this.VERTEXALPHA=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHABLEND=!1,this.ALPHAFROMALBEDO=!1,this.ALPHATESTVALUE="0.5",this.SPECULAROVERALPHA=!1,this.RADIANCEOVERALPHA=!1,this.ALPHAFRESNEL=!1,this.LINEARALPHAFRESNEL=!1,this.PREMULTIPLYALPHA=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.GAMMAEMISSIVE=!1,this.REFLECTIVITY=!1,this.REFLECTIVITY_GAMMA=!1,this.REFLECTIVITYDIRECTUV=0,this.SPECULARTERM=!1,this.MICROSURFACEFROMREFLECTIVITYMAP=!1,this.MICROSURFACEAUTOMATIC=!1,this.LODBASEDMICROSFURACE=!1,this.MICROSURFACEMAP=!1,this.MICROSURFACEMAPDIRECTUV=0,this.METALLICWORKFLOW=!1,this.ROUGHNESSSTOREINMETALMAPALPHA=!1,this.ROUGHNESSSTOREINMETALMAPGREEN=!1,this.METALLNESSSTOREINMETALMAPBLUE=!1,this.AOSTOREINMETALMAPRED=!1,this.METALLIC_REFLECTANCE=!1,this.METALLIC_REFLECTANCE_GAMMA=!1,this.METALLIC_REFLECTANCEDIRECTUV=0,this.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=!1,this.REFLECTANCE=!1,this.REFLECTANCE_GAMMA=!1,this.REFLECTANCEDIRECTUV=0,this.ENVIRONMENTBRDF=!1,this.ENVIRONMENTBRDF_RGBD=!1,this.NORMAL=!1,this.TANGENT=!1,this.BUMP=!1,this.BUMPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.NORMALXYSCALE=!0,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.USELIGHTMAPASSHADOWMAP=!1,this.GAMMALIGHTMAP=!1,this.RGBDLIGHTMAP=!1,this.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.INVERTCUBICMAP=!1,this.USESPHERICALFROMREFLECTIONMAP=!1,this.USEIRRADIANCEMAP=!1,this.USE_IRRADIANCE_DOMINANT_DIRECTION=!1,this.USESPHERICALINVERTEX=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1,this.LINEARSPECULARREFLECTION=!1,this.RADIANCEOCCLUSION=!1,this.HORIZONOCCLUSION=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.NONUNIFORMSCALING=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_POSITION=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.MORPHTARGETS_UV2=!1,this.MORPHTARGETS_COLOR=!1,this.MORPHTARGETTEXTURE_HASPOSITIONS=!1,this.MORPHTARGETTEXTURE_HASNORMALS=!1,this.MORPHTARGETTEXTURE_HASTANGENTS=!1,this.MORPHTARGETTEXTURE_HASUVS=!1,this.MORPHTARGETTEXTURE_HASUV2S=!1,this.MORPHTARGETTEXTURE_HASCOLORS=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.USEPHYSICALLIGHTFALLOFF=!1,this.USEGLTFLIGHTFALLOFF=!1,this.TWOSIDEDLIGHTING=!1,this.MIRRORED=!1,this.SHADOWFLOAT=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.LOGARITHMICDEPTH=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.AREALIGHTSUPPORTED=!0,this.FORCENORMALFORWARD=!1,this.SPECULARAA=!1,this.UNLIT=!1,this.DECAL_AFTER_DETAIL=!1,this.DEBUGMODE=0,this.USE_VERTEX_PULLING=!1,this.VERTEX_PULLING_USE_INDEX_BUFFER=!1,this.VERTEX_PULLING_INDEX_BUFFER_32BITS=!1,this.RIGHT_HANDED=!1,this.CLUSTLIGHT_SLICES=0,this.CLUSTLIGHT_BATCH=0,this.rebuild()}reset(){super.reset(),this.ALPHATESTVALUE="0.5",this.PBR=!0,this.NORMALXYSCALE=!0}},aO=class extends Km(hl){},Er=class n extends aO{get realTimeFiltering(){return this._realTimeFiltering}set realTimeFiltering(e){this._realTimeFiltering=e,this.markAsDirty(1)}get realTimeFilteringQuality(){return this._realTimeFilteringQuality}set realTimeFilteringQuality(e){this._realTimeFilteringQuality=e,this.markAsDirty(1)}get canRenderToMRT(){return!0}constructor(e,t,i=!1){super(e,t,void 0,i||n.ForceGLSL),this._directIntensity=1,this._emissiveIntensity=1,this._environmentIntensity=1,this._specularIntensity=1,this._lightingInfos=new bi(this._directIntensity,this._emissiveIntensity,this._environmentIntensity,this._specularIntensity),this._disableBumpMap=!1,this._albedoTexture=null,this._baseWeightTexture=null,this._baseDiffuseRoughnessTexture=null,this._ambientTexture=null,this._ambientTextureStrength=1,this._ambientTextureImpactOnAnalyticalLights=n.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._reflectivityTexture=null,this._metallicTexture=null,this._metallic=null,this._roughness=null,this._metallicF0Factor=1,this._metallicReflectanceColor=ve.White(),this._useOnlyMetallicFromMetallicReflectanceTexture=!1,this._metallicReflectanceTexture=null,this._reflectanceTexture=null,this._microSurfaceTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._ambientColor=new ve(0,0,0),this._albedoColor=new ve(1,1,1),this._baseWeight=1,this._baseDiffuseRoughness=null,this._reflectivityColor=new ve(1,1,1),this._reflectionColor=new ve(1,1,1),this._emissiveColor=new ve(0,0,0),this._microSurface=.9,this._useLightmapAsShadowmap=!1,this._useHorizonOcclusion=!0,this._useRadianceOcclusion=!0,this._useAlphaFromAlbedoTexture=!1,this._useSpecularOverAlpha=!0,this._useMicroSurfaceFromReflectivityMapAlpha=!1,this._useRoughnessFromMetallicTextureAlpha=!0,this._useRoughnessFromMetallicTextureGreen=!1,this._useMetallnessFromMetallicTextureBlue=!1,this._useAmbientOcclusionFromMetallicTextureRed=!1,this._useAmbientInGrayScale=!1,this._useAutoMicroSurfaceFromReflectivityMap=!1,this._lightFalloff=n.LIGHTFALLOFF_PHYSICAL,this._useRadianceOverAlpha=!0,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this._parallaxScaleBias=.05,this._disableLighting=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._alphaCutOff=.4,this._useAlphaFresnel=!1,this._useLinearAlphaFresnel=!1,this._environmentBRDFTexture=null,this._forceIrradianceInFragment=!1,this._realTimeFiltering=!1,this._realTimeFilteringQuality=8,this._forceNormalForward=!1,this._enableSpecularAntiAliasing=!1,this._renderTargets=new Bi(16),this._globalAmbientColor=new ve(0,0,0),this._unlit=!1,this._applyDecalMapAfterDetailMap=!1,this._debugMode=0,this._shadersLoaded=!1,this._breakShaderLoadedCheck=!1,this._vertexPullingMetadata=null,this.debugMode=0,this.debugLimit=-1,this.debugFactor=1,this._cacheHasRenderTargetTextures=!1,this.brdf=new Mr(this),this.clearCoat=new sn(this),this.iridescence=new Ps(this),this.anisotropy=new xc(this),this.sheen=new Qs(this),this.subSurface=new Ai(this),this.detailMap=new Oa(this),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),ce.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=ER(this.getScene()),this.prePassConfiguration=new Cs}get hasRenderTargetTextures(){return ce.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget?!0:this._cacheHasRenderTargetTextures}get isPrePassCapable(){return!this.disableDepthWrite}getClassName(){return"PBRBaseMaterial"}get _disableAlphaBlending(){var e;return this._transparencyMode===n.PBRMATERIAL_OPAQUE||this._transparencyMode===n.PBRMATERIAL_ALPHATEST||((e=this.subSurface)==null?void 0:e.disableAlphaBlending)}needAlphaBlending(){return this._hasTransparencyMode?this._transparencyModeIsBlend:this._disableAlphaBlending?!1:this.alpha<1||this._opacityTexture!=null||this._shouldUseAlphaFromAlbedoTexture()}needAlphaTesting(){var e;return this._hasTransparencyMode?this._transparencyModeIsTest:(e=this.subSurface)!=null&&e.disableAlphaBlending?!1:this._hasAlphaChannel()&&(this._transparencyMode==null||this._transparencyMode===n.PBRMATERIAL_ALPHATEST)}_shouldUseAlphaFromAlbedoTexture(){return this._albedoTexture!=null&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==n.PBRMATERIAL_OPAQUE}_hasAlphaChannel(){return this._albedoTexture!=null&&this._albedoTexture.hasAlpha||this._opacityTexture!=null}getAlphaTestTexture(){return this._albedoTexture}isReadyForSubMesh(e,t,i){var d;this._uniformBufferLayoutBuilt||this.buildUniformLayout();let r=t._drawWrapper;if(r.effect&&this.isFrozen&&r._wasPreviouslyReady&&r._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(4,this._eventInfo),t.materialDefines=new MR(this._eventInfo.defineNames));let s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let a=this.getScene(),o=a.getEngine();if(s._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,a.texturesEnabled)){if(this._albedoTexture&&ce.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking()||this._baseWeightTexture&&ce.BaseWeightTextureEnabled&&!this._baseWeightTexture.isReadyOrNotBlocking()||this._baseDiffuseRoughnessTexture&&ce.BaseDiffuseRoughnessTextureEnabled&&!this._baseDiffuseRoughnessTexture.isReadyOrNotBlocking()||this._ambientTexture&&ce.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking()||this._opacityTexture&&ce.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;let u=this._getReflectionTexture();if(u&&ce.ReflectionTextureEnabled){if(!u.isReadyOrNotBlocking())return!1;if(u.irradianceTexture){if(!u.irradianceTexture.isReadyOrNotBlocking())return!1}else if(!u.sphericalPolynomial&&((d=u.getInternalTexture())!=null&&d._sphericalPolynomialPromise))return!1}if(this._lightmapTexture&&ce.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking()||this._emissiveTexture&&ce.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(ce.SpecularTextureEnabled){if(this._metallicTexture){if(!this._metallicTexture.isReadyOrNotBlocking())return!1}else if(this._reflectivityTexture&&!this._reflectivityTexture.isReadyOrNotBlocking())return!1;if(this._metallicReflectanceTexture&&!this._metallicReflectanceTexture.isReadyOrNotBlocking()||this._reflectanceTexture&&!this._reflectanceTexture.isReadyOrNotBlocking()||this._microSurfaceTexture&&!this._microSurfaceTexture.isReadyOrNotBlocking())return!1}if(o.getCaps().standardDerivatives&&this._bumpTexture&&ce.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady()||this._environmentBRDFTexture&&ce.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady())return!1}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh||s._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;if(s.AREALIGHTUSED||s.CLUSTLIGHT_BATCH){for(let u=0;u{m.push(`vp_${R}_info`)}))}else this._vertexPullingMetadata=null;kt&&(kt.PrepareUniforms(m,i),kt.PrepareSamplers(p,i)),Lm({uniformsNames:m,uniformBuffersNames:_,samplers:p,defines:i,maxSimultaneousLights:this._maxSimultaneousLights,shaderLanguage:this._shaderLanguage});let v={};this.customShaderNameResolve&&(u=this.customShaderNameResolve(u,m,_,p,i,d,v));let x=i.toString(),A=c.createEffect(u,{attributes:d,uniformsNames:m,uniformBuffersNames:_,samplers:p,defines:x,fallbacks:f,onCompiled:r,onError:s,indexParameters:g,processFinalCode:v.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:i.PREPASS,shaderLanguage:this._shaderLanguage,extraInitializationsAsync:this._shadersLoaded?void 0:async()=>{this.shaderLanguage===1?await Promise.all([Promise.resolve().then(()=>(x6(),A6)),Promise.resolve().then(()=>(m7(),u7))]):await Promise.all([Promise.resolve().then(()=>(S7(),E7)),Promise.resolve().then(()=>(_9(),p9))]),this._shadersLoaded=!0}},c);return this._eventInfo.customCode=void 0,A}_prepareDefines(e,t,i,r=null,s=null){let a=t.hasThinInstances,o=this.getScene(),l=o.getEngine();Im(o,e,i,!0,this._maxSimultaneousLights,this._disableLighting),i._needNormals=!0,ym(o,i);let c=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(Dm(o,i,this.canRenderToMRT&&!c),Pm(o,i,c),Hn.PrepareDefines(l.currentRenderPassId,e,i),i.METALLICWORKFLOW=this.isMetallicWorkflow(),i._areTexturesDirty){i._needUVs=!1;for(let f=1;f<=6;++f)i["MAINUV"+f]=!1;if(o.texturesEnabled){i.ALBEDODIRECTUV=0,i.BASE_WEIGHTDIRECTUV=0,i.BASE_DIFFUSE_ROUGHNESSDIRECTUV=0,i.AMBIENTDIRECTUV=0,i.OPACITYDIRECTUV=0,i.EMISSIVEDIRECTUV=0,i.REFLECTIVITYDIRECTUV=0,i.MICROSURFACEMAPDIRECTUV=0,i.METALLIC_REFLECTANCEDIRECTUV=0,i.REFLECTANCEDIRECTUV=0,i.BUMPDIRECTUV=0,i.LIGHTMAPDIRECTUV=0,l.getCaps().textureLOD&&(i.LODBASEDMICROSFURACE=!0),this._albedoTexture&&ce.DiffuseTextureEnabled?(ni(this._albedoTexture,i,"ALBEDO"),i.GAMMAALBEDO=this._albedoTexture.gammaSpace):i.ALBEDO=!1,this._baseWeightTexture&&ce.BaseWeightTextureEnabled?ni(this._baseWeightTexture,i,"BASE_WEIGHT"):i.BASE_WEIGHT=!1,this._baseDiffuseRoughnessTexture&&ce.BaseDiffuseRoughnessTextureEnabled?ni(this._baseDiffuseRoughnessTexture,i,"BASE_DIFFUSE_ROUGHNESS"):i.BASE_DIFFUSE_ROUGHNESS=!1,this._ambientTexture&&ce.AmbientTextureEnabled?(ni(this._ambientTexture,i,"AMBIENT"),i.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):i.AMBIENT=!1,this._opacityTexture&&ce.OpacityTextureEnabled?(ni(this._opacityTexture,i,"OPACITY"),i.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):i.OPACITY=!1;let f=this._getReflectionTexture(),h=this._forceIrradianceInFragment||this.realTimeFiltering||this._twoSidedLighting||l.getCaps().maxVaryingVectors<=8||this._baseDiffuseRoughnessTexture!=null;xf(o,f,i,this.realTimeFiltering,this.realTimeFilteringQuality,!h),this._lightmapTexture&&ce.LightmapTextureEnabled?(ni(this._lightmapTexture,i,"LIGHTMAP"),i.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,i.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace,i.RGBDLIGHTMAP=this._lightmapTexture.isRGBD):i.LIGHTMAP=!1,this._emissiveTexture&&ce.EmissiveTextureEnabled?(ni(this._emissiveTexture,i,"EMISSIVE"),i.GAMMAEMISSIVE=this._emissiveTexture.gammaSpace):i.EMISSIVE=!1,ce.SpecularTextureEnabled?(this._metallicTexture?(ni(this._metallicTexture,i,"REFLECTIVITY"),i.ROUGHNESSSTOREINMETALMAPALPHA=this._useRoughnessFromMetallicTextureAlpha,i.ROUGHNESSSTOREINMETALMAPGREEN=!this._useRoughnessFromMetallicTextureAlpha&&this._useRoughnessFromMetallicTextureGreen,i.METALLNESSSTOREINMETALMAPBLUE=this._useMetallnessFromMetallicTextureBlue,i.AOSTOREINMETALMAPRED=this._useAmbientOcclusionFromMetallicTextureRed,i.REFLECTIVITY_GAMMA=!1):this._reflectivityTexture?(ni(this._reflectivityTexture,i,"REFLECTIVITY"),i.MICROSURFACEFROMREFLECTIVITYMAP=this._useMicroSurfaceFromReflectivityMapAlpha,i.MICROSURFACEAUTOMATIC=this._useAutoMicroSurfaceFromReflectivityMap,i.REFLECTIVITY_GAMMA=this._reflectivityTexture.gammaSpace):i.REFLECTIVITY=!1,this._metallicReflectanceTexture||this._reflectanceTexture?(i.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=this._useOnlyMetallicFromMetallicReflectanceTexture,this._metallicReflectanceTexture?(ni(this._metallicReflectanceTexture,i,"METALLIC_REFLECTANCE"),i.METALLIC_REFLECTANCE_GAMMA=this._metallicReflectanceTexture.gammaSpace):i.METALLIC_REFLECTANCE=!1,this._reflectanceTexture&&(!this._metallicReflectanceTexture||this._metallicReflectanceTexture&&this._useOnlyMetallicFromMetallicReflectanceTexture)?(ni(this._reflectanceTexture,i,"REFLECTANCE"),i.REFLECTANCE_GAMMA=this._reflectanceTexture.gammaSpace):i.REFLECTANCE=!1):(i.METALLIC_REFLECTANCE=!1,i.REFLECTANCE=!1),this._microSurfaceTexture?ni(this._microSurfaceTexture,i,"MICROSURFACEMAP"):i.MICROSURFACEMAP=!1):(i.REFLECTIVITY=!1,i.MICROSURFACEMAP=!1),l.getCaps().standardDerivatives&&this._bumpTexture&&ce.BumpTextureEnabled&&!this._disableBumpMap?(ni(this._bumpTexture,i,"BUMP"),this._useParallax&&this._albedoTexture&&ce.DiffuseTextureEnabled?(i.PARALLAX=!0,i.PARALLAX_RHS=o.useRightHandedSystem,i.PARALLAXOCCLUSION=!!this._useParallaxOcclusion):i.PARALLAX=!1,i.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap):(i.BUMP=!1,i.PARALLAX=!1,i.PARALLAX_RHS=!1,i.PARALLAXOCCLUSION=!1,i.OBJECTSPACE_NORMALMAP=!1),this._environmentBRDFTexture&&ce.ReflectionTextureEnabled?(i.ENVIRONMENTBRDF=!0,i.ENVIRONMENTBRDF_RGBD=this._environmentBRDFTexture.isRGBD):(i.ENVIRONMENTBRDF=!1,i.ENVIRONMENTBRDF_RGBD=!1),this._shouldUseAlphaFromAlbedoTexture()?i.ALPHAFROMALBEDO=!0:i.ALPHAFROMALBEDO=!1}i.SPECULAROVERALPHA=this._useSpecularOverAlpha,this._lightFalloff===n.LIGHTFALLOFF_STANDARD?(i.USEPHYSICALLIGHTFALLOFF=!1,i.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===n.LIGHTFALLOFF_GLTF?(i.USEPHYSICALLIGHTFALLOFF=!1,i.USEGLTFLIGHTFALLOFF=!0):(i.USEPHYSICALLIGHTFALLOFF=!0,i.USEGLTFLIGHTFALLOFF=!1),i.RADIANCEOVERALPHA=this._useRadianceOverAlpha,!this.backFaceCulling&&this._twoSidedLighting?i.TWOSIDEDLIGHTING=!0:i.TWOSIDEDLIGHTING=!1,i.MIRRORED=!!o._mirroredCameraPosition,i.SPECULARAA=l.getCaps().standardDerivatives&&this._enableSpecularAntiAliasing}(i._areTexturesDirty||i._areMiscDirty)&&(i.ALPHATESTVALUE=`${this._alphaCutOff}${this._alphaCutOff%1===0?".":""}`,i.PREMULTIPLYALPHA=this.alphaMode===7||this.alphaMode===8,i.ALPHABLEND=this.needAlphaBlendingForMesh(e),i.ALPHAFRESNEL=this._useAlphaFresnel||this._useLinearAlphaFresnel,i.LINEARALPHAFRESNEL=this._useLinearAlphaFresnel),i._areImageProcessingDirty&&this._imageProcessingConfiguration&&this._imageProcessingConfiguration.prepareDefines(i),i.FORCENORMALFORWARD=this._forceNormalForward,i.RADIANCEOCCLUSION=this._useRadianceOcclusion,i.HORIZONOCCLUSION=this._useHorizonOcclusion,i._areMiscDirty&&(Rm(e,o,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this.needAlphaTestingForMesh(e),i,this._applyDecalMapAfterDetailMap,this._useVertexPulling,t,this._isVertexOutputInvariant),i.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent(L.NormalKind),i.DEBUGMODE=this._debugMode),Mm(o,l,this,i,!!r,s,a),this._eventInfo.defines=i,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),Cm(e,i,!0,!0,!0,this._transparencyMode!==n.PBRMATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}forceCompilation(e,t,i){let r={clipPlane:!1,useInstances:!1,...i};this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(4,this._eventInfo),(()=>{if(this._breakShaderLoadedCheck)return;let a=new MR(this._eventInfo.defineNames),o=this._prepareEffect(e,e,a,void 0,void 0,r.useInstances,r.clipPlane);this._onEffectCreatedObservable&&(op.effect=o,op.subMesh=null,this._onEffectCreatedObservable.notifyObservers(op)),o.isReady()?t&&t(this):o.onCompileObservable.add(()=>{t&&t(this)})})()}buildUniformLayout(){let e=this._uniformBuffer;e.addUniform("vAlbedoInfos",2),e.addUniform("vBaseWeightInfos",2),e.addUniform("vBaseDiffuseRoughnessInfos",2),e.addUniform("vAmbientInfos",4),e.addUniform("vOpacityInfos",2),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vReflectivityInfos",3),e.addUniform("vMicroSurfaceSamplerInfos",2),e.addUniform("vBumpInfos",3),e.addUniform("albedoMatrix",16),e.addUniform("baseWeightMatrix",16),e.addUniform("baseDiffuseRoughnessMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("reflectivityMatrix",16),e.addUniform("microSurfaceSamplerMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("vAlbedoColor",4),e.addUniform("baseWeight",1),e.addUniform("baseDiffuseRoughness",1),e.addUniform("vLightingIntensity",4),e.addUniform("pointSize",1),e.addUniform("vReflectivityColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vAmbientColor",3),e.addUniform("vDebugMode",2),e.addUniform("vMetallicReflectanceFactors",4),e.addUniform("vMetallicReflectanceInfos",2),e.addUniform("metallicReflectanceMatrix",16),e.addUniform("vReflectanceInfos",2),e.addUniform("reflectanceMatrix",16),e.addUniform("cameraInfo",4),Om(e,!0,!0,!0,!0,!0),super.buildUniformLayout()}bindForSubMesh(e,t,i){var d,u,m,p;let r=this.getScene(),s=i.materialDefines;if(!s)return;let a=i.effect;if(!a)return;this._activeEffect=a,t.getMeshUniformBuffer().bindToEffect(a,"Mesh"),t.transferToEffect(e);let o=r.getEngine();this._uniformBuffer.bindToEffect(a,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,r,t,e,this.isFrozen),Hn.Bind(o.currentRenderPassId,this._activeEffect,t,e,this);let l=r.activeCamera;l?this._uniformBuffer.updateFloat4("cameraInfo",l.minZ,l.maxZ,0,0):this._uniformBuffer.updateFloat4("cameraInfo",0,0,0,0),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),s.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));let c=this._mustRebind(r,a,i,t.visibility);Rs(t,this._activeEffect,this.prePassConfiguration),this._vertexPullingMetadata&&Of(this._activeEffect,this._vertexPullingMetadata);let f=null,h=this._uniformBuffer;if(c){if(this.bindViewProjection(a),f=this._getReflectionTexture(),!h.useUbo||!this.isFrozen||!h.isSync||i._drawWrapper._forceRebindOnNextCall){if(r.texturesEnabled&&(this._albedoTexture&&ce.DiffuseTextureEnabled&&(h.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),si(this._albedoTexture,h,"albedo")),this._baseWeightTexture&&ce.BaseWeightTextureEnabled&&(h.updateFloat2("vBaseWeightInfos",this._baseWeightTexture.coordinatesIndex,this._baseWeightTexture.level),si(this._baseWeightTexture,h,"baseWeight")),this._baseDiffuseRoughnessTexture&&ce.BaseDiffuseRoughnessTextureEnabled&&(h.updateFloat2("vBaseDiffuseRoughnessInfos",this._baseDiffuseRoughnessTexture.coordinatesIndex,this._baseDiffuseRoughnessTexture.level),si(this._baseDiffuseRoughnessTexture,h,"baseDiffuseRoughness")),this._ambientTexture&&ce.AmbientTextureEnabled&&(h.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),si(this._ambientTexture,h,"ambient")),this._opacityTexture&&ce.OpacityTextureEnabled&&(h.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),si(this._opacityTexture,h,"opacity")),this._emissiveTexture&&ce.EmissiveTextureEnabled&&(h.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),si(this._emissiveTexture,h,"emissive")),this._lightmapTexture&&ce.LightmapTextureEnabled&&(h.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),si(this._lightmapTexture,h,"lightmap")),ce.SpecularTextureEnabled&&(this._metallicTexture?(h.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),si(this._metallicTexture,h,"reflectivity")):this._reflectivityTexture&&(h.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),si(this._reflectivityTexture,h,"reflectivity")),this._metallicReflectanceTexture&&(h.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),si(this._metallicReflectanceTexture,h,"metallicReflectance")),this._reflectanceTexture&&s.REFLECTANCE&&(h.updateFloat2("vReflectanceInfos",this._reflectanceTexture.coordinatesIndex,this._reflectanceTexture.level),si(this._reflectanceTexture,h,"reflectance")),this._microSurfaceTexture&&(h.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),si(this._microSurfaceTexture,h,"microSurfaceSampler"))),this._bumpTexture&&o.getCaps().standardDerivatives&&ce.BumpTextureEnabled&&!this._disableBumpMap&&(h.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),si(this._bumpTexture,h,"bump"),r._mirroredCameraPosition?h.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):h.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),vm(r,s,h,this._reflectionColor,f,this.realTimeFiltering,!0,!0,!0,!0,!0)),this.pointsCloud&&h.updateFloat("pointSize",this.pointSize),s.METALLICWORKFLOW){En.Color4[0].r=this._metallic===void 0||this._metallic===null?1:this._metallic,En.Color4[0].g=this._roughness===void 0||this._roughness===null?1:this._roughness;let _=(u=(d=this.subSurface)==null?void 0:d._indexOfRefraction)!=null?u:1.5,g=1;En.Color4[0].b=_;let v=Math.pow((_-g)/(_+g),2);En.Color4[0].a=v,h.updateDirectColor4("vReflectivityColor",En.Color4[0]),h.updateColor4("vMetallicReflectanceFactors",this._metallicReflectanceColor,this._metallicF0Factor)}else h.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);h.updateColor3("vEmissiveColor",ce.EmissiveTextureEnabled?this._emissiveColor:ve.BlackReadOnly),!s.SS_REFRACTION&&((m=this.subSurface)!=null&&m._linkRefractionWithTransparency)?h.updateColor4("vAlbedoColor",this._albedoColor,1):h.updateColor4("vAlbedoColor",this._albedoColor,this.alpha),h.updateFloat("baseWeight",this._baseWeight),h.updateFloat("baseDiffuseRoughness",this._baseDiffuseRoughness||0),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity*r.environmentIntensity,this._lightingInfos.w=this._specularIntensity,h.updateVector4("vLightingIntensity",this._lightingInfos),r.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor),h.updateColor3("vAmbientColor",this._globalAmbientColor),h.updateFloat2("vDebugMode",this.debugLimit,this.debugFactor)}r.texturesEnabled&&(this._albedoTexture&&ce.DiffuseTextureEnabled&&h.setTexture("albedoSampler",this._albedoTexture),this._baseWeightTexture&&ce.BaseWeightTextureEnabled&&h.setTexture("baseWeightSampler",this._baseWeightTexture),this._baseDiffuseRoughnessTexture&&ce.BaseDiffuseRoughnessTextureEnabled&&h.setTexture("baseDiffuseRoughnessSampler",this._baseDiffuseRoughnessTexture),this._ambientTexture&&ce.AmbientTextureEnabled&&h.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&ce.OpacityTextureEnabled&&h.setTexture("opacitySampler",this._opacityTexture),LA(r,s,h,f,this.realTimeFiltering),s.ENVIRONMENTBRDF&&h.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&ce.EmissiveTextureEnabled&&h.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&ce.LightmapTextureEnabled&&h.setTexture("lightmapSampler",this._lightmapTexture),ce.SpecularTextureEnabled&&(this._metallicTexture?h.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&h.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&h.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._reflectanceTexture&&s.REFLECTANCE&&h.setTexture("reflectanceSampler",this._reflectanceTexture),this._microSurfaceTexture&&h.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&o.getCaps().standardDerivatives&&ce.BumpTextureEnabled&&!this._disableBumpMap&&h.setTexture("bumpSampler",this._bumpTexture)),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(a),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),Fn(this._activeEffect,this,r),this.bindEyePosition(a)}else r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(c||!this.isFrozen)&&(r.lightsEnabled&&!this._disableLighting&&Sm(r,t,this._activeEffect,s,this._maxSimultaneousLights),(r.fogEnabled&&t.applyFog&&r.fogMode!==Jt.FOGMODE_NONE||f||this.subSurface.refractionTexture||t.receiveShadows||s.PREPASS||s.CLUSTLIGHT_BATCH)&&this.bindView(a),Tf(r,t,this._activeEffect,!0),s.NUM_MORPH_INFLUENCERS&&Bn(t,this._activeEffect),s.BAKED_VERTEX_ANIMATION_TEXTURE&&((p=t.bakedVertexAnimationManager)==null||p.bind(a,s.INSTANCES)),this._imageProcessingConfiguration.bind(this._activeEffect),Sf(s,this._activeEffect,r)),this._afterBind(t,this._activeEffect,i),h.update()}getAnimatables(){let e=super.getAnimatables();return this._albedoTexture&&this._albedoTexture.animations&&this._albedoTexture.animations.length>0&&e.push(this._albedoTexture),this._baseWeightTexture&&this._baseWeightTexture.animations&&this._baseWeightTexture.animations.length>0&&e.push(this._baseWeightTexture),this._baseDiffuseRoughnessTexture&&this._baseDiffuseRoughnessTexture.animations&&this._baseDiffuseRoughnessTexture.animations.length>0&&e.push(this._baseDiffuseRoughnessTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._metallicTexture&&this._metallicTexture.animations&&this._metallicTexture.animations.length>0?e.push(this._metallicTexture):this._reflectivityTexture&&this._reflectivityTexture.animations&&this._reflectivityTexture.animations.length>0&&e.push(this._reflectivityTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._metallicReflectanceTexture&&this._metallicReflectanceTexture.animations&&this._metallicReflectanceTexture.animations.length>0&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&this._reflectanceTexture.animations&&this._reflectanceTexture.animations.length>0&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&this._microSurfaceTexture.animations&&this._microSurfaceTexture.animations.length>0&&e.push(this._microSurfaceTexture),e}_getReflectionTexture(){return this._reflectionTexture?this._reflectionTexture:this.getScene().environmentTexture}getActiveTextures(){let e=super.getActiveTextures();return this._albedoTexture&&e.push(this._albedoTexture),this._baseWeightTexture&&e.push(this._baseWeightTexture),this._baseDiffuseRoughnessTexture&&e.push(this._baseDiffuseRoughnessTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._reflectivityTexture&&e.push(this._reflectivityTexture),this._metallicTexture&&e.push(this._metallicTexture),this._metallicReflectanceTexture&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&e.push(this._microSurfaceTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),e}hasTexture(e){return!!(super.hasTexture(e)||this._albedoTexture===e||this._baseWeightTexture===e||this._baseDiffuseRoughnessTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._reflectivityTexture===e||this._metallicTexture===e||this._metallicReflectanceTexture===e||this._reflectanceTexture===e||this._microSurfaceTexture===e||this._bumpTexture===e||this._lightmapTexture===e)}setPrePassRenderer(){var t;if(!((t=this.subSurface)!=null&&t.isScatteringEnabled))return!1;let e=this.getScene().enableSubSurfaceForPrePass();return e&&(e.enabled=!0),!0}dispose(e,t){var i,r,s,a,o,l,c,f,h,d,u,m,p,_;this._breakShaderLoadedCheck=!0,t&&(this._environmentBRDFTexture&&this.getScene().environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),(i=this._albedoTexture)==null||i.dispose(),(r=this._baseWeightTexture)==null||r.dispose(),(s=this._baseDiffuseRoughnessTexture)==null||s.dispose(),(a=this._ambientTexture)==null||a.dispose(),(o=this._opacityTexture)==null||o.dispose(),(l=this._reflectionTexture)==null||l.dispose(),(c=this._emissiveTexture)==null||c.dispose(),(f=this._metallicTexture)==null||f.dispose(),(h=this._reflectivityTexture)==null||h.dispose(),(d=this._bumpTexture)==null||d.dispose(),(u=this._lightmapTexture)==null||u.dispose(),(m=this._metallicReflectanceTexture)==null||m.dispose(),(p=this._reflectanceTexture)==null||p.dispose(),(_=this._microSurfaceTexture)==null||_.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}};Er.PBRMATERIAL_OPAQUE=Ee.MATERIAL_OPAQUE;Er.PBRMATERIAL_ALPHATEST=Ee.MATERIAL_ALPHATEST;Er.PBRMATERIAL_ALPHABLEND=Ee.MATERIAL_ALPHABLEND;Er.PBRMATERIAL_ALPHATESTANDBLEND=Ee.MATERIAL_ALPHATESTANDBLEND;Er.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0;Er.LIGHTFALLOFF_PHYSICAL=0;Er.LIGHTFALLOFF_GLTF=1;Er.LIGHTFALLOFF_STANDARD=2;Er.ForceGLSL=!1;P([le("_markAllSubMeshesAsMiscDirty")],Er.prototype,"debugMode",void 0)});var v9={};tt(v9,{PBRMaterial:()=>dt});var dt,E9=C(()=>{Gt();Vt();SR();zt();g9();Hi();Vn();Tr();dt=class n extends Er{get refractionTexture(){return this.subSurface.refractionTexture}set refractionTexture(e){this.subSurface.refractionTexture=e,e?this.subSurface.isRefractionEnabled=!0:this.subSurface.linkRefractionWithTransparency||(this.subSurface.isRefractionEnabled=!1)}get indexOfRefraction(){return this.subSurface.indexOfRefraction}set indexOfRefraction(e){this.subSurface.indexOfRefraction=e}get invertRefractionY(){return this.subSurface.invertRefractionY}set invertRefractionY(e){this.subSurface.invertRefractionY=e}get linkRefractionWithTransparency(){return this.subSurface.linkRefractionWithTransparency}set linkRefractionWithTransparency(e){this.subSurface.linkRefractionWithTransparency=e,e&&(this.subSurface.isRefractionEnabled=!0)}get usePhysicalLightFalloff(){return this._lightFalloff===Er.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=Er.LIGHTFALLOFF_PHYSICAL:this._lightFalloff=Er.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===Er.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=Er.LIGHTFALLOFF_GLTF:this._lightFalloff=Er.LIGHTFALLOFF_STANDARD)}constructor(e,t,i=!1){super(e,t,i),this.directIntensity=1,this.emissiveIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.disableBumpMap=!1,this.ambientTextureStrength=1,this.ambientTextureImpactOnAnalyticalLights=n.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this.metallicF0Factor=1,this.metallicReflectanceColor=ve.White(),this.useOnlyMetallicFromMetallicReflectanceTexture=!1,this.ambientColor=new ve(0,0,0),this.albedoColor=new ve(1,1,1),this.baseWeight=1,this.reflectivityColor=new ve(1,1,1),this.reflectionColor=new ve(1,1,1),this.emissiveColor=new ve(0,0,0),this.microSurface=1,this.useLightmapAsShadowmap=!1,this.useAlphaFromAlbedoTexture=!1,this.forceAlphaTest=!1,this.alphaCutOff=.4,this.useSpecularOverAlpha=!0,this.useMicroSurfaceFromReflectivityMapAlpha=!1,this.useRoughnessFromMetallicTextureAlpha=!0,this.useRoughnessFromMetallicTextureGreen=!1,this.useMetallnessFromMetallicTextureBlue=!1,this.useAmbientOcclusionFromMetallicTextureRed=!1,this.useAmbientInGrayScale=!1,this.useAutoMicroSurfaceFromReflectivityMap=!1,this.useRadianceOverAlpha=!0,this.useObjectSpaceNormalMap=!1,this.useParallax=!1,this.useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this.disableLighting=!1,this.forceIrradianceInFragment=!1,this.maxSimultaneousLights=4,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.twoSidedLighting=!1,this.useAlphaFresnel=!1,this.useLinearAlphaFresnel=!1,this.environmentBRDFTexture=null,this.forceNormalForward=!1,this.enableSpecularAntiAliasing=!1,this.useHorizonOcclusion=!0,this.useRadianceOcclusion=!0,this.unlit=!1,this.applyDecalMapAfterDetailMap=!1,this._environmentBRDFTexture=ER(this.getScene())}getClassName(){return"PBRMaterial"}clone(e,t=!0,i=""){let r=it.Clone(()=>new n(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return r.id=e,r.name=e,this.stencil.copyTo(r.stencil),this._clonePlugins(r,i),r}serialize(){let e=super.serialize();return e.customType="BABYLON.PBRMaterial",e}static Parse(e,t,i){let r=it.Parse(()=>new n(e.name,t),e,t,i);return e.stencil&&r.stencil.parse(e.stencil,t,i),Ee._ParsePlugins(e,r,t,i),e.clearCoat&&r.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&r.anisotropy.parse(e.anisotropy,t,i),e.brdf&&r.brdf.parse(e.brdf,t,i),e.sheen&&r.sheen.parse(e.sheen,t,i),e.subSurface&&r.subSurface.parse(e.subSurface,t,i),e.iridescence&&r.iridescence.parse(e.iridescence,t,i),r}};dt.PBRMATERIAL_OPAQUE=Er.PBRMATERIAL_OPAQUE;dt.PBRMATERIAL_ALPHATEST=Er.PBRMATERIAL_ALPHATEST;dt.PBRMATERIAL_ALPHABLEND=Er.PBRMATERIAL_ALPHABLEND;dt.PBRMATERIAL_ALPHATESTANDBLEND=Er.PBRMATERIAL_ALPHATESTANDBLEND;dt.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=Er.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;P([w(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"directIntensity",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"emissiveIntensity",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"environmentIntensity",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"specularIntensity",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"disableBumpMap",void 0);P([Ut(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"albedoTexture",void 0);P([Ut(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"baseWeightTexture",void 0);P([Ut(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"baseDiffuseRoughnessTexture",void 0);P([Ut(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"ambientTexture",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"ambientTextureStrength",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"ambientTextureImpactOnAnalyticalLights",void 0);P([Ut(),le("_markAllSubMeshesAsTexturesAndMiscDirty")],dt.prototype,"opacityTexture",void 0);P([Ut(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"reflectionTexture",void 0);P([Ut(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"emissiveTexture",void 0);P([Ut(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"reflectivityTexture",void 0);P([Ut(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"metallicTexture",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"metallic",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"roughness",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"metallicF0Factor",void 0);P([gr(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"metallicReflectanceColor",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"useOnlyMetallicFromMetallicReflectanceTexture",void 0);P([Ut(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"metallicReflectanceTexture",void 0);P([Ut(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"reflectanceTexture",void 0);P([Ut(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"microSurfaceTexture",void 0);P([Ut(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"bumpTexture",void 0);P([Ut(),le("_markAllSubMeshesAsTexturesDirty",null)],dt.prototype,"lightmapTexture",void 0);P([gr("ambient"),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"ambientColor",void 0);P([gr("albedo"),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"albedoColor",void 0);P([w("baseWeight"),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"baseWeight",void 0);P([w("baseDiffuseRoughness"),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"baseDiffuseRoughness",void 0);P([gr("reflectivity"),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"reflectivityColor",void 0);P([gr("reflection"),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"reflectionColor",void 0);P([gr("emissive"),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"emissiveColor",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"microSurface",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"useLightmapAsShadowmap",void 0);P([w(),le("_markAllSubMeshesAsTexturesAndMiscDirty")],dt.prototype,"useAlphaFromAlbedoTexture",void 0);P([w(),le("_markAllSubMeshesAsTexturesAndMiscDirty")],dt.prototype,"forceAlphaTest",void 0);P([w(),le("_markAllSubMeshesAsTexturesAndMiscDirty")],dt.prototype,"alphaCutOff",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"useSpecularOverAlpha",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"useRoughnessFromMetallicTextureAlpha",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"useRoughnessFromMetallicTextureGreen",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"useMetallnessFromMetallicTextureBlue",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"useAmbientInGrayScale",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0);P([w()],dt.prototype,"usePhysicalLightFalloff",null);P([w()],dt.prototype,"useGLTFLightFalloff",null);P([w(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"useRadianceOverAlpha",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"useObjectSpaceNormalMap",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"useParallax",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"useParallaxOcclusion",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"parallaxScaleBias",void 0);P([w(),le("_markAllSubMeshesAsLightsDirty")],dt.prototype,"disableLighting",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"forceIrradianceInFragment",void 0);P([w(),le("_markAllSubMeshesAsLightsDirty")],dt.prototype,"maxSimultaneousLights",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"invertNormalMapX",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"invertNormalMapY",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"twoSidedLighting",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"useAlphaFresnel",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"useLinearAlphaFresnel",void 0);P([le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"environmentBRDFTexture",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"forceNormalForward",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"enableSpecularAntiAliasing",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"useHorizonOcclusion",void 0);P([w(),le("_markAllSubMeshesAsTexturesDirty")],dt.prototype,"useRadianceOcclusion",void 0);P([w(),le("_markAllSubMeshesAsMiscDirty")],dt.prototype,"unlit",void 0);P([w(),le("_markAllSubMeshesAsMiscDirty")],dt.prototype,"applyDecalMapAfterDetailMap",void 0);Ft("BABYLON.PBRMaterial",dt)});var S9={};tt(S9,{PBRMaterialLoadingAdapter:()=>oO});var oO,T9=C(()=>{zt();GD();Ge();oO=class{constructor(e){this._material=e,this._material.enableSpecularAntiAliasing=!0}get material(){return this._material}get isUnlit(){return this._material.unlit}set isUnlit(e){this._material.unlit=e}set backFaceCulling(e){this._material.backFaceCulling=e}get backFaceCulling(){return this._material.backFaceCulling}set twoSidedLighting(e){this._material.twoSidedLighting=e}get twoSidedLighting(){return this._material.twoSidedLighting}set alphaCutOff(e){this._material.alphaCutOff=e}get alphaCutOff(){return this._material.alphaCutOff}set useAlphaFromBaseColorTexture(e){this._material.useAlphaFromAlbedoTexture=e}get useAlphaFromBaseColorTexture(){return this._material.useAlphaFromAlbedoTexture}get transparencyAsAlphaCoverage(){return this._material.useRadianceOverAlpha||this._material.useSpecularOverAlpha}set transparencyAsAlphaCoverage(e){this._material.useRadianceOverAlpha=!e,this._material.useSpecularOverAlpha=!e}set baseColor(e){this._material.albedoColor=e}get baseColor(){return this._material.albedoColor}set baseColorTexture(e){this._material.albedoTexture=e}get baseColorTexture(){return this._material.albedoTexture}set baseDiffuseRoughness(e){this._material.baseDiffuseRoughness=e,e>0&&(this._material.brdf.baseDiffuseModel=W.MATERIAL_DIFFUSE_MODEL_E_OREN_NAYAR)}get baseDiffuseRoughness(){var e;return(e=this._material.baseDiffuseRoughness)!=null?e:0}set baseDiffuseRoughnessTexture(e){this._material.baseDiffuseRoughnessTexture=e}get baseDiffuseRoughnessTexture(){return this._material.baseDiffuseRoughnessTexture}set baseMetalness(e){this._material.metallic=e}get baseMetalness(){var e;return(e=this._material.metallic)!=null?e:1}set baseMetalnessTexture(e){this._material.metallicTexture=e}get baseMetalnessTexture(){return this._material.metallicTexture}set useRoughnessFromMetallicTextureGreen(e){this._material.useRoughnessFromMetallicTextureGreen=e,this._material.useRoughnessFromMetallicTextureAlpha=!e}set useMetallicFromMetallicTextureBlue(e){this._material.useMetallnessFromMetallicTextureBlue=e}enableSpecularEdgeColor(e=!1){e&&(this._material.brdf.dielectricSpecularModel=W.MATERIAL_DIELECTRIC_SPECULAR_MODEL_OPENPBR,this._material.brdf.conductorSpecularModel=W.MATERIAL_CONDUCTOR_SPECULAR_MODEL_OPENPBR)}set specularWeight(e){this._material.metallicF0Factor=e}get specularWeight(){var e;return(e=this._material.metallicF0Factor)!=null?e:1}set specularWeightTexture(e){e?(this._material.metallicReflectanceTexture=e,this._material.useOnlyMetallicFromMetallicReflectanceTexture=!0):(this._material.metallicReflectanceTexture=null,this._material.useOnlyMetallicFromMetallicReflectanceTexture=!1)}get specularWeightTexture(){return this._material.metallicReflectanceTexture}set specularColor(e){this._material.metallicReflectanceColor=e}get specularColor(){return this._material.metallicReflectanceColor}set specularColorTexture(e){this._material.reflectanceTexture=e}get specularColorTexture(){return this._material.reflectanceTexture}set specularRoughness(e){this._material.roughness=e}get specularRoughness(){var e;return(e=this._material.roughness)!=null?e:1}set specularRoughnessTexture(e){this.baseMetalnessTexture||(this._material.metallicTexture=e)}get specularRoughnessTexture(){return this._material.metallicTexture}set specularIor(e){this._material.indexOfRefraction=e}get specularIor(){return this._material.indexOfRefraction}set emissionColor(e){this._material.emissiveColor=e}get emissionColor(){return this._material.emissiveColor}set emissionLuminance(e){this._material.emissiveIntensity=e}get emissionLuminance(){return this._material.emissiveIntensity}set emissionColorTexture(e){this._material.emissiveTexture=e}get emissionColorTexture(){return this._material.emissiveTexture}set ambientOcclusionTexture(e){this._material.ambientTexture=e,e&&(this._material.useAmbientInGrayScale=!0)}get ambientOcclusionTexture(){return this._material.ambientTexture}set ambientOcclusionTextureStrength(e){this._material.ambientTextureStrength=e}get ambientOcclusionTextureStrength(){var e;return(e=this._material.ambientTextureStrength)!=null?e:1}configureCoat(){this._material.clearCoat.isEnabled=!0,this._material.clearCoat.useRoughnessFromMainTexture=!1,this._material.clearCoat.remapF0OnInterfaceChange=!1}set coatWeight(e){this._material.clearCoat.isEnabled=!0,this._material.clearCoat.intensity=e}get coatWeight(){return this._material.clearCoat.intensity}set coatWeightTexture(e){this._material.clearCoat.isEnabled=!0,this._material.clearCoat.texture=e}get coatWeightTexture(){return this._material.clearCoat.texture}set coatColor(e){this._material.clearCoat.isTintEnabled=e!=ve.White(),this._material.clearCoat.tintColor=e}set coatColorTexture(e){this._material.clearCoat.tintTexture=e}set coatRoughness(e){this._material.clearCoat.isEnabled=!0,this._material.clearCoat.roughness=e}get coatRoughness(){var e;return(e=this._material.clearCoat.roughness)!=null?e:0}set coatRoughnessTexture(e){this._material.clearCoat.isEnabled=!0,this._material.clearCoat.useRoughnessFromMainTexture=!1,this._material.clearCoat.textureRoughness=e}get coatRoughnessTexture(){return this._material.clearCoat.textureRoughness}set coatIor(e){this._material.clearCoat.indexOfRefraction=e}set coatDarkening(e){}set coatDarkeningTexture(e){}set coatRoughnessAnisotropy(e){}get coatRoughnessAnisotropy(){return 0}set geometryCoatTangentAngle(e){}set geometryCoatTangentTexture(e){}get geometryCoatTangentTexture(){return null}set transmissionWeight(e){this._material.subSurface.isRefractionEnabled=e>0,this._material.subSurface.refractionIntensity=e}get transmissionWeight(){return this._material.subSurface.isRefractionEnabled?this._material.subSurface.refractionIntensity:0}set transmissionWeightTexture(e){this._material.subSurface.isRefractionEnabled=!0,this._material.subSurface.refractionIntensityTexture=e,this._material.subSurface.useGltfStyleTextures=!0}set transmissionDepth(e){this.transmissionWeight>0?this._material.subSurface.tintColorAtDistance=e:this.subsurfaceWeight>0&&this._material.subSurface.diffusionDistance.multiplyInPlace(new ve(e,e,e))}get transmissionDepth(){return this.transmissionWeight>0?this._material.subSurface.tintColorAtDistance:0}set transmissionColor(e){this.transmissionWeight>0?this._material.subSurface.tintColor=e:this.subsurfaceWeight>0&&this._material.subSurface.diffusionDistance.multiplyInPlace(e)}get transmissionColor(){return this.transmissionWeight>0?this._material.subSurface.tintColor:this.subsurfaceWeight>0?this._material.subSurface.diffusionDistance:new ve(0,0,0)}set transmissionScatter(e){this._material.subSurface.diffusionDistance=e}get transmissionScatter(){return this._material.subSurface.diffusionDistance}set transmissionScatterTexture(e){}set transmissionScatterAnisotropy(e){}set transmissionDispersionAbbeNumber(e){}set transmissionDispersionScale(e){e>0?(this._material.subSurface.isDispersionEnabled=!0,this._material.subSurface.dispersion=20/e):(this._material.subSurface.isDispersionEnabled=!1,this._material.subSurface.dispersion=0)}get refractionBackgroundTexture(){return this._material.subSurface.refractionTexture}set refractionBackgroundTexture(e){this._material.subSurface.refractionTexture=e}configureTransmission(){this._material.subSurface.volumeIndexOfRefraction=1,this._material.subSurface.useAlbedoToTintRefraction=!0,this._material.subSurface.minimumThickness=0,this._material.subSurface.maximumThickness=0}configureVolume(){}set geometryThinWalled(e){}get geometryThinWalled(){return!0}set volumeThicknessTexture(e){this._material.subSurface.thicknessTexture=e,this._material.subSurface.useGltfStyleTextures=!0}set volumeThickness(e){this._material.subSurface.minimumThickness=0,this._material.subSurface.maximumThickness=e,this._material.subSurface.useThicknessAsDepth=!0,e>0&&(this._material.subSurface.volumeIndexOfRefraction=this._material.indexOfRefraction)}configureSubsurface(){this._material.subSurface.useGltfStyleTextures=!0,this._material.subSurface.volumeIndexOfRefraction=1,this._material.subSurface.minimumThickness=0,this._material.subSurface.maximumThickness=0,this._material.subSurface.useAlbedoToTintTranslucency=!1}set subsurfaceWeight(e){this._material.subSurface.isTranslucencyEnabled=e>0,this._material.subSurface.translucencyIntensity=e}get subsurfaceWeight(){return this._material.subSurface.isTranslucencyEnabled?this._material.subSurface.translucencyIntensity:0}set subsurfaceWeightTexture(e){this._material.subSurface.translucencyIntensityTexture=e}set subsurfaceColor(e){let t=new b(-Math.log(this.transmissionColor.r),-Math.log(this.transmissionColor.g),-Math.log(this.transmissionColor.b));t.scaleInPlace(1/Math.max(this.transmissionDepth,.001));let i=t,r=Math.max(i.x,Math.max(i.y,i.z)),s=r>0?1/r:1;this._material.subSurface.diffusionDistance=new ve(Math.exp(-i.x*s),Math.exp(-i.y*s),Math.exp(-i.z*s))}set subsurfaceColorTexture(e){}set diffuseTransmissionTint(e){this._material.subSurface.tintColor=e}get diffuseTransmissionTint(){return this._material.subSurface.tintColor}set diffuseTransmissionTintTexture(e){this._material.subSurface.translucencyColorTexture=e}get subsurfaceRadius(){return 1}set subsurfaceRadius(e){}get subsurfaceRadiusScale(){var e;return(e=this._material.subSurface.scatteringDiffusionProfile)!=null?e:ve.White()}set subsurfaceRadiusScale(e){this._material.subSurface.scatteringDiffusionProfile=e}set subsurfaceScatterAnisotropy(e){}isTranslucent(){return this.transmissionWeight>0||this.subsurfaceWeight>0}configureFuzz(){this._material.sheen.isEnabled=!0,this._material.sheen.useRoughnessFromMainTexture=!1,this._material.sheen.albedoScaling=!0}set fuzzWeight(e){this._material.sheen.isEnabled=!0,this._material.sheen.intensity=e}set fuzzWeightTexture(e){this._material.sheen.texture||(this._material.sheen.texture=e)}set fuzzColor(e){this._material.sheen.isEnabled=!0,this._material.sheen.color=e}set fuzzColorTexture(e){this._material.sheen.texture=e}set fuzzRoughness(e){this._material.sheen.isEnabled=!0,this._material.sheen.roughness=e}set fuzzRoughnessTexture(e){this._material.sheen.isEnabled=!0,this._material.sheen.textureRoughness=e}set specularRoughnessAnisotropy(e){this._material.anisotropy.isEnabled=!0,this._material.anisotropy.intensity=e}get specularRoughnessAnisotropy(){return this._material.anisotropy.intensity}set geometryTangentAngle(e){this._material.anisotropy.isEnabled=!0,this._material.anisotropy.angle=e}set geometryTangentTexture(e){this._material.anisotropy.isEnabled=!0,this._material.anisotropy.texture=e}get geometryTangentTexture(){return this._material.anisotropy.texture}configureGltfStyleAnisotropy(e=!0){}set thinFilmWeight(e){this._material.iridescence.isEnabled=e>0,this._material.iridescence.intensity=e}set thinFilmIor(e){this._material.iridescence.indexOfRefraction=e}set thinFilmThicknessMinimum(e){this._material.iridescence.minimumThickness=e}set thinFilmThicknessMaximum(e){this._material.iridescence.maximumThickness=e}set thinFilmWeightTexture(e){this._material.iridescence.texture=e}set thinFilmThicknessTexture(e){this._material.iridescence.thicknessTexture=e}set unlit(e){this._material.unlit=e}set geometryOpacity(e){this._material.alpha=e}get geometryOpacity(){return this._material.alpha}set geometryNormalTexture(e){this._material.bumpTexture=e,this._material.forceIrradianceInFragment=!0}get geometryNormalTexture(){return this._material.bumpTexture}setNormalMapInversions(e,t){this._material.invertNormalMapX=e,this._material.invertNormalMapY=t}set geometryCoatNormalTexture(e){this._material.clearCoat.isEnabled=!0,this._material.clearCoat.bumpTexture=e}get geometryCoatNormalTexture(){return this._material.clearCoat.bumpTexture}set geometryCoatNormalTextureScale(e){this._material.clearCoat.bumpTexture&&(this._material.clearCoat.bumpTexture.level=e)}}});function xde(n){if(n.min&&n.max){let e=n.min,t=n.max,i=$.Vector3[0].copyFromFloats(e[0],e[1],e[2]),r=$.Vector3[1].copyFromFloats(t[0],t[1],t[2]);if(n.normalized&&n.componentType!==5126){let s=1;switch(n.componentType){case 5120:s=127;break;case 5121:s=255;break;case 5122:s=32767;break;case 5123:s=65535;break}let a=1/s;i.scaleInPlace(a),r.scaleInPlace(a)}return new un(i,r)}return null}var Tde,Ade,Kt,CR,A9=C(()=>{UX();Ge();zt();Ii();sl();XX();dR();KX();Vn();Fr();qh();ki();yA();_m();Mi();BD();qX();FD();Wl();Pt();mm();VD();kD();JX();rm();e5();Tde=new zg(()=>Promise.resolve().then(()=>(s5(),n5))),Ade=new zg(()=>Promise.resolve().then(()=>(c5(),l5))),Kt=class{static Get(e,t,i){if(!t||i==null||!t[i])throw new Error(`${e}: Failed to find index (${i})`);return t[i]}static TryGet(e,t){return!e||t==null||!e[t]?null:e[t]}static Assign(e){if(e)for(let t=0;tt.dispose&&t.dispose()),this._extensions.length=0;for(let t of Array.from(this._materialAdapters))(e=t.finalize)==null||e.call(t);this._materialAdapters.clear(),this._gltf=null,this._bin=null,this._babylonScene=null,this._rootBabylonMesh=null,this._defaultBabylonMaterialData={},this._postSceneLoadActions.length=0,this._parent.dispose()}}async importMeshAsync(e,t,i,r,s,a,o=""){return await Promise.resolve().then(async()=>{this._babylonScene=t,this._assetContainer=i,this._loadData(r);let l=null;if(e){let c={};if(this._gltf.nodes)for(let h of this._gltf.nodes)h.name&&(c[h.name]=h.index);l=(e instanceof Array?e:[e]).map(h=>{let d=c[h];if(d===void 0)throw new Error(`Failed to find node '${h}'`);return d})}return await this._loadAsync(s,o,l,()=>({meshes:this._getMeshes(),particleSystems:[],skeletons:this._getSkeletons(),animationGroups:this._getAnimationGroups(),lights:this._babylonLights,transformNodes:this._getTransformNodes(),geometries:this._getGeometries(),spriteManagers:[]}))})}async loadAsync(e,t,i,r,s=""){return this._babylonScene=e,this._loadData(t),await this._loadAsync(i,s,null,()=>{})}async _loadAsync(e,t,i,r){return await Promise.resolve().then(async()=>{this._rootUrl=e,this._uniqueRootUrl=!e.startsWith("file:")&&t?e:`${e}${Date.now()}/`,this._fileName=t,this._allMaterialsDirtyRequired=!1,await this._loadExtensionsAsync(),!this.parent.skipMaterials&&this._pbrMaterialImpl==null&&(this.parent.useOpenPBR||this.isExtensionUsed("KHR_materials_openpbr")?this._pbrMaterialImpl={materialClass:(await Promise.resolve().then(()=>(h6(),f6))).OpenPBRMaterial,adapterClass:(await Promise.resolve().then(()=>(u6(),d6))).OpenPBRMaterialLoadingAdapter}:this._pbrMaterialImpl={materialClass:(await Promise.resolve().then(()=>(E9(),v9))).PBRMaterial,adapterClass:(await Promise.resolve().then(()=>(T9(),S9))).PBRMaterialLoadingAdapter});let s=`${rs[rs.LOADING]} => ${rs[rs.READY]}`,a=`${rs[rs.LOADING]} => ${rs[rs.COMPLETE]}`;this._parent._startPerformanceCounter(s),this._parent._startPerformanceCounter(a),this._parent._setState(rs.LOADING),this._extensionsOnLoading();let o=new Array,l=this._babylonScene.blockMaterialDirtyMechanism;if(this._babylonScene.blockMaterialDirtyMechanism=!0,!this.parent.loadOnlyMaterials){if(i)o.push(this.loadSceneAsync("/nodes",{nodes:i,index:-1}));else if(this._gltf.scene!=null||this._gltf.scenes&&this._gltf.scenes[0]){let f=Kt.Get("/scene",this._gltf.scenes,this._gltf.scene||0);o.push(this.loadSceneAsync(`/scenes/${f.index}`,f))}}if(!this.parent.skipMaterials&&this.parent.loadAllMaterials&&this._gltf.materials)for(let f=0;f{}))}return this._allMaterialsDirtyRequired?this._babylonScene.blockMaterialDirtyMechanism=l:this._babylonScene._forceBlockMaterialDirtyMechanism(l),this._parent.compileMaterials&&o.push(this._compileMaterialsAsync()),this._parent.compileShadowGenerators&&o.push(this._compileShadowGeneratorsAsync()),await Promise.all(o).then(()=>{this._rootBabylonMesh&&this._rootBabylonMesh!==this._parent.customRootNode&&this._rootBabylonMesh.setEnabled(!0);for(let f of this._babylonScene.materials){let h=f;h.maxSimultaneousLights!==void 0&&(h.maxSimultaneousLights=Math.max(h.maxSimultaneousLights,this._babylonScene.lights.length))}return this._extensionsOnReady(),this._parent._setState(rs.READY),this._skipStartAnimationStep||this._startAnimations(),r()}).then(f=>(this._parent._endPerformanceCounter(s),_e.SetImmediate(()=>{this._disposed||Promise.all(this._completePromises).then(()=>{this._parent._endPerformanceCounter(a),this._parent._setState(rs.COMPLETE),this._parent.onCompleteObservable.notifyObservers(void 0),this._parent.onCompleteObservable.clear(),this.dispose()},h=>{this._parent.onErrorObservable.notifyObservers(h),this._parent.onErrorObservable.clear(),this.dispose()})}),f))}).catch(s=>{throw this._disposed||(this._parent.onErrorObservable.notifyObservers(s),this._parent.onErrorObservable.clear(),this.dispose()),s})}_loadData(e){if(this._gltf=e.json,this._setupData(),e.bin){let t=this._gltf.buffers;if(t&&t[0]&&!t[0].uri){let i=t[0];(i.byteLengthe.bin.byteLength)&&te.Warn(`Binary buffer length (${i.byteLength}) from JSON does not match chunk length (${e.bin.byteLength})`),this._bin=e.bin}else te.Warn("Unexpected BIN chunk")}}_setupData(){if(Kt.Assign(this._gltf.accessors),Kt.Assign(this._gltf.animations),Kt.Assign(this._gltf.buffers),Kt.Assign(this._gltf.bufferViews),Kt.Assign(this._gltf.cameras),Kt.Assign(this._gltf.images),Kt.Assign(this._gltf.materials),Kt.Assign(this._gltf.meshes),Kt.Assign(this._gltf.nodes),Kt.Assign(this._gltf.samplers),Kt.Assign(this._gltf.scenes),Kt.Assign(this._gltf.skins),Kt.Assign(this._gltf.textures),this._gltf.nodes){let e={};for(let i of this._gltf.nodes)if(i.children)for(let r of i.children)e[r]=i.index;let t=this._createRootNode();for(let i of this._gltf.nodes){let r=e[i.index];i.parent=r===void 0?t:this._gltf.nodes[r]}}}async _loadExtensionsAsync(){var t;let e=[];if(ZX.forEach((i,r)=>{var s;((s=this.parent.extensionOptions[r])==null?void 0:s.enabled)===!1?i.isGLTFExtension&&this.isExtensionUsed(r)&&te.Warn(`Extension ${r} is used but has been explicitly disabled.`):(!i.isGLTFExtension||this.isExtensionUsed(r))&&e.push((async()=>{let a=await i.factory(this);return a.name!==r&&te.Warn(`The name of the glTF loader extension instance does not match the registered name: ${a.name} !== ${r}`),this._parent.onExtensionLoadedObservable.notifyObservers(a),a})())}),this._extensions.push(...await Promise.all(e)),this._extensions.sort((i,r)=>(i.order||Number.MAX_VALUE)-(r.order||Number.MAX_VALUE)),this._parent.onExtensionLoadedObservable.clear(),this._gltf.extensionsRequired){for(let i of this._gltf.extensionsRequired)if(!this._extensions.some(s=>s.name===i&&s.enabled))throw((t=this.parent.extensionOptions[i])==null?void 0:t.enabled)===!1?new Error(`Required extension ${i} is disabled`):new Error(`Required extension ${i} is not available`)}}_createRootNode(){if(this._parent.customRootNode!==void 0)return this._rootBabylonMesh=this._parent.customRootNode,{_babylonTransformNode:this._rootBabylonMesh===null?void 0:this._rootBabylonMesh,index:-1};this._babylonScene._blockEntityCollection=!!this._assetContainer;let e=new q("__root__",this._babylonScene);this._rootBabylonMesh=e,this._rootBabylonMesh._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._rootBabylonMesh.setEnabled(!1);let t={_babylonTransformNode:this._rootBabylonMesh,index:-1};switch(this._parent.coordinateSystemMode){case ep.AUTO:{this._babylonScene.useRightHandedSystem||(t.rotation=[0,1,0,0],t.scale=[1,1,-1],n._LoadTransform(t,this._rootBabylonMesh));break}case ep.FORCE_RIGHT_HANDED:{this._babylonScene.useRightHandedSystem=!0;break}default:throw new Error(`Invalid coordinate system mode (${this._parent.coordinateSystemMode})`)}return this._parent.onMeshLoadedObservable.notifyObservers(e),t}loadSceneAsync(e,t){let i=this._extensionsLoadSceneAsync(e,t);if(i)return i;let r=new Array;if(this.logOpen(`${e} ${t.name||""}`),t.nodes)for(let s of t.nodes){let a=Kt.Get(`${e}/nodes/${s}`,this._gltf.nodes,s);r.push(this.loadNodeAsync(`/nodes/${a.index}`,a,o=>{o.parent=this._rootBabylonMesh}))}for(let s of this._postSceneLoadActions)s();return r.push(this._loadAnimationsAsync()),this.logClose(),Promise.all(r).then(()=>{})}_forEachPrimitive(e,t){if(e._primitiveBabylonMeshes)for(let i of e._primitiveBabylonMeshes)t(i)}_getGeometries(){let e=[],t=this._gltf.nodes;if(t)for(let i of t)this._forEachPrimitive(i,r=>{let s=r.geometry;s&&e.indexOf(s)===-1&&e.push(s)});return e}_getMeshes(){let e=[];this._rootBabylonMesh instanceof vr&&e.push(this._rootBabylonMesh);let t=this._gltf.nodes;if(t)for(let i of t)this._forEachPrimitive(i,r=>{e.push(r)});return e}_getTransformNodes(){let e=[],t=this._gltf.nodes;if(t)for(let i of t)i._babylonTransformNode&&i._babylonTransformNode.getClassName()==="TransformNode"&&e.push(i._babylonTransformNode),i._babylonTransformNodeForSkin&&e.push(i._babylonTransformNodeForSkin);return e}_getSkeletons(){let e=[],t=this._gltf.skins;if(t)for(let i of t)i._data&&e.push(i._data.babylonSkeleton);return e}_getAnimationGroups(){let e=[],t=this._gltf.animations;if(t)for(let i of t)i._babylonAnimationGroup&&e.push(i._babylonAnimationGroup);return e}_startAnimations(){switch(this._parent.animationStartMode){case ld.NONE:break;case ld.FIRST:{let e=this._getAnimationGroups();e.length!==0&&e[0].start(!0);break}case ld.ALL:{let e=this._getAnimationGroups();for(let t of e)t.start(!0);break}default:{te.Error(`Invalid animation start mode (${this._parent.animationStartMode})`);return}}}loadNodeAsync(e,t,i=()=>{}){let r=this._extensionsLoadNodeAsync(e,t,i);if(r)return r;if(t._babylonTransformNode)throw new Error(`${e}: Invalid recursive node hierarchy`);let s=new Array;this.logOpen(`${e} ${t.name||""}`);let a=c=>{if(n.AddPointerMetadata(c,e),n._LoadTransform(t,c),t.camera!=null){let f=Kt.Get(`${e}/camera`,this._gltf.cameras,t.camera);s.push(this.loadCameraAsync(`/cameras/${f.index}`,f,h=>{h.parent=c,this._babylonScene.useRightHandedSystem||(c.scaling.x=-1)}))}if(t.children)for(let f of t.children){let h=Kt.Get(`${e}/children/${f}`,this._gltf.nodes,f);s.push(this.loadNodeAsync(`/nodes/${h.index}`,h,d=>{d.parent=c}))}i(c)},o=t.mesh!=null,l=this._parent.loadSkins&&t.skin!=null;if(!o||l){let c=t.name||`node${t.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;let f=new ei(c,this._babylonScene);f._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t.mesh==null?t._babylonTransformNode=f:t._babylonTransformNodeForSkin=f,a(f)}if(o)if(l){let c=Kt.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);s.push(this._loadMeshAsync(`/meshes/${c.index}`,t,c,f=>{let h=t._babylonTransformNodeForSkin;f.metadata=WD(h.metadata,f.metadata||{});let d=Kt.Get(`${e}/skin`,this._gltf.skins,t.skin);s.push(this._loadSkinAsync(`/skins/${d.index}`,t,d,u=>{this._forEachPrimitive(t,m=>{m.skeleton=u}),this._postSceneLoadActions.push(()=>{if(d.skeleton!=null){let m=Kt.Get(`/skins/${d.index}/skeleton`,this._gltf.nodes,d.skeleton).parent;t.index===m.index?f.parent=h.parent:f.parent=m._babylonTransformNode}else f.parent=this._rootBabylonMesh;this._parent.onSkinLoadedObservable.notifyObservers({node:h,skinnedNode:f})})}))}))}else{let c=Kt.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);s.push(this._loadMeshAsync(`/meshes/${c.index}`,t,c,a))}return this.logClose(),Promise.all(s).then(()=>(this._forEachPrimitive(t,c=>{let f=c;!f.isAnInstance&&f.geometry&&f.geometry.useBoundingInfoFromGeometry?c._updateBoundingInfo():c.refreshBoundingInfo(!0,!0)}),t._babylonTransformNode))}_loadMeshAsync(e,t,i,r){let s=i.primitives;if(!s||!s.length)throw new Error(`${e}: Primitives are missing`);s[0].index==null&&Kt.Assign(s);let a=new Array;this.logOpen(`${e} ${i.name||""}`);let o=t.name||`node${t.index}`;if(s.length===1){let l=i.primitives[0];a.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${l.index}`,o,t,i,l,c=>{t._babylonTransformNode=c,t._primitiveBabylonMeshes=[c]}))}else{this._babylonScene._blockEntityCollection=!!this._assetContainer,t._babylonTransformNode=new ei(o,this._babylonScene),t._babylonTransformNode._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._primitiveBabylonMeshes=[];for(let l of s)a.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${l.index}`,`${o}_primitive${l.index}`,t,i,l,c=>{c.parent=t._babylonTransformNode,t._primitiveBabylonMeshes.push(c)}))}return r(t._babylonTransformNode),this.logClose(),Promise.all(a).then(()=>t._babylonTransformNode)}_loadMeshPrimitiveAsync(e,t,i,r,s,a){let o=this._extensionsLoadMeshPrimitiveAsync(e,t,i,r,s,a);if(o)return o;this.logOpen(`${e}`);let l=this._disableInstancedMesh===0&&this._parent.createInstances&&i.skin==null&&!r.primitives[0].targets,c,f;if(l&&s._instanceData)this._babylonScene._blockEntityCollection=!!this._assetContainer,c=s._instanceData.babylonSourceMesh.createInstance(t),c._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,f=s._instanceData.promise;else{let h=new Array;this._babylonScene._blockEntityCollection=!!this._assetContainer;let d=new q(t,this._babylonScene);if(d._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,d.sideOrientation=this._babylonScene.useRightHandedSystem?Ee.CounterClockWiseSideOrientation:Ee.ClockWiseSideOrientation,this._createMorphTargets(e,i,r,s,d),h.push(this._loadVertexDataAsync(e,s,d).then(async u=>await this._loadMorphTargetsAsync(e,s,d,u).then(()=>{this._disposed||(this._babylonScene._blockEntityCollection=!!this._assetContainer,u.applyToMesh(d),u._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1)}))),!this.parent.skipMaterials){let u=n._GetDrawMode(e,s.mode);if(s.material==null){let m=this._defaultBabylonMaterialData[u];m||(m=this._createDefaultMaterial("__GLTFLoader._default",u),this._parent.onMaterialLoadedObservable.notifyObservers(m),this._defaultBabylonMaterialData[u]=m),d.material=m}else{let m=Kt.Get(`${e}/material`,this._gltf.materials,s.material);h.push(this._loadMaterialAsync(`/materials/${m.index}`,m,d,u,p=>{d.material=p}))}}f=Promise.all(h),l&&(s._instanceData={babylonSourceMesh:d,promise:f}),c=d}return n.AddPointerMetadata(c,e),this._parent.onMeshLoadedObservable.notifyObservers(c),a(c),this.logClose(),f.then(()=>c)}_loadVertexDataAsync(e,t,i){let r=this._extensionsLoadVertexDataAsync(e,t,i);if(r)return r;let s=t.attributes;if(!s)throw new Error(`${e}: Attributes are missing`);let a=new Array,o=new mn(i.name,this._babylonScene);if(t.indices==null)i.isUnIndexed=!0;else{let c=Kt.Get(`${e}/indices`,this._gltf.accessors,t.indices);a.push(this._loadIndicesAccessorAsync(`/accessors/${c.index}`,c).then(f=>{o.setIndices(f)}))}let l=(c,f,h)=>{if(s[c]==null)return;i._delayInfo=i._delayInfo||[],i._delayInfo.indexOf(f)===-1&&i._delayInfo.push(f);let d=Kt.Get(`${e}/attributes/${c}`,this._gltf.accessors,s[c]);a.push(this._loadVertexAccessorAsync(`/accessors/${d.index}`,d,f).then(u=>{if(u.getKind()===L.PositionKind&&!this.parent.alwaysComputeBoundingBox&&!i.skeleton){let m=xde(d);m&&(o._boundingInfo=m,o.useBoundingInfoFromGeometry=!0)}o.setVerticesBuffer(u,d.count)})),f==L.MatricesIndicesExtraKind&&(i.numBoneInfluencers=8),h&&h(d)};return l("POSITION",L.PositionKind),l("NORMAL",L.NormalKind),l("TANGENT",L.TangentKind),l("TEXCOORD_0",L.UVKind),l("TEXCOORD_1",L.UV2Kind),l("TEXCOORD_2",L.UV3Kind),l("TEXCOORD_3",L.UV4Kind),l("TEXCOORD_4",L.UV5Kind),l("TEXCOORD_5",L.UV6Kind),l("JOINTS_0",L.MatricesIndicesKind),l("WEIGHTS_0",L.MatricesWeightsKind),l("JOINTS_1",L.MatricesIndicesExtraKind),l("WEIGHTS_1",L.MatricesWeightsExtraKind),l("COLOR_0",L.ColorKind,c=>{c.type==="VEC4"&&(i.hasVertexAlpha=!0)}),Promise.all(a).then(()=>o)}_createMorphTargets(e,t,i,r,s){if(!r.targets||!this._parent.loadMorphTargets)return;if(t._numMorphTargets==null)t._numMorphTargets=r.targets.length;else if(r.targets.length!==t._numMorphTargets)throw new Error(`${e}: Primitives do not have the same number of targets`);let a=i.extras?i.extras.targetNames:null;this._babylonScene._blockEntityCollection=!!this._assetContainer,s.morphTargetManager=new dd(this._babylonScene),s.morphTargetManager._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,s.morphTargetManager.areUpdatesFrozen=!0;for(let o=0;o{a.areUpdatesFrozen=!1})}async _loadMorphTargetVertexDataAsync(e,t,i,r){let s=new Array,a=(o,l,c)=>{if(i[o]==null)return;let f=t.getVertexBuffer(l);if(!f)return;let h=Kt.Get(`${e}/${o}`,this._gltf.accessors,i[o]);s.push(this._loadFloatAccessorAsync(`/accessors/${h.index}`,h).then(d=>{c(f,d)}))};return a("POSITION",L.PositionKind,(o,l)=>{let c=new Float32Array(l.length);o.forEach(l.length,(f,h)=>{c[h]=l[h]+f}),r.setPositions(c)}),a("NORMAL",L.NormalKind,(o,l)=>{let c=new Float32Array(l.length);o.forEach(c.length,(f,h)=>{c[h]=l[h]+f}),r.setNormals(c)}),a("TANGENT",L.TangentKind,(o,l)=>{let c=new Float32Array(l.length/3*4),f=0;o.forEach(l.length/3*4,(h,d)=>{(d+1)%4!==0&&(c[f]=l[f]+h,f++)}),r.setTangents(c)}),a("TEXCOORD_0",L.UVKind,(o,l)=>{let c=new Float32Array(l.length);o.forEach(l.length,(f,h)=>{c[h]=l[h]+f}),r.setUVs(c)}),a("TEXCOORD_1",L.UV2Kind,(o,l)=>{let c=new Float32Array(l.length);o.forEach(l.length,(f,h)=>{c[h]=l[h]+f}),r.setUV2s(c)}),a("COLOR_0",L.ColorKind,(o,l)=>{let c=null,f=o.getSize();if(f===3){c=new Float32Array(l.length/3*4),o.forEach(l.length,(h,d)=>{let u=Math.floor(d/3),m=d%3;c[4*u+m]=l[3*u+m]+h});for(let h=0;h{c[d]=l[d]+h});else throw new Error(`${e}: Invalid number of components (${f}) for COLOR_0 attribute`);r.setColors(c)}),await Promise.all(s).then(()=>{})}static _LoadTransform(e,t){if(e.skin!=null)return;let i=b.Zero(),r=Xe.Identity(),s=b.One();e.matrix?K.FromArray(e.matrix).decompose(s,r,i):(e.translation&&(i=b.FromArray(e.translation)),e.rotation&&(r=Xe.FromArray(e.rotation)),e.scale&&(s=b.FromArray(e.scale))),t.position=i,t.rotationQuaternion=r,t.scaling=s}_loadSkinAsync(e,t,i,r){if(!this._parent.loadSkins)return Promise.resolve();let s=this._extensionsLoadSkinAsync(e,t,i);if(s)return s;if(i._data)return r(i._data.babylonSkeleton),i._data.promise;let a=`skeleton${i.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;let o=new uR(i.name||a,a,this._babylonScene);o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._loadBones(e,i,o);let l=this._loadSkinInverseBindMatricesDataAsync(e,i).then(c=>{this._updateBoneMatrices(o,c)});return i._data={babylonSkeleton:o,promise:l},r(o),l}_loadBones(e,t,i){if(t.skeleton==null||this._parent.alwaysComputeSkeletonRootNode){let s=this._findSkeletonRootNode(`${e}/joints`,t.joints);if(s)if(t.skeleton===void 0)t.skeleton=s.index;else{let a=(l,c)=>{for(;c.parent;c=c.parent)if(c.parent===l)return!0;return!1},o=Kt.Get(`${e}/skeleton`,this._gltf.nodes,t.skeleton);o!==s&&!a(o,s)&&(te.Warn(`${e}/skeleton: Overriding with nearest common ancestor as skeleton node is not a common root`),t.skeleton=s.index)}else te.Warn(`${e}: Failed to find common root`)}let r={};for(let s of t.joints){let a=Kt.Get(`${e}/joints/${s}`,this._gltf.nodes,s);this._loadBone(a,t,i,r)}}_findSkeletonRootNode(e,t){if(t.length===0)return null;let i={};for(let s of t){let a=[],o=Kt.Get(`${e}/${s}`,this._gltf.nodes,s);for(;o.index!==-1;)a.unshift(o),o=o.parent;i[s]=a}let r=null;for(let s=0;;++s){let a=i[t[0]];if(s>=a.length)return r;let o=a[s];for(let l=1;l=a.length||o!==a[s])return r;r=o}}_loadBone(e,t,i,r){e._isJoint=!0;let s=r[e.index];if(s)return s;let a=null;e.index!==t.skeleton&&(e.parent&&e.parent.index!==-1?a=this._loadBone(e.parent,t,i,r):t.skeleton!==void 0&&te.Warn(`/skins/${t.index}/skeleton: Skeleton node is not a common root`));let o=t.joints.indexOf(e.index);return s=new wa(e.name||`joint${e.index}`,i,a,this._getNodeMatrix(e),null,null,o),r[e.index]=s,this._postSceneLoadActions.push(()=>{s.linkTransformNode(e._babylonTransformNode)}),s}_loadSkinInverseBindMatricesDataAsync(e,t){if(t.inverseBindMatrices==null)return Promise.resolve(null);let i=Kt.Get(`${e}/inverseBindMatrices`,this._gltf.accessors,t.inverseBindMatrices);return this._loadFloatAccessorAsync(`/accessors/${i.index}`,i)}_updateBoneMatrices(e,t){for(let i of e.bones){let r=K.Identity(),s=i._index;t&&s!==-1&&(K.FromArrayToRef(t,s*16,r),r.invertToRef(r));let a=i.getParent();a&&r.multiplyToRef(a.getAbsoluteInverseBindMatrix(),r),i.updateMatrix(r,!1,!1),i._updateAbsoluteBindMatrices(void 0,!1)}}_getNodeMatrix(e){return e.matrix?K.FromArray(e.matrix):K.Compose(e.scale?b.FromArray(e.scale):b.One(),e.rotation?Xe.FromArray(e.rotation):Xe.Identity(),e.translation?b.FromArray(e.translation):b.Zero())}loadCameraAsync(e,t,i=()=>{}){let r=this._extensionsLoadCameraAsync(e,t,i);if(r)return r;let s=new Array;this.logOpen(`${e} ${t.name||""}`),this._babylonScene._blockEntityCollection=!!this._assetContainer;let a=new Ac(t.name||`camera${t.index}`,b.Zero(),this._babylonScene,!1);switch(a._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._babylonCamera=a,a.setTarget(new b(0,0,-1)),t.type){case"perspective":{let o=t.perspective;if(!o)throw new Error(`${e}: Camera perspective properties are missing`);a.fov=o.yfov,a.minZ=o.znear,a.maxZ=o.zfar||0;break}case"orthographic":{if(!t.orthographic)throw new Error(`${e}: Camera orthographic properties are missing`);a.mode=mt.ORTHOGRAPHIC_CAMERA,a.orthoLeft=-t.orthographic.xmag,a.orthoRight=t.orthographic.xmag,a.orthoBottom=-t.orthographic.ymag,a.orthoTop=t.orthographic.ymag,a.minZ=t.orthographic.znear,a.maxZ=t.orthographic.zfar;break}default:throw new Error(`${e}: Invalid camera type (${t.type})`)}return n.AddPointerMetadata(a,e),this._parent.onCameraLoadedObservable.notifyObservers(a),i(a),this.logClose(),Promise.all(s).then(()=>a)}_loadAnimationsAsync(){this._parent._startPerformanceCounter("Load animations");let e=this._gltf.animations;if(!e)return Promise.resolve();let t=new Array;for(let i=0;i{s.targetedAnimations.length===0&&s.dispose()}))}return Promise.all(t).then(()=>{this._parent._endPerformanceCounter("Load animations")})}loadAnimationAsync(e,t){this._parent._startPerformanceCounter("Load animation");let i=this._extensionsLoadAnimationAsync(e,t);return i||Tde.value.then(({AnimationGroup:r})=>{this._babylonScene._blockEntityCollection=!!this._assetContainer;let s=new r(t.name||`animation${t.index}`,this._babylonScene);s._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._babylonAnimationGroup=s;let a=new Array;Kt.Assign(t.channels),Kt.Assign(t.samplers);for(let o of t.channels)a.push(this._loadAnimationChannelAsync(`${e}/channels/${o.index}`,e,t,o,(l,c)=>{l.animations=l.animations||[],l.animations.push(c),s.addTargetedAnimation(c,l)}));return this._parent._endPerformanceCounter("Load animation"),Promise.all(a).then(()=>(s.normalize(0),s))})}_loadAnimationChannelAsync(e,t,i,r,s){let a=this._extensionsLoadAnimationChannelAsync(e,t,i,r,s);if(a)return a;if(r.target.node==null)return Promise.resolve();let o=Kt.Get(`${e}/target/node`,this._gltf.nodes,r.target.node),l=r.target.path,c=l==="weights";return c&&!o._numMorphTargets||!c&&!o._babylonTransformNode||!this._parent.loadNodeAnimations&&!c&&!o._isJoint?Promise.resolve():Ade.value.then(()=>{var d,u,m,p;let f;switch(l){case"translation":{f=(d=Wg("/nodes/{}/translation"))==null?void 0:d.interpolation;break}case"rotation":{f=(u=Wg("/nodes/{}/rotation"))==null?void 0:u.interpolation;break}case"scale":{f=(m=Wg("/nodes/{}/scale"))==null?void 0:m.interpolation;break}case"weights":{f=(p=Wg("/nodes/{}/weights"))==null?void 0:p.interpolation;break}default:throw new Error(`${e}/target/path: Invalid value (${r.target.path})`)}if(!f)throw new Error(`${e}/target/path: Could not find interpolation properties for target path (${r.target.path})`);let h={object:o,info:f};return this._loadAnimationChannelFromTargetInfoAsync(e,t,i,r,h,s)})}_loadAnimationChannelFromTargetInfoAsync(e,t,i,r,s,a){let o=this.parent.targetFps,l=1/o,c=Kt.Get(`${e}/sampler`,i.samplers,r.sampler);return this._loadAnimationSamplerAsync(`${t}/samplers/${r.sampler}`,c).then(f=>{let h=0,d=s.object,u=s.info;for(let m of u){let p=m.getStride(d),_=f.input,g=f.output,v=new Array(_.length),x=0;switch(f.interpolation){case"STEP":{for(let A=0;A<_.length;A++){let S=m.getValue(d,g,x,1);x+=p,v[A]={frame:_[A]*o,value:S,interpolation:1}}break}case"CUBICSPLINE":{for(let A=0;A<_.length;A++){let S=m.getValue(d,g,x,l);x+=p;let E=m.getValue(d,g,x,1);x+=p;let R=m.getValue(d,g,x,l);x+=p,v[A]={frame:_[A]*o,inTangent:S,value:E,outTangent:R}}break}case"LINEAR":{for(let A=0;A<_.length;A++){let S=m.getValue(d,g,x,1);x+=p,v[A]={frame:_[A]*o,value:S}}break}}if(x>0){let A=`${i.name||`animation${i.index}`}_channel${r.index}_${h}`,S=m.buildAnimations(d,A,o,v);for(let E of S)h++,a(E.babylonAnimatable,E.babylonAnimation)}}})}_loadAnimationSamplerAsync(e,t){if(t._data)return t._data;let i=t.interpolation||"LINEAR";switch(i){case"STEP":case"LINEAR":case"CUBICSPLINE":break;default:throw new Error(`${e}/interpolation: Invalid value (${t.interpolation})`)}let r=Kt.Get(`${e}/input`,this._gltf.accessors,t.input),s=Kt.Get(`${e}/output`,this._gltf.accessors,t.output);return t._data=Promise.all([this._loadFloatAccessorAsync(`/accessors/${r.index}`,r),this._loadFloatAccessorAsync(`/accessors/${s.index}`,s)]).then(([a,o])=>({input:a,interpolation:i,output:o})),t._data}loadBufferAsync(e,t,i,r){let s=this._extensionsLoadBufferAsync(e,t,i,r);if(s)return s;if(!t._data)if(t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{if(!this._bin)throw new Error(`${e}: Uri is missing or the binary glTF is missing its binary chunk`);t._data=this._bin.readAsync(0,t.byteLength)}return t._data.then(a=>{try{return new Uint8Array(a.buffer,a.byteOffset+i,r)}catch(o){throw new Error(`${e}: ${o.message}`,{cause:o})}})}loadBufferViewAsync(e,t){let i=this._extensionsLoadBufferViewAsync(e,t);if(i)return i;if(t._data)return t._data;let r=Kt.Get(`${e}/buffer`,this._gltf.buffers,t.buffer);return t._data=this.loadBufferAsync(`/buffers/${r.index}`,r,t.byteOffset||0,t.byteLength),t._data}_loadAccessorAsync(e,t,i){if(t._data)return t._data;let r=n._GetNumComponents(e,t.type),s=r*L.GetTypeByteLength(t.componentType),a=r*t.count;if(t.bufferView==null)t._data=Promise.resolve(new i(a));else{let o=Kt.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${o.index}`,o).then(l=>{if(t.componentType===5126&&!t.normalized&&(!o.byteStride||o.byteStride===s))return n._GetTypedArray(e,t.componentType,l,t.byteOffset,a);{let c=new i(a);return L.ForEach(l,t.byteOffset||0,o.byteStride||s,r,t.componentType,c.length,t.normalized||!1,(f,h)=>{c[h]=f}),c}})}if(t.sparse){let o=t.sparse;t._data=t._data.then(l=>{let c=l,f=Kt.Get(`${e}/sparse/indices/bufferView`,this._gltf.bufferViews,o.indices.bufferView),h=Kt.Get(`${e}/sparse/values/bufferView`,this._gltf.bufferViews,o.values.bufferView);return Promise.all([this.loadBufferViewAsync(`/bufferViews/${f.index}`,f),this.loadBufferViewAsync(`/bufferViews/${h.index}`,h)]).then(([d,u])=>{let m=n._GetTypedArray(`${e}/sparse/indices`,o.indices.componentType,d,o.indices.byteOffset,o.count),p=r*o.count,_;if(t.componentType===5126&&!t.normalized)_=n._GetTypedArray(`${e}/sparse/values`,t.componentType,u,o.values.byteOffset,p);else{let v=n._GetTypedArray(`${e}/sparse/values`,t.componentType,u,o.values.byteOffset,p);_=new i(p),L.ForEach(v,0,s,r,t.componentType,_.length,t.normalized||!1,(x,A)=>{_[A]=x})}let g=0;for(let v=0;vn._GetTypedArray(e,t.componentType,r,t.byteOffset,t.count))}return t._data}_loadVertexBufferViewAsync(e){if(e._babylonBuffer)return e._babylonBuffer;let t=this._babylonScene.getEngine();return e._babylonBuffer=this.loadBufferViewAsync(`/bufferViews/${e.index}`,e).then(i=>new ro(t,i,!1)),e._babylonBuffer}_loadVertexAccessorAsync(e,t,i){var s;if((s=t._babylonVertexBuffer)!=null&&s[i])return t._babylonVertexBuffer[i];t._babylonVertexBuffer||(t._babylonVertexBuffer={});let r=this._babylonScene.getEngine();if(t.sparse||t.bufferView==null)t._babylonVertexBuffer[i]=this._loadFloatAccessorAsync(e,t).then(a=>new L(r,a,i,!1));else{let a=Kt.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._babylonVertexBuffer[i]=this._loadVertexBufferViewAsync(a).then(o=>{let l=n._GetNumComponents(e,t.type);return new L(r,o,i,!1,void 0,a.byteStride,void 0,t.byteOffset,l,t.componentType,t.normalized,!0,void 0,!0)})}return t._babylonVertexBuffer[i]}_loadMaterialMetallicRoughnessPropertiesAsync(e,t,i){let r=new Array,s=this._getOrCreateMaterialAdapter(i);return t&&(t.baseColorFactor?(s.baseColor=ve.FromArray(t.baseColorFactor),s.geometryOpacity=t.baseColorFactor[3]):s.baseColor=ve.White(),s.baseMetalness=t.metallicFactor==null?1:t.metallicFactor,s.specularRoughness=t.roughnessFactor==null?1:t.roughnessFactor,t.baseColorTexture&&r.push(this.loadTextureInfoAsync(`${e}/baseColorTexture`,t.baseColorTexture,a=>{a.name=`${i.name} (Base Color)`,s.baseColorTexture=a})),t.metallicRoughnessTexture&&(t.metallicRoughnessTexture.nonColorData=!0,r.push(this.loadTextureInfoAsync(`${e}/metallicRoughnessTexture`,t.metallicRoughnessTexture,a=>{a.name=`${i.name} (Metallic Roughness)`,s.baseMetalnessTexture=a,s.specularRoughnessTexture=a})),s.useRoughnessFromMetallicTextureGreen=!0,s.useMetallicFromMetallicTextureBlue=!0)),Promise.all(r).then(()=>{})}_loadMaterialAsync(e,t,i,r,s=()=>{}){let a=this._extensionsLoadMaterialAsync(e,t,i,r,s);if(a)return a;t._data=t._data||{};let o=t._data[r];if(!o){this.logOpen(`${e} ${t.name||""}`);let l=this.createMaterial(e,t,r);o={babylonMaterial:l,babylonMeshes:[],promise:this.loadMaterialPropertiesAsync(e,t,l)},t._data[r]=o,n.AddPointerMetadata(l,e),this._parent.onMaterialLoadedObservable.notifyObservers(l),this.logClose()}return i&&(o.babylonMeshes.push(i),i.onDisposeObservable.addOnce(()=>{let l=o.babylonMeshes.indexOf(i);l!==-1&&o.babylonMeshes.splice(l,1)})),s(o.babylonMaterial),o.promise.then(()=>o.babylonMaterial)}_createDefaultMaterial(e,t){if(!this._pbrMaterialImpl)throw new Error("PBR Material class not loaded");this._babylonScene._blockEntityCollection=!!this._assetContainer;let i=new this._pbrMaterialImpl.materialClass(e,this._babylonScene);i._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,i.fillMode=t,i.transparencyMode=this._pbrMaterialImpl.materialClass.MATERIAL_OPAQUE;let r=this._getOrCreateMaterialAdapter(i);return r.transparencyAsAlphaCoverage=this._parent.transparencyAsCoverage,r.baseMetalness=1,r.specularRoughness=1,i}createMaterial(e,t,i){let r=this._extensionsCreateMaterial(e,t,i);if(r)return r;let s=t.name||`material${t.index}`;return this._createDefaultMaterial(s,i)}loadMaterialPropertiesAsync(e,t,i){let r=this._extensionsLoadMaterialPropertiesAsync(e,t,i);if(r)return r;let s=new Array;return s.push(this.loadMaterialBasePropertiesAsync(e,t,i)),t.pbrMetallicRoughness&&s.push(this._loadMaterialMetallicRoughnessPropertiesAsync(`${e}/pbrMetallicRoughness`,t.pbrMetallicRoughness,i)),this.loadMaterialAlphaProperties(e,t,i),Promise.all(s).then(()=>{})}loadMaterialBasePropertiesAsync(e,t,i){let r=new Array,s=this._getOrCreateMaterialAdapter(i);s.emissionColor=t.emissiveFactor?ve.FromArray(t.emissiveFactor):new ve(0,0,0),t.doubleSided&&(s.backFaceCulling=!1,s.twoSidedLighting=!0),t.normalTexture&&(t.normalTexture.nonColorData=!0,r.push(this.loadTextureInfoAsync(`${e}/normalTexture`,t.normalTexture,c=>{var f;c.name=`${i.name} (Normal)`,s.geometryNormalTexture=c,((f=t.normalTexture)==null?void 0:f.scale)!=null&&(c.level=t.normalTexture.scale)})),s.setNormalMapInversions(!this._babylonScene.useRightHandedSystem,this._babylonScene.useRightHandedSystem));let a,o=1,l;return t.occlusionTexture&&(t.occlusionTexture.nonColorData=!0,r.push(this.loadTextureInfoAsync(`${e}/occlusionTexture`,t.occlusionTexture,c=>{c.name=`${i.name} (Occlusion)`,a=c})),t.occlusionTexture.strength!=null&&(o=t.occlusionTexture.strength)),t.emissiveTexture&&r.push(this.loadTextureInfoAsync(`${e}/emissiveTexture`,t.emissiveTexture,c=>{c.name=`${i.name} (Emissive)`,l=c})),Promise.all(r).then(()=>{a&&(s.ambientOcclusionTexture=a,s.ambientOcclusionTextureStrength=o),l&&(s.emissionColorTexture=l)})}loadMaterialAlphaProperties(e,t,i){if(!this._pbrMaterialImpl)throw new Error(`${e}: Material type not supported`);let r=this._getOrCreateMaterialAdapter(i),s=r.baseColorTexture;switch(t.alphaMode||"OPAQUE"){case"OPAQUE":{i.transparencyMode=this._pbrMaterialImpl.materialClass.MATERIAL_OPAQUE,i.alpha=1;break}case"MASK":{i.transparencyMode=this._pbrMaterialImpl.materialClass.MATERIAL_ALPHATEST,r.alphaCutOff=t.alphaCutoff==null?.5:t.alphaCutoff,s&&(s.hasAlpha=!0);break}case"BLEND":{i.transparencyMode=this._pbrMaterialImpl.materialClass.MATERIAL_ALPHABLEND,s&&(s.hasAlpha=!0,r.useAlphaFromBaseColorTexture=!0);break}default:throw new Error(`${e}/alphaMode: Invalid value (${t.alphaMode})`)}}loadTextureInfoAsync(e,t,i=()=>{}){let r=this._extensionsLoadTextureInfoAsync(e,t,i);if(r)return r;if(this.logOpen(`${e}`),t.texCoord>=6)throw new Error(`${e}/texCoord: Invalid value (${t.texCoord})`);let s=Kt.Get(`${e}/index`,this._gltf.textures,t.index);s._textureInfo=t;let a=this._loadTextureAsync(`/textures/${t.index}`,s,o=>{o.coordinatesIndex=t.texCoord||0,n.AddPointerMetadata(o,e),this._parent.onTextureLoadedObservable.notifyObservers(o),i(o)});return this.logClose(),a}_loadTextureAsync(e,t,i=()=>{}){let r=this._extensionsLoadTextureAsync(e,t,i);if(r)return r;this.logOpen(`${e} ${t.name||""}`);let s=t.sampler==null?n.DefaultSampler:Kt.Get(`${e}/sampler`,this._gltf.samplers,t.sampler),a=Kt.Get(`${e}/source`,this._gltf.images,t.source),o=this._createTextureAsync(e,s,a,i,void 0,!t._textureInfo.nonColorData);return this.logClose(),o}_createTextureAsync(e,t,i,r=()=>{},s,a){var m,p;let o=this._loadSampler(`/samplers/${t.index}`,t),l=new Array,c=new fR;this._babylonScene._blockEntityCollection=!!this._assetContainer;let f={noMipmap:o.noMipMaps,invertY:!1,samplingMode:o.samplingMode,onLoad:()=>{this._disposed||c.resolve()},onError:(_,g)=>{this._disposed||c.reject(new Error(`${e}: ${g&&g.message?g.message:_||"Failed to load texture"}`))},mimeType:(p=i.mimeType)!=null?p:F2((m=i.uri)!=null?m:""),loaderOptions:s,useSRGBBuffer:!!a&&this._parent.useSRGBBuffers},h=new ge(null,this._babylonScene,f);h._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,l.push(c.promise);let d=i.uri&&!ff(i.uri)?i.uri:void 0,u=d!=null?d:`${this._fileName}#image${i.index}`;if(l.push(this.loadImageAsync(`/images/${i.index}`,i).then(_=>{let g=`data:${this._uniqueRootUrl}${u}`;h.updateURL(g,_);let v=h.getInternalTexture();v&&(v.label=i.name)})),h.wrapU=o.wrapU,h.wrapV=o.wrapV,r(h),this._parent.useGltfTextureNames){let _=i.name||d||`image${i.index}`;h.name=_}return Promise.all(l).then(()=>h)}_loadSampler(e,t){return t._data||(t._data={noMipMaps:t.minFilter===9728||t.minFilter===9729,samplingMode:n._GetTextureSamplingMode(e,t),wrapU:n._GetTextureWrapMode(`${e}/wrapS`,t.wrapS),wrapV:n._GetTextureWrapMode(`${e}/wrapT`,t.wrapT)}),t._data}loadImageAsync(e,t){if(!t._data){if(this.logOpen(`${e} ${t.name||""}`),t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{let i=Kt.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${i.index}`,i)}this.logClose()}return t._data}loadUriAsync(e,t,i){let r=this._extensionsLoadUriAsync(e,t,i);if(r)return r;if(!n._ValidateUri(i))throw new Error(`${e}: '${i}' is invalid`);if(ff(i)){let s=new Uint8Array(hf(i));return this.log(`${e}: Decoded ${i.substring(0,64)}... (${s.length} bytes)`),Promise.resolve(s)}return this.log(`${e}: Loading ${i}`),this._parent.preprocessUrlAsync(this._rootUrl+i).then(s=>new Promise((a,o)=>{this._parent._loadFile(this._babylonScene,s,l=>{this._disposed||(this.log(`${e}: Loaded ${i} (${l.byteLength} bytes)`),a(new Uint8Array(l)))},!0,l=>{o(new nm(`${e}: Failed to load '${i}'${l?": "+l.status+" "+l.statusText:""}`,l))})}))}static AddPointerMetadata(e,t){e.metadata=e.metadata||{};let i=e._internalMetadata=e._internalMetadata||{},r=i.gltf=i.gltf||{};(r.pointers=r.pointers||[]).push(t)}static _GetTextureWrapMode(e,t){switch(t=t==null?10497:t,t){case 33071:return ge.CLAMP_ADDRESSMODE;case 33648:return ge.MIRROR_ADDRESSMODE;case 10497:return ge.WRAP_ADDRESSMODE;default:return te.Warn(`${e}: Invalid value (${t})`),ge.WRAP_ADDRESSMODE}}static _GetTextureSamplingMode(e,t){let i=t.magFilter==null?9729:t.magFilter,r=t.minFilter==null?9987:t.minFilter;if(i===9729)switch(r){case 9728:return ge.LINEAR_NEAREST;case 9729:return ge.LINEAR_LINEAR;case 9984:return ge.LINEAR_NEAREST_MIPNEAREST;case 9985:return ge.LINEAR_LINEAR_MIPNEAREST;case 9986:return ge.LINEAR_NEAREST_MIPLINEAR;case 9987:return ge.LINEAR_LINEAR_MIPLINEAR;default:return te.Warn(`${e}/minFilter: Invalid value (${r})`),ge.LINEAR_LINEAR_MIPLINEAR}else switch(i!==9728&&te.Warn(`${e}/magFilter: Invalid value (${i})`),r){case 9728:return ge.NEAREST_NEAREST;case 9729:return ge.NEAREST_LINEAR;case 9984:return ge.NEAREST_NEAREST_MIPNEAREST;case 9985:return ge.NEAREST_LINEAR_MIPNEAREST;case 9986:return ge.NEAREST_NEAREST_MIPLINEAR;case 9987:return ge.NEAREST_LINEAR_MIPLINEAR;default:return te.Warn(`${e}/minFilter: Invalid value (${r})`),ge.NEAREST_NEAREST_MIPNEAREST}}static _GetTypedArrayConstructor(e,t){try{return UM(t)}catch(i){throw new Error(`${e}: ${i.message}`,{cause:i})}}static _GetTypedArray(e,t,i,r,s){let a=i.buffer;r=i.byteOffset+(r||0);let o=n._GetTypedArrayConstructor(`${e}/componentType`,t),l=L.GetTypeByteLength(t);return r%l!==0?(te.Warn(`${e}: Copying buffer as byte offset (${r}) is not a multiple of component type byte length (${l})`),new o(a.slice(r,r+s*l),0)):new o(a,r,s)}static _GetNumComponents(e,t){switch(t){case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3;case"VEC4":return 4;case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16}throw new Error(`${e}: Invalid type (${t})`)}static _ValidateUri(e){return _e.IsBase64(e)||e.indexOf("..")===-1}static _GetDrawMode(e,t){switch(t==null&&(t=4),t){case 0:return Ee.PointListDrawMode;case 1:return Ee.LineListDrawMode;case 2:return Ee.LineLoopDrawMode;case 3:return Ee.LineStripDrawMode;case 4:return Ee.TriangleFillMode;case 5:return Ee.TriangleStripDrawMode;case 6:return Ee.TriangleFanDrawMode}throw new Error(`${e}: Invalid mesh primitive mode (${t})`)}_compileMaterialsAsync(){this._parent._startPerformanceCounter("Compile materials");let e=new Array;if(this._gltf.materials){for(let t of this._gltf.materials)if(t._data)for(let i in t._data){let r=t._data[i];for(let s of r.babylonMeshes){s.computeWorldMatrix(!0);let a=r.babylonMaterial;e.push(a.forceCompilationAsync(s)),e.push(a.forceCompilationAsync(s,{useInstances:!0})),this._parent.useClipPlane&&(e.push(a.forceCompilationAsync(s,{clipPlane:!0})),e.push(a.forceCompilationAsync(s,{clipPlane:!0,useInstances:!0})))}}}return Promise.all(e).then(()=>{this._parent._endPerformanceCounter("Compile materials")})}_compileShadowGeneratorsAsync(){this._parent._startPerformanceCounter("Compile shadow generators");let e=new Array,t=this._babylonScene.lights;for(let i of t){let r=i.getShadowGenerator();r&&e.push(r.forceCompilationAsync())}return Promise.all(e).then(()=>{this._parent._endPerformanceCounter("Compile shadow generators")})}_forEachExtensions(e){for(let t of this._extensions)t.enabled&&e(t)}_applyExtensions(e,t,i){for(let r of this._extensions)if(r.enabled){let s=`${r.name}.${t}`,a=e;a._activeLoaderExtensionFunctions=a._activeLoaderExtensionFunctions||{};let o=a._activeLoaderExtensionFunctions;if(!o[s]){o[s]=!0;try{let l=i(r);if(l)return l}finally{delete o[s]}}}return null}_extensionsOnLoading(){this._forEachExtensions(e=>e.onLoading&&e.onLoading())}_extensionsOnReady(){this._forEachExtensions(e=>e.onReady&&e.onReady())}_extensionsLoadSceneAsync(e,t){return this._applyExtensions(t,"loadScene",i=>i.loadSceneAsync&&i.loadSceneAsync(e,t))}_extensionsLoadNodeAsync(e,t,i){return this._applyExtensions(t,"loadNode",r=>r.loadNodeAsync&&r.loadNodeAsync(e,t,i))}_extensionsLoadCameraAsync(e,t,i){return this._applyExtensions(t,"loadCamera",r=>r.loadCameraAsync&&r.loadCameraAsync(e,t,i))}_extensionsLoadVertexDataAsync(e,t,i){return this._applyExtensions(t,"loadVertexData",r=>r._loadVertexDataAsync&&r._loadVertexDataAsync(e,t,i))}_extensionsLoadMeshPrimitiveAsync(e,t,i,r,s,a){return this._applyExtensions(s,"loadMeshPrimitive",o=>o._loadMeshPrimitiveAsync&&o._loadMeshPrimitiveAsync(e,t,i,r,s,a))}_extensionsLoadMaterialAsync(e,t,i,r,s){return this._applyExtensions(t,"loadMaterial",a=>a._loadMaterialAsync&&a._loadMaterialAsync(e,t,i,r,s))}_extensionsCreateMaterial(e,t,i){return this._applyExtensions(t,"createMaterial",r=>r.createMaterial&&r.createMaterial(e,t,i))}_extensionsLoadMaterialPropertiesAsync(e,t,i){return this._applyExtensions(t,"loadMaterialProperties",r=>r.loadMaterialPropertiesAsync&&r.loadMaterialPropertiesAsync(e,t,i))}_extensionsLoadTextureInfoAsync(e,t,i){return this._applyExtensions(t,"loadTextureInfo",r=>r.loadTextureInfoAsync&&r.loadTextureInfoAsync(e,t,i))}_extensionsLoadTextureAsync(e,t,i){return this._applyExtensions(t,"loadTexture",r=>r._loadTextureAsync&&r._loadTextureAsync(e,t,i))}_extensionsLoadAnimationAsync(e,t){return this._applyExtensions(t,"loadAnimation",i=>i.loadAnimationAsync&&i.loadAnimationAsync(e,t))}_extensionsLoadAnimationChannelAsync(e,t,i,r,s){return this._applyExtensions(i,"loadAnimationChannel",a=>a._loadAnimationChannelAsync&&a._loadAnimationChannelAsync(e,t,i,r,s))}_extensionsLoadSkinAsync(e,t,i){return this._applyExtensions(i,"loadSkin",r=>r._loadSkinAsync&&r._loadSkinAsync(e,t,i))}_extensionsLoadUriAsync(e,t,i){return this._applyExtensions(t,"loadUri",r=>r._loadUriAsync&&r._loadUriAsync(e,t,i))}_extensionsLoadBufferViewAsync(e,t){return this._applyExtensions(t,"loadBufferView",i=>i.loadBufferViewAsync&&i.loadBufferViewAsync(e,t))}_extensionsLoadBufferAsync(e,t,i,r){return this._applyExtensions(t,"loadBuffer",s=>s.loadBufferAsync&&s.loadBufferAsync(e,t,i,r))}static LoadExtensionAsync(e,t,i,r){if(!t.extensions)return null;let a=t.extensions[i];return a?r(`${e}/extensions/${i}`,a):null}static LoadExtraAsync(e,t,i,r){if(!t.extras)return null;let a=t.extras[i];return a?r(`${e}/extras/${i}`,a):null}isExtensionUsed(e){return!!this._gltf.extensionsUsed&&this._gltf.extensionsUsed.indexOf(e)!==-1}logOpen(e){this._parent._logOpen(e)}logClose(){this._parent._logClose()}log(e){this._parent._log(e)}startPerformanceCounter(e){this._parent._startPerformanceCounter(e)}endPerformanceCounter(e){this._parent._endPerformanceCounter(e)}};CR.DefaultSampler={index:-1};Kf._CreateGLTF2Loader=n=>new CR(n)});var cO,lO,x9=C(()=>{VD();cO="ExtrasAsMetadata",lO=class{_assignExtras(e,t){if(t.extras&&Object.keys(t.extras).length>0){let i=e.metadata=e.metadata||{},r=i.gltf=i.gltf||{};r.extras=t.extras}}constructor(e){this.name=cO,this.enabled=!0,this._loader=e}dispose(){this._loader=null}loadNodeAsync(e,t,i){return this._loader.loadNodeAsync(e,t,r=>{this._assignExtras(r,t),i(r)})}loadCameraAsync(e,t,i){return this._loader.loadCameraAsync(e,t,r=>{this._assignExtras(r,t),i(r)})}createMaterial(e,t,i){let r=this._loader.createMaterial(e,t,i);return this._assignExtras(r,t),r}loadAnimationAsync(e,t){return this._loader.loadAnimationAsync(e,t).then(i=>(this._assignExtras(i,t),i))}};kg(cO);pR(cO,!1,n=>new lO(n))});var yR,R9=C(()=>{yR={name:"obj",extensions:".obj"}});var ud,b9=C(()=>{zt();Fr();Sc();ud=class n{constructor(){this.materials=[]}parseMTL(e,t,i,r){if(t instanceof ArrayBuffer)return;let s=t.split(` +`),a=/\s+/,o,l=null;for(let c=0;c=0?f.substring(0,h):f;d=d.toLowerCase();let u=h>=0?f.substring(h+1).trim():"";if(d==="newmtl")l&&this.materials.push(l),e._blockEntityCollection=!!r,l=new ke(u,e),l._parentContainer=r,e._blockEntityCollection=!1;else if(d==="kd"&&l)o=u.split(a,3).map(parseFloat),l.diffuseColor=ve.FromArray(o);else if(d==="ka"&&l)o=u.split(a,3).map(parseFloat),l.ambientColor=ve.FromArray(o);else if(d==="ks"&&l)o=u.split(a,3).map(parseFloat),l.specularColor=ve.FromArray(o);else if(d==="ke"&&l)o=u.split(a,3).map(parseFloat),l.emissiveColor=ve.FromArray(o);else if(d==="ns"&&l)l.specularPower=parseFloat(u);else if(d==="d"&&l)l.alpha=parseFloat(u);else if(d==="map_ka"&&l)l.ambientTexture=n._GetTexture(i,u,e);else if(d==="map_kd"&&l)l.diffuseTexture=n._GetTexture(i,u,e);else if(d==="map_ks"&&l)l.specularTexture=n._GetTexture(i,u,e);else if(d!=="map_ns")if(d==="map_bump"&&l){let m=u.split(a),p=m.indexOf("-bm"),_=null;p>=0&&(_=m[p+1],m.splice(p,2)),l.bumpTexture=n._GetTexture(i,m.join(" "),e),l.bumpTexture&&_!==null&&(l.bumpTexture.level=parseFloat(_))}else d==="map_d"&&l&&(l.opacityTexture=n._GetTexture(i,u,e))}l&&this.materials.push(l)}static _GetTexture(e,t,i){if(!t)return null;let r=e;if(e==="file:"){let s=t.lastIndexOf("\\");s===-1&&(s=t.lastIndexOf("/")),s>-1?r+=t.substring(s+1):r+=t}else r+=t;return new ge(r,i,!1,n.INVERT_TEXTURE_Y)}};ud.INVERT_TEXTURE_Y=!0});var Kr,I9=C(()=>{ki();Sc();zt();Ge();yA();Mi();dr();Pt();Kr=class n{constructor(e,t,i){this._positions=[],this._normals=[],this._uvs=[],this._colors=[],this._extColors=[],this._meshesFromObj=[],this._indicesForBabylon=[],this._wrappedPositionForBabylon=[],this._wrappedUvsForBabylon=[],this._wrappedColorsForBabylon=[],this._wrappedNormalsForBabylon=[],this._tuplePosNorm=[],this._curPositionInIndices=0,this._hasMeshes=!1,this._unwrappedPositionsForBabylon=[],this._unwrappedColorsForBabylon=[],this._unwrappedNormalsForBabylon=[],this._unwrappedUVForBabylon=[],this._triangles=[],this._materialNameFromObj="",this._objMeshName="",this._increment=1,this._isFirstMaterial=!0,this._grayColor=new lt(.5,.5,.5,1),this._hasLineData=!1,this._materialToUse=e,this._babylonMeshesArray=t,this._loadingOptions=i}_isInArray(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[]});let i=e[t[0]].normals.indexOf(t[1]);return i===-1?-1:e[t[0]].idx[i]}_isInArrayUV(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[],uv:[]});let i=e[t[0]].normals.indexOf(t[1]);return i!=1&&t[2]===e[t[0]].uv[i]?e[t[0]].idx[i]:-1}_setData(e){var i,r;(i=e.indiceUvsFromObj)!=null||(e.indiceUvsFromObj=-1),(r=e.indiceNormalFromObj)!=null||(e.indiceNormalFromObj=-1);let t;this._loadingOptions.optimizeWithUV?t=this._isInArrayUV(this._tuplePosNorm,[e.indicePositionFromObj,e.indiceNormalFromObj,e.indiceUvsFromObj]):t=this._isInArray(this._tuplePosNorm,[e.indicePositionFromObj,e.indiceNormalFromObj]),t===-1?(this._indicesForBabylon.push(this._wrappedPositionForBabylon.length),this._wrappedPositionForBabylon.push(e.positionVectorFromOBJ),e.textureVectorFromOBJ!==void 0&&this._wrappedUvsForBabylon.push(e.textureVectorFromOBJ),e.normalsVectorFromOBJ!==void 0&&this._wrappedNormalsForBabylon.push(e.normalsVectorFromOBJ),e.positionColorsFromOBJ!==void 0&&this._wrappedColorsForBabylon.push(e.positionColorsFromOBJ),this._tuplePosNorm[e.indicePositionFromObj].normals.push(e.indiceNormalFromObj),this._tuplePosNorm[e.indicePositionFromObj].idx.push(this._curPositionInIndices++),this._loadingOptions.optimizeWithUV&&this._tuplePosNorm[e.indicePositionFromObj].uv.push(e.indiceUvsFromObj)):this._indicesForBabylon.push(t)}_unwrapData(){try{for(let e=0;e0&&(this._handledMesh=this._meshesFromObj[this._meshesFromObj.length-1],this._unwrapData(),this._loadingOptions.useLegacyBehavior&&this._indicesForBabylon.reverse(),this._handledMesh.indices=this._indicesForBabylon.slice(),this._handledMesh.positions=this._unwrappedPositionsForBabylon.slice(),this._unwrappedNormalsForBabylon.length&&(this._handledMesh.normals=this._unwrappedNormalsForBabylon.slice()),this._unwrappedUVForBabylon.length&&(this._handledMesh.uvs=this._unwrappedUVForBabylon.slice()),this._unwrappedColorsForBabylon.length&&(this._handledMesh.colors=this._unwrappedColorsForBabylon.slice()),this._handledMesh.hasLines=this._hasLineData,this._indicesForBabylon.length=0,this._unwrappedPositionsForBabylon.length=0,this._unwrappedColorsForBabylon.length=0,this._unwrappedNormalsForBabylon.length=0,this._unwrappedUVForBabylon.length=0,this._hasLineData=!1)}_optimizeNormals(e){let t=e.getVerticesData(L.PositionKind),i=e.getVerticesData(L.NormalKind),r={};if(!t||!i)return;for(let a=0;athis._triangles.push(d[0],d[u],d[u+1]),this._handednessSign=1):i.useRightHandedSystem?(this._pushTriangle=(d,u)=>this._triangles.push(d[0],d[u+1],d[u]),this._handednessSign=1):(this._pushTriangle=(d,u)=>this._triangles.push(d[0],d[u],d[u+1]),this._handednessSign=-1);let a=t.split(` +`),o=[],l=[];o.push(l);for(let d=0;d=7){let p=parseFloat(m[4]),_=parseFloat(m[5]),g=parseFloat(m[6]);this._colors.push(new lt(p>1?p/255:p,_>1?_/255:_,g>1?g/255:g,m.length===7||m[7]===void 0?1:parseFloat(m[7])))}else this._colors.push(this._grayColor)}else if((m=n.NormalPattern.exec(u))!==null)this._normals.push(new b(parseFloat(m[1]),parseFloat(m[2]),parseFloat(m[3])));else if((m=n.UVPattern.exec(u))!==null)this._uvs.push(new we(parseFloat(m[1])*this._loadingOptions.UVScaling.x,parseFloat(m[2])*this._loadingOptions.UVScaling.y));else if((m=n.FacePattern3.exec(u))!==null)this._setDataForCurrentFaceWithPattern3(m[1].trim().split(" "),1);else if((m=n.FacePattern4.exec(u))!==null)this._setDataForCurrentFaceWithPattern4(m[1].trim().split(" "),1);else if((m=n.FacePattern5.exec(u))!==null)this._setDataForCurrentFaceWithPattern5(m[1].trim().split(" "),1);else if((m=n.FacePattern2.exec(u))!==null)this._setDataForCurrentFaceWithPattern2(m[1].trim().split(" "),1);else if((m=n.FacePattern1.exec(u))!==null)this._setDataForCurrentFaceWithPattern1(m[1].trim().split(" "),1);else if((m=n.LinePattern1.exec(u))!==null)this._setDataForCurrentFaceWithPattern1(m[1].trim().split(" "),0),this._hasLineData=!0;else if((m=n.LinePattern2.exec(u))!==null)this._setDataForCurrentFaceWithPattern2(m[1].trim().split(" "),0),this._hasLineData=!0;else if(m=n._GetZbrushMRGB(u,!this._loadingOptions.importVertexColors))for(let p of m)this._extColors.push(p);else if((m=n.LinePattern3.exec(u))!==null)this._setDataForCurrentFaceWithPattern3(m[1].trim().split(" "),0),this._hasLineData=!0;else if(n.GroupDescriptor.test(u)||n.ObjectDescriptor.test(u)){let p={name:u.substring(2).trim(),indices:null,positions:null,normals:null,uvs:null,colors:null,materialName:this._materialNameFromObj,isObject:n.ObjectDescriptor.test(u)};this._addPreviousObjMesh(),this._meshesFromObj.push(p),this._hasMeshes=!0,this._isFirstMaterial=!0,this._increment=1}else if(n.UseMtlDescriptor.test(u)){if(this._materialNameFromObj=u.substring(7).trim(),!this._isFirstMaterial||!this._hasMeshes){this._addPreviousObjMesh();let p={name:(this._objMeshName||"mesh")+"_mm"+this._increment.toString(),indices:null,positions:null,normals:null,uvs:null,colors:null,materialName:this._materialNameFromObj,isObject:!1};this._increment++,this._meshesFromObj.push(p),this._hasMeshes=!0}this._hasMeshes&&this._isFirstMaterial&&(this._meshesFromObj[this._meshesFromObj.length-1].materialName=this._materialNameFromObj,this._isFirstMaterial=!1)}else n.MtlLibGroupDescriptor.test(u)?s(u.substring(7).trim()):n.SmoothDescriptor.test(u)||te.Log("Unhandled expression at line : "+u)}if(this._hasMeshes&&(this._handledMesh=this._meshesFromObj[this._meshesFromObj.length-1],this._loadingOptions.useLegacyBehavior&&this._indicesForBabylon.reverse(),this._unwrapData(),this._handledMesh.indices=this._indicesForBabylon,this._handledMesh.positions=this._unwrappedPositionsForBabylon,this._unwrappedNormalsForBabylon.length&&(this._handledMesh.normals=this._unwrappedNormalsForBabylon),this._unwrappedUVForBabylon.length&&(this._handledMesh.uvs=this._unwrappedUVForBabylon),this._unwrappedColorsForBabylon.length&&(this._handledMesh.colors=this._unwrappedColorsForBabylon),this._handledMesh.hasLines=this._hasLineData),!this._hasMeshes){let d=null;if(this._indicesForBabylon.length)this._loadingOptions.useLegacyBehavior&&this._indicesForBabylon.reverse(),this._unwrapData();else{for(let u of this._positions)this._unwrappedPositionsForBabylon.push(u.x,u.y,u.z);if(this._normals.length)for(let u of this._normals)this._unwrappedNormalsForBabylon.push(u.x,u.y,u.z);if(this._uvs.length)for(let u of this._uvs)this._unwrappedUVForBabylon.push(u.x,u.y);if(this._extColors.length)for(let u of this._extColors)this._unwrappedColorsForBabylon.push(u.r,u.g,u.b,u.a);else if(this._colors.length)for(let u of this._colors)this._unwrappedColorsForBabylon.push(u.r,u.g,u.b,u.a);this._materialNameFromObj||(d=new ke(mn.RandomId(),i),d.pointsCloud=!0,this._materialNameFromObj=d.name,this._normals.length||(d.disableLighting=!0,d.emissiveColor=ve.White()))}this._meshesFromObj.push({name:mn.RandomId(),indices:this._indicesForBabylon,positions:this._unwrappedPositionsForBabylon,colors:this._unwrappedColorsForBabylon,normals:this._unwrappedNormalsForBabylon,uvs:this._unwrappedUVForBabylon,materialName:this._materialNameFromObj,directMaterial:d,isObject:!0,hasLines:this._hasLineData})}for(let d=0;d=0;--p)if(this._meshesFromObj[p].isObject&&this._meshesFromObj[p]._babylonMesh){u.parent=this._meshesFromObj[p]._babylonMesh;break}}if(this._materialToUse.push(this._meshesFromObj[d].materialName),this._handledMesh.hasLines&&((f=u._internalMetadata)!=null||(u._internalMetadata={}),u._internalMetadata._isLine=!0),((h=this._handledMesh.positions)==null?void 0:h.length)===0){this._babylonMeshesArray.push(u);continue}let m=new Ce;if(m.indices=this._handledMesh.indices,m.positions=this._handledMesh.positions,this._loadingOptions.computeNormals||!this._handledMesh.normals){let p=new Array;Ce.ComputeNormals(this._handledMesh.positions,this._handledMesh.indices,p),m.normals=p}else m.normals=this._handledMesh.normals;this._handledMesh.uvs&&(m.uvs=this._handledMesh.uvs),this._handledMesh.colors&&(m.colors=this._handledMesh.colors),m.applyToMesh(u),this._loadingOptions.invertY&&(u.scaling.y*=-1),this._loadingOptions.optimizeNormals&&this._optimizeNormals(u),this._babylonMeshesArray.push(u),this._handledMesh.directMaterial&&(u.material=this._handledMesh.directMaterial)}}};Kr.ObjectDescriptor=/^o/;Kr.GroupDescriptor=/^g/;Kr.MtlLibGroupDescriptor=/^mtllib /;Kr.UseMtlDescriptor=/^usemtl /;Kr.SmoothDescriptor=/^s /;Kr.VertexPattern=/^v(\s+[\d|.|+|\-|e|E]+){3,7}/;Kr.NormalPattern=/^vn(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/;Kr.UVPattern=/^vt(\s+[\d|.|+|\-|e|E]+)( +[\d|.|+|\-|e|E]+)/;Kr.FacePattern1=/^f\s+(([\d]{1,}[\s]?){3,})+/;Kr.FacePattern2=/^f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;Kr.FacePattern3=/^f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;Kr.FacePattern4=/^f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;Kr.FacePattern5=/^f\s+(((-[\d]{1,}\/-[\d]{1,}\/-[\d]{1,}[\s]?){3,})+)/;Kr.LinePattern1=/^l\s+(([\d]{1,}[\s]?){2,})+/;Kr.LinePattern2=/^l\s+((([\d]{1,}\/[\d]{1,}[\s]?){2,})+)/;Kr.LinePattern3=/^l\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){2,})+)/});var M9={};tt(M9,{OBJFileLoader:()=>$s});var $s,fO=C(()=>{Ge();Ii();$m();Ug();R9();b9();I9();Sc();$s=class n{static get INVERT_TEXTURE_Y(){return ud.INVERT_TEXTURE_Y}static set INVERT_TEXTURE_Y(e){ud.INVERT_TEXTURE_Y=e}constructor(e){this.name=yR.name,this.extensions=yR.extensions,this._assetContainer=null,this._loadingOptions={...n._DefaultLoadingOptions,...e!=null?e:{}}}static get _DefaultLoadingOptions(){return{computeNormals:n.COMPUTE_NORMALS,optimizeNormals:n.OPTIMIZE_NORMALS,importVertexColors:n.IMPORT_VERTEX_COLORS,invertY:n.INVERT_Y,invertTextureY:n.INVERT_TEXTURE_Y,UVScaling:n.UV_SCALING,materialLoadingFailsSilently:n.MATERIAL_LOADING_FAILS_SILENTLY,optimizeWithUV:n.OPTIMIZE_WITH_UV,skipMaterials:n.SKIP_MATERIALS,useLegacyBehavior:n.USE_LEGACY_BEHAVIOR}}_loadMTL(e,t,i,r){let s=t+e;_e.LoadFile(s,i,void 0,void 0,!1,(a,o)=>{r(s,o)})}createPlugin(e){return new n(e[yR.name])}canDirectLoad(){return!1}importMeshAsync(e,t,i,r){return this._parseSolidAsync(e,t,i,r).then(s=>({meshes:s,particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]}))}loadAsync(e,t,i){return this.importMeshAsync(null,e,t,i).then(()=>{})}loadAssetContainerAsync(e,t,i){let r=new ul(e);return this._assetContainer=r,this.importMeshAsync(null,e,t,i).then(s=>(s.meshes.forEach(a=>r.meshes.push(a)),s.meshes.forEach(a=>{let o=a.material;o&&r.materials.indexOf(o)==-1&&(r.materials.push(o),o.getActiveTextures().forEach(c=>{r.textures.indexOf(c)==-1&&r.textures.push(c)}))}),this._assetContainer=null,r)).catch(s=>{throw this._assetContainer=null,s})}_parseSolidAsync(e,t,i,r){let s="",a=new ud,o=[],l=[];i=i.replace(/#.*$/gm,"").trim(),new Kr(o,l,this._loadingOptions).parse(e,i,t,this._assetContainer,h=>{s=h});let f=[];return s!==""&&!this._loadingOptions.skipMaterials&&f.push(new Promise((h,d)=>{this._loadMTL(s,r,u=>{try{a.parseMTL(t,u,r,this._assetContainer);for(let m=0;m-1;)_.push(g),p=g+1;if(g===-1&&_.length===0)a.materials[m].dispose();else for(let v=0;v<_.length;v++){let x=l[_[v]],A=a.materials[m];x.material=A,x.getTotalIndices()||(A.pointsCloud=!0)}}h()}catch(m){_e.Warn(`Error processing MTL file: '${s}'`),this._loadingOptions.materialLoadingFailsSilently?h():d(m)}},(u,m)=>{_e.Warn(`Error downloading MTL file: '${s}'`),this._loadingOptions.materialLoadingFailsSilently?h():d(m)})})),Promise.all(f).then(()=>{let h=d=>{var u,m;return!!((m=(u=d._internalMetadata)==null?void 0:u._isLine)!=null&&m)};return l.forEach(d=>{var u,m;if(h(d)){let p=(u=d.material)!=null?u:new ke(d.name+"_line",t);p.getBindedMeshes().filter(g=>!h(g)).length>0&&(p=(m=p.clone(p.name+"_line"))!=null?m:p),p.wireframe=!0,d.material=p,d._internalMetadata&&(d._internalMetadata._isLine=void 0)}}),l})}};$s.OPTIMIZE_WITH_UV=!0;$s.INVERT_Y=!1;$s.IMPORT_VERTEX_COLORS=!1;$s.COMPUTE_NORMALS=!1;$s.OPTIMIZE_NORMALS=!1;$s.UV_SCALING=new we(1,1);$s.SKIP_MATERIALS=!1;$s.MATERIAL_LOADING_FAILS_SILENTLY=!0;$s.USE_LEGACY_BEHAVIOR=!1;Yf(new $s)});function Rde(n){let e=n.trim();return/^https?:\/\//i.test(e)||/^wss?:\/\//i.test(e)||/^\/\//.test(e)}function hO(n,e){if(Rde(n))throw new Error(`[AI3D] Babylon ${e} is limited to local vault resources. Refused remote URL: ${n}`);return n}function PR(n){throw new Error(`[AI3D] Babylon script loading is disabled in this plugin build. Refused script URL: ${n}`)}function y9(){if(C9)return;let n=i=>hO(i,"asset loading"),e=i=>hO(i,"script loading"),t=()=>-1;_e.PreprocessUrl=n,_e.ScriptPreprocessUrl=e,_e.DefaultRetryStrategy=t,_e.LoadScript=(i,r,s)=>{try{e(i),PR(i)}catch(a){s==null||s(a instanceof Error?a.message:String(a),a);return}r==null||r()},_e.LoadScriptAsync=async i=>{e(i),PR(i)},_e.LoadBabylonScript=(i,r,s)=>{try{PR(i)}catch(a){s==null||s(a instanceof Error?a.message:String(a),a);return}r()},_e.LoadBabylonScriptAsync=async i=>{PR(i)},Gi.PreprocessUrl=n,Gi.ScriptPreprocessUrl=e,Gi.DefaultRetryStrategy=t,Ir.CustomRequestModifiers.push((i,r)=>hO(r,"request")),C9=!0}var C9,P9=C(()=>{"use strict";Wl();Ii();Bh();C9=!1});function DR(n,e){if(e.byteLength<84)throw new Error(`STL buffer too small: ${e.byteLength} bytes (need 84+)`);if(e.byteLength>=6){let p=new TextDecoder().decode(new Uint8Array(e,0,6));if(p==="solid "||p===`solid +`){let _=new TextDecoder().decode(new Uint8Array(e,0,Math.min(e.byteLength,800)));if(_.includes("facet")||_.includes("endsolid"))throw new Error("ASCII STL detected \u2014 only binary STL is supported. Convert to binary STL first.")}}let t=new DataView(e),i=t.getUint32(80,!0);if(i===0)throw new Error("STL file contains 0 triangles");let r=84+i*50;if(e.byteLength>0&31)/31,N=(v>>5&31)/31,F=(v>>10&31)/31,U=p*12;l[U+0]=V,l[U+1]=N,l[U+2]=F,l[U+3]=1,l[U+4]=V,l[U+5]=N,l[U+6]=F,l[U+7]=1,l[U+8]=V,l[U+9]=N,l[U+10]=F,l[U+11]=1}let x=a[_+3]-a[_+0],A=a[_+4]-a[_+1],S=a[_+5]-a[_+2],E=a[_+6]-a[_+0],R=a[_+7]-a[_+1],I=a[_+8]-a[_+2],y=A*I-S*R,M=S*E-x*I,D=x*R-A*E,O=Math.sqrt(y*y+M*M+D*D);O>1e-8?(y/=O,M/=O,D/=O):(y=0,M=0,D=1,f++),o[_+0]=y,o[_+1]=M,o[_+2]=D,o[_+3]=y,o[_+4]=M,o[_+5]=D,o[_+6]=y,o[_+7]=M,o[_+8]=D,c[g+0]=_/3+0,c[g+1]=_/3+1,c[g+2]=_/3+2}f>0&&console.warn(`[AI3D STL] ${f} degenerate triangles with zero-area normals`);let d=new Ce;d.positions=a,d.normals=o,d.indices=c,l&&(d.colors=l);let u=new q("stl-model",n);d.applyToMesh(u);let m=new ke("stl-mat",n);return m.backFaceCulling=!1,m.specularColor=new ve(.3,.3,.3),m.specularPower=32,l?(m.diffuseColor=new ve(1,1,1),m.emissiveColor=new ve(.05,.05,.05),m.vertexColorEnabled=!0):(m.diffuseColor=new ve(.85,.85,.85),m.emissiveColor=new ve(.1,.1,.1)),u.material=m,u}function D9(n,e){return DR(n,e)}function L9(n){n(bde)}var bde,dO=C(()=>{"use strict";Mi();Ug();dr();Sc();zt();bde={name:"stl",extensions:".stl",importMeshAsync(n,e,t){return Promise.resolve().then(()=>({meshes:[DR(e,t)],particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]}))},loadAsync(n,e){return Promise.resolve().then(()=>{DR(n,e)})},loadAssetContainerAsync(n,e){return Promise.resolve().then(()=>{let t=DR(n,e),i=new ul(n);return i.meshes.push(t),t.material&&i.materials.push(t.material),i})},canDirectLoad(){return!1},rewriteRootURL(n){return n}}});function Ide(n){let e=n.split(` +`),t=[],i="binary_little_endian",r=null;for(let s of e){let a=s.trim();if(a==="end_header")break;if(a==="ply"||a===""||a.startsWith("comment"))continue;let o=a.split(/\s+/),l=o[0];l==="format"?i=o[1]:l==="element"?(r={name:o[1],count:parseInt(o[2],10),properties:[]},t.push(r)):l==="property"&&r&&(o[1]==="list"?r.properties.push({name:o[4],type:"list",isList:!0,countType:o[2],itemType:o[3]}):r.properties.push({name:o[2],type:o[1],isList:!1}))}return{format:i,elements:t}}function lp(n){switch(n){case"uchar":case"uint8":return 1;case"char":case"int8":return 1;case"ushort":case"uint16":return 2;case"short":case"int16":return 2;case"uint":case"uint32":return 4;case"int":case"int32":return 4;case"float":case"float32":return 4;case"double":case"float64":return 8;default:return 4}}function LR(n,e,t,i){switch(t){case"uchar":case"uint8":return n.getUint8(e);case"char":case"int8":return n.getInt8(e);case"ushort":case"uint16":return n.getUint16(e,i);case"short":case"int16":return n.getInt16(e,i);case"uint":case"uint32":return n.getUint32(e,i);case"int":case"int32":return n.getInt32(e,i);case"float":case"float32":return n.getFloat32(e,i);case"double":case"float64":return n.getFloat64(e,i);default:return 0}}function Mde(n,e,t,i){let r=i,s=new DataView(n),a=[],o=[],l=[],c=e.elements.find(h=>h.name==="vertex"),f=e.elements.find(h=>h.name==="face");if(c){let h=c.properties.some(u=>u.name==="x"),d=c.properties.some(u=>u.name==="red"||u.name==="r");for(let u=0;ud.name==="vertex"),c=e.elements.find(d=>d.name==="face"),f=0;if(l){let d=l.properties.some(p=>p.name==="x"),u=l.properties.some(p=>p.name==="red"||p.name==="r"),m=l.properties.filter(p=>!p.isList);for(let p=0;p0){c.indices=o.indices;let d=new Array(l.length).fill(0),u=o.indices,m=l.length-3;for(let p=0;pm||g>m||v>m)continue;let x=l[_],A=l[_+1],S=l[_+2],E=l[g]-x,R=l[g+1]-A,I=l[g+2]-S,y=l[v]-x,M=l[v+1]-A,D=l[v+2]-S,O=R*D-I*M,V=I*y-E*D,N=E*M-R*y;d[_]+=O,d[_+1]+=V,d[_+2]+=N,d[g]+=O,d[g+1]+=V,d[g+2]+=N,d[v]+=O,d[v+1]+=V,d[v+2]+=N}for(let p=0;p0&&(d[p]/=_,d[p+1]/=_,d[p+2]/=_)}c.normals=d}else{let d=o.positions.length/3,u=[];for(let m=0;m=3&&u.push(0,1,2),c.indices=u}let f=new q("ply-model",n);c.applyToMesh(f);let h=new ke("ply-mat",n);return h.backFaceCulling=!1,o.colors.length>0?(c.colors=o.colors,c.applyToMesh(f),h.diffuseColor=new ve(1,1,1),h.vertexColorEnabled=!0):h.diffuseColor=new ve(.7,.7,.7),f.material=h,f}function O9(n,e){return OR(n,e)}function N9(n){n(yde)}var yde,uO=C(()=>{"use strict";Mi();Ug();dr();Sc();zt();yde={name:"ply",extensions:".ply",importMeshAsync(n,e,t){return Promise.resolve().then(()=>({meshes:[OR(e,t)],particleSystems:[],skeletons:[],animationGroups:[],transformNodes:[],geometries:[],lights:[],spriteManagers:[]}))},loadAsync(n,e){return Promise.resolve().then(()=>{OR(n,e)})},loadAssetContainerAsync(n,e){return Promise.resolve().then(()=>{let t=OR(n,e),i=new ul(n);return i.meshes.push(t),t.material&&i.materials.push(t.material),i})},canDirectLoad(){return!1},rewriteRootURL(n){return n}}});async function jg(){w9||(y9(),L9(Yf),N9(Yf),w9=!0)}var w9,qg=C(()=>{"use strict";FD();A9();x9();fO();$m();P9();dO();uO();w9=!1});function Zg(n){return Math.floor(n.getTotalIndices()/3)}function md(n){return n.getTotalVertices()}function pd(n,e=[]){let t=[n,...e,...n.getChildMeshes(!0)],i=new Set;return t.filter(r=>!r||i.has(r)||r.isDisposed()?!1:(i.add(r),md(r)>0||r.getTotalIndices()>0))}function F9(n){let e=Array.from(n),t=new Set(e);return e.filter(i=>{let r=i.parent;return!r||!t.has(r)})}function mO(n){n.computeWorldMatrix(!0);let e=n.getBoundingInfo().boundingBox;return I_(Ht(e.minimumWorld),Ht(e.maximumWorld))}function cp(n){let e=null;for(let t of n)!t||t.isDisposed()||(e=Z1(e,mO(t)));return e}function NR(n,e=[]){var t;return(t=cp(pd(n,e)))!=null?t:mO(n)}function wR(n,e,t,i={}){return kS({rootName:n,boundingSize:Wr(e),meshes:t.map(r=>({triangleCount:Zg(r),vertexCount:md(r),materialKeys:r.material?[r.material.name]:[]})),splatCount:i.splatCount,resourceWarnings:i.resourceWarnings})}function B9(n){var t,i;let e=mO(n);return Ih({name:n.name||`mesh-${n.uniqueId}`,triangleCount:Zg(n),vertexCount:md(n),materialName:(i=(t=n.material)==null?void 0:t.name)!=null?i:null,boundingSize:Wr(e),center:fn(e)})}var FR=C(()=>{"use strict";tf();ws();C_()});function Zf(n){return qr(n)}function U9(n,e,t,i=[]){qS(new BR(n,i),e,t)}function pO(n,e=[]){ZS(new BR(n,e))}var BR,V9=C(()=>{"use strict";Ge();tf();ws();sM();FR();BR=class{constructor(e,t=[]){this.rootMesh=e,this.loadedMeshes=t}getParts(){return pd(this.rootMesh,this.loadedMeshes)}getRootCenter(){return fn(NR(this.rootMesh,this.loadedMeshes))}getPartPosition(e){return Ht(e.position)}getPartCenter(e){return Ht(e.getBoundingInfo().boundingBox.centerWorld)}setPartPosition(e,t){e.position=new b(t.x,t.y,t.z)}getPartState(e){let t=e.metadata;return t!=null&&t._previewExplodeState?{originalPosition:Zf(t._previewExplodeState.originalPosition),originalCenter:Zf(t._previewExplodeState.originalCenter)}:t!=null&&t._originalPos&&(t!=null&&t._originalCenter)?{originalPosition:Zf(t._originalPos),originalCenter:Zf(t._originalCenter)}:null}setPartState(e,t){(!e.metadata||typeof e.metadata!="object")&&(e.metadata={});let i=e.metadata;i._previewExplodeState={originalPosition:Zf(t.originalPosition),originalCenter:Zf(t.originalCenter)},i._originalPos=Zf(t.originalPosition),i._originalCenter=Zf(t.originalCenter)}}});var UR={};tt(UR,{glowBlurPostProcessPixelShaderWGSL:()=>Pde});var _O,G9,Pde,VR=C(()=>{k();_O="glowBlurPostProcessPixelShader",G9=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform screenSize: vec2f;uniform direction: vec2f;uniform blurWidth: f32;fn getLuminance(color: vec3f)->f32 {return dot(color, vec3f(0.2126,0.7152,0.0722));} #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {var weights: array;weights[0]=0.05;weights[1]=0.1;weights[2]=0.2;weights[3]=0.3;weights[4]=0.2;weights[5]=0.1;weights[6]=0.05;var texelSize: vec2f= vec2f(1.0/uniforms.screenSize.x,1.0/uniforms.screenSize.y);var texelStep: vec2f=texelSize*uniforms.direction*uniforms.blurWidth;var start: vec2f=input.vUV-3.0*texelStep;var baseColor: vec4f= vec4f(0.,0.,0.,0.);var texelOffset: vec2f= vec2f(0.,0.);for (var i: i32=0; i<7; i++) {var texel: vec4f=textureSample(textureSampler,textureSamplerSampler,start+texelOffset);baseColor=vec4f(baseColor.rgb,baseColor.a+texel.a*weights[i]);var luminance: f32=getLuminance(baseColor.rgb);var luminanceTexel: f32=getLuminance(texel.rgb);var choice: f32=step(luminanceTexel,luminance);baseColor=vec4f(choice*baseColor.rgb+(1.0-choice)*texel.rgb,baseColor.a);texelOffset+=texelStep;} -fragmentOutputs.color=baseColor;}`;T.ShadersStoreWGSL[_O]||(T.ShadersStoreWGSL[_O]=G9);Pde={name:_O,shader:G9}});var VR={};tt(VR,{glowBlurPostProcessPixelShader:()=>Dde});var gO,k9,Dde,GR=C(()=>{W();gO="glowBlurPostProcessPixelShader",k9=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 direction;uniform float blurWidth;float getLuminance(vec3 color) +fragmentOutputs.color=baseColor;}`;T.ShadersStoreWGSL[_O]||(T.ShadersStoreWGSL[_O]=G9);Pde={name:_O,shader:G9}});var GR={};tt(GR,{glowBlurPostProcessPixelShader:()=>Dde});var gO,k9,Dde,kR=C(()=>{k();gO="glowBlurPostProcessPixelShader",k9=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 direction;uniform float blurWidth;float getLuminance(vec3 color) {return dot(color,vec3(0.2126,0.7152,0.0722));} #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {float weights[7];weights[0]=0.05;weights[1]=0.1;weights[2]=0.2;weights[3]=0.3;weights[4]=0.2;weights[5]=0.1;weights[6]=0.05;vec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);vec2 texelStep=texelSize*direction*blurWidth;vec2 start=vUV-3.0*texelStep;vec4 baseColor=vec4(0.,0.,0.,0.);vec2 texelOffset=vec2(0.,0.);for (int i=0; i<7; i++) {vec4 texel=texture2D(textureSampler,start+texelOffset);baseColor.a+=texel.a*weights[i];float luminance=getLuminance(baseColor.rgb);float luminanceTexel=getLuminance(texel.rgb);float choice=step(luminanceTexel,luminance);baseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;texelOffset+=texelStep;} -gl_FragColor=baseColor;}`;T.ShadersStore[gO]||(T.ShadersStore[gO]=k9);Dde={name:gO,shader:k9}});var H9={};tt(H9,{glowMapGenerationVertexShaderWGSL:()=>Lde});var vO,W9,Lde,z9=C(()=>{W();rc();nc();Uf();Vf();sc();wf();Gf();kf();ac();oc();lc();cc();vO="glowMapGenerationVertexShader",W9=`attribute position: vec3f; +gl_FragColor=baseColor;}`;T.ShadersStore[gO]||(T.ShadersStore[gO]=k9);Dde={name:gO,shader:k9}});var H9={};tt(H9,{glowMapGenerationVertexShaderWGSL:()=>Lde});var vO,W9,Lde,z9=C(()=>{k();ic();rc();Bf();Uf();nc();Nf();Vf();Gf();sc();ac();oc();lc();vO="glowMapGenerationVertexShader",W9=`attribute position: vec3f; #include #include #include @@ -23489,7 +23489,7 @@ vertexOutputs.vUVEmissive= (uniforms.emissiveMatrix* vec4f(uv2Updated,1.0,0.0)). vertexOutputs.vColor=vertexInputs.color; #endif #include -}`;T.ShadersStoreWGSL[vO]||(T.ShadersStoreWGSL[vO]=W9);Lde={name:vO,shader:W9}});var Y9={};tt(Y9,{glowMapGenerationPixelShaderWGSL:()=>Ode});var EO,X9,Ode,K9=C(()=>{W();Ca();fc();hc();EO="glowMapGenerationPixelShader",X9=`#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR) +}`;T.ShadersStoreWGSL[vO]||(T.ShadersStoreWGSL[vO]=W9);Lde={name:vO,shader:W9}});var Y9={};tt(Y9,{glowMapGenerationPixelShaderWGSL:()=>Ode});var EO,X9,Ode,K9=C(()=>{k();Ma();cc();fc();EO="glowMapGenerationPixelShader",X9=`#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR) #include #endif #ifdef DIFFUSE @@ -23551,7 +23551,7 @@ fragmentOutputs.color=finalColor*uniforms.glowIntensity; fragmentOutputs.color=vec4f(fragmentOutputs.color.rgb,uniforms.glowColor.a); #endif } -`;T.ShadersStoreWGSL[EO]||(T.ShadersStoreWGSL[EO]=X9);Ode={name:EO,shader:X9}});var q9={};tt(q9,{glowMapGenerationVertexShader:()=>Nde});var SO,j9,Nde,Z9=C(()=>{W();dc();uc();Wf();Hf();mc();Ff();zf();Xf();pc();_c();gc();vc();SO="glowMapGenerationVertexShader",j9=`attribute vec3 position; +`;T.ShadersStoreWGSL[EO]||(T.ShadersStoreWGSL[EO]=X9);Ode={name:EO,shader:X9}});var q9={};tt(q9,{glowMapGenerationVertexShader:()=>Nde});var SO,j9,Nde,Z9=C(()=>{k();hc();dc();kf();Wf();uc();wf();Hf();zf();mc();pc();_c();gc();SO="glowMapGenerationVertexShader",j9=`attribute vec3 position; #include #include #include @@ -23625,7 +23625,7 @@ vUVEmissive=vec2(emissiveMatrix*vec4(uv2Updated,1.0,0.0)); vColor=color; #endif #include -}`;T.ShadersStore[SO]||(T.ShadersStore[SO]=j9);Nde={name:SO,shader:j9}});var $9={};tt($9,{glowMapGenerationPixelShader:()=>wde});var TO,Q9,wde,J9=C(()=>{W();ya();Ec();Sc();TO="glowMapGenerationPixelShader",Q9=`#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR) +}`;T.ShadersStore[SO]||(T.ShadersStore[SO]=j9);Nde={name:SO,shader:j9}});var $9={};tt($9,{glowMapGenerationPixelShader:()=>wde});var TO,Q9,wde,J9=C(()=>{k();Ca();vc();Ec();TO="glowMapGenerationPixelShader",Q9=`#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR) #include #endif #ifdef DIFFUSE @@ -23687,8 +23687,8 @@ gl_FragColor=finalColor*glowIntensity; #ifdef HIGHLIGHT gl_FragColor.a=glowColor.a; #endif -}`;T.ShadersStore[TO]||(T.ShadersStore[TO]=Q9);wde={name:TO,shader:Q9}});var To,bc,kR=C(()=>{hi();zt();Pi();Gi();kh();Vn();Lf();Gh();ol();Un();zM();To=class n extends zr{constructor(e,t=null,i,r,s){super({...s,name:e,engine:t||Le.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:n.FragmentUrl,uniforms:n.Uniforms}),this.direction=i,this.kernel=r,this.textureWidth=0,this.textureHeight=0}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.resolve().then(()=>(UR(),BR)))):t.push(Promise.resolve().then(()=>(GR(),VR))),super._gatherImports(e,t)}bind(){super.bind(),this._drawWrapper.effect.setFloat2("screenSize",this.textureWidth,this.textureHeight),this._drawWrapper.effect.setVector2("direction",this.direction),this._drawWrapper.effect.setFloat("blurWidth",this.kernel)}};To.FragmentUrl="glowBlurPostProcess";To.Uniforms=["screenSize","direction","blurWidth"];bc=class n{get camera(){return this._options.camera}set camera(e){this._options.camera=e}get renderingGroupId(){return this._options.renderingGroupId}set renderingGroupId(e){this._options.renderingGroupId=e}get objectRenderer(){return this._objectRenderer}get shaderLanguage(){return this._shaderLanguage}setMaterialForRendering(e,t){if(this._objectRenderer.setMaterialForRendering(e,t),Array.isArray(e))for(let i=0;i{t=this._scene.getBoundingBoxRenderer().enabled,this._scene.getBoundingBoxRenderer().enabled=!this.disableBoundingBoxesFromEffectLayer&&t}),this._objectRenderer.onAfterRenderObservable.add(()=>{this._scene.getBoundingBoxRenderer().enabled=t})),this._objectRenderer.customIsReadyFunction=(i,r,s)=>{if((s||r===0)&&i.subMeshes)for(let a=0;a{this.onBeforeRenderLayerObservable.notifyObservers(this);let o,l=this._scene.getEngine();if(a.length){for(l.setColorWrite(!1),o=0;o4&&(c.push(L.MatricesIndicesExtraKind),c.push(L.MatricesWeightsExtraKind)),l.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers);let S=s.skeleton;S&&S.isUsingTextureForMatrices?l.push("#define BONETEXTURE"):l.push("#define BonesPerMesh "+(S?S.bones.length+1:0)),s.numBoneInfluencers>0&&u.addCPUSkinningFallback(0,s)}else l.push("#define NUM_BONE_INFLUENCERS 0");let m=s.morphTargetManager?ll(s.morphTargetManager,l,c,s,!0,!1,!1,f,h,d):0;t&&(l.push("#define INSTANCES"),mo(c),e.getRenderingMesh().hasThinInstances&&l.push("#define THIN_INSTANCES"));let p=s.bakedVertexAnimationManager;p&&p.isEnabled&&(l.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),t&&c.push("bakedVertexAnimationSettingsInstanced")),al(o,this._scene,l),this._addCustomEffectDefines(l);let _=e._getDrawWrapper(void 0,!0),g=_.defines,v=l.join(` -`);if(g!==v){let S=["world","mBones","viewProjection","glowColor","morphTargetInfluences","morphTargetCount","boneTextureInfo","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture","glowIntensity"];wn(S),_.setEffect(this._engine.createEffect("glowMapGeneration",c,S,["diffuseSampler","emissiveSampler","opacitySampler","boneSampler","morphTargets","bakedVertexAnimationTexture"],v,u,void 0,void 0,{maxSimultaneousMorphTargets:m},this._shaderLanguage,this._shadersLoaded?void 0:async()=>{await this._importShadersAsync(),this._shadersLoaded=!0}),v)}return _.effect.isReady()&&(this._dontCheckIfReady||!this._dontCheckIfReady&&this.isLayerReady())}_isSubMeshReady(e,t,i){return this._internalIsSubMeshReady(e,t,i)}async _importShadersAsync(){var e;this._shaderLanguage===1?await Promise.all([Promise.resolve().then(()=>(z9(),H9)),Promise.resolve().then(()=>(K9(),Y9))]):await Promise.all([Promise.resolve().then(()=>(Z9(),q9)),Promise.resolve().then(()=>(J9(),$9))]),(e=this._additionalImportShadersAsync)==null||e.call(this)}_internalIsLayerReady(){let e=!0;for(let i=0;iv.setMatrix("world",R)),(i.disableDepthWrite||i.forceDepthWrite)&&c.setDepthWrite(x),i.disableColorWrite&&c.setColorWrite(A),i.depthFunction!==0&&c.setDepthFunction(S)}else this._objectRenderer.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(r)}_useMeshMaterial(e){return!1}_rebuild(){let e=this._vertexBuffers[L.PositionKind];e&&e._rebuild(),this._generateIndexBuffer()}dispose(){let e=this._vertexBuffers[L.PositionKind];e&&(e.dispose(),this._vertexBuffers[L.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null);for(let t of this._mergeDrawWrapper)t.dispose();this._mergeDrawWrapper=[],this._objectRenderer.dispose(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderLayerObservable.clear(),this.onBeforeComposeObservable.clear(),this.onBeforeRenderMeshToEffect.clear(),this.onAfterRenderMeshToEffect.clear(),this.onAfterComposeObservable.clear()}};bc.ForceGLSL=!1});var Ls,AO=C(()=>{Gt();Ut();bi();hi();Pi();Fr();gf();hn();$a();kR();mA();Ls=class n{get _shouldRender(){return this._thinEffectLayer._shouldRender}set _shouldRender(e){this._thinEffectLayer._shouldRender=e}get _emissiveTextureAndColor(){return this._thinEffectLayer._emissiveTextureAndColor}set _emissiveTextureAndColor(e){this._thinEffectLayer._emissiveTextureAndColor=e}get _effectIntensity(){return this._thinEffectLayer._effectIntensity}set _effectIntensity(e){this._thinEffectLayer._effectIntensity=e}static get ForceGLSL(){return bc.ForceGLSL}static set ForceGLSL(e){bc.ForceGLSL=e}get name(){return this._thinEffectLayer.name}set name(e){this._thinEffectLayer.name=e}get neutralColor(){return this._thinEffectLayer.neutralColor}set neutralColor(e){this._thinEffectLayer.neutralColor=e}get isEnabled(){return this._thinEffectLayer.isEnabled}set isEnabled(e){this._thinEffectLayer.isEnabled=e}get camera(){return this._thinEffectLayer.camera}get renderingGroupId(){return this._thinEffectLayer.renderingGroupId}set renderingGroupId(e){this._thinEffectLayer.renderingGroupId=e}get disableBoundingBoxesFromEffectLayer(){return this._thinEffectLayer.disableBoundingBoxesFromEffectLayer}set disableBoundingBoxesFromEffectLayer(e){this._thinEffectLayer.disableBoundingBoxesFromEffectLayer=e}get mainTexture(){return this._mainTexture}get _shaderLanguage(){return this._thinEffectLayer.shaderLanguage}get shaderLanguage(){return this._thinEffectLayer.shaderLanguage}setMaterialForRendering(e,t){this._thinEffectLayer.setMaterialForRendering(e,t)}getEffectIntensity(e){return this._thinEffectLayer.getEffectIntensity(e)}setEffectIntensity(e,t){this._thinEffectLayer.setEffectIntensity(e,t)}constructor(e,t,i=!1,r){this._mainTextureCreatedSize={width:0,height:0},this._maxSize=0,this._mainTextureDesiredSize={width:0,height:0},this._postProcesses=[],this._textures=[],this.uniqueId=$l.UniqueId,this.onDisposeObservable=new ie,this.onBeforeRenderMainTextureObservable=new ie,this.onBeforeComposeObservable=new ie,this.onBeforeRenderMeshToEffect=new ie,this.onAfterRenderMeshToEffect=new ie,this.onAfterComposeObservable=new ie,this.onSizeChangedObservable=new ie,this._internalThinEffectLayer=!r,r||(r=new bc(e,t,i,!1,this._importShadersAsync.bind(this)),r.getEffectName=this.getEffectName.bind(this),r.isReady=this.isReady.bind(this),r._createMergeEffect=this._createMergeEffect.bind(this),r._createTextureAndPostProcesses=this._createTextureAndPostProcesses.bind(this),r._internalCompose=this._internalRender.bind(this),r._setEmissiveTextureAndColor=this._setEmissiveTextureAndColor.bind(this),r._numInternalDraws=this._numInternalDraws.bind(this),r._addCustomEffectDefines=this._addCustomEffectDefines.bind(this),r.hasMesh=this.hasMesh.bind(this),r.shouldRender=this.shouldRender.bind(this),r._shouldRenderMesh=this._shouldRenderMesh.bind(this),r._canRenderMesh=this._canRenderMesh.bind(this),r._useMeshMaterial=this._useMeshMaterial.bind(this)),this._thinEffectLayer=r,this.name=e,this._scene=t||Le.LastCreatedScene,n._SceneComponentInitialization(this._scene),this._engine=this._scene.getEngine(),this._maxSize=this._engine.getCaps().maxTextureSize,this._scene.addEffectLayer(this),this._thinEffectLayer.onDisposeObservable.add(()=>{this.onDisposeObservable.notifyObservers(this)}),this._thinEffectLayer.onBeforeRenderLayerObservable.add(()=>{this.onBeforeRenderMainTextureObservable.notifyObservers(this)}),this._thinEffectLayer.onBeforeComposeObservable.add(()=>{this.onBeforeComposeObservable.notifyObservers(this)}),this._thinEffectLayer.onBeforeRenderMeshToEffect.add(s=>{this.onBeforeRenderMeshToEffect.notifyObservers(s)}),this._thinEffectLayer.onAfterRenderMeshToEffect.add(s=>{this.onAfterRenderMeshToEffect.notifyObservers(s)}),this._thinEffectLayer.onAfterComposeObservable.add(()=>{this.onAfterComposeObservable.notifyObservers(this)})}get _shadersLoaded(){return this._thinEffectLayer._shadersLoaded}set _shadersLoaded(e){this._thinEffectLayer._shadersLoaded=e}_numInternalDraws(){return this._internalThinEffectLayer?1:this._thinEffectLayer._numInternalDraws()}_init(e){this._effectLayerOptions={mainTextureRatio:.5,alphaBlendingMode:2,camera:null,renderingGroupId:-1,mainTextureType:0,mainTextureFormat:5,generateStencilBuffer:!1,...e},this._setMainTextureSize(),this._thinEffectLayer._init(e),this._createMainTexture(),this._createTextureAndPostProcesses()}_setMainTextureSize(){this._effectLayerOptions.mainTextureFixedSize?(this._mainTextureDesiredSize.width=this._effectLayerOptions.mainTextureFixedSize,this._mainTextureDesiredSize.height=this._effectLayerOptions.mainTextureFixedSize):(this._mainTextureDesiredSize.width=this._engine.getRenderWidth()*this._effectLayerOptions.mainTextureRatio,this._mainTextureDesiredSize.height=this._engine.getRenderHeight()*this._effectLayerOptions.mainTextureRatio,this._mainTextureDesiredSize.width=this._engine.needPOTTextures?gn(this._mainTextureDesiredSize.width,this._maxSize):this._mainTextureDesiredSize.width,this._mainTextureDesiredSize.height=this._engine.needPOTTextures?gn(this._mainTextureDesiredSize.height,this._maxSize):this._mainTextureDesiredSize.height),this._mainTextureDesiredSize.width=Math.floor(this._mainTextureDesiredSize.width),this._mainTextureDesiredSize.height=Math.floor(this._mainTextureDesiredSize.height)}_createMainTexture(){this._mainTexture=new Br("EffectLayerMainRTT",{width:this._mainTextureDesiredSize.width,height:this._mainTextureDesiredSize.height},this._scene,{type:this._effectLayerOptions.mainTextureType,format:this._effectLayerOptions.mainTextureFormat,samplingMode:_e.TRILINEAR_SAMPLINGMODE,generateStencilBuffer:this._effectLayerOptions.generateStencilBuffer,existingObjectRenderer:this._thinEffectLayer.objectRenderer}),this._mainTexture.activeCamera=this._effectLayerOptions.camera,this._mainTexture.wrapU=_e.CLAMP_ADDRESSMODE,this._mainTexture.wrapV=_e.CLAMP_ADDRESSMODE,this._mainTexture.anisotropicFilteringLevel=1,this._mainTexture.updateSamplingMode(_e.BILINEAR_SAMPLINGMODE),this._mainTexture.renderParticles=!1,this._mainTexture.renderList=null,this._mainTexture.ignoreCameraViewport=!0,this._mainTexture.onClearObservable.add(e=>{e.clear(this.neutralColor,!0,!0,!0)})}_addCustomEffectDefines(e){}_isReady(e,t,i){return this._internalThinEffectLayer?this._thinEffectLayer._internalIsSubMeshReady(e,t,i):this._thinEffectLayer._isSubMeshReady(e,t,i)}async _importShadersAsync(){}_arePostProcessAndMergeReady(){return this._internalThinEffectLayer?this._thinEffectLayer._internalIsLayerReady():this._thinEffectLayer.isLayerReady()}isLayerReady(){return this._arePostProcessAndMergeReady()&&this._mainTexture.isReady()}render(){this._thinEffectLayer.compose()&&(this._setMainTextureSize(),(this._mainTextureCreatedSize.width!==this._mainTextureDesiredSize.width||this._mainTextureCreatedSize.height!==this._mainTextureDesiredSize.height)&&this._mainTextureDesiredSize.width!==0&&this._mainTextureDesiredSize.height!==0&&(this.onSizeChangedObservable.notifyObservers(this),this._disposeTextureAndPostProcesses(),this._createMainTexture(),this._createTextureAndPostProcesses(),this._mainTextureCreatedSize.width=this._mainTextureDesiredSize.width,this._mainTextureCreatedSize.height=this._mainTextureDesiredSize.height))}hasMesh(e){return this._internalThinEffectLayer?this._thinEffectLayer._internalHasMesh(e):this._thinEffectLayer.hasMesh(e)}shouldRender(){return this._internalThinEffectLayer?this._thinEffectLayer._internalShouldRender():this._thinEffectLayer.shouldRender()}_shouldRenderMesh(e){return this._internalThinEffectLayer?!0:this._thinEffectLayer._shouldRenderMesh(e)}_canRenderMesh(e,t){return this._internalThinEffectLayer?this._thinEffectLayer._internalCanRenderMesh(e,t):this._thinEffectLayer._canRenderMesh(e,t)}_shouldRenderEmissiveTextureForMesh(){return!0}_useMeshMaterial(e){return this._internalThinEffectLayer?!1:this._thinEffectLayer._useMeshMaterial(e)}_rebuild(){this._thinEffectLayer._rebuild()}_disposeTextureAndPostProcesses(){this._mainTexture.dispose();for(let e=0;e{throw Ze("EffectLayerSceneComponent")};P([w()],Ls.prototype,"name",null);P([im()],Ls.prototype,"neutralColor",null);P([w()],Ls.prototype,"isEnabled",null);P([M2()],Ls.prototype,"camera",null);P([w()],Ls.prototype,"renderingGroupId",null);P([w()],Ls.prototype,"disableBoundingBoxesFromEffectLayer",null)});var tK={};tt(tK,{glowMapMergePixelShaderWGSL:()=>Fde});var xO,eK,Fde,iK=C(()=>{W();xO="glowMapMergePixelShader",eK=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d; +}`;T.ShadersStore[TO]||(T.ShadersStore[TO]=Q9);wde={name:TO,shader:Q9}});var To,Rc,WR=C(()=>{di();zt();Di();ki();kh();Vn();Df();Gh();ol();Un();zM();To=class n extends zr{constructor(e,t=null,i,r,s){super({...s,name:e,engine:t||Oe.LastCreatedEngine,useShaderStore:!0,useAsPostProcess:!0,fragmentShader:n.FragmentUrl,uniforms:n.Uniforms}),this.direction=i,this.kernel=r,this.textureWidth=0,this.textureHeight=0}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.resolve().then(()=>(VR(),UR)))):t.push(Promise.resolve().then(()=>(kR(),GR))),super._gatherImports(e,t)}bind(){super.bind(),this._drawWrapper.effect.setFloat2("screenSize",this.textureWidth,this.textureHeight),this._drawWrapper.effect.setVector2("direction",this.direction),this._drawWrapper.effect.setFloat("blurWidth",this.kernel)}};To.FragmentUrl="glowBlurPostProcess";To.Uniforms=["screenSize","direction","blurWidth"];Rc=class n{get camera(){return this._options.camera}set camera(e){this._options.camera=e}get renderingGroupId(){return this._options.renderingGroupId}set renderingGroupId(e){this._options.renderingGroupId=e}get objectRenderer(){return this._objectRenderer}get shaderLanguage(){return this._shaderLanguage}setMaterialForRendering(e,t){if(this._objectRenderer.setMaterialForRendering(e,t),Array.isArray(e))for(let i=0;i{t=this._scene.getBoundingBoxRenderer().enabled,this._scene.getBoundingBoxRenderer().enabled=!this.disableBoundingBoxesFromEffectLayer&&t}),this._objectRenderer.onAfterRenderObservable.add(()=>{this._scene.getBoundingBoxRenderer().enabled=t})),this._objectRenderer.customIsReadyFunction=(i,r,s)=>{if((s||r===0)&&i.subMeshes)for(let a=0;a{this.onBeforeRenderLayerObservable.notifyObservers(this);let o,l=this._scene.getEngine();if(a.length){for(l.setColorWrite(!1),o=0;o4&&(c.push(L.MatricesIndicesExtraKind),c.push(L.MatricesWeightsExtraKind)),l.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers);let S=s.skeleton;S&&S.isUsingTextureForMatrices?l.push("#define BONETEXTURE"):l.push("#define BonesPerMesh "+(S?S.bones.length+1:0)),s.numBoneInfluencers>0&&u.addCPUSkinningFallback(0,s)}else l.push("#define NUM_BONE_INFLUENCERS 0");let m=s.morphTargetManager?ll(s.morphTargetManager,l,c,s,!0,!1,!1,f,h,d):0;t&&(l.push("#define INSTANCES"),mo(c),e.getRenderingMesh().hasThinInstances&&l.push("#define THIN_INSTANCES"));let p=s.bakedVertexAnimationManager;p&&p.isEnabled&&(l.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),t&&c.push("bakedVertexAnimationSettingsInstanced")),al(o,this._scene,l),this._addCustomEffectDefines(l);let _=e._getDrawWrapper(void 0,!0),g=_.defines,v=l.join(` +`);if(g!==v){let S=["world","mBones","viewProjection","glowColor","morphTargetInfluences","morphTargetCount","boneTextureInfo","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices","bakedVertexAnimationSettings","bakedVertexAnimationTextureSizeInverted","bakedVertexAnimationTime","bakedVertexAnimationTexture","glowIntensity"];wn(S),_.setEffect(this._engine.createEffect("glowMapGeneration",c,S,["diffuseSampler","emissiveSampler","opacitySampler","boneSampler","morphTargets","bakedVertexAnimationTexture"],v,u,void 0,void 0,{maxSimultaneousMorphTargets:m},this._shaderLanguage,this._shadersLoaded?void 0:async()=>{await this._importShadersAsync(),this._shadersLoaded=!0}),v)}return _.effect.isReady()&&(this._dontCheckIfReady||!this._dontCheckIfReady&&this.isLayerReady())}_isSubMeshReady(e,t,i){return this._internalIsSubMeshReady(e,t,i)}async _importShadersAsync(){var e;this._shaderLanguage===1?await Promise.all([Promise.resolve().then(()=>(z9(),H9)),Promise.resolve().then(()=>(K9(),Y9))]):await Promise.all([Promise.resolve().then(()=>(Z9(),q9)),Promise.resolve().then(()=>(J9(),$9))]),(e=this._additionalImportShadersAsync)==null||e.call(this)}_internalIsLayerReady(){let e=!0;for(let i=0;iv.setMatrix("world",R)),(i.disableDepthWrite||i.forceDepthWrite)&&c.setDepthWrite(x),i.disableColorWrite&&c.setColorWrite(A),i.depthFunction!==0&&c.setDepthFunction(S)}else this._objectRenderer.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(r)}_useMeshMaterial(e){return!1}_rebuild(){let e=this._vertexBuffers[L.PositionKind];e&&e._rebuild(),this._generateIndexBuffer()}dispose(){let e=this._vertexBuffers[L.PositionKind];e&&(e.dispose(),this._vertexBuffers[L.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null);for(let t of this._mergeDrawWrapper)t.dispose();this._mergeDrawWrapper=[],this._objectRenderer.dispose(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderLayerObservable.clear(),this.onBeforeComposeObservable.clear(),this.onBeforeRenderMeshToEffect.clear(),this.onAfterRenderMeshToEffect.clear(),this.onAfterComposeObservable.clear()}};Rc.ForceGLSL=!1});var Ds,AO=C(()=>{Gt();Vt();Ii();di();Di();Fr();_f();hn();$a();WR();pA();Ds=class n{get _shouldRender(){return this._thinEffectLayer._shouldRender}set _shouldRender(e){this._thinEffectLayer._shouldRender=e}get _emissiveTextureAndColor(){return this._thinEffectLayer._emissiveTextureAndColor}set _emissiveTextureAndColor(e){this._thinEffectLayer._emissiveTextureAndColor=e}get _effectIntensity(){return this._thinEffectLayer._effectIntensity}set _effectIntensity(e){this._thinEffectLayer._effectIntensity=e}static get ForceGLSL(){return Rc.ForceGLSL}static set ForceGLSL(e){Rc.ForceGLSL=e}get name(){return this._thinEffectLayer.name}set name(e){this._thinEffectLayer.name=e}get neutralColor(){return this._thinEffectLayer.neutralColor}set neutralColor(e){this._thinEffectLayer.neutralColor=e}get isEnabled(){return this._thinEffectLayer.isEnabled}set isEnabled(e){this._thinEffectLayer.isEnabled=e}get camera(){return this._thinEffectLayer.camera}get renderingGroupId(){return this._thinEffectLayer.renderingGroupId}set renderingGroupId(e){this._thinEffectLayer.renderingGroupId=e}get disableBoundingBoxesFromEffectLayer(){return this._thinEffectLayer.disableBoundingBoxesFromEffectLayer}set disableBoundingBoxesFromEffectLayer(e){this._thinEffectLayer.disableBoundingBoxesFromEffectLayer=e}get mainTexture(){return this._mainTexture}get _shaderLanguage(){return this._thinEffectLayer.shaderLanguage}get shaderLanguage(){return this._thinEffectLayer.shaderLanguage}setMaterialForRendering(e,t){this._thinEffectLayer.setMaterialForRendering(e,t)}getEffectIntensity(e){return this._thinEffectLayer.getEffectIntensity(e)}setEffectIntensity(e,t){this._thinEffectLayer.setEffectIntensity(e,t)}constructor(e,t,i=!1,r){this._mainTextureCreatedSize={width:0,height:0},this._maxSize=0,this._mainTextureDesiredSize={width:0,height:0},this._postProcesses=[],this._textures=[],this.uniqueId=Ql.UniqueId,this.onDisposeObservable=new ie,this.onBeforeRenderMainTextureObservable=new ie,this.onBeforeComposeObservable=new ie,this.onBeforeRenderMeshToEffect=new ie,this.onAfterRenderMeshToEffect=new ie,this.onAfterComposeObservable=new ie,this.onSizeChangedObservable=new ie,this._internalThinEffectLayer=!r,r||(r=new Rc(e,t,i,!1,this._importShadersAsync.bind(this)),r.getEffectName=this.getEffectName.bind(this),r.isReady=this.isReady.bind(this),r._createMergeEffect=this._createMergeEffect.bind(this),r._createTextureAndPostProcesses=this._createTextureAndPostProcesses.bind(this),r._internalCompose=this._internalRender.bind(this),r._setEmissiveTextureAndColor=this._setEmissiveTextureAndColor.bind(this),r._numInternalDraws=this._numInternalDraws.bind(this),r._addCustomEffectDefines=this._addCustomEffectDefines.bind(this),r.hasMesh=this.hasMesh.bind(this),r.shouldRender=this.shouldRender.bind(this),r._shouldRenderMesh=this._shouldRenderMesh.bind(this),r._canRenderMesh=this._canRenderMesh.bind(this),r._useMeshMaterial=this._useMeshMaterial.bind(this)),this._thinEffectLayer=r,this.name=e,this._scene=t||Oe.LastCreatedScene,n._SceneComponentInitialization(this._scene),this._engine=this._scene.getEngine(),this._maxSize=this._engine.getCaps().maxTextureSize,this._scene.addEffectLayer(this),this._thinEffectLayer.onDisposeObservable.add(()=>{this.onDisposeObservable.notifyObservers(this)}),this._thinEffectLayer.onBeforeRenderLayerObservable.add(()=>{this.onBeforeRenderMainTextureObservable.notifyObservers(this)}),this._thinEffectLayer.onBeforeComposeObservable.add(()=>{this.onBeforeComposeObservable.notifyObservers(this)}),this._thinEffectLayer.onBeforeRenderMeshToEffect.add(s=>{this.onBeforeRenderMeshToEffect.notifyObservers(s)}),this._thinEffectLayer.onAfterRenderMeshToEffect.add(s=>{this.onAfterRenderMeshToEffect.notifyObservers(s)}),this._thinEffectLayer.onAfterComposeObservable.add(()=>{this.onAfterComposeObservable.notifyObservers(this)})}get _shadersLoaded(){return this._thinEffectLayer._shadersLoaded}set _shadersLoaded(e){this._thinEffectLayer._shadersLoaded=e}_numInternalDraws(){return this._internalThinEffectLayer?1:this._thinEffectLayer._numInternalDraws()}_init(e){this._effectLayerOptions={mainTextureRatio:.5,alphaBlendingMode:2,camera:null,renderingGroupId:-1,mainTextureType:0,mainTextureFormat:5,generateStencilBuffer:!1,...e},this._setMainTextureSize(),this._thinEffectLayer._init(e),this._createMainTexture(),this._createTextureAndPostProcesses()}_setMainTextureSize(){this._effectLayerOptions.mainTextureFixedSize?(this._mainTextureDesiredSize.width=this._effectLayerOptions.mainTextureFixedSize,this._mainTextureDesiredSize.height=this._effectLayerOptions.mainTextureFixedSize):(this._mainTextureDesiredSize.width=this._engine.getRenderWidth()*this._effectLayerOptions.mainTextureRatio,this._mainTextureDesiredSize.height=this._engine.getRenderHeight()*this._effectLayerOptions.mainTextureRatio,this._mainTextureDesiredSize.width=this._engine.needPOTTextures?gn(this._mainTextureDesiredSize.width,this._maxSize):this._mainTextureDesiredSize.width,this._mainTextureDesiredSize.height=this._engine.needPOTTextures?gn(this._mainTextureDesiredSize.height,this._maxSize):this._mainTextureDesiredSize.height),this._mainTextureDesiredSize.width=Math.floor(this._mainTextureDesiredSize.width),this._mainTextureDesiredSize.height=Math.floor(this._mainTextureDesiredSize.height)}_createMainTexture(){this._mainTexture=new Br("EffectLayerMainRTT",{width:this._mainTextureDesiredSize.width,height:this._mainTextureDesiredSize.height},this._scene,{type:this._effectLayerOptions.mainTextureType,format:this._effectLayerOptions.mainTextureFormat,samplingMode:ge.TRILINEAR_SAMPLINGMODE,generateStencilBuffer:this._effectLayerOptions.generateStencilBuffer,existingObjectRenderer:this._thinEffectLayer.objectRenderer}),this._mainTexture.activeCamera=this._effectLayerOptions.camera,this._mainTexture.wrapU=ge.CLAMP_ADDRESSMODE,this._mainTexture.wrapV=ge.CLAMP_ADDRESSMODE,this._mainTexture.anisotropicFilteringLevel=1,this._mainTexture.updateSamplingMode(ge.BILINEAR_SAMPLINGMODE),this._mainTexture.renderParticles=!1,this._mainTexture.renderList=null,this._mainTexture.ignoreCameraViewport=!0,this._mainTexture.onClearObservable.add(e=>{e.clear(this.neutralColor,!0,!0,!0)})}_addCustomEffectDefines(e){}_isReady(e,t,i){return this._internalThinEffectLayer?this._thinEffectLayer._internalIsSubMeshReady(e,t,i):this._thinEffectLayer._isSubMeshReady(e,t,i)}async _importShadersAsync(){}_arePostProcessAndMergeReady(){return this._internalThinEffectLayer?this._thinEffectLayer._internalIsLayerReady():this._thinEffectLayer.isLayerReady()}isLayerReady(){return this._arePostProcessAndMergeReady()&&this._mainTexture.isReady()}render(){this._thinEffectLayer.compose()&&(this._setMainTextureSize(),(this._mainTextureCreatedSize.width!==this._mainTextureDesiredSize.width||this._mainTextureCreatedSize.height!==this._mainTextureDesiredSize.height)&&this._mainTextureDesiredSize.width!==0&&this._mainTextureDesiredSize.height!==0&&(this.onSizeChangedObservable.notifyObservers(this),this._disposeTextureAndPostProcesses(),this._createMainTexture(),this._createTextureAndPostProcesses(),this._mainTextureCreatedSize.width=this._mainTextureDesiredSize.width,this._mainTextureCreatedSize.height=this._mainTextureDesiredSize.height))}hasMesh(e){return this._internalThinEffectLayer?this._thinEffectLayer._internalHasMesh(e):this._thinEffectLayer.hasMesh(e)}shouldRender(){return this._internalThinEffectLayer?this._thinEffectLayer._internalShouldRender():this._thinEffectLayer.shouldRender()}_shouldRenderMesh(e){return this._internalThinEffectLayer?!0:this._thinEffectLayer._shouldRenderMesh(e)}_canRenderMesh(e,t){return this._internalThinEffectLayer?this._thinEffectLayer._internalCanRenderMesh(e,t):this._thinEffectLayer._canRenderMesh(e,t)}_shouldRenderEmissiveTextureForMesh(){return!0}_useMeshMaterial(e){return this._internalThinEffectLayer?!1:this._thinEffectLayer._useMeshMaterial(e)}_rebuild(){this._thinEffectLayer._rebuild()}_disposeTextureAndPostProcesses(){this._mainTexture.dispose();for(let e=0;e{throw qe("EffectLayerSceneComponent")};P([w()],Ds.prototype,"name",null);P([tm()],Ds.prototype,"neutralColor",null);P([w()],Ds.prototype,"isEnabled",null);P([M2()],Ds.prototype,"camera",null);P([w()],Ds.prototype,"renderingGroupId",null);P([w()],Ds.prototype,"disableBoundingBoxesFromEffectLayer",null)});var tK={};tt(tK,{glowMapMergePixelShaderWGSL:()=>Fde});var xO,eK,Fde,iK=C(()=>{k();xO="glowMapMergePixelShader",eK=`varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d; #ifdef EMISSIVE var textureSampler2Sampler: sampler;var textureSampler2: texture_2d; #endif @@ -23712,14 +23712,14 @@ baseColor=clamp(baseColor,vec4f(0.),vec4f(1.0)); fragmentOutputs.color=baseColor; #define CUSTOM_FRAGMENT_MAIN_END } -`;T.ShadersStoreWGSL[xO]||(T.ShadersStoreWGSL[xO]=eK);Fde={name:xO,shader:eK}});var nK={};tt(nK,{glowMapMergeVertexShaderWGSL:()=>Bde});var RO,rK,Bde,sK=C(()=>{W();RO="glowMapMergeVertexShader",rK=`attribute position: vec2f;varying vUV: vec2f; +`;T.ShadersStoreWGSL[xO]||(T.ShadersStoreWGSL[xO]=eK);Fde={name:xO,shader:eK}});var nK={};tt(nK,{glowMapMergeVertexShaderWGSL:()=>Bde});var RO,rK,Bde,sK=C(()=>{k();RO="glowMapMergeVertexShader",rK=`attribute position: vec2f;varying vUV: vec2f; #define CUSTOM_VERTEX_DEFINITIONS @vertex fn main(input : VertexInputs)->FragmentInputs {const madd: vec2f= vec2f(0.5,0.5); #define CUSTOM_VERTEX_MAIN_BEGIN vertexOutputs.vUV=vertexInputs.position*madd+madd;vertexOutputs.position= vec4f(vertexInputs.position,0.0,1.0); #define CUSTOM_VERTEX_MAIN_END -}`;T.ShadersStoreWGSL[RO]||(T.ShadersStoreWGSL[RO]=rK);Bde={name:RO,shader:rK}});var oK={};tt(oK,{glowMapMergePixelShader:()=>Ude});var bO,aK,Ude,lK=C(()=>{W();bO="glowMapMergePixelShader",aK=`varying vec2 vUV;uniform sampler2D textureSampler; +}`;T.ShadersStoreWGSL[RO]||(T.ShadersStoreWGSL[RO]=rK);Bde={name:RO,shader:rK}});var oK={};tt(oK,{glowMapMergePixelShader:()=>Ude});var bO,aK,Ude,lK=C(()=>{k();bO="glowMapMergePixelShader",aK=`varying vec2 vUV;uniform sampler2D textureSampler; #ifdef EMISSIVE uniform sampler2D textureSampler2; #endif @@ -23741,14 +23741,14 @@ baseColor=clamp(baseColor,0.,1.0); #endif gl_FragColor=baseColor; #define CUSTOM_FRAGMENT_MAIN_END -}`;T.ShadersStore[bO]||(T.ShadersStore[bO]=aK);Ude={name:bO,shader:aK}});var fK={};tt(fK,{glowMapMergeVertexShader:()=>Vde});var IO,cK,Vde,hK=C(()=>{W();IO="glowMapMergeVertexShader",cK=`attribute vec2 position;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); +}`;T.ShadersStore[bO]||(T.ShadersStore[bO]=aK);Ude={name:bO,shader:aK}});var fK={};tt(fK,{glowMapMergeVertexShader:()=>Vde});var IO,cK,Vde,hK=C(()=>{k();IO="glowMapMergeVertexShader",cK=`attribute vec2 position;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0); #define CUSTOM_VERTEX_MAIN_END -}`;T.ShadersStore[IO]||(T.ShadersStore[IO]=cK);Vde={name:IO,shader:cK}});var ml,dK=C(()=>{Ve();Gi();Vn();sC();kR();zt();iD();ml=class n extends bc{set blurHorizontalSize(e){this._horizontalBlurPostprocess.kernel=e,this._options.blurHorizontalSize=e}set blurVerticalSize(e){this._verticalBlurPostprocess.kernel=e,this._options.blurVerticalSize=e}get blurHorizontalSize(){return this._horizontalBlurPostprocess.kernel}get blurVerticalSize(){return this._verticalBlurPostprocess.kernel}get stencilReference(){return this._instanceGlowingMeshStencilReference<<8-this.numStencilBits}constructor(e,t,i,r=!1){super(e,t,i!==void 0?!!i.forceGLSL:!1),this.innerGlow=!0,this.outerGlow=!0,this._instanceGlowingMeshStencilReference=n.GlowingMeshStencilReference++,this._meshes={},this._excludedMeshes={},this._mainObjectRendererRenderPassId=-1,this.numStencilBits=8,this.neutralColor=n.NeutralColor,this._options={mainTextureRatio:.5,blurTextureSizeRatio:.5,mainTextureFixedSize:0,blurHorizontalSize:1,blurVerticalSize:1,alphaBlendingMode:2,camera:null,renderingGroupId:-1,forceGLSL:!1,mainTextureType:0,mainTextureFormat:5,isStroke:!1,...i},this._init(this._options),this._shouldRender=!1,r&&this._createTextureAndPostProcesses()}getClassName(){return"HighlightLayer"}async _importShadersAsync(){this._shaderLanguage===1?await Promise.all([Promise.resolve().then(()=>(iK(),tK)),Promise.resolve().then(()=>(sK(),nK)),Promise.resolve().then(()=>(UR(),BR))]):await Promise.all([Promise.resolve().then(()=>(lK(),oK)),Promise.resolve().then(()=>(hK(),fK)),Promise.resolve().then(()=>(GR(),VR))]),await super._importShadersAsync()}getEffectName(){return n.EffectName}_numInternalDraws(){return 2}_createMergeEffect(){return this._engine.createEffect("glowMapMerge",[L.PositionKind],["offset"],["textureSampler"],this._options.isStroke?`#define STROKE -`:void 0,void 0,void 0,void 0,void 0,this._shaderLanguage,this._shadersLoaded?void 0:async()=>{await this._importShadersAsync(),this._shadersLoaded=!0})}_createTextureAndPostProcesses(){this._options.alphaBlendingMode===2?(this._downSamplePostprocess=new jl("HighlightLayerPPP",this._scene.getEngine()),this._horizontalBlurPostprocess=new To("HighlightLayerHBP",this._scene.getEngine(),new we(1,0),this._options.blurHorizontalSize),this._verticalBlurPostprocess=new To("HighlightLayerVBP",this._scene.getEngine(),new we(0,1),this._options.blurVerticalSize),this._postProcesses=[this._downSamplePostprocess,this._horizontalBlurPostprocess,this._verticalBlurPostprocess]):(this._horizontalBlurPostprocess=new rs("HighlightLayerHBP",this._scene.getEngine(),new we(1,0),this._options.blurHorizontalSize/2),this._verticalBlurPostprocess=new rs("HighlightLayerVBP",this._scene.getEngine(),new we(0,1),this._options.blurVerticalSize/2),this._postProcesses=[this._horizontalBlurPostprocess,this._verticalBlurPostprocess])}needStencil(){return!0}isReady(e,t){let i=e.getMaterial(),r=e.getRenderingMesh();if(!i||!r||!this._meshes)return!1;let s=null,a=this._meshes[r.uniqueId];return a&&a.glowEmissiveOnly&&i&&(s=i.emissiveTexture),super._isSubMeshReady(e,t,s)}_canRenderMesh(e,t){return!0}_internalCompose(e,t){this.bindTexturesForCompose(e);let i=this._engine;i.cacheStencilState(),i.setStencilOperationPass(7681),i.setStencilOperationFail(7680),i.setStencilOperationDepthFail(7680),i.setStencilMask(0),i.setStencilBuffer(!0),i.setStencilFunctionReference(this._instanceGlowingMeshStencilReference<<8-this.numStencilBits),i.setStencilFunctionMask(255-((1<<8-this.numStencilBits)-1)),this.outerGlow&&t===0&&(e.setFloat("offset",0),i.setStencilFunction(517),i.drawElementsType(Ee.TriangleFillMode,0,6)),this.innerGlow&&t===1&&(e.setFloat("offset",1),i.setStencilFunction(514),i.drawElementsType(Ee.TriangleFillMode,0,6)),i.restoreStencilState()}_setEmissiveTextureAndColor(e,t,i){let r=this._meshes[e.uniqueId];r?this._emissiveTextureAndColor.color.set(r.color.r,r.color.g,r.color.b,1):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a),r&&r.glowEmissiveOnly&&i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.color.set(1,1,1,1)):this._emissiveTextureAndColor.texture=null}shouldRender(){return!!(this._meshes&&super.shouldRender())}_shouldRenderMesh(e){return this._excludedMeshes&&this._excludedMeshes[e.uniqueId]?!1:super.hasMesh(e)}_addCustomEffectDefines(e){e.push("#define HIGHLIGHT")}addExcludedMesh(e){if(!this._excludedMeshes)return;if(!this._excludedMeshes[e.uniqueId]){let i={mesh:e,beforeBind:null,afterRender:null,stencilState:!1};i.beforeBind=e.onBeforeBindObservable.add(r=>{this._mainObjectRendererRenderPassId!==-1&&this._mainObjectRendererRenderPassId!==this._engine.currentRenderPassId||(i.stencilState=r.getEngine().getStencilBuffer(),r.getEngine().setStencilBuffer(!1))}),i.afterRender=e.onAfterRenderObservable.add(r=>{this._mainObjectRendererRenderPassId!==-1&&this._mainObjectRendererRenderPassId!==this._engine.currentRenderPassId||r.getEngine().setStencilBuffer(i.stencilState)}),this._excludedMeshes[e.uniqueId]=i}}removeExcludedMesh(e){if(!this._excludedMeshes)return;let t=this._excludedMeshes[e.uniqueId];t&&(t.beforeBind&&e.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&e.onAfterRenderObservable.remove(t.afterRender)),this._excludedMeshes[e.uniqueId]=null}hasMesh(e){return!this._meshes||!super.hasMesh(e)?!1:!!this._meshes[e.uniqueId]}addMesh(e,t,i=!1){if(!this._meshes)return;let r=this._meshes[e.uniqueId];r?r.color=t:(this._meshes[e.uniqueId]={mesh:e,color:t,observerHighlight:e.onBeforeBindObservable.add(s=>{this._mainObjectRendererRenderPassId!==-1&&this._mainObjectRendererRenderPassId!==this._engine.currentRenderPassId||this.isEnabled&&(this._excludedMeshes&&this._excludedMeshes[s.uniqueId]?this._defaultStencilReference(s):s.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference<<8-this.numStencilBits))}),observerDefault:e.onAfterRenderObservable.add(s=>{this._mainObjectRendererRenderPassId!==-1&&this._mainObjectRendererRenderPassId!==this._engine.currentRenderPassId||this.isEnabled&&this._defaultStencilReference(s)}),glowEmissiveOnly:i},e.onDisposeObservable.add(()=>{this._disposeMesh(e)})),this._shouldRender=!0}removeMesh(e){if(!this._meshes)return;let t=this._meshes[e.uniqueId];t&&(t.observerHighlight&&e.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&e.onAfterRenderObservable.remove(t.observerDefault),delete this._meshes[e.uniqueId]),this._shouldRender=!1;for(let i in this._meshes)if(this._meshes[i]){this._shouldRender=!0;break}}removeAllMeshes(){if(this._meshes){for(let e in this._meshes)if(Object.prototype.hasOwnProperty.call(this._meshes,e)){let t=this._meshes[e];t&&this.removeMesh(t.mesh)}}}_defaultStencilReference(e){e.getScene().getEngine().setStencilFunctionReference(n.NormalMeshStencilReference<<8-this.numStencilBits)}_disposeMesh(e){this.removeMesh(e),this.removeExcludedMesh(e)}dispose(){if(this._meshes){for(let e in this._meshes){let t=this._meshes[e];t&&t.mesh&&(t.observerHighlight&&t.mesh.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&t.mesh.onAfterRenderObservable.remove(t.observerDefault))}this._meshes=null}if(this._excludedMeshes){for(let e in this._excludedMeshes){let t=this._excludedMeshes[e];t&&(t.beforeBind&&t.mesh.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&t.mesh.onAfterRenderObservable.remove(t.afterRender))}this._excludedMeshes=null}super.dispose()}};ml.EffectName="HighlightLayer";ml.NeutralColor=new lt(0,0,0,0);ml.GlowingMeshStencilReference=2;ml.NormalMeshStencilReference=1});var WR,ea,uK=C(()=>{Gt();Ut();hi();xs();Ve();Fr();gf();Kl();oC();rD();AO();yt();Hi();zt();dK();Tr();$a();kR();$t.prototype.getHighlightLayerByName=function(n){var e;for(let t=0;t<((e=this.effectLayers)==null?void 0:e.length);t++)if(this.effectLayers[t].name===n&&this.effectLayers[t].getEffectName()===ea.EffectName)return this.effectLayers[t];return null};WR=class extends xi{constructor(e,t,i,r,s=null,a=_e.BILINEAR_SAMPLINGMODE,o,l){let c={uniforms:To.Uniforms,size:typeof r=="number"?r:void 0,camera:s,samplingMode:a,engine:o,reusable:l,...r};super(e,To.FragmentUrl,{effectWrapper:typeof r=="number"||!r.effectWrapper?new To(e,o,t,i,c):void 0,...c}),this.direction=t,this.kernel=i,this.onApplyObservable.add(()=>{this._effectWrapper.textureWidth=this.width,this._effectWrapper.textureHeight=this.height})}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.resolve().then(()=>(UR(),BR)))):t.push(Promise.resolve().then(()=>(GR(),VR))),super._gatherImports(e,t)}},ea=class n extends Ls{static get NeutralColor(){return ml.NeutralColor}static set NeutralColor(e){ml.NeutralColor=e}get innerGlow(){return this._thinEffectLayer.innerGlow}set innerGlow(e){this._thinEffectLayer.innerGlow=e}get outerGlow(){return this._thinEffectLayer.outerGlow}set outerGlow(e){this._thinEffectLayer.outerGlow=e}set blurHorizontalSize(e){this._thinEffectLayer.blurHorizontalSize=e}set blurVerticalSize(e){this._thinEffectLayer.blurVerticalSize=e}get blurHorizontalSize(){return this._thinEffectLayer.blurHorizontalSize}get blurVerticalSize(){return this._thinEffectLayer.blurVerticalSize}get numStencilBits(){return this._thinEffectLayer.numStencilBits}set numStencilBits(e){this._thinEffectLayer.numStencilBits=e}get stencilReference(){return this._thinEffectLayer.stencilReference}constructor(e,t,i){super(e,t,i!==void 0?!!i.forceGLSL:!1,new ml(e,t,i)),this.onBeforeBlurObservable=new ie,this.onAfterBlurObservable=new ie,this._engine.isStencilEnable||te.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }"),this._options={mainTextureRatio:.5,blurTextureSizeRatio:.5,mainTextureFixedSize:0,blurHorizontalSize:1,blurVerticalSize:1,alphaBlendingMode:2,camera:null,renderingGroupId:-1,mainTextureType:0,mainTextureFormat:5,forceGLSL:!1,isStroke:!1,generateStencilBuffer:!1,...i},this._init(this._options),this._shouldRender=!1}getEffectName(){return n.EffectName}_numInternalDraws(){return 2}_createMergeEffect(){return this._thinEffectLayer._createMergeEffect()}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width*this._options.blurTextureSizeRatio,t=this._mainTextureDesiredSize.height*this._options.blurTextureSizeRatio;e=this._engine.needPOTTextures?gn(e,this._maxSize):e,t=this._engine.needPOTTextures?gn(t,this._maxSize):t;let i;this._engine.getCaps().textureHalfFloatRender?i=2:i=0,this._blurTexture=new Br("HighlightLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture.wrapU=_e.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=_e.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(_e.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._blurTexture.ignoreCameraViewport=!0,this._textures=[this._blurTexture],this._thinEffectLayer.bindTexturesForCompose=r=>{r.setTexture("textureSampler",this._blurTexture)},this._thinEffectLayer._createTextureAndPostProcesses(),this._options.alphaBlendingMode===2?(this._downSamplePostprocess=new Wh("HighlightLayerPPP",{size:this._options.blurTextureSizeRatio,samplingMode:_e.BILINEAR_SAMPLINGMODE,engine:this._scene.getEngine(),effectWrapper:this._thinEffectLayer._postProcesses[0]}),this._downSamplePostprocess.externalTextureSamplerBinding=!0,this._downSamplePostprocess.onApplyObservable.add(r=>{r.setTexture("textureSampler",this._mainTexture)}),this._horizontalBlurPostprocess=new WR("HighlightLayerHBP",new we(1,0),this._options.blurHorizontalSize,{samplingMode:_e.BILINEAR_SAMPLINGMODE,engine:this._scene.getEngine(),effectWrapper:this._thinEffectLayer._postProcesses[1]}),this._horizontalBlurPostprocess.onApplyObservable.add(r=>{r.setFloat2("screenSize",e,t)}),this._verticalBlurPostprocess=new WR("HighlightLayerVBP",new we(0,1),this._options.blurVerticalSize,{samplingMode:_e.BILINEAR_SAMPLINGMODE,engine:this._scene.getEngine(),effectWrapper:this._thinEffectLayer._postProcesses[2]}),this._verticalBlurPostprocess.onApplyObservable.add(r=>{r.setFloat2("screenSize",e,t)}),this._postProcesses=[this._downSamplePostprocess,this._horizontalBlurPostprocess,this._verticalBlurPostprocess]):(this._horizontalBlurPostprocess=new wa("HighlightLayerHBP",new we(1,0),this._options.blurHorizontalSize/2,{size:{width:e,height:t},samplingMode:_e.BILINEAR_SAMPLINGMODE,engine:this._scene.getEngine(),textureType:i,effectWrapper:this._thinEffectLayer._postProcesses[0]}),this._horizontalBlurPostprocess.width=e,this._horizontalBlurPostprocess.height=t,this._horizontalBlurPostprocess.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess.onApplyObservable.add(r=>{r.setTexture("textureSampler",this._mainTexture)}),this._verticalBlurPostprocess=new wa("HighlightLayerVBP",new we(0,1),this._options.blurVerticalSize/2,{size:{width:e,height:t},samplingMode:_e.BILINEAR_SAMPLINGMODE,engine:this._scene.getEngine(),textureType:i}),this._postProcesses=[this._horizontalBlurPostprocess,this._verticalBlurPostprocess]),this._mainTexture.onAfterUnbindObservable.add(()=>{this.onBeforeBlurObservable.notifyObservers(this);let r=this._blurTexture.renderTarget;r&&(this._scene.postProcessManager.directRender(this._postProcesses,r,!0),this._engine.unBindFramebuffer(r,!0)),this.onAfterBlurObservable.notifyObservers(this)}),this._postProcesses.map(r=>{r.autoClear=!1}),this._mainTextureCreatedSize.width=this._mainTextureDesiredSize.width,this._mainTextureCreatedSize.height=this._mainTextureDesiredSize.height}needStencil(){return this._thinEffectLayer.needStencil()}isReady(e,t){return this._thinEffectLayer.isReady(e,t)}_internalRender(e,t){this._thinEffectLayer._internalCompose(e,t)}shouldRender(){return this._thinEffectLayer.shouldRender()}_shouldRenderMesh(e){return this._thinEffectLayer._shouldRenderMesh(e)}_canRenderMesh(e,t){return this._thinEffectLayer._canRenderMesh(e,t)}_addCustomEffectDefines(e){this._thinEffectLayer._addCustomEffectDefines(e)}_setEmissiveTextureAndColor(e,t,i){this._thinEffectLayer._setEmissiveTextureAndColor(e,t,i)}addExcludedMesh(e){this._thinEffectLayer.addExcludedMesh(e)}removeExcludedMesh(e){this._thinEffectLayer.removeExcludedMesh(e)}hasMesh(e){return this._thinEffectLayer.hasMesh(e)}addMesh(e,t,i=!1){this._thinEffectLayer.addMesh(e,t,i)}removeMesh(e){this._thinEffectLayer.removeMesh(e)}removeAllMeshes(){this._thinEffectLayer.removeAllMeshes()}_disposeMesh(e){this._thinEffectLayer._disposeMesh(e)}getClassName(){return"HighlightLayer"}serialize(){let e=it.Serialize(this);e.customType="BABYLON.HighlightLayer",e.meshes=[];let t=this._thinEffectLayer._meshes;if(t)for(let r in t){let s=t[r];s&&e.meshes.push({glowEmissiveOnly:s.glowEmissiveOnly,color:s.color.asArray(),meshId:s.mesh.id})}e.excludedMeshes=[];let i=this._thinEffectLayer._excludedMeshes;if(i)for(let r in i){let s=i[r];s&&e.excludedMeshes.push(s.mesh.id)}return e}static Parse(e,t,i){let r=it.Parse(()=>new n(e.name,t,e.options),e,t,i),s;for(s=0;s{sl();om();AO();Pi();xD();sR($e.NAME_EFFECTLAYER,(n,e,t,i)=>{if(n.effectLayers){t.effectLayers||(t.effectLayers=[]);for(let r=0;r0){this._previousStencilState=this._engine.getStencilBuffer();for(let r of i)if(r.shouldRender()&&(!r.camera||r.camera.cameraRigMode===ut.RIG_MODE_NONE&&e===r.camera||r.camera.cameraRigMode!==ut.RIG_MODE_NONE&&r.camera._rigCameras.indexOf(e)>-1)){this._renderEffects=!0,this._needStencil=this._needStencil||r.needStencil();let s=r._mainTexture;s._shouldRender()&&(this.scene.incrementRenderId(),s.render(!1,!1),t=!0)}this.scene.incrementRenderId()}return t}_setStencil(){this._needStencil&&this._engine.setStencilBuffer(!0)}_setStencilBack(){this._needStencil&&this._engine.setStencilBuffer(this._previousStencilState)}_draw(e){if(this._renderEffects){this._engine.setDepthBuffer(!1);let t=this.scene.effectLayers;for(let i=0;i{let e=n._getComponent($e.NAME_EFFECTLAYER);e||(e=new MO(n),n._addComponent(e))}});function pK(n,e,t=()=>!0){let i=new ea("ai3d-pick-highlight",n),r=new ge(.15,.45,1),s=null;function a(){i.removeAllMeshes(),s&&!s.isDisposed()&&(s.renderOutline=!1,s.outlineWidth=0),s=null}function o(c){c.isDisposed()||(i.addMesh(c,r),c.renderOutline=!0,c.outlineColor=r,c.outlineWidth=.045,s=c)}let l=n.onPointerObservable.add(c=>{var m;if(c.type!==st.POINTERDOWN)return;let f=c.event,h=f.clientX,d=f.clientY,u=c.pickInfo;u!=null&&u.hit&&u.pickedMesh?(t()?s!==u.pickedMesh&&(a(),o(u.pickedMesh)):a(),e({mesh:u.pickedMesh,pickedPoint:(m=u.pickedPoint)!=null?m:null,screenX:h,screenY:d})):(a(),e({mesh:null,pickedPoint:null,screenX:h,screenY:d}))});return()=>{a(),i.dispose(),n.onPointerObservable.remove(l)}}var _K=C(()=>{"use strict";oo();zt();uK();mK()});function Yde(n,e,t){let i=ge.FromHexString(e),r=new Ge(n,t);return r.emissiveColor=i,r.diffuseColor=ge.Black(),r.specularColor=ge.Black(),r.backFaceCulling=!1,r}function Kde(n){let e=new Ge("gizmo-origin-mat",n);return e.emissiveColor=new ge(.72,.78,.86),e.diffuseColor=ge.Black(),e.specularColor=ge.Black(),e}var Gde,HR,kde,yO,Wde,Hde,CO,zde,Xde,zR,gK=C(()=>{"use strict";xs();VA();GA();Ve();zt();Ju();TP();Tc();Gde=.32,HR=1.05,kde=.075,yO=.28,Wde=.22,Hde=.16,CO=(HR+yO)*.42,zde=new b(CO,CO,CO),Xde=[{name:"x",color:"#e74c3c",rot:new b(0,0,-Math.PI/2),dir:new b(1,0,0)},{name:"y",color:"#2ecc71",rot:new b(0,0,0),dir:new b(0,1,0)},{name:"z",color:"#3498db",rot:new b(Math.PI/2,0,0),dir:new b(0,0,1)}];zR=class{constructor(e,t){this.engine=e,this.scene=new $t(e),this.scene.clearColor=new lt(0,0,0,0),this.scene.autoClear=!1,this.camera=new gi("gizmo-cam",0,0,4.1,zde,this.scene),this.camera.minZ=.01,this.camera.fov=.56,this.camera.detachControl(),new Qs("gizmo-light",new b(0,1,.5),this.scene);let i=is.CreateSphere("gizmo-origin",{diameter:Hde,segments:16},this.scene);i.material=Kde(this.scene);for(let{name:s,color:a,rot:o,dir:l}of Xde){let c=Yde(`gizmo-${s}-mat`,a,this.scene),f=is.CreateCylinder(`gizmo-${s}-shaft`,{height:HR,diameter:kde,tessellation:8},this.scene);f.material=c,f.position=l.scale(HR/2),f.rotation=o;let h=is.CreateCylinder(`gizmo-${s}-head`,{height:yO,diameterTop:0,diameterBottom:Wde,tessellation:8},this.scene);h.material=c;let d=HR+yO/2;h.position=l.scale(d),h.rotation=o}let r=Gde;this.viewport=new io(.02,.03,r,r),this.camera.viewport=this.viewport,this.syncWith(t)}syncWith(e){this.camera.alpha=e.alpha,this.camera.beta=e.beta}render(){let e=this.engine.getRenderWidth(),t=this.engine.getRenderHeight(),i=this.viewport.x*e,r=this.viewport.y*t,s=this.viewport.width*e,a=this.viewport.height*t;this.engine.enableScissor(i,r,s,a),this.engine.clear(null,!1,!0,!0),this.scene.render(),this.engine.disableScissor()}dispose(){this.scene.dispose()}}});var DO={};tt(DO,{boundingBoxRendererVertexShaderWGSL:()=>jde});var PO,vK,jde,LO=C(()=>{W();PO="boundingBoxRendererVertexShader",vK=`attribute position: vec3f;uniform world: mat4x4f;uniform viewProjection: mat4x4f; +}`;T.ShadersStore[IO]||(T.ShadersStore[IO]=cK);Vde={name:IO,shader:cK}});var ml,dK=C(()=>{Ge();ki();Vn();sC();WR();zt();iD();ml=class n extends Rc{set blurHorizontalSize(e){this._horizontalBlurPostprocess.kernel=e,this._options.blurHorizontalSize=e}set blurVerticalSize(e){this._verticalBlurPostprocess.kernel=e,this._options.blurVerticalSize=e}get blurHorizontalSize(){return this._horizontalBlurPostprocess.kernel}get blurVerticalSize(){return this._verticalBlurPostprocess.kernel}get stencilReference(){return this._instanceGlowingMeshStencilReference<<8-this.numStencilBits}constructor(e,t,i,r=!1){super(e,t,i!==void 0?!!i.forceGLSL:!1),this.innerGlow=!0,this.outerGlow=!0,this._instanceGlowingMeshStencilReference=n.GlowingMeshStencilReference++,this._meshes={},this._excludedMeshes={},this._mainObjectRendererRenderPassId=-1,this.numStencilBits=8,this.neutralColor=n.NeutralColor,this._options={mainTextureRatio:.5,blurTextureSizeRatio:.5,mainTextureFixedSize:0,blurHorizontalSize:1,blurVerticalSize:1,alphaBlendingMode:2,camera:null,renderingGroupId:-1,forceGLSL:!1,mainTextureType:0,mainTextureFormat:5,isStroke:!1,...i},this._init(this._options),this._shouldRender=!1,r&&this._createTextureAndPostProcesses()}getClassName(){return"HighlightLayer"}async _importShadersAsync(){this._shaderLanguage===1?await Promise.all([Promise.resolve().then(()=>(iK(),tK)),Promise.resolve().then(()=>(sK(),nK)),Promise.resolve().then(()=>(VR(),UR))]):await Promise.all([Promise.resolve().then(()=>(lK(),oK)),Promise.resolve().then(()=>(hK(),fK)),Promise.resolve().then(()=>(kR(),GR))]),await super._importShadersAsync()}getEffectName(){return n.EffectName}_numInternalDraws(){return 2}_createMergeEffect(){return this._engine.createEffect("glowMapMerge",[L.PositionKind],["offset"],["textureSampler"],this._options.isStroke?`#define STROKE +`:void 0,void 0,void 0,void 0,void 0,this._shaderLanguage,this._shadersLoaded?void 0:async()=>{await this._importShadersAsync(),this._shadersLoaded=!0})}_createTextureAndPostProcesses(){this._options.alphaBlendingMode===2?(this._downSamplePostprocess=new Kl("HighlightLayerPPP",this._scene.getEngine()),this._horizontalBlurPostprocess=new To("HighlightLayerHBP",this._scene.getEngine(),new we(1,0),this._options.blurHorizontalSize),this._verticalBlurPostprocess=new To("HighlightLayerVBP",this._scene.getEngine(),new we(0,1),this._options.blurVerticalSize),this._postProcesses=[this._downSamplePostprocess,this._horizontalBlurPostprocess,this._verticalBlurPostprocess]):(this._horizontalBlurPostprocess=new is("HighlightLayerHBP",this._scene.getEngine(),new we(1,0),this._options.blurHorizontalSize/2),this._verticalBlurPostprocess=new is("HighlightLayerVBP",this._scene.getEngine(),new we(0,1),this._options.blurVerticalSize/2),this._postProcesses=[this._horizontalBlurPostprocess,this._verticalBlurPostprocess])}needStencil(){return!0}isReady(e,t){let i=e.getMaterial(),r=e.getRenderingMesh();if(!i||!r||!this._meshes)return!1;let s=null,a=this._meshes[r.uniqueId];return a&&a.glowEmissiveOnly&&i&&(s=i.emissiveTexture),super._isSubMeshReady(e,t,s)}_canRenderMesh(e,t){return!0}_internalCompose(e,t){this.bindTexturesForCompose(e);let i=this._engine;i.cacheStencilState(),i.setStencilOperationPass(7681),i.setStencilOperationFail(7680),i.setStencilOperationDepthFail(7680),i.setStencilMask(0),i.setStencilBuffer(!0),i.setStencilFunctionReference(this._instanceGlowingMeshStencilReference<<8-this.numStencilBits),i.setStencilFunctionMask(255-((1<<8-this.numStencilBits)-1)),this.outerGlow&&t===0&&(e.setFloat("offset",0),i.setStencilFunction(517),i.drawElementsType(Ee.TriangleFillMode,0,6)),this.innerGlow&&t===1&&(e.setFloat("offset",1),i.setStencilFunction(514),i.drawElementsType(Ee.TriangleFillMode,0,6)),i.restoreStencilState()}_setEmissiveTextureAndColor(e,t,i){let r=this._meshes[e.uniqueId];r?this._emissiveTextureAndColor.color.set(r.color.r,r.color.g,r.color.b,1):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a),r&&r.glowEmissiveOnly&&i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.color.set(1,1,1,1)):this._emissiveTextureAndColor.texture=null}shouldRender(){return!!(this._meshes&&super.shouldRender())}_shouldRenderMesh(e){return this._excludedMeshes&&this._excludedMeshes[e.uniqueId]?!1:super.hasMesh(e)}_addCustomEffectDefines(e){e.push("#define HIGHLIGHT")}addExcludedMesh(e){if(!this._excludedMeshes)return;if(!this._excludedMeshes[e.uniqueId]){let i={mesh:e,beforeBind:null,afterRender:null,stencilState:!1};i.beforeBind=e.onBeforeBindObservable.add(r=>{this._mainObjectRendererRenderPassId!==-1&&this._mainObjectRendererRenderPassId!==this._engine.currentRenderPassId||(i.stencilState=r.getEngine().getStencilBuffer(),r.getEngine().setStencilBuffer(!1))}),i.afterRender=e.onAfterRenderObservable.add(r=>{this._mainObjectRendererRenderPassId!==-1&&this._mainObjectRendererRenderPassId!==this._engine.currentRenderPassId||r.getEngine().setStencilBuffer(i.stencilState)}),this._excludedMeshes[e.uniqueId]=i}}removeExcludedMesh(e){if(!this._excludedMeshes)return;let t=this._excludedMeshes[e.uniqueId];t&&(t.beforeBind&&e.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&e.onAfterRenderObservable.remove(t.afterRender)),this._excludedMeshes[e.uniqueId]=null}hasMesh(e){return!this._meshes||!super.hasMesh(e)?!1:!!this._meshes[e.uniqueId]}addMesh(e,t,i=!1){if(!this._meshes)return;let r=this._meshes[e.uniqueId];r?r.color=t:(this._meshes[e.uniqueId]={mesh:e,color:t,observerHighlight:e.onBeforeBindObservable.add(s=>{this._mainObjectRendererRenderPassId!==-1&&this._mainObjectRendererRenderPassId!==this._engine.currentRenderPassId||this.isEnabled&&(this._excludedMeshes&&this._excludedMeshes[s.uniqueId]?this._defaultStencilReference(s):s.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference<<8-this.numStencilBits))}),observerDefault:e.onAfterRenderObservable.add(s=>{this._mainObjectRendererRenderPassId!==-1&&this._mainObjectRendererRenderPassId!==this._engine.currentRenderPassId||this.isEnabled&&this._defaultStencilReference(s)}),glowEmissiveOnly:i},e.onDisposeObservable.add(()=>{this._disposeMesh(e)})),this._shouldRender=!0}removeMesh(e){if(!this._meshes)return;let t=this._meshes[e.uniqueId];t&&(t.observerHighlight&&e.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&e.onAfterRenderObservable.remove(t.observerDefault),delete this._meshes[e.uniqueId]),this._shouldRender=!1;for(let i in this._meshes)if(this._meshes[i]){this._shouldRender=!0;break}}removeAllMeshes(){if(this._meshes){for(let e in this._meshes)if(Object.prototype.hasOwnProperty.call(this._meshes,e)){let t=this._meshes[e];t&&this.removeMesh(t.mesh)}}}_defaultStencilReference(e){e.getScene().getEngine().setStencilFunctionReference(n.NormalMeshStencilReference<<8-this.numStencilBits)}_disposeMesh(e){this.removeMesh(e),this.removeExcludedMesh(e)}dispose(){if(this._meshes){for(let e in this._meshes){let t=this._meshes[e];t&&t.mesh&&(t.observerHighlight&&t.mesh.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&t.mesh.onAfterRenderObservable.remove(t.observerDefault))}this._meshes=null}if(this._excludedMeshes){for(let e in this._excludedMeshes){let t=this._excludedMeshes[e];t&&(t.beforeBind&&t.mesh.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&t.mesh.onAfterRenderObservable.remove(t.afterRender))}this._excludedMeshes=null}super.dispose()}};ml.EffectName="HighlightLayer";ml.NeutralColor=new lt(0,0,0,0);ml.GlowingMeshStencilReference=2;ml.NormalMeshStencilReference=1});var HR,Js,uK=C(()=>{Gt();Vt();di();As();Ge();Fr();_f();Yl();oC();rD();AO();Pt();Hi();zt();dK();Tr();$a();WR();Jt.prototype.getHighlightLayerByName=function(n){var e;for(let t=0;t<((e=this.effectLayers)==null?void 0:e.length);t++)if(this.effectLayers[t].name===n&&this.effectLayers[t].getEffectName()===Js.EffectName)return this.effectLayers[t];return null};HR=class extends Ri{constructor(e,t,i,r,s=null,a=ge.BILINEAR_SAMPLINGMODE,o,l){let c={uniforms:To.Uniforms,size:typeof r=="number"?r:void 0,camera:s,samplingMode:a,engine:o,reusable:l,...r};super(e,To.FragmentUrl,{effectWrapper:typeof r=="number"||!r.effectWrapper?new To(e,o,t,i,c):void 0,...c}),this.direction=t,this.kernel=i,this.onApplyObservable.add(()=>{this._effectWrapper.textureWidth=this.width,this._effectWrapper.textureHeight=this.height})}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.resolve().then(()=>(VR(),UR)))):t.push(Promise.resolve().then(()=>(kR(),GR))),super._gatherImports(e,t)}},Js=class n extends Ds{static get NeutralColor(){return ml.NeutralColor}static set NeutralColor(e){ml.NeutralColor=e}get innerGlow(){return this._thinEffectLayer.innerGlow}set innerGlow(e){this._thinEffectLayer.innerGlow=e}get outerGlow(){return this._thinEffectLayer.outerGlow}set outerGlow(e){this._thinEffectLayer.outerGlow=e}set blurHorizontalSize(e){this._thinEffectLayer.blurHorizontalSize=e}set blurVerticalSize(e){this._thinEffectLayer.blurVerticalSize=e}get blurHorizontalSize(){return this._thinEffectLayer.blurHorizontalSize}get blurVerticalSize(){return this._thinEffectLayer.blurVerticalSize}get numStencilBits(){return this._thinEffectLayer.numStencilBits}set numStencilBits(e){this._thinEffectLayer.numStencilBits=e}get stencilReference(){return this._thinEffectLayer.stencilReference}constructor(e,t,i){super(e,t,i!==void 0?!!i.forceGLSL:!1,new ml(e,t,i)),this.onBeforeBlurObservable=new ie,this.onAfterBlurObservable=new ie,this._engine.isStencilEnable||te.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }"),this._options={mainTextureRatio:.5,blurTextureSizeRatio:.5,mainTextureFixedSize:0,blurHorizontalSize:1,blurVerticalSize:1,alphaBlendingMode:2,camera:null,renderingGroupId:-1,mainTextureType:0,mainTextureFormat:5,forceGLSL:!1,isStroke:!1,generateStencilBuffer:!1,...i},this._init(this._options),this._shouldRender=!1}getEffectName(){return n.EffectName}_numInternalDraws(){return 2}_createMergeEffect(){return this._thinEffectLayer._createMergeEffect()}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width*this._options.blurTextureSizeRatio,t=this._mainTextureDesiredSize.height*this._options.blurTextureSizeRatio;e=this._engine.needPOTTextures?gn(e,this._maxSize):e,t=this._engine.needPOTTextures?gn(t,this._maxSize):t;let i;this._engine.getCaps().textureHalfFloatRender?i=2:i=0,this._blurTexture=new Br("HighlightLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture.wrapU=ge.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=ge.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(ge.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._blurTexture.ignoreCameraViewport=!0,this._textures=[this._blurTexture],this._thinEffectLayer.bindTexturesForCompose=r=>{r.setTexture("textureSampler",this._blurTexture)},this._thinEffectLayer._createTextureAndPostProcesses(),this._options.alphaBlendingMode===2?(this._downSamplePostprocess=new Wh("HighlightLayerPPP",{size:this._options.blurTextureSizeRatio,samplingMode:ge.BILINEAR_SAMPLINGMODE,engine:this._scene.getEngine(),effectWrapper:this._thinEffectLayer._postProcesses[0]}),this._downSamplePostprocess.externalTextureSamplerBinding=!0,this._downSamplePostprocess.onApplyObservable.add(r=>{r.setTexture("textureSampler",this._mainTexture)}),this._horizontalBlurPostprocess=new HR("HighlightLayerHBP",new we(1,0),this._options.blurHorizontalSize,{samplingMode:ge.BILINEAR_SAMPLINGMODE,engine:this._scene.getEngine(),effectWrapper:this._thinEffectLayer._postProcesses[1]}),this._horizontalBlurPostprocess.onApplyObservable.add(r=>{r.setFloat2("screenSize",e,t)}),this._verticalBlurPostprocess=new HR("HighlightLayerVBP",new we(0,1),this._options.blurVerticalSize,{samplingMode:ge.BILINEAR_SAMPLINGMODE,engine:this._scene.getEngine(),effectWrapper:this._thinEffectLayer._postProcesses[2]}),this._verticalBlurPostprocess.onApplyObservable.add(r=>{r.setFloat2("screenSize",e,t)}),this._postProcesses=[this._downSamplePostprocess,this._horizontalBlurPostprocess,this._verticalBlurPostprocess]):(this._horizontalBlurPostprocess=new Na("HighlightLayerHBP",new we(1,0),this._options.blurHorizontalSize/2,{size:{width:e,height:t},samplingMode:ge.BILINEAR_SAMPLINGMODE,engine:this._scene.getEngine(),textureType:i,effectWrapper:this._thinEffectLayer._postProcesses[0]}),this._horizontalBlurPostprocess.width=e,this._horizontalBlurPostprocess.height=t,this._horizontalBlurPostprocess.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess.onApplyObservable.add(r=>{r.setTexture("textureSampler",this._mainTexture)}),this._verticalBlurPostprocess=new Na("HighlightLayerVBP",new we(0,1),this._options.blurVerticalSize/2,{size:{width:e,height:t},samplingMode:ge.BILINEAR_SAMPLINGMODE,engine:this._scene.getEngine(),textureType:i}),this._postProcesses=[this._horizontalBlurPostprocess,this._verticalBlurPostprocess]),this._mainTexture.onAfterUnbindObservable.add(()=>{this.onBeforeBlurObservable.notifyObservers(this);let r=this._blurTexture.renderTarget;r&&(this._scene.postProcessManager.directRender(this._postProcesses,r,!0),this._engine.unBindFramebuffer(r,!0)),this.onAfterBlurObservable.notifyObservers(this)}),this._postProcesses.map(r=>{r.autoClear=!1}),this._mainTextureCreatedSize.width=this._mainTextureDesiredSize.width,this._mainTextureCreatedSize.height=this._mainTextureDesiredSize.height}needStencil(){return this._thinEffectLayer.needStencil()}isReady(e,t){return this._thinEffectLayer.isReady(e,t)}_internalRender(e,t){this._thinEffectLayer._internalCompose(e,t)}shouldRender(){return this._thinEffectLayer.shouldRender()}_shouldRenderMesh(e){return this._thinEffectLayer._shouldRenderMesh(e)}_canRenderMesh(e,t){return this._thinEffectLayer._canRenderMesh(e,t)}_addCustomEffectDefines(e){this._thinEffectLayer._addCustomEffectDefines(e)}_setEmissiveTextureAndColor(e,t,i){this._thinEffectLayer._setEmissiveTextureAndColor(e,t,i)}addExcludedMesh(e){this._thinEffectLayer.addExcludedMesh(e)}removeExcludedMesh(e){this._thinEffectLayer.removeExcludedMesh(e)}hasMesh(e){return this._thinEffectLayer.hasMesh(e)}addMesh(e,t,i=!1){this._thinEffectLayer.addMesh(e,t,i)}removeMesh(e){this._thinEffectLayer.removeMesh(e)}removeAllMeshes(){this._thinEffectLayer.removeAllMeshes()}_disposeMesh(e){this._thinEffectLayer._disposeMesh(e)}getClassName(){return"HighlightLayer"}serialize(){let e=it.Serialize(this);e.customType="BABYLON.HighlightLayer",e.meshes=[];let t=this._thinEffectLayer._meshes;if(t)for(let r in t){let s=t[r];s&&e.meshes.push({glowEmissiveOnly:s.glowEmissiveOnly,color:s.color.asArray(),meshId:s.mesh.id})}e.excludedMeshes=[];let i=this._thinEffectLayer._excludedMeshes;if(i)for(let r in i){let s=i[r];s&&e.excludedMeshes.push(s.mesh.id)}return e}static Parse(e,t,i){let r=it.Parse(()=>new n(e.name,t,e.options),e,t,i),s;for(s=0;s{sl();am();AO();Di();xD();aR(et.NAME_EFFECTLAYER,(n,e,t,i)=>{if(n.effectLayers){t.effectLayers||(t.effectLayers=[]);for(let r=0;r0){this._previousStencilState=this._engine.getStencilBuffer();for(let r of i)if(r.shouldRender()&&(!r.camera||r.camera.cameraRigMode===mt.RIG_MODE_NONE&&e===r.camera||r.camera.cameraRigMode!==mt.RIG_MODE_NONE&&r.camera._rigCameras.indexOf(e)>-1)){this._renderEffects=!0,this._needStencil=this._needStencil||r.needStencil();let s=r._mainTexture;s._shouldRender()&&(this.scene.incrementRenderId(),s.render(!1,!1),t=!0)}this.scene.incrementRenderId()}return t}_setStencil(){this._needStencil&&this._engine.setStencilBuffer(!0)}_setStencilBack(){this._needStencil&&this._engine.setStencilBuffer(this._previousStencilState)}_draw(e){if(this._renderEffects){this._engine.setDepthBuffer(!1);let t=this.scene.effectLayers;for(let i=0;i{let e=n._getComponent(et.NAME_EFFECTLAYER);e||(e=new MO(n),n._addComponent(e))}});function pK(n,e,t=()=>!0){let i=new Js("ai3d-pick-highlight",n),r=new ve(.15,.45,1),s=null;function a(){i.removeAllMeshes(),s&&!s.isDisposed()&&(s.renderOutline=!1,s.outlineWidth=0),s=null}function o(c){c.isDisposed()||(i.addMesh(c,r),c.renderOutline=!0,c.outlineColor=r,c.outlineWidth=.045,s=c)}let l=n.onPointerObservable.add(c=>{var m;if(c.type!==st.POINTERDOWN)return;let f=c.event,h=f.clientX,d=f.clientY,u=c.pickInfo;u!=null&&u.hit&&u.pickedMesh?(t()?s!==u.pickedMesh&&(a(),o(u.pickedMesh)):a(),e({mesh:u.pickedMesh,pickedPoint:(m=u.pickedPoint)!=null?m:null,screenX:h,screenY:d})):(a(),e({mesh:null,pickedPoint:null,screenX:h,screenY:d}))});return()=>{a(),i.dispose(),n.onPointerObservable.remove(l)}}var _K=C(()=>{"use strict";oo();zt();uK();mK()});function Yde(n,e,t){let i=ve.FromHexString(e),r=new ke(n,t);return r.emissiveColor=i,r.diffuseColor=ve.Black(),r.specularColor=ve.Black(),r.backFaceCulling=!1,r}function Kde(n){let e=new ke("gizmo-origin-mat",n);return e.emissiveColor=new ve(.72,.78,.86),e.diffuseColor=ve.Black(),e.specularColor=ve.Black(),e}var Gde,zR,kde,yO,Wde,Hde,CO,zde,Xde,XR,gK=C(()=>{"use strict";As();GA();kA();Ge();zt();$u();TP();Sc();Gde=.32,zR=1.05,kde=.075,yO=.28,Wde=.22,Hde=.16,CO=(zR+yO)*.42,zde=new b(CO,CO,CO),Xde=[{name:"x",color:"#e74c3c",rot:new b(0,0,-Math.PI/2),dir:new b(1,0,0)},{name:"y",color:"#2ecc71",rot:new b(0,0,0),dir:new b(0,1,0)},{name:"z",color:"#3498db",rot:new b(Math.PI/2,0,0),dir:new b(0,0,1)}];XR=class{constructor(e,t){this.engine=e,this.scene=new Jt(e),this.scene.clearColor=new lt(0,0,0,0),this.scene.autoClear=!1,this.camera=new gi("gizmo-cam",0,0,4.1,zde,this.scene),this.camera.minZ=.01,this.camera.fov=.56,this.camera.detachControl(),new Zs("gizmo-light",new b(0,1,.5),this.scene);let i=ts.CreateSphere("gizmo-origin",{diameter:Hde,segments:16},this.scene);i.material=Kde(this.scene);for(let{name:s,color:a,rot:o,dir:l}of Xde){let c=Yde(`gizmo-${s}-mat`,a,this.scene),f=ts.CreateCylinder(`gizmo-${s}-shaft`,{height:zR,diameter:kde,tessellation:8},this.scene);f.material=c,f.position=l.scale(zR/2),f.rotation=o;let h=ts.CreateCylinder(`gizmo-${s}-head`,{height:yO,diameterTop:0,diameterBottom:Wde,tessellation:8},this.scene);h.material=c;let d=zR+yO/2;h.position=l.scale(d),h.rotation=o}let r=Gde;this.viewport=new io(.02,.03,r,r),this.camera.viewport=this.viewport,this.syncWith(t)}syncWith(e){this.camera.alpha=e.alpha,this.camera.beta=e.beta}render(){let e=this.engine.getRenderWidth(),t=this.engine.getRenderHeight(),i=this.viewport.x*e,r=this.viewport.y*t,s=this.viewport.width*e,a=this.viewport.height*t;this.engine.enableScissor(i,r,s,a),this.engine.clear(null,!1,!0,!0),this.scene.render(),this.engine.disableScissor()}dispose(){this.scene.dispose()}}});var DO={};tt(DO,{boundingBoxRendererVertexShaderWGSL:()=>jde});var PO,vK,jde,LO=C(()=>{k();PO="boundingBoxRendererVertexShader",vK=`attribute position: vec3f;uniform world: mat4x4f;uniform viewProjection: mat4x4f; #ifdef INSTANCES attribute world0 : vec4;attribute world1 : vec4;attribute world2 : vec4;attribute world3 : vec4; #endif @@ -23764,18 +23764,18 @@ var worldPos: vec4f=uniforms.world* vec4f(vertexInputs.position,1.0); vertexOutputs.position=uniforms.viewProjection*worldPos; #define CUSTOM_VERTEX_MAIN_END } -`;T.ShadersStoreWGSL[PO]||(T.ShadersStoreWGSL[PO]=vK);jde={name:PO,shader:vK}});var NO={};tt(NO,{boundingBoxRendererPixelShaderWGSL:()=>qde});var OO,EK,qde,wO=C(()=>{W();OO="boundingBoxRendererPixelShader",EK=`uniform color: vec4f; +`;T.ShadersStoreWGSL[PO]||(T.ShadersStoreWGSL[PO]=vK);jde={name:PO,shader:vK}});var NO={};tt(NO,{boundingBoxRendererPixelShaderWGSL:()=>qde});var OO,EK,qde,wO=C(()=>{k();OO="boundingBoxRendererPixelShader",EK=`uniform color: vec4f; #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs { #define CUSTOM_FRAGMENT_MAIN_BEGIN fragmentOutputs.color=uniforms.color; #define CUSTOM_FRAGMENT_MAIN_END -}`;T.ShadersStoreWGSL[OO]||(T.ShadersStoreWGSL[OO]=EK);qde={name:OO,shader:EK}});var SK,Zde,TK=C(()=>{W();SK="boundingBoxRendererVertexDeclaration",Zde=`uniform mat4 world;uniform mat4 viewProjection; +}`;T.ShadersStoreWGSL[OO]||(T.ShadersStoreWGSL[OO]=EK);qde={name:OO,shader:EK}});var SK,Zde,TK=C(()=>{k();SK="boundingBoxRendererVertexDeclaration",Zde=`uniform mat4 world;uniform mat4 viewProjection; #ifdef MULTIVIEW uniform mat4 viewProjectionR; #endif -`;T.IncludesShadersStore[SK]||(T.IncludesShadersStore[SK]=Zde)});var AK,Qde,FO=C(()=>{W();AK="boundingBoxRendererUboDeclaration",Qde=`#ifdef WEBGL2 +`;T.IncludesShadersStore[SK]||(T.IncludesShadersStore[SK]=Zde)});var AK,Qde,FO=C(()=>{k();AK="boundingBoxRendererUboDeclaration",Qde=`#ifdef WEBGL2 uniform vec4 color;uniform mat4 world;uniform mat4 viewProjection; #ifdef MULTIVIEW uniform mat4 viewProjectionR; @@ -23783,7 +23783,7 @@ uniform mat4 viewProjectionR; #else layout(std140,column_major) uniform;uniform BoundingBoxRenderer {vec4 color;mat4 world;mat4 viewProjection;mat4 viewProjectionR;}; #endif -`;T.IncludesShadersStore[AK]||(T.IncludesShadersStore[AK]=Qde)});var UO={};tt(UO,{boundingBoxRendererVertexShader:()=>$de});var BO,xK,$de,VO=C(()=>{W();TK();FO();BO="boundingBoxRendererVertexShader",xK=`attribute vec3 position; +`;T.IncludesShadersStore[AK]||(T.IncludesShadersStore[AK]=Qde)});var UO={};tt(UO,{boundingBoxRendererVertexShader:()=>$de});var BO,xK,$de,VO=C(()=>{k();TK();FO();BO="boundingBoxRendererVertexShader",xK=`attribute vec3 position; #include<__decl__boundingBoxRendererVertex> #ifdef INSTANCES attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3; @@ -23803,30 +23803,30 @@ gl_Position=viewProjection*worldPos; #endif #define CUSTOM_VERTEX_MAIN_END } -`;T.ShadersStore[BO]||(T.ShadersStore[BO]=xK);$de={name:BO,shader:xK}});var RK,Jde,bK=C(()=>{W();RK="boundingBoxRendererFragmentDeclaration",Jde=`uniform vec4 color; -`;T.IncludesShadersStore[RK]||(T.IncludesShadersStore[RK]=Jde)});var kO={};tt(kO,{boundingBoxRendererPixelShader:()=>eue});var GO,IK,eue,WO=C(()=>{W();bK();FO();GO="boundingBoxRendererPixelShader",IK=`#include<__decl__boundingBoxRendererFragment> +`;T.ShadersStore[BO]||(T.ShadersStore[BO]=xK);$de={name:BO,shader:xK}});var RK,Jde,bK=C(()=>{k();RK="boundingBoxRendererFragmentDeclaration",Jde=`uniform vec4 color; +`;T.IncludesShadersStore[RK]||(T.IncludesShadersStore[RK]=Jde)});var kO={};tt(kO,{boundingBoxRendererPixelShader:()=>eue});var GO,IK,eue,WO=C(()=>{k();bK();FO();GO="boundingBoxRendererPixelShader",IK=`#include<__decl__boundingBoxRendererFragment> #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #define CUSTOM_FRAGMENT_MAIN_BEGIN gl_FragColor=color; #define CUSTOM_FRAGMENT_MAIN_END -}`;T.ShadersStore[GO]||(T.ShadersStore[GO]=IK);eue={name:GO,shader:IK}});var yK,MK,XR,tue,iue,CK,HO,PK=C(()=>{xs();Gi();gm();Ve();so();om();gy();Vn();Jy();zt();hi();Gh();pf();zy();jo();yt();Object.defineProperty($t.prototype,"forceShowBoundingBoxes",{get:function(){return this._forceShowBoundingBoxes||!1},set:function(n){this._forceShowBoundingBoxes=n,n&&this.getBoundingBoxRenderer()},enumerable:!0,configurable:!0});$t.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer||(this._boundingBoxRenderer=new HO(this)),this._boundingBoxRenderer};Object.defineProperty(gr.prototype,"showBoundingBox",{get:function(){return this._showBoundingBox||!1},set:function(n){this._showBoundingBox=n,n&&this.getScene().getBoundingBoxRenderer()},enumerable:!0,configurable:!0});yK=j.Identity(),MK=new j,XR=new b,tue=new b,iue=yK.asArray(),CK=new Sf(XR,XR),HO=class{get shaderLanguage(){return this._shaderLanguage}constructor(e){this.name=$e.NAME_BOUNDINGBOXRENDERER,this.frontColor=new ge(1,1,1),this.backColor=new ge(.1,.1,.1),this.showBackLines=!0,this.onBeforeBoxRenderingObservable=new ie,this.onAfterBoxRenderingObservable=new ie,this.onResourcesReadyObservable=new ie,this.enabled=!0,this._shaderLanguage=0,this.renderList=new wi(32),this._vertexBuffers={},this._fillIndexBuffer=null,this._fillIndexData=null,this._matrixBuffer=null,this._matrices=null,this._useInstances=!1,this._drawWrapperFront=null,this._drawWrapperBack=null,this.scene=e,this.scene.getEngine().isWebGPU&&(this._shaderLanguage=1),e._addComponent(this),this._uniformBufferFront=new fr(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererFront",!0),this._buildUniformLayout(this._uniformBufferFront),this._uniformBufferBack=new fr(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererBack",!0),this._buildUniformLayout(this._uniformBufferBack)}_buildUniformLayout(e){e.addUniform("color",4),e.addUniform("world",16),e.addUniform("viewProjection",16),e.addUniform("viewProjectionR",16),e.create()}register(){this.scene._beforeEvaluateActiveMeshStage.registerStep($e.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER,this,this.reset),this.scene._preActiveMeshStage.registerStep($e.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER,this,this._preActiveMesh),this.scene._evaluateSubMeshStage.registerStep($e.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER,this,this._evaluateSubMesh),this.scene._afterRenderingGroupDrawStage.registerStep($e.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER,this,this.render)}async whenReadyAsync(e=16,t=3e4){return this._prepareResources(),await new Promise(i=>{Ko(()=>this._colorShader.isReady(),()=>{i()},(r,s)=>{s?(te.Error("BoundingBoxRenderer: Timeout while waiting for the renderer to be ready."),r&&te.Error(r)):(te.Error("BoundingBoxRenderer: An unexpected error occurred while waiting for the renderer to be ready."),r&&(te.Error(r),r.stack&&te.Error(r.stack)))},e,t)})}_evaluateSubMesh(e,t){if(e.showSubMeshesBoundingBox){let i=t.getBoundingInfo();i!=null&&(i.boundingBox._tag=e.renderingGroupId,this.renderList.push(i.boundingBox))}}_preActiveMesh(e){if(e.showBoundingBox||this.scene.forceShowBoundingBoxes){let t=e.getBoundingInfo();t.boundingBox._tag=e.renderingGroupId,this.renderList.push(t.boundingBox)}}_prepareResources(){if(this._colorShader)return;this._colorShader=new vo("colorShader",this.scene,"boundingBoxRenderer",{attributes:[L.PositionKind,"world0","world1","world2","world3"],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"],shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{this._shaderLanguage===1?await Promise.all([Promise.resolve().then(()=>(LO(),DO)),Promise.resolve().then(()=>(wO(),NO))]):await Promise.all([Promise.resolve().then(()=>(VO(),UO)),Promise.resolve().then(()=>(WO(),kO))])}},!1),this._colorShader.setDefine("INSTANCES",this._useInstances),this._colorShader.doNotSerialize=!0,this._colorShader.reservedDataStore={hidden:!0},this._colorShaderForOcclusionQuery=new vo("colorShaderOccQuery",this.scene,"boundingBoxRenderer",{attributes:[L.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"],shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{this._shaderLanguage===1?await Promise.all([Promise.resolve().then(()=>(LO(),DO)),Promise.resolve().then(()=>(wO(),NO))]):await Promise.all([Promise.resolve().then(()=>(VO(),UO)),Promise.resolve().then(()=>(WO(),kO))])}},!0),this._colorShaderForOcclusionQuery.doNotSerialize=!0,this._colorShaderForOcclusionQuery.reservedDataStore={hidden:!0};let e=this.scene.getEngine(),t=WA({size:1});this._vertexBuffers[L.PositionKind]=new L(e,t.positions,L.PositionKind,!1),this._createIndexBuffer(),this._fillIndexData=t.indices,this.onResourcesReadyObservable.notifyObservers(this)}_createIndexBuffer(){let e=this.scene.getEngine();this._indexBuffer=e.createIndexBuffer([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,7,1,6,2,5,3,4])}rebuild(){let e=this._vertexBuffers[L.PositionKind];e&&e._rebuild(),this._createIndexBuffer(),this._matrixBuffer&&this._matrixBuffer._rebuild()}reset(){this.renderList.reset()}render(e){var r,s;if(this.renderList.length===0||!this.enabled)return;if(this._useInstances){this._renderInstanced(e);return}if(this._prepareResources(),!this._colorShader.isReady())return;let t=this.scene.getEngine();t.setDepthWrite(!1);let i=this.scene.getTransformMatrix();for(let a=0;ar*2)&&(i=new Float32Array(r),this._matrices=i),this.onBeforeBoxRenderingObservable.notifyObservers(CK);let s=0,a=this.scene.floatingOriginOffset;for(let g=0;g{"use strict";Ve();qP();zt();oo();PK();Fs();rM();$f=class $f{constructor(e,t,i){this.occlusionDirection=b.Zero();this.occlusionRay=new Yr(b.Zero(),b.Zero(),1);this.lastOccluded=!1;this.selected=null;this.partPointerActive=!1;this.activePointerId=null;this.scene=e,this.camera=t,this.meshes=i,this.setBoundingBoxColor($f.BBOX_VISIBLE)}getParts(){return this.meshes}getPartId(e){return e.uniqueId}isDisposed(e){return e.isDisposed()}captureTransform(e){var t,i;return{parent:e.parent,position:e.position.clone(),rotation:e.rotation.clone(),rotationQuaternion:(i=(t=e.rotationQuaternion)==null?void 0:t.clone())!=null?i:null,scaling:e.scaling.clone()}}restoreTransform(e,t){var i,r;e.setParent(t.parent),e.position.copyFrom(t.position),e.rotation.copyFrom(t.rotation),e.rotationQuaternion=(r=(i=t.rotationQuaternion)==null?void 0:i.clone())!=null?r:null,e.scaling.copyFrom(t.scaling),e.computeWorldMatrix(!0)}subscribe(e){let t=this.scene.getEngine().getRenderingCanvas();t==null||t.classList.add("ai3d-disassembly-active");let i=this.scene.onPointerObservable.add(s=>{var o,l,c,f;let a=s.event;if(a.isPrimary!==!1){if(s.type===st.POINTERDOWN){if(a.button!==0)return;let h=(l=(o=s.pickInfo)==null?void 0:o.pickedMesh)!=null?l:null;if(this.partPointerActive=!!this.resolvePart(h),this.partPointerActive){a.preventDefault(),a.stopPropagation(),this.activePointerId=a.pointerId;try{(c=t==null?void 0:t.setPointerCapture)==null||c.call(t,a.pointerId)}catch(d){}this.camera.detachControl()}e.onPointerDown(h,a)}else if(s.type===st.POINTERMOVE){if(this.activePointerId!==null&&a.pointerId!==this.activePointerId)return;this.partPointerActive&&(a.preventDefault(),a.stopPropagation()),e.onPointerMove(a)}else if(s.type===st.POINTERUP){if(this.activePointerId!==null&&a.pointerId!==this.activePointerId)return;if(this.partPointerActive&&(a.preventDefault(),a.stopPropagation()),e.onPointerUp(a),this.activePointerId!==null&&((f=t==null?void 0:t.hasPointerCapture)!=null&&f.call(t,this.activePointerId)))try{t.releasePointerCapture(this.activePointerId)}catch(h){}this.partPointerActive=!1,this.activePointerId=null,this.camera.attachControl(this.scene.getEngine().getRenderingCanvas(),!0)}}}),r=this.scene.onAfterRenderCameraObservable.add(s=>{s===this.camera&&e.onRender()});return()=>{var s;if(this.scene.onPointerObservable.remove(i),this.scene.onAfterRenderCameraObservable.remove(r),t==null||t.classList.remove("ai3d-disassembly-active","ai3d-disassembly-dragging"),this.activePointerId!==null&&((s=t==null?void 0:t.hasPointerCapture)!=null&&s.call(t,this.activePointerId)))try{t.releasePointerCapture(this.activePointerId)}catch(a){}this.partPointerActive=!1,this.activePointerId=null,this.camera.attachControl(t,!0)}}resolvePart(e){if(!e||typeof e!="object")return null;if(this.isMeshInSet(e))return e;let t=e.parent;return t&&"uniqueId"in t&&this.isMeshInSet(t)?t:null}setSelected(e){this.selected&&!this.selected.isDisposed()&&(this.selected.showBoundingBox=!1),this.selected=e,this.lastOccluded=!1,this.setBoundingBoxColor($f.BBOX_VISIBLE),this.selected&&!this.selected.isDisposed()&&(this.selected.showBoundingBox=!0)}beginDrag(e,t){var o,l,c;let i=this.getPointOnDragPlane(e,t);if(!i)return null;t.preventDefault(),t.stopPropagation(),(o=this.scene.getEngine().getRenderingCanvas())==null||o.classList.add("ai3d-disassembly-dragging"),e.setParent(null),e.computeWorldMatrix(!0),t.shiftKey&&!e.rotationQuaternion&&(e.rotationQuaternion=Ye.FromEulerVector(e.rotation),e.rotation.set(0,0,0));let r=e.getBoundingInfo().boundingBox.centerWorld.clone(),s=Vd(Ht(i),Ht(this.camera.getForwardRay().direction));if(!s)return null;let a={mesh:e,mode:t.shiftKey?"rotate":"move",plane:s,startPoint:i,startPosition:e.position.clone(),startRotationQuaternion:(c=(l=e.rotationQuaternion)==null?void 0:l.clone())!=null?c:null,pivot:r,pointerX:t.clientX,pointerY:t.clientY};return this.camera.detachControl(),a}updateDrag(e,t){if(t.preventDefault(),t.stopPropagation(),e.mode==="rotate"){this.updateRotation(e,t);return}let i=this.getRayPlanePoint(t,e.plane);if(!i)return;let r=i.subtract(e.startPoint);e.mesh.position=e.startPosition.add(r),e.mesh.computeWorldMatrix(!0)}endDrag(e){var t;(t=this.scene.getEngine().getRenderingCanvas())==null||t.classList.remove("ai3d-disassembly-dragging"),this.camera.attachControl(this.scene.getEngine().getRenderingCanvas(),!0)}updateSelectionOcclusion(e){let t=e.getBoundingInfo().boundingBox.centerWorld,i=this.camera.position,r=wc(Ht(i),Ht(t));if(!r)return;let s=this.occlusionDirection;s.set(r.direction.x,r.direction.y,r.direction.z),this.occlusionRay.origin=i,this.occlusionRay.direction=s,this.occlusionRay.length=r.distance;let a=this.scene.pickWithRay(this.occlusionRay),o=!!(a!=null&&a.hit)&&Nc(a.distance,r.distance,r.epsilon);o!==this.lastOccluded&&(this.lastOccluded=o,this.setBoundingBoxColor(o?$f.BBOX_OCCLUDED:$f.BBOX_VISIBLE))}isMeshInSet(e){return this.meshes.includes(e)}setBoundingBoxColor(e){var i,r;let t=(r=(i=this.scene).getBoundingBoxRenderer)==null?void 0:r.call(i);t&&(t.frontColor=e,t.backColor=e)}updateRotation(e,t){if(!e.startRotationQuaternion)return;let i=t.clientX-e.pointerX,r=t.clientY-e.pointerY,s=gv({startPosition:Ht(e.startPosition),pivot:Ht(e.pivot),startRotationQuaternion:_v(e.startRotationQuaternion),yawAxis:Ht(this.camera.getDirection(b.Up()).normalize()),pitchAxis:Ht(this.camera.getDirection(b.Right()).normalize()),deltaX:i,deltaY:r,sensitivity:.01});s&&(e.mesh.position=new b(s.position.x,s.position.y,s.position.z),e.mesh.rotationQuaternion=new Ye(s.rotationQuaternion.x,s.rotationQuaternion.y,s.rotationQuaternion.z,s.rotationQuaternion.w),e.mesh.rotation.set(0,0,0),e.mesh.computeWorldMatrix(!0))}getPointOnDragPlane(e,t){var s;let i=e.getBoundingInfo().boundingBox.centerWorld.clone(),r=Vd(Ht(i),Ht(this.camera.getForwardRay().direction));return r&&(s=this.getRayPlanePoint(t,r))!=null?s:i}getRayPlanePoint(e,t){let i=this.scene.getEngine().getRenderingCanvas();if(!i)return null;let r=i.getBoundingClientRect(),s=e.clientX-r.left,a=e.clientY-r.top,o=this.scene.createPickingRay(s,a,j.Identity(),this.camera),l=pv({origin:Ht(o.origin),direction:Ht(o.direction)},t);return l?new b(l.x,l.y,l.z):null}};$f.BBOX_VISIBLE=new ge(.25,.7,1),$f.BBOX_OCCLUDED=new ge(.1,.25,.4);zO=$f});var BK={};tt(BK,{BabylonModelPreview:()=>jR,createBabylonModelPreview:()=>mue});function aue(n){let e=n.getClassName();return e==="DirectionalLight"||e==="PointLight"||e==="SpotLight"}function XO(n){return n.getClassName()==="GaussianSplattingMesh"}function KR(n,e){var i;return((i=nf(n.metadata,{name:n.name}).displayName)==null?void 0:i.trim())||n.name||e}function NK(n){let e=[],t=n;for(;t&&typeof t=="object"&&"name"in t;){let i=t,r=KR(i,"node");r.trim()&&e.push(r),t=i.parent}return e.reverse().join("/")}function wK(n,e){var t;return((t=n.displayName)==null?void 0:t.trim())||n.partNumber||n.componentId||e}function oue(n,e){try{if(e==="gltf")return JSON.parse(new TextDecoder().decode(new Uint8Array(n)));if(e!=="glb")return null;let t=new DataView(n);if(t.byteLength<20||t.getUint32(0,!0)!==1179937895)return null;let i=t.getUint32(12,!0);if(t.getUint32(16,!0)!==1313821514||20+i>t.byteLength)return null;let s=new Uint8Array(n,20,i);return JSON.parse(new TextDecoder().decode(s))}catch(t){return null}}function lue(n,e){let t=oue(n,e),i=new Map;if(!t)return i;let r=Array.isArray(t.nodes)?t.nodes:[];for(let a of r){if(!a||typeof a!="object")continue;let o=a,l=typeof o.name=="string"?o.name:"";l&&o.extras&&i.set(`node:${l}`,o.extras)}let s=Array.isArray(t.meshes)?t.meshes:[];for(let a of s){if(!a||typeof a!="object")continue;let o=a,l=typeof o.name=="string"?o.name:"";l&&o.extras&&i.set(`mesh:${l}`,o.extras)}return i}function FK(n,e){return e===void 0?n:n==null?e:{metadata:n,extras:e}}function cue(n){return!!n&&typeof n=="object"&&"getBoundingInfo"in n}function Qg(n){return new b(n.x,n.y,n.z)}function fue(n){let e=n.replace(/\s+#.*$/,"").trim();if(e.startsWith('"')){let t=e.indexOf('"',1);if(t>1)return e.slice(1,t)}return e}function hue(n){let e=n.trim().split(/\s+/),t=e.findIndex(i=>!i.startsWith("-")&&!/^[-+]?\d*\.?\d+$/.test(i));return e.slice(Math.max(0,t)).join(" ").replace(/^"|"$/g,"")}function due(n){var t,i;let e=(i=(t=n.split(".").pop())==null?void 0:t.toLowerCase())!=null?i:"png";return e==="jpg"||e==="jpeg"?"image/jpeg":e==="png"?"image/png":e==="bmp"?"image/bmp":e==="tga"?"image/x-tga":e==="webp"?"image/webp":`image/${e}`}function uue(n,e,t){let i=oa(e),r=i.replace(/\.[^.]+$/,""),s=jr(t),a=[ws(n,e),ws(n,i)];if(s)for(let o of OK)a.push(ws(n,`${s}.${o}`));for(let o of OK){let l=`${r}.${o}`;l!==i&&a.push(ws(n,l))}return a}function mue(n){return new jR(n)}var YR,OK,rue,nue,sue,as,jR,UK=C(()=>{"use strict";dy();xs();VA();GA();CG();yG();Fy();Ve();zt();Ii();TP();Tc();mz();qP();eR();bX();by();Jm();qg();qg();dO();uO();V9();_K();FS();Ks();la();gK();LK();wR();rf();US();Fs();zS();C_();tM();YR=null,OK=["jpg","jpeg","png","bmp","tga","webp","tif","tiff"],rue=/^\s*(map_Kd|map_Ka|map_Ks|map_Ns|map_d|map_bump|bump|disp|decal)\s+(.+)/i,nue=.242,sue=320;as=class as{constructor(e){this.rootMesh=null;this.loadedMeshes=[];this.loadedTransformNodes=[];this.loadedExt="";this.rendering=!1;this.contextLost=!1;this.viewportVisible=!0;this.viewportObserver=null;this.cleanupPicking=null;this.configLights=[];this.shadowGenerator=null;this.groundMesh=null;this.gridMesh=null;this.axisMeshes=[];this.autoRotateBehavior=null;this.wireframeEnabled=!1;this.gizmo=null;this.gizmoEnabled=!1;this.disassembly=null;this.focusSelectionEnabled=!1;this.focusedMesh=null;this.originalMeshVisibility=new Map;this.bboxMesh=null;this.bboxEnabled=!1;this.currentQuality="high";this.resourceWarnings=[];this.gltfComponentMetadata=new Map;this.animPlaying=!1;this.initialCamera={alpha:Math.PI/4,beta:Math.PI/3,radius:5,target:b.Zero()};this.focusWorldPointFrame=0;this._lastPickResult={mesh:null,pickedPoint:null,screenX:0,screenY:0};this._onPickCallbacks=[];this.measurementActive=!1;this.measurementScale={x:1,y:1,z:1};this.measurementUnit="mm";this.measurementSegments=[];this.measurementMarkers=[];this.pendingPoint=null;this.pendingMarker=null;this.hoveredMarkerIndex=-1;this.lastPointerClient={x:0,y:0};this.previewLine=null;this.handlePointerMove=e=>{if(this.lastPointerClient={x:e.clientX,y:e.clientY},!this.measurementActive||(this.pendingPoint&&this.updatePreviewLine(),this.measurementMarkers.length===0))return;let t=this.engine.getRenderingCanvas();if(!t)return;let i=t.getBoundingClientRect(),r=e.clientX-i.left,s=e.clientY-i.top,a=this.scene.pick(r,s,l=>this.measurementMarkers.includes(l)),o=a.hit?this.measurementMarkers.indexOf(a.pickedMesh):-1;if(o!==this.hoveredMarkerIndex){if(this.hoveredMarkerIndex>=0&&this.hoveredMarkerIndex=0&&o{e.preventDefault(),e.stopPropagation()};this.handleViewportIntersection=e=>{let t=e.some(i=>i.isIntersecting);t!==this.viewportVisible&&(this.viewportVisible=t,t?this.startRenderLoop():this.rendering&&(this.engine.stopRenderLoop(),this.rendering=!1))};this.handleContextLost=e=>{e.preventDefault(),this.contextLost=!0,this.rendering&&(this.engine.stopRenderLoop(),this.rendering=!1)};this.handleContextRestored=()=>{this.contextLost=!1,this.engine.resize(),this.startRenderLoop()};this.engine=new Ue(e,!0,{preserveDrawingBuffer:!0}),this.scene=new $t(this.engine),this.scene.clearColor=new lt(.12,.12,.14,1),this.camera=new gi("cam",Math.PI/4,Math.PI/3,5,b.Zero(),this.scene),this.camera.attachControl(e,!0),this.camera.lowerRadiusLimit=.1,this.camera.wheelPrecision=30,e.addEventListener("wheel",this.preventCanvasWheelScroll,{passive:!1}),e.addEventListener("pointermove",this.handlePointerMove),e.addEventListener("webglcontextlost",this.handleContextLost),e.addEventListener("webglcontextrestored",this.handleContextRestored),this.scene.ambientColor=new ge(.3,.3,.3);let t=new Qs("default-light",new b(0,1,.5),this.scene);t.intensity=1.2,this.resizeObs=new ResizeObserver(()=>this.engine.resize()),this.resizeObs.observe(e),typeof IntersectionObserver!="undefined"&&(this.viewportObserver=new IntersectionObserver(this.handleViewportIntersection,{root:null,threshold:[0,.01]}),this.viewportObserver.observe(e)),window.requestAnimationFrame(()=>this.engine.resize())}canRender(){let e=this.engine.getRenderingCanvas();return!!(e!=null&&e.isConnected)&&e.clientWidth>0&&e.clientHeight>0}ensureDisassemblyController(){return this.rootMesh?(this.disassembly||(this.disassembly=DK(this.scene,this.camera,this.getRenderableMeshes(this.rootMesh))),this.disassembly):null}isDisassemblyActive(){var e,t;return(t=(e=this.disassembly)==null?void 0:e.isEnabled())!=null?t:!1}async loadModel(e,t,i,r){var h,d,u;if(await jg(),this.rootMesh){let m=this.rootMesh;m.dispose(!0,!0);for(let p of this.loadedMeshes)p!==m&&!p.isDisposed()&&p.dispose(!0,!0);this.rootMesh=null}this.loadedMeshes=[],this.loadedTransformNodes=[],this.clearMeasurements(),(h=this.disassembly)==null||h.dispose(),this.disassembly=null,this.clearFocusedMesh(),this.originalMeshVisibility.clear();let s=t.toLowerCase().replace(".","");this.loadedExt=s,this.resourceWarnings=[],this.gltfComponentMetadata=lue(e,s);let a=this.scene,l=(d={glb:".glb",gltf:".gltf",stl:".stl",obj:".obj",splat:".splat",ply:".ply"}[s])!=null?d:`.${s}`,c=`data:application/octet-stream;base64,${Nl(e)}`;if(s==="obj"&&i&&r){YR&&await YR;let m;YR=new Promise(p=>{m=p});try{let{OBJFileLoader:p}=await Promise.resolve().then(()=>(fO(),M9)),_=p.prototype;typeof _._loadMTL!="function"&&console.warn("[AI3D] OBJFileLoader._loadMTL not found \u2014 MTL vault resolution disabled");let g=_._loadMTL,x=new TextDecoder().decode(new Uint8Array(e)).match(/mtllib\s+(.+)/),A=null;if(x&&i&&r){let E=fue(x[1]),R=Ip(r),I=ws(R,E);try{let y=await i(I),D=new TextDecoder().decode(new Uint8Array(y)).split(` -`);for(let N=0;NN!=="");if(!O.some(N=>/^\s*Kd\s+/i.test(N))){let N=O.findIndex(F=>/^\s*newmtl\s+/i.test(F));O.splice(N>=0?N+1:0,0,"Kd 0.80 0.80 0.80")}A=O.join(` -`)}catch(y){this.resourceWarnings.push(`OBJ material library not found: ${I}`)}}_._loadMTL=function(E,R,I){let y=A!=null?A:"";I(y)};let S=await Bg(c,a,{meshNames:"",pluginExtension:l});this.loadedMeshes=S.meshes,this.loadedTransformNodes=S.transformNodes,S.meshes.length>0&&(this.rootMesh=S.meshes[0]),_._loadMTL=g}catch(p){throw console.error("[AI3D] OBJ load error:",p),p}finally{m(),YR=null}}else if(s==="stl")this.rootMesh=D9(a,e),this.rootMesh&&(this.loadedMeshes=[this.rootMesh]);else if(s==="ply")this.rootMesh=O9(a,e),this.rootMesh&&(this.loadedMeshes=[this.rootMesh]);else{let m=await Bg(c,a,{meshNames:"",pluginExtension:l});this.loadedMeshes=m.meshes,this.loadedTransformNodes=m.transformNodes,m.meshes.length>0&&(this.rootMesh=m.meshes[0])}if(!this.rootMesh)throw new Error("No mesh found in model file");for(let m of this.getRenderableMeshes(this.rootMesh))m.material&&(m.material.backFaceCulling=!1);let f=BS(this.getRenderableBounds(this.rootMesh));return this.camera.target=Qg(f.target),this.camera.radius=f.radius,this.camera.lowerRadiusLimit=f.lowerRadiusLimit,this.camera.upperRadiusLimit=f.upperRadiusLimit,this.camera.minZ=f.near,this.camera.maxZ=f.far,this.initialCamera={alpha:this.camera.alpha,beta:this.camera.beta,radius:this.camera.radius,target:this.camera.target.clone()},this.startRenderLoop(),this.engine.resize(),(u=this.cleanupPicking)==null||u.call(this),this.cleanupPicking=pK(this.scene,m=>{if(!this.isDisassemblyActive()){if(this.measurementActive&&m.pickedPoint){this.addMeasurementPoint(Qg(m.pickedPoint));return}this._lastPickResult=m,this.focusSelectionEnabled&&m.mesh&&this.setFocusedMesh(m.mesh),this._onPickCallbacks.forEach(p=>p(m))}},()=>!this.focusSelectionEnabled),this.ensureDisassemblyController(),this.computeSummary(this.rootMesh)}applyConfig(e){e.camera&&this.applyCameraConfig(e.camera),e.lights&&this.applyLightConfig(e.lights),e.scene&&this.applySceneConfig(e.scene),e.stl&&this.loadedExt==="stl"&&(e.stl.color&&this.setSTLColor(e.stl.color),e.stl.wireframe!==void 0&&this.setWireframe(e.stl.wireframe))}applyCameraConfig(e){var i;let t=this.engine.getRenderingCanvas();if(t){if(e.mode==="orthographic"){let r=this.camera.radius,s=t.clientWidth/t.clientHeight,a=(i=e.zoom)!=null?i:1,o=r/a;this.camera.mode=1,this.camera.orthoLeft=-o*s,this.camera.orthoRight=o*s,this.camera.orthoTop=o,this.camera.orthoBottom=-o}else this.camera.mode=0,e.fov&&(this.camera.fov=e.fov*Math.PI/180);if(e.position){let[r,s,a]=e.position;this.camera.setPosition(new b(r,s,a))}if(e.lookAt){let[r,s,a]=e.lookAt;this.camera.setTarget(new b(r,s,a))}e.near!==void 0&&(this.camera.minZ=e.near),e.far!==void 0&&(this.camera.maxZ=e.far)}}applyLightConfig(e){var i;for(let r of this.configLights)r.dispose();this.configLights=[],(i=this.shadowGenerator)==null||i.dispose(),this.shadowGenerator=null;let t=this.scene.getLightByName("default-light");t&&t.dispose();for(let r of e){let s=this.createLight(r);s&&this.configLights.push(s)}}createLight(e){var r,s;let t=e.color?ge.FromHexString(e.color):ge.White(),i=(r=e.intensity)!=null?r:1;switch(e.type){case"hemisphere":{let a=e.groundColor?ge.FromHexString(e.groundColor):new ge(.2,.2,.2),o=new Qs("hemi",new b(0,1,0),this.scene);return o.diffuse=t,o.groundColor=a,o.intensity=i,o}case"directional":{let a=e.position?new b(...e.position).normalize():new b(-1,-2,-1).normalize(),o=new Cs("dir",a,this.scene);return o.diffuse=t,o.intensity=i,e.castShadow&&this.rootMesh&&this.setupShadow(o),o}case"point":{let a=e.position?new b(...e.position):new b(0,5,0),o=new Df("point",a,this.scene);return o.diffuse=t,o.intensity=i,e.decay!==void 0&&(o.decay=e.decay),o}case"spot":{let a=e.position?new b(...e.position):new b(0,5,0),l=(e.target?new b(...e.target):b.Zero()).subtract(a).normalize(),c=e.angle?e.angle*Math.PI/180:Math.PI/4,f=(s=e.penumbra)!=null?s:.5,h=new Ur("spot",a,l,c,f,this.scene);return h.diffuse=t,h.intensity=i,e.decay!==void 0&&(h.decay=e.decay),e.castShadow&&this.rootMesh&&this.setupShadow(h),h}case"attachToCam":{let a=new Df("cam-light",b.Zero(),this.scene);return a.diffuse=t,a.intensity=i,a.parent=this.camera,a}default:return null}}setupShadow(e){if(!this.rootMesh)return;if(!aue(e)){console.warn("[AI3D] Light type does not support shadows:",e.name);return}let t=new Mi(1024,e);t.useBlurExponentialShadowMap=!0,t.blurKernel=32;for(let i of this.getRenderableMeshes(this.rootMesh))t.addShadowCaster(i),i.receiveShadows=!0;this.shadowGenerator=t}applySceneConfig(e){var t,i;if(e.background!==void 0){let r=lt.FromColor3(ge.FromHexString(e.background),e.transparent?0:1);this.scene.clearColor=r}e.autoRotate&&(this.autoRotateBehavior?this.autoRotateBehavior.idleRotationSpeed=(i=e.autoRotateSpeed)!=null?i:.5:(this.autoRotateBehavior=new Bm,this.autoRotateBehavior.idleRotationSpeed=(t=e.autoRotateSpeed)!=null?t:.5,this.autoRotateBehavior.idleRotationWaitTime=1e3,this.autoRotateBehavior.idleRotationSpinupTime=500,this.camera.addBehavior(this.autoRotateBehavior))),e.groundShadow&&this.rootMesh&&this.createGround(),e.grid&&this.createGrid(),e.axis&&this.createAxis()}createGround(){if(!this.rootMesh||this.groundMesh)return;let e=this.getRenderableBounds(this.rootMesh),t=Wr(e),i=Math.max(t.x,t.z)*3,r=e.min.y;this.groundMesh=is.CreateGround("ground",{width:i,height:i},this.scene),this.groundMesh.position.y=r;let s=new Ge("ground-mat",this.scene);s.diffuseColor=new ge(.15,.15,.15),s.specularColor=ge.Black(),s.alpha=.5,this.groundMesh.material=s,this.groundMesh.receiveShadows=!0}createGrid(){if(!this.rootMesh||this.gridMesh)return;let e=this.getRenderableBounds(this.rootMesh),t=Wr(e),i=Math.max(t.x,t.z)*2,r=e.min.y-.01;this.gridMesh=is.CreateGround("grid",{width:i,height:i,subdivisions:20},this.scene),this.gridMesh.position.y=r;let s=new Ge("grid-mat",this.scene);s.wireframe=!0,s.diffuseColor=new ge(.3,.3,.3),s.emissiveColor=new ge(.1,.1,.1),this.gridMesh.material=s}createAxis(){if(!this.rootMesh||this.axisMeshes.length>0)return;let e=this.getRenderableBounds(this.rootMesh),t=$1(e)*1.5,i=Qg(e.min),r=M_(e)*.01,s=[["x",ge.Red(),new b(t,0,0)],["y",ge.Green(),new b(0,t,0)],["z",ge.Blue(),new b(0,0,t)]];for(let[a,o,l]of s){let c=is.CreateTube(`axis-${a}`,{path:[i,i.add(l)],radius:r,tessellation:8},this.scene),f=new Ge(`axis-${a}-mat`,this.scene);f.emissiveColor=o,f.diffuseColor=ge.Black(),c.material=f,this.axisMeshes.push(c)}}setSTLColor(e){if(!this.rootMesh)return;let t=ge.FromHexString(e);for(let i of this.getRenderableMeshes(this.rootMesh))if(i.material&&i.material.name==="stl-mat"){let r=i.material;r.diffuseColor=t,r.emissiveColor=t.scale(.1)}}setWireframe(e){this.rootMesh&&(XO(this.rootMesh)||(this.wireframeEnabled=e,this.scene.forceWireframe=e))}toggleWireframe(){return this.setWireframe(!this.wireframeEnabled),this.wireframeEnabled}hasAnimations(){return this.scene.animationGroups.length>0}toggleAnimation(){let e=this.scene.animationGroups;if(e.length===0)return!1;this.animPlaying=!this.animPlaying;for(let t of e)this.animPlaying?t.play(!0):t.pause();return this.animPlaying}toggleMeasurement(){return this.measurementActive=!this.measurementActive,this.measurementActive||this.clearMeasurements(),this.measurementActive}isMeasurementActive(){return this.measurementActive}clearMeasurements(){this.measurementActive=!1,this.pendingPoint=null,this.pendingMarker=null,this.hoveredMarkerIndex=-1,this.removePreviewLine();for(let e of this.measurementSegments)e.line.dispose(),e.label.dispose();this.measurementSegments=[];for(let e of this.measurementMarkers)e.dispose();this.measurementMarkers=[]}setMeasurementScale(e){this.measurementScale={...e},this.updateMeasurementLabels()}getMeasurementScale(){return{...this.measurementScale}}getMeasurementBounds(){if(!this.rootMesh)return null;let e=this.getRenderableBounds(this.rootMesh);return e?{x:e.max.x-e.min.x,y:e.max.y-e.min.y,z:e.max.z-e.min.z}:null}getRealDistance(e,t){let i=(t.x-e.x)*this.measurementScale.x,r=(t.y-e.y)*this.measurementScale.y,s=(t.z-e.z)*this.measurementScale.z;return Math.sqrt(i*i+r*r+s*s)}formatMeasurementDistance(e){let t=this.measurementUnit;return t==="um"||t==="\u03BCm"?e<1e3?`${e.toFixed(2)} \u03BCm`:`${(e/1e3).toFixed(2)} mm`:t==="mm"?e<1?`${(e*1e3).toFixed(2)} \u03BCm`:e<1e3?`${e.toFixed(2)} mm`:`${(e/1e3).toFixed(3)} m`:t==="cm"?e<1?`${(e*10).toFixed(2)} mm`:e<100?`${e.toFixed(2)} cm`:`${(e/100).toFixed(3)} m`:t==="m"?e<.01?`${(e*1e3).toFixed(2)} mm`:e<1?`${e.toFixed(3)} m`:`${e.toFixed(2)} m`:`${e.toFixed(3)} ${t}`}updateMeasurementLabels(){if(this.measurementSegments.length===0)return;let e=this.getMeasurementMarkerSize()*4;for(let t of this.measurementSegments){let i=this.getRealDistance(t.start,t.end),r=this.formatMeasurementDistance(i);t.label.dispose(!1,!0);let s=b.Center(t.start,t.end);t.label=this.createMeasurementLabelMesh(r,s,e)}}setAnimationSpeed(e){for(let t of this.scene.animationGroups)t.speedRatio=e}captureSnapshot(){let e=this.engine.getRenderingCanvas();return e?(this.scene.render(),e.toDataURL("image/png")):null}toggleOrientationGizmo(){return this.gizmoEnabled=!this.gizmoEnabled,this.gizmoEnabled&&!this.gizmo&&(this.gizmo=new zR(this.engine,this.camera)),this.gizmoEnabled}isOrientationGizmoEnabled(){return this.gizmoEnabled}setRenderScale(e){let t=Math.max(.25,Math.min(e,2)),i={low:2,medium:1.33,high:1}[this.currentQuality],r=ur()?1.5:1;return this.engine.setHardwareScalingLevel(i*r/t),t}getPerformanceSnapshot(){return{backend:"babylon",renderScale:Number((1/this.engine.getHardwareScalingLevel()).toFixed(2)),quality:this.currentQuality,meshCount:this.rootMesh?this.getRenderableMeshes(this.rootMesh).length:0}}toggleBoundingBox(){var e;if(this.bboxEnabled=!this.bboxEnabled,this.bboxEnabled){if(!this.rootMesh)return this.bboxEnabled;this.bboxMesh&&this.bboxMesh.dispose();let t=this.getRenderableBounds(this.rootMesh),i=Qg(fn(t)),r=Qg(Wr(t));this.bboxMesh=is.CreateBox("bbox",{width:r.x,height:r.y,depth:r.z},this.scene),this.bboxMesh.position=i;let s=new Ge("bbox-mat",this.scene);s.wireframe=!0,s.emissiveColor=new ge(1,1,0),s.disableLighting=!0,s.alpha=.6,this.bboxMesh.material=s}else(e=this.bboxMesh)==null||e.dispose(),this.bboxMesh=null;return this.bboxEnabled}toggleFocusSelection(){var t;let e=!this.focusSelectionEnabled;return e&&this.isDisassemblyActive()&&((t=this.disassembly)==null||t.setEnabled(!1)),this.focusSelectionEnabled=e,this.focusSelectionEnabled?this._lastPickResult.mesh&&this.setFocusedMesh(this._lastPickResult.mesh):this.clearFocusedMesh(),this.focusSelectionEnabled}isFocusSelectionEnabled(){return this.focusSelectionEnabled}toggleDisassembly(){let e=this.ensureDisassemblyController();if(!e)return!1;let t=!e.isEnabled();return t&&(this.focusSelectionEnabled=!1,this.clearFocusedMesh()),e.setEnabled(t)}resetDisassembly(){var e;(e=this.disassembly)==null||e.reset()}isDisassemblyEnabled(){return this.isDisassemblyActive()}setExplode(e,t){this.rootMesh&&U9(this.rootMesh,e,t,this.loadedMeshes)}resetExplode(){this.rootMesh&&pO(this.rootMesh,this.loadedMeshes)}resetView(){this.rootMesh&&pO(this.rootMesh,this.loadedMeshes),this.resetDisassembly(),this.clearFocusedMesh(),this.camera.mode=0,this.camera.alpha=this.initialCamera.alpha,this.camera.beta=this.initialCamera.beta,this.camera.radius=this.initialCamera.radius,this.camera.target=this.initialCamera.target.clone()}exportModelInfo(e){if(!this.rootMesh)return"";let t=this.computeSummary(this.rootMesh),i=this.getRenderableMeshes(this.rootMesh),r=XO(this.rootMesh),s=e&&oa(e)||t.rootName;return WS({title:s,format:this.loadedExt.toUpperCase(),summary:t,meshBreakdown:i.map(a=>{var o,l;return{name:a.name,triangleCount:r?null:Zg(a),vertexCount:md(a),materialName:(l=(o=a.material)==null?void 0:o.name)!=null?l:null}}),materialNames:i.map(a=>{var o;return(o=a.material)==null?void 0:o.name})})}getModelEvidence(){var a;if(!this.rootMesh)return null;let e=this.getRenderableMeshes(this.rootMesh),t=this.computeComponentPartSummaries(e),i=e.filter(o=>!t.groupedMeshes.has(o)).map(o=>this.computePartSummary(o)),r=t.parts.length>0?[...t.parts,...i]:i,s=new Set;for(let o of e)(a=o.material)!=null&&a.name&&s.add(o.material.name);return{summary:this.computeSummary(this.rootMesh),parts:r,materialNames:Array.from(s).sort((o,l)=>o.localeCompare(l)),resourceWarnings:[...this.resourceWarnings],capturedAt:new Date().toISOString()}}getSelectedPartInfo(){var i;let e=(i=this.focusedMesh)!=null?i:this._lastPickResult.mesh,t=e?this.findRenderableMesh(e):null;return!t||t.isDisposed()?null:this.computePartSummary(t)}exportSelectedPartInfo(){let e=this.getSelectedPartInfo();return e?HS(e):""}getPickWorldPoint(e){if(e.pickedPoint&&typeof e.pickedPoint=="object")return Ht(e.pickedPoint);if(cue(e.mesh)){let t=e.mesh.getBoundingInfo().boundingBox.centerWorld;return Ht(t)}return null}focusWorldPoint(e){let t=new b(e.x,e.y,e.z),i=this.camera.target.clone(),r=performance.now();this.focusWorldPointFrame&&(activeWindow.cancelAnimationFrame(this.focusWorldPointFrame),this.focusWorldPointFrame=0);let s=a=>{let o=Math.min(1,Math.max(0,(a-r)/sue)),l=o<.5?4*o*o*o:1-Math.pow(-2*o+2,3)/2;if(this.camera.target=b.Lerp(i,t,l),o<1&&!this.scene.isDisposed){this.focusWorldPointFrame=window.requestAnimationFrame(s);return}this.focusWorldPointFrame=0};this.focusWorldPointFrame=window.requestAnimationFrame(s)}getAnnotationCameraStateKey(){return`${this.camera.alpha.toFixed(3)}_${this.camera.beta.toFixed(3)}_${this.camera.radius.toFixed(3)}_${this.camera.target.x.toFixed(2)}_${this.camera.target.y.toFixed(2)}_${this.camera.target.z.toFixed(2)}`}projectAnnotationWorldPoint(e,t){let i=this.engine.getRenderingCanvas();if(!i||this.scene.isDisposed)return!1;let r=this.engine.getRenderWidth(),s=this.engine.getRenderHeight();if(r===0||s===0||i.clientWidth===0||i.clientHeight===0)return!1;let a=as.annotationWorldPoint;a.set(e.x,e.y,e.z),b.ProjectToRef(a,as.annotationIdentity,this.scene.getTransformMatrix(),this.camera.viewport.toGlobal(r,s),as.annotationProjection);let o=i.clientWidth/r,l=i.clientHeight/s;return t.screenX=as.annotationProjection.x*o,t.screenY=as.annotationProjection.y*l,t.depth=as.annotationProjection.z,!0}isAnnotationWorldPointOccluded(e){if(this.scene.isDisposed)return!1;let t=wc(Ht(this.camera.position),e);if(!t)return!1;let i=as.annotationDirection,r=as.annotationRay;i.set(t.direction.x,t.direction.y,t.direction.z),r.origin=this.camera.position,r.direction=i,r.length=t.distance;let s=this.scene.pickWithRay(r);return!!(s!=null&&s.hit)&&Nc(s.distance,t.distance,t.epsilon)}getAnnotationProvider(){let e=this.engine.getRenderingCanvas();if(!e)throw new Error("Preview canvas is unavailable");return{canvas:e,observeRender:t=>{let i=this.scene.onAfterRenderCameraObservable.add(r=>{r===this.camera&&t()});return{remove:()=>this.scene.onAfterRenderCameraObservable.remove(i)}},getCameraStateKey:()=>this.getAnnotationCameraStateKey(),projectWorldPoint:(t,i)=>this.projectAnnotationWorldPoint(t,i),isWorldPointOccluded:t=>this.isAnnotationWorldPointOccluded(t)}}getCanvas(){return this.engine.getRenderingCanvas()}getLastPickResult(){return this._lastPickResult}onPick(e){return this._onPickCallbacks.push(e),()=>{this._onPickCallbacks=this._onPickCallbacks.filter(t=>t!==e)}}setRenderQuality(e,t=1){this.currentQuality=e;let i={low:2,medium:1.33,high:1},r=ur()?1.5:1,s=i[e]*r/Math.max(t,.25);if(this.engine.setHardwareScalingLevel(s),this.shadowGenerator){let a={low:0,medium:16,high:32};this.shadowGenerator.blurKernel=a[e],e==="low"?(this.shadowGenerator.useBlurExponentialShadowMap=!1,this.shadowGenerator.useExponentialShadowMap=!0):(this.shadowGenerator.useBlurExponentialShadowMap=!0,this.shadowGenerator.useExponentialShadowMap=!1)}}destroy(){var t,i,r,s,a,o,l,c;this.engine.stopRenderLoop(),this.focusWorldPointFrame&&(activeWindow.cancelAnimationFrame(this.focusWorldPointFrame),this.focusWorldPointFrame=0),this._onPickCallbacks=[],(t=this.cleanupPicking)==null||t.call(this),this.cleanupPicking=null,(i=this.gizmo)==null||i.dispose(),this.gizmo=null,(r=this.disassembly)==null||r.dispose(),this.disassembly=null,this.clearMeasurements(),this.clearFocusedMesh(),this.originalMeshVisibility.clear(),(s=this.bboxMesh)==null||s.dispose(),this.bboxMesh=null,this.camera.detachControl();let e=this.engine.getRenderingCanvas();e==null||e.removeEventListener("wheel",this.preventCanvasWheelScroll),e==null||e.removeEventListener("pointermove",this.handlePointerMove),e==null||e.removeEventListener("webglcontextlost",this.handleContextLost),e==null||e.removeEventListener("webglcontextrestored",this.handleContextRestored),(a=this.viewportObserver)==null||a.disconnect(),this.viewportObserver=null,this.resizeObs.disconnect(),this.autoRotateBehavior&&(this.camera.removeBehavior(this.autoRotateBehavior),this.autoRotateBehavior=null);for(let f of this.configLights)f.dispose();this.configLights=[],(o=this.shadowGenerator)==null||o.dispose(),this.shadowGenerator=null,(l=this.groundMesh)==null||l.dispose(),this.groundMesh=null,(c=this.gridMesh)==null||c.dispose(),this.gridMesh=null;for(let f of this.axisMeshes)f.dispose();this.axisMeshes=[],this.scene.dispose(),this.engine.dispose()}startRenderLoop(){this.rendering||!this.viewportVisible||this.contextLost||(this.rendering=!0,this.engine.runRenderLoop(()=>{if(!this.canRender()||!this.viewportVisible||this.contextLost){this.engine.stopRenderLoop(),this.rendering=!1;return}this.scene.render(),this.gizmo&&this.gizmoEnabled&&(this.gizmo.syncWith(this.camera),this.gizmo.render())}))}getRenderableMeshes(e){return pd(e,this.loadedMeshes)}getRenderableBounds(e){return OR(e,this.loadedMeshes)}setFocusedMesh(e){if(!this.rootMesh)return;let t=e?this.findRenderableMesh(e):null;if(!t||t.isDisposed()){this.clearFocusedMesh();return}if(this.focusedMesh===t)return;let i=this.getRenderableMeshes(this.rootMesh);for(let r of i){this.originalMeshVisibility.has(r.uniqueId)||this.originalMeshVisibility.set(r.uniqueId,r.visibility);let s=r===t;r.visibility=s?1:nue,r.renderOutline=s,r.outlineColor=new ge(.18,.76,1),r.outlineWidth=s?.045:0}this.focusedMesh=t}clearFocusedMesh(){if(!this.rootMesh){this.focusedMesh=null;return}for(let e of this.getRenderableMeshes(this.rootMesh)){let t=this.originalMeshVisibility.get(e.uniqueId);t!==void 0&&(e.visibility=t),e.renderOutline=!1,e.outlineWidth=0}this.originalMeshVisibility.clear(),this.focusedMesh=null}findRenderableMesh(e){if(!this.rootMesh)return null;let t=this.getRenderableMeshes(this.rootMesh);if(t.includes(e))return e;let i=e.parent;for(;i&&"uniqueId"in i;){let r=i;if(t.includes(r))return r;i=i.parent}return null}computePartSummary(e){var s;let t=e.name||`mesh-${e.uniqueId}`,i=FK(e.metadata,(s=this.gltfComponentMetadata.get(`node:${t}`))!=null?s:this.gltfComponentMetadata.get(`mesh:${t}`)),r=nf(i,{name:t,path:NK(e)});return{...B9(e),name:wK(r,t),source:r.hasExplicitIdentity?"component":"mesh",meshNames:[t],childCount:1,componentId:r.componentId,occurrenceId:r.occurrenceId,partNumber:r.partNumber,componentPath:r.componentPath}}computeComponentPartSummaries(e){let t=new Set(e),i=[],r=new Set,s=[];for(let a of this.loadedTransformNodes){let o=a.getChildMeshes(!1).filter(h=>t.has(h)),l=KR(a,`component-${a.uniqueId}`),c=FK(a.metadata,this.gltfComponentMetadata.get(`node:${l}`)),f=nf(c,{name:KR(a,`component-${a.uniqueId}`),path:NK(a)});o.length<1||o.length===e.length||!f.hasExplicitIdentity&&(!a.name.trim()||o.length<2)||s.push({node:a,childMeshes:o,identity:f})}return s.sort((a,o)=>a.childMeshes.length-o.childMeshes.length).forEach(({node:a,childMeshes:o,identity:l})=>{var m;let c=o.filter(p=>!r.has(p));if(c.length<1||!l.hasExplicitIdentity&&c.length<2)return;for(let p of c)r.add(p);let f=fp(c);if(!f)return;let h=new Set,d=0,u=0;for(let p of c)d+=Zg(p),u+=md(p),(m=p.material)!=null&&m.name&&h.add(p.material.name);i.push(Ih({name:wK(l,KR(a,`component-${a.uniqueId}`)),triangleCount:d,vertexCount:u,materialName:h.size===0?null:h.size===1?Array.from(h)[0]:`${h.size} materials`,boundingSize:Wr(f),center:fn(f),source:l.hasExplicitIdentity?"component":"group",meshNames:c.map(p=>p.name||`mesh-${p.uniqueId}`),childCount:c.length,componentId:l.componentId,occurrenceId:l.occurrenceId,partNumber:l.partNumber,componentPath:l.componentPath}))}),{parts:i,groupedMeshes:r}}getMeasurementMarkerSize(){if(!this.rootMesh)return .02;let e=this.getRenderableBounds(this.rootMesh);return e?Math.max(e.max.x-e.min.x,e.max.y-e.min.y,e.max.z-e.min.z,.001)*.015:.02}findNearestMarkerIndex(e){let t=this.getMeasurementMarkerSize()*2.5;for(let i=0;i=0?this.measurementMarkers[t].position.clone():e;if(this.pendingPoint){if(b.Distance(i,this.pendingPoint)<1e-4)return;if(t<0){let r=this.getMeasurementMarkerSize(),s=is.CreateSphere("measure-marker",{diameter:r},this.scene);s.position=i,s.isPickable=!1;let a=new Ge("measure-marker-mat",this.scene);a.diffuseColor=new ge(1,.42,.42),a.emissiveColor=new ge(1,.42,.42),s.material=a,s.renderingGroupId=2,this.measurementMarkers.push(s)}this.createMeasurementSegment(this.pendingPoint,i),this.pendingMarker&&(this.pendingMarker.scaling.setAll(1),this.pendingMarker.material.diffuseColor=new ge(1,.42,.42),this.pendingMarker.material.emissiveColor=new ge(1,.42,.42)),this.pendingPoint=null,this.pendingMarker=null,this.removePreviewLine()}else{if(t<0){let r=this.getMeasurementMarkerSize(),s=is.CreateSphere("measure-marker",{diameter:r},this.scene);s.position=i,s.isPickable=!1;let a=new Ge("measure-marker-mat",this.scene);a.diffuseColor=new ge(1,.42,.42),a.emissiveColor=new ge(1,.42,.42),s.material=a,s.renderingGroupId=2,this.measurementMarkers.push(s),this.pendingMarker=s}else this.pendingMarker=this.measurementMarkers[t];this.pendingMarker.scaling.setAll(1.6),this.pendingMarker.material.diffuseColor=new ge(.32,.81,.4),this.pendingMarker.material.emissiveColor=new ge(.32,.81,.4),this.pendingPoint=i,this.ensurePreviewLine()}}createMeasurementSegment(e,t){let i=is.CreateLines("measure-line",{points:[e,t]},this.scene);i.color=new ge(1,.42,.42),i.isPickable=!1,i.renderingGroupId=2;let r=this.getRealDistance(e,t),s=this.formatMeasurementDistance(r),a=b.Center(e,t),o=this.createMeasurementLabelMesh(s,a,this.getMeasurementMarkerSize()*4);this.measurementSegments.push({start:e,end:t,line:i,label:o})}createMeasurementLabelMesh(e,t,i){let r=is.CreatePlane("measure-label",{width:i*4,height:i},this.scene);r.position=t,r.billboardMode=Z.BILLBOARDMODE_ALL,r.isPickable=!1,r.renderingGroupId=2;let s=new qx("measure-label-tex",{width:512,height:128},this.scene),a=s.getContext();a.fillStyle="rgba(32, 36, 46, 0.9)",a.fillRect(0,0,512,128),a.strokeStyle="#ff6b6b",a.lineWidth=4,a.strokeRect(0,0,512,128),a.fillStyle="#ffffff",a.font="bold 48px sans-serif",a.textAlign="center",a.textBaseline="middle",a.fillText(e,256,64),s.update();let o=new Ge("measure-label-mat",this.scene);return o.diffuseTexture=s,o.emissiveColor=new ge(1,1,1),o.disableLighting=!0,o.opacityTexture=s,r.material=o,r}ensurePreviewLine(){this.previewLine||(this.previewLine=is.CreateLines("measure-preview",{points:[b.Zero(),b.Zero()]},this.scene),this.previewLine.color=new ge(1,1,1),this.previewLine.alpha=.5,this.previewLine.isPickable=!1,this.previewLine.renderingGroupId=2)}updatePreviewLine(){if(!this.pendingPoint||!this.previewLine||!this.rootMesh)return;let e=this.engine.getRenderingCanvas();if(!e)return;let t=e.getBoundingClientRect(),i=this.lastPointerClient.x-t.left,r=this.lastPointerClient.y-t.top,s=this.scene.pick(i,r,o=>o!==this.previewLine&&!this.measurementMarkers.includes(o)),a;if(s.hit&&s.pickedPoint)a=s.pickedPoint;else{let o=this.scene.createPickingRay(i,r,j.Identity(),this.camera);a=this.pendingPoint.add(o.direction.scale(5))}this.previewLine.dispose(),this.previewLine=is.CreateLines("measure-preview",{points:[this.pendingPoint,a]},this.scene),this.previewLine.color=new ge(1,1,1),this.previewLine.alpha=.5,this.previewLine.isPickable=!1,this.previewLine.renderingGroupId=2}removePreviewLine(){this.previewLine&&(this.previewLine.dispose(),this.previewLine=null)}computeSummary(e){let t=this.getRenderableMeshes(e),i=XO(e),r=t.reduce((s,a)=>s+md(a),0);return NR(e.name,this.getRenderableBounds(e),t,{splatCount:i?r:void 0,resourceWarnings:this.resourceWarnings})}};as.annotationIdentity=j.Identity(),as.annotationWorldPoint=b.Zero(),as.annotationProjection=b.Zero(),as.annotationDirection=b.Zero(),as.annotationRay=new Yr(b.Zero(),b.Zero(),1);jR=as});async function VK(n,e){if(Wd(e).backend==="three"){let{createThreeModelPreview:r}=await Promise.resolve().then(()=>(p3(),m3));return r(n)}let{createBabylonModelPreview:i}=await Promise.resolve().then(()=>(UK(),BK));return i(n)}var GK=C(()=>{"use strict";Ev()});var kK={};tt(kK,{createBabylonGridRenderer:()=>_ue});function pue(n){return n.replace(/\|/g,"\\|").replace(/\r?\n/g," ")}function YO(n){return new b(n.x,n.y,n.z)}function _ue(n){return new KO(n)}var hp,KO,WK=C(()=>{"use strict";dy();xs();VA();GA();Ve();zt();Ju();Jm();qh();Tc();qg();qg();wR();FS();Ks();rf();US();hp=32;KO=class{constructor(e){this.cells=[];this.initialCameras=[];this.wireframeEnabled=!1;this.rendering=!1;this.dirty=!0;this.contextLost=!1;this.preventCanvasWheelScroll=e=>{e.preventDefault(),e.stopPropagation()};this.handleContextLost=e=>{e.preventDefault(),this.contextLost=!0,this.rendering&&(this.engine.stopRenderLoop(),this.rendering=!1)};this.handleContextRestored=()=>{this.contextLost=!1,this.engine.resize(),this.startRenderLoop(),this.markDirty()};e.className="ai3d-canvas-full",e.addEventListener("wheel",this.preventCanvasWheelScroll,{passive:!1}),this.engine=new Ue(e,!0,{preserveDrawingBuffer:!0}),e.addEventListener("webglcontextlost",this.handleContextLost),e.addEventListener("webglcontextrestored",this.handleContextRestored),this.scene=new $t(this.engine),this.scene.clearColor=new lt(.12,.12,.14,1),this.scene.autoClear=!1,new Qs("default-light",new b(0,1,.5),this.scene),this.resizeObs=new ResizeObserver(()=>{this.engine.resize(),this.markDirty()}),this.resizeObs.observe(e),window.requestAnimationFrame(()=>this.engine.resize())}canRender(){let e=this.engine.getRenderingCanvas();return!!(e!=null&&e.isConnected)&&e.clientWidth>0&&e.clientHeight>0}markDirty(){this.dirty=!0}getCellBounds(e){let t=fp(e);if(!t)throw new Error("Grid cell has no renderable meshes");return t}async loadModels(e,t,i){var h,d,u;await jg();let r=e.length>hp?(console.warn(`[AI3D Grid] Capping ${e.length} models to ${hp} (layerMask limit)`),e.slice(0,hp)):e,s=(h=t.columns)!=null?h:Math.min(r.length,3),a=(d=t.gapX)!=null?d:.02,o=(u=t.gapY)!=null?u:.02,l=Math.ceil(r.length/s),c=(1-a*(s+1))/s,f=(1-o*(l+1))/l;for(let m=0;mhp?(console.warn(`[AI3D Preset] Capping ${e.placements.length} placements to ${hp} (layerMask limit)`),e.placements.slice(0,hp)):e.placements,r=[];for(let f=0;f0&&(d.push(...r[p]),u|=1<this.markDirty())),this.initialCameras.push({alpha:f.alpha,beta:f.beta,radius:f.radius,target:f.target.clone()}),f}async loadOne(e,t,i,r,s,a,o){var d,u;let l=await t(e.path),c=(u=(d=e.path.split(".").pop())==null?void 0:d.replace(".","").toLowerCase())!=null?u:"glb",{renderableMeshes:f}=await this.importMesh(e.path,l,o);if(c==="stl"&&e.color){let m=ge.FromHexString(e.color);for(let p of f)p.material instanceof Ge&&p.material.name==="stl-mat"&&(p.material.diffuseColor=m)}if(c==="stl"&&e.wireframe!==void 0)for(let m of f)m.material instanceof Ge&&(m.material.wireframe=e.wireframe);let h=this.createCellCamera(f,o,i,r,s,a);this.cells.push({meshes:f,camera:h})}createCellCamera(e,t,i,r,s,a){let o=BS(this.getCellBounds(e)),l=new gi(`cell-cam-${t}`,Math.PI/4,Math.PI/3,o.radius,YO(o.target),this.scene);l.fov=45*Math.PI/180,l.minZ=o.near,l.maxZ=o.far,l.lowerRadiusLimit=o.lowerRadiusLimit,l.upperRadiusLimit=o.upperRadiusLimit,l.wheelPrecision=30,l.viewport=new io(i,r,s,a),l.layerMask=1<this.markDirty())),this.initialCameras.push({alpha:l.alpha,beta:l.beta,radius:l.radius,target:l.target.clone()}),l}renderFrame(){if(!this.canRender()||!this.dirty||this.contextLost)return;this.dirty=!1;let e=this.engine,t=this.scene;e.clear(t.clearColor,!0,!0);for(let i of this.cells){e.setViewport(i.camera.viewport);let r=i.camera.viewport,s=e.getRenderWidth(),a=e.getRenderHeight();e.enableScissor(r.x*s,r.y*a,r.width*s,r.height*a),t.activeCamera=i.camera,t.render(),e.disableScissor()}}startRenderLoop(){this.rendering||(this.rendering=!0,this.engine.runRenderLoop(()=>this.renderFrame()))}captureSnapshot(){let e=this.engine.getRenderingCanvas();return e?(this.renderFrame(),e.toDataURL("image/png")):null}getEngine(){return this.engine}getScene(){return this.scene}getCellCount(){return this.cells.length}getCanvas(){return this.engine.getRenderingCanvas()}getPrimaryCamera(){var e,t;return(t=(e=this.cells[0])==null?void 0:e.camera)!=null?t:null}setRenderScale(e){let t=Math.max(.25,Math.min(e,2)),i=ur()?1.5:1;return this.engine.setHardwareScalingLevel(i/t),t}resetView(){for(let e=0;e(WK(),kK));return e(n)}var zK=C(()=>{"use strict"});function gue(n,e,t){n.info("select preview backend",{...e,backend:t.backend,reason:t.reason,ext:t.ext,annotationMode:t.annotationMode,requireWorkbenchFeatures:t.requireWorkbenchFeatures,rendererRollout:t.rendererRollout})}async function _d(n,e,t,i){let r=Wd(i);return gue(n,e,r),{preview:await VK(t,i),route:r}}function vue(n,e,t){n.info("select preview backend",{...e,backend:t.backend,reason:t.reason})}async function XK(n,e,t){let i=uw();return vue(n,e,i),{renderer:await HK(t),route:i}}var qR=C(()=>{"use strict";GK();zK();Ev()});function jO(n){KK=n}function ZR(n){return YK[n]>=YK[KK]}function QR(){return new Date().toISOString()}function $R(n){return n&&Object.keys(n).length>0?n:void 0}function ki(n){let e=`[AI3D][${n}]`;return{debug(t,i){ZR("debug")&&console.debug(e,QR(),t,$R(i))},info(t,i){ZR("info")&&console.debug(e,QR(),t,$R(i))},warn(t,i){ZR("warn")&&console.warn(e,QR(),t,$R(i))},error(t,i){ZR("error")&&console.error(e,QR(),t,$R(i))}}}var YK,KK,Tn=C(()=>{"use strict";YK={debug:10,info:20,warn:30,error:40},KK="warn"});function an(n,e){return!!n&&typeof n=="object"&&e in n}function JR(n){return an(n,"getAnnotationProvider")}function jK(n){return an(n,"hasAnimations")&&an(n,"toggleAnimation")}function Ao(n){return an(n,"toggleMeasurement")&&an(n,"isMeasurementActive")&&an(n,"clearMeasurements")&&an(n,"setMeasurementScale")&&an(n,"getMeasurementScale")&&an(n,"getMeasurementBounds")&&an(n,"updateMeasurementLabels")}function eb(n){return an(n,"toggleDisassembly")&&an(n,"resetDisassembly")&&an(n,"isDisassemblyEnabled")}function tb(n){return an(n,"toggleFocusSelection")&&an(n,"isFocusSelectionEnabled")}function qK(n){return an(n,"toggleWireframe")}function qO(n){return an(n,"toggleOrientationGizmo")}function ZK(n){return an(n,"toggleBoundingBox")}function QK(n){return an(n,"setRenderScale")}var ib=C(()=>{"use strict"});function Cr(n){let e=createSvg("svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("width","16"),e.setAttribute("height","16");let t=new DOMParser().parseFromString(`${n}`,"image/svg+xml");for(let i of Array.from(t.documentElement.childNodes))e.appendChild(activeDocument.importNode(i,!0));return e}function $K(n){var a,o;let[e,t]=n.split(","),i=(o=(a=e.match(/:(.*?);/))==null?void 0:a[1])!=null?o:"image/png",r=atob(t),s=new Uint8Array(r.length);for(let l=0;l{G.stopPropagation()};d.addEventListener("pointerdown",_),d.addEventListener("mousedown",_),d.addEventListener("click",_),f&&(d.classList.add("is-mobile"),JK(e,!1));let g=G=>(G.classList.add("is-secondary"),G),v=(G,ve)=>{G.classList.toggle("ai3d-btn-active",ve),G.setAttribute("aria-pressed",String(ve))},x=()=>{for(let G of[u,m,p]){let ve=Array.from(G.querySelectorAll(".ai3d-inline-btn")).filter(ke=>!ke.classList.contains("is-hidden")),Ae=ve.length>0,He=ve.some(ke=>!ke.classList.contains("is-secondary"));G.classList.toggle("is-hidden",!Ae),G.classList.toggle("has-primary-visible",He)}},A=!1,S=!1,E=f?u.createEl("button",{cls:"ai3d-inline-btn ai3d-mobile-mode-btn",attr:{"aria-label":J("helper.enableInteractionLabel"),"aria-pressed":"false"}}):null;E==null||E.appendChild(Cr(''));let R=(jt=E==null?void 0:E.createSpan({cls:"ai3d-mobile-mode-btn-label"}))!=null?jt:null,I=()=>{f&&E&&(JK(e,A),v(E,A),R==null||R.setText(A?J("helper.scrollAction"):J("helper.interactAction")),E.setAttribute("aria-label",A?J("helper.disableInteractionLabel"):J("helper.enableInteractionLabel"))),v(Qt,S),d.classList.toggle("show-secondary",S),x()},y=G=>{A=G,I()};E==null||E.addEventListener("click",()=>{let G=!A;l==null||l(G),y(G),Li(E,G?J("helper.interactionOn"):J("helper.interactionOff"))});let M=(G,ve)=>{G.classList.toggle("is-hidden",!ve)},D=null,O=()=>{var He;let G=i(),ve=G&&tb(G)?G:null,Ae=G&&eb(G)?G:null;v(Q,!!(ve!=null&&ve.isFocusSelectionEnabled())),v(Y,!!(Ae!=null&&Ae.isDisassemblyEnabled())),G&&qO(G)&&v(ee,!!((He=G.isOrientationGizmoEnabled)!=null&&He.call(G)))},V=()=>{let G=i(),ve=G&&tb(G)?G:null,Ae=G&&eb(G)?G:null,He=G&&jK(G)?G:null;G!==D&&(D=G,v(k,!1),v(q,!1),v(ue,!1),ue.replaceChildren(Cr('')),M(N,!!(G!=null&&G.resetView)),M(F,!!(G!=null&&G.exportModelInfo)),M(U,!!(G!=null&&G.exportSelectedPartInfo)),M(k,!!G&&qK(G)),M(ee,!!G&&qO(G)),M(q,!!G&&ZK(G)),M(Q,!!ve),M(Y,!!Ae),M(se,!!G&&QK(G)),M(ue,!!(He!=null&&He.hasAnimations()))),M(K,!!(Ae!=null&&Ae.isDisassemblyEnabled())),M(re,!!G&&Ao(G)),M(he,!!G&&Ao(G)),M(De,!!G&&Ao(G)),O(),x()},N=u.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":J("helper.resetViewLabel")}});on(N,"reset-view"),N.appendChild(Cr('')),N.addEventListener("click",()=>{let G=i();G!=null&&G.resetView&&(G.resetView(),V(),Li(N,J("helper.resetViewDone")))});let F=g(m.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":J("helper.copyModelInfoLabel")}}));on(F,"copy-model-info"),F.appendChild(Cr('')),F.addEventListener("click",()=>{let G=i();if(G!=null&&G.exportModelInfo)try{let ve=G.exportModelInfo(r());if(!ve)return;navigator.clipboard.writeText(ve).then(()=>{Li(F,J("helper.copied"))}).catch(()=>{Li(F,J("helper.failed"))})}catch(ve){console.error("[AI3D] Export model info failed:",ve),Li(F,J("helper.failed"))}});let U=g(m.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":J("helper.copySelectedPartInfoLabel")}}));on(U,"copy-selected-part-info"),U.appendChild(Cr('')),U.addEventListener("click",()=>{let G=i();if(G!=null&&G.exportSelectedPartInfo)try{let ve=G.exportSelectedPartInfo();if(!ve){Li(U,J("helper.noSelectedPart"));return}navigator.clipboard.writeText(ve).then(()=>{Li(U,J("helper.copied"))}).catch(()=>{Li(U,J("helper.failed"))})}catch(ve){console.error("[AI3D] Export selected part info failed:",ve),Li(U,J("helper.failed"))}});let k=g(u.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":J("helper.toggleWireframeLabel"),"aria-pressed":"false"}}));on(k,"toggle-wireframe"),k.appendChild(Cr('')),k.addEventListener("click",()=>{let G=i();if(!(G!=null&&G.toggleWireframe))return;let ve=G.toggleWireframe();v(k,ve),Li(k,ve?J("helper.wireframeOn"):J("helper.wireframeOff"))});let ee=g(u.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":J("helper.toggleAxesLabel"),"aria-pressed":"false"}}));on(ee,"toggle-axes"),ee.appendChild(Cr('')),ee.addEventListener("click",()=>{let G=i();if(!(G!=null&&G.toggleOrientationGizmo))return;let ve=G.toggleOrientationGizmo();v(ee,ve),Li(ee,ve?J("helper.axesOn"):J("helper.axesOff"))});let q=g(u.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":J("helper.toggleBoundingBoxLabel"),"aria-pressed":"false"}}));on(q,"toggle-bounding-box"),q.appendChild(Cr('')),q.addEventListener("click",()=>{let G=i();if(!(G!=null&&G.toggleBoundingBox))return;let ve=G.toggleBoundingBox();v(q,ve),Li(q,ve?J("helper.boundingBoxOn"):J("helper.boundingBoxOff"))});let Q=g(m.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":J("helper.toggleFocusSelectionLabel"),"aria-pressed":"false"}}));on(Q,"toggle-focus"),Q.appendChild(Cr('')),Q.addEventListener("click",()=>{let G=i();if(!G||!tb(G))return;let ve=G.toggleFocusSelection();V(),Li(Q,ve?J("helper.focusSelectionOn"):J("helper.focusSelectionOff"))});let Y=g(m.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":J("helper.toggleDisassemblyLabel"),"aria-pressed":"false"}}));on(Y,"toggle-disassembly"),Y.appendChild(Cr('')),Y.addEventListener("click",()=>{let G=i();if(!G||!eb(G))return;let ve=G.toggleDisassembly();V(),Li(Y,ve?J("helper.disassemblyOn"):J("helper.disassemblyOff"))});let K=g(m.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":J("helper.resetPartsLabel")}}));on(K,"reset-parts"),K.appendChild(Cr('')),K.addEventListener("click",()=>{let G=i();G!=null&&G.resetDisassembly&&(G.resetDisassembly(),V(),Li(K,J("helper.partsReset")))});let de=[.5,.75,1,1.5,2],Re=(vi=a==null?void 0:a().renderScale)!=null?vi:1,Fe=de.reduce((G,ve,Ae)=>{let He=Math.abs(ve-Re),ke=Math.abs(de[G]-Re);return He{let G=i();if(!(G!=null&&G.setRenderScale))return;Fe=(Fe+1)%de.length;let ve=G.setRenderScale(de[Fe]);se.textContent=`${ve.toFixed(1)}x`,Li(se,dr("helper.resolutionValue",{value:`${ve}x`}))});let ue=g(u.createEl("button",{cls:"ai3d-inline-btn is-hidden",attr:{"aria-label":J("helper.toggleAnimationLabel"),"aria-pressed":"false"}}));on(ue,"toggle-animation"),ue.appendChild(Cr('')),ue.addEventListener("click",()=>{let G=i();if(!(G!=null&&G.toggleAnimation))return;let ve=G.toggleAnimation();ue.replaceChildren(Cr(ve?'':'')),v(ue,ve),Li(ue,ve?J("helper.playing"):J("helper.paused"))});let re=g(m.createEl("button",{cls:"ai3d-inline-btn is-hidden",attr:{"aria-label":J("helper.toggleMeasurementLabel"),"aria-pressed":"false"}}));on(re,"toggle-measurement"),re.appendChild(Cr('')),re.addEventListener("click",()=>{let G=i();if(!G||!Ao(G))return;let ve=G.toggleMeasurement();v(re,ve),Li(re,ve?J("helper.measurementOn"):J("helper.measurementOff")),ve||v(he,!1)});let he=g(m.createEl("button",{cls:"ai3d-inline-btn is-hidden",attr:{"aria-label":J("helper.clearMeasurementsLabel")}}));on(he,"clear-measurements"),he.appendChild(Cr('')),he.addEventListener("click",()=>{let G=i();!G||!Ao(G)||(G.clearMeasurements(),v(re,!1),Li(he,J("helper.measurementsCleared")))});let De=g(m.createEl("button",{cls:"ai3d-inline-btn is-hidden",attr:{"aria-label":J("helper.calibrateLabel")}}));on(De,"toggle-calibration"),De.appendChild(Cr(''));let fe=g(p.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":J("helper.removePreviewLabel")}}));on(fe,"remove-preview"),fe.appendChild(Cr('')),fe.addEventListener("click",s);let be=p.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":J("helper.copySnapshotLabel")}});on(be,"copy-snapshot"),be.appendChild(Cr('')),be.addEventListener("click",()=>{let G=i();if(G)try{let ve=G.captureSnapshot();if(!ve)return;let Ae=$K(ve);navigator.clipboard.write([new ClipboardItem({"image/png":Ae})]).then(()=>{Li(be,J("helper.copied"))}).catch(()=>{Li(be,J("helper.failed"))})}catch(ve){console.error("[AI3D] Copy snapshot failed:",ve),Li(be,J("helper.failed"))}});let Xe=g(p.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":J("helper.saveSnapshotLabel")}}));on(Xe,"save-snapshot"),Xe.appendChild(Cr('')),Xe.addEventListener("click",()=>{var ve,Ae;let G=i();if(G)try{let He=G.captureSnapshot();if(!He)return;let ke=r(),Oe=jr(ke)||"model",Tt=a==null?void 0:a(),Wt=(ve=Tt==null?void 0:Tt.snapshotFolder)!=null?ve:"Media/3D Previews",nr=(Ae=Tt==null?void 0:Tt.snapshotNaming)!=null?Ae:"model-name",di=Date.now(),xn=nr==="timestamp"?`snapshot_${di}.png`:`${Oe}_snapshot_${di}.png`,Er=$K(He),Xn=new FileReader;Xn.onload=()=>{let Pb=Xn.result;t.vault.adapter.exists(Wt).then(Id=>Id?Promise.resolve():t.vault.createFolder(Wt).catch(_l=>{Eue.warn("Failed to create vault folder",{path:Wt,error:String(_l)})})).then(()=>t.vault.createBinary(`${Wt}/${xn}`,Pb)).then(()=>{Li(Xe,J("helper.saved"))}).catch(Id=>{console.error("[AI3D] Save snapshot failed:",Id),Li(Xe,J("helper.failed"))})},Xn.onerror=()=>{console.error("[AI3D] FileReader error"),Li(Xe,J("helper.failed"))},Xn.onabort=()=>{console.error("[AI3D] FileReader aborted"),Li(Xe,J("helper.failed"))},Xn.readAsArrayBuffer(Er)}catch(He){console.error("[AI3D] Save snapshot failed:",He),Li(Xe,J("helper.failed"))}});let Et=g(p.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":J("helper.downloadSnapshotLabel")}}));on(Et,"download-snapshot"),Et.appendChild(Cr('')),Et.addEventListener("click",()=>{let G=i();if(G)try{let ve=G.captureSnapshot();if(!ve)return;let Ae=r(),ke=`${jr(Ae)||"model"}_snapshot_${Date.now()}.png`,Oe=createEl("a");Oe.href=ve,Oe.download=ke,activeDocument.body.appendChild(Oe),Oe.click(),Oe.remove(),Li(Et,J("helper.downloaded"))}catch(ve){console.error("[AI3D] Download snapshot failed:",ve),Li(Et,J("helper.failed"))}});let Ke=g(m.createEl("button",{cls:"ai3d-inline-btn is-hidden ai3d-annot-btn",attr:{"aria-label":J(h.labelKey),"aria-pressed":"false"}}));on(Ke,"toggle-annotation"),Ke.appendChild(Cr(''));let qe=Ke.createSpan({cls:"ai3d-pin-badge is-hidden"});Ke.addEventListener("click",()=>{if(!o)return;let G=o();v(Ke,G),Li(Ke,G?J(h.activeTooltipKey):J(h.inactiveTooltipKey))});let Qt=d.createEl("button",{cls:"ai3d-inline-btn ai3d-mobile-more-toggle",attr:{"aria-label":J("helper.showMoreActionsLabel"),"aria-pressed":"false"}});Qt.appendChild(Cr('')),Qt.addEventListener("click",()=>{S=!S,Qt.setAttribute("aria-label",S?J("helper.hideMoreActionsLabel"):J("helper.showMoreActionsLabel")),I(),Li(Qt,S?J("helper.moreActionsShown"):J("helper.moreActionsHidden"))}),n.insertBefore(d,e.nextSibling);let Dt=n.createDiv({cls:"ai3d-calibrate-panel is-hidden"}),Fi=Dt.createEl("div",{cls:"ai3d-calibrate-title",text:J("helper.calibrateTitle")}),ae=Dt.createDiv({cls:"ai3d-calibrate-row"});ae.createEl("span",{cls:"ai3d-calibrate-label",text:J("helper.calibrateCurrent")});let Bi=ae.createEl("span",{cls:"ai3d-calibrate-readonly"}),ei=ae.createEl("span",{cls:"ai3d-calibrate-readonly"}),Wi=ae.createEl("span",{cls:"ai3d-calibrate-readonly"}),ot=Dt.createDiv({cls:"ai3d-calibrate-row"});ot.createEl("span",{cls:"ai3d-calibrate-label",text:J("helper.calibrateReal")});let Ci=ot.createEl("input",{cls:"ai3d-calibrate-input",attr:{type:"number",step:"any",placeholder:"X"}}),X=ot.createEl("input",{cls:"ai3d-calibrate-input",attr:{type:"number",step:"any",placeholder:"Y"}}),B=ot.createEl("input",{cls:"ai3d-calibrate-input",attr:{type:"number",step:"any",placeholder:"Z"}}),me=Dt.createDiv({cls:"ai3d-calibrate-row"}),ye=me.createEl("select",{cls:"ai3d-calibrate-select"});for(let G of[{v:"um",l:"\u03BCm"},{v:"mm",l:"mm"},{v:"cm",l:"cm"},{v:"m",l:"m"}])ye.createEl("option",{text:G.l,value:G.v});ye.value="mm";let Be=me.createEl("label",{cls:"ai3d-calibrate-lock"}),Je=Be.createEl("input",{attr:{type:"checkbox",checked:"true"}});Be.appendText(" "+J("helper.calibrateLock"));let rt=Dt.createDiv({cls:"ai3d-calibrate-row ai3d-calibrate-actions"}),Ce=rt.createEl("button",{cls:"ai3d-inline-btn",text:J("helper.calibrateApply")}),Pe=rt.createEl("button",{cls:"ai3d-inline-btn is-secondary",text:J("helper.calibrateReset")}),je=null;function St(){var Ae,He;let G=i();if(!G||!Ao(G))return;let ve=(He=(Ae=G.getMeasurementBounds)==null?void 0:Ae.call(G))!=null?He:null;je=ve,ve?(Bi.textContent=`X: ${ve.x.toFixed(3)}`,ei.textContent=`Y: ${ve.y.toFixed(3)}`,Wi.textContent=`Z: ${ve.z.toFixed(3)}`):(Bi.textContent="X: -",ei.textContent="Y: -",Wi.textContent="Z: -")}function nt(){var Oe;let G=i();if(!G||!Ao(G)||!je)return;let ve=parseFloat(Ci.value),Ae=parseFloat(X.value),He=parseFloat(B.value);if(!isFinite(ve)||!isFinite(Ae)||!isFinite(He))return;let ke={x:je.x>1e-4?ve/je.x:1,y:je.y>1e-4?Ae/je.y:1,z:je.z>1e-4?He/je.z:1};(Oe=G.setMeasurementScale)==null||Oe.call(G,ke),Li(Ce,J("helper.calibrated"))}function et(){var ve;let G=i();!G||!Ao(G)||((ve=G.setMeasurementScale)==null||ve.call(G,{x:1,y:1,z:1}),St(),je?(Ci.value=je.x.toFixed(3),X.value=je.y.toFixed(3),B.value=je.z.toFixed(3)):(Ci.value="",X.value="",B.value=""),Li(Pe,J("helper.calibrateResetDone")))}function Vt(G){if(!Je.checked||!je)return;let Ae=parseFloat((G==="x"?Ci:G==="y"?X:B).value);if(!isFinite(Ae)||Ae===0)return;let He=je[G];if(He<=1e-4)return;let ke=Ae/He;G!=="x"&&(Ci.value=(je.x*ke).toFixed(3)),G!=="y"&&(X.value=(je.y*ke).toFixed(3)),G!=="z"&&(B.value=(je.z*ke).toFixed(3))}return Ci.addEventListener("input",()=>Vt("x")),X.addEventListener("input",()=>Vt("y")),B.addEventListener("input",()=>Vt("z")),Ce.addEventListener("click",nt),Pe.addEventListener("click",et),De.addEventListener("click",()=>{let G=Dt.classList.contains("is-hidden");G&&(St(),je&&(Ci.value=je.x.toFixed(3),X.value=je.y.toFixed(3),B.value=je.z.toFixed(3))),Dt.classList.toggle("is-hidden",!G),v(De,G),Li(De,G?J("helper.calibrateOpen"):J("helper.calibrateClose"))}),I(),V(),{showAnimButton(){ue.classList.remove("is-hidden"),x()},showAnnotateButton(){Ke.classList.remove("is-hidden"),x()},updateAnnotationBadge(G){G>0?(qe.textContent=String(G),qe.classList.remove("is-hidden")):qe.classList.add("is-hidden")},setMobileInteractionMode(G){f&&y(G)},syncCapabilities:V}}function Li(n,e){var i;(i=ZO.get(n))==null||i.remove();let t=n.createSpan({cls:"ai3d-tooltip"});t.textContent=e,ZO.set(n,t),window.setTimeout(()=>{t.remove(),ZO.delete(n)},1500)}var Eue,ZO,QO=C(()=>{"use strict";ra();Tn();ib();Ks();la();Eue=ki("helper-buttons");ZO=new WeakMap});function Tue(n,e,t){let i=new Promise((r,s)=>{let a=setTimeout(()=>{s(new $O(`Conversion did not complete within ${e}ms`))},e);n.then(()=>clearTimeout(a)).catch(()=>clearTimeout(a))});return Promise.race([n,i])}var Jg,Sue,$O,rb,ej=C(()=>{"use strict";Io();Tn();Jg=ki("conversion-manager"),Sue=12e4,$O=class extends Error{constructor(e="Conversion timed out"){super(e),this.name="ConversionTimeoutError"}};rb=class{constructor(){this.converters=new Map;this.pending=new Map}getConverter(e){return this.converters.get(Ba(e))}registerConverter(e){Jg.info("register converter",{converterId:e.id,sourceExts:[...e.sourceExts]});for(let t of e.sourceExts)this.converters.set(Ba(t),e)}canConvert(e){let t=Ba(e),i=this.converters.has(t);return Jg.debug("can convert",{ext:t,ok:i}),i}async getConverterCacheIdentity(e){let t=this.getConverter(e);if(t)return{converterId:t.id,cacheKey:await t.getCacheKey()}}async convert(e){var o;let t=Ba(e.sourceExt),i=this.getConverter(t);if(!i)throw Jg.error("converter missing",{ext:t,targetExt:e.targetExt}),new Error(`No converter registered for .${t}`);let r=`${e.sourcePath}::${t}::${e.targetExt}`,s=this.pending.get(r);if(s)return Jg.info("joining in-flight conversion",{key:r}),s;Jg.info("dispatch conversion",{converterId:i.id,ext:t,targetExt:e.targetExt});let a=Tue(i.convert({...e,sourceExt:t}),(o=e.timeoutMs)!=null?o:Sue,{converterId:i.id,ext:t,targetExt:e.targetExt});this.pending.set(r,a);try{return await a}finally{this.pending.delete(r)}}}});function tN(...n){let e=(We==null?void 0:We.platform)==="darwin"?["/opt/homebrew/bin","/usr/local/bin","/opt/local/bin","/usr/bin"]:["/usr/local/bin","/opt/homebrew/bin","/opt/local/bin","/usr/bin"];return Array.from(new Set(e.flatMap(t=>n.map(i=>`${t}/${i}`))))}function xue(){var r,s,a;if((We==null?void 0:We.platform)==="darwin")return["/Applications/FreeCAD.app/Contents/MacOS/FreeCADCmd","/Applications/FreeCAD.app/Contents/Resources/bin/FreeCADCmd","/Applications/FreeCAD.app/Contents/Resources/bin/freecadcmd",...tN("FreeCADCmd","freecadcmd")];if((We==null?void 0:We.platform)!=="win32")return["/usr/local/bin/freecadcmd","/opt/homebrew/bin/freecadcmd","/opt/local/bin/freecadcmd","/snap/freecad/current/usr/bin/freecadcmd","/usr/bin/freecadcmd"];let n=[],e=(r=We==null?void 0:We.env)==null?void 0:r.LOCALAPPDATA,t=(s=We==null?void 0:We.env)==null?void 0:s.ProgramFiles,i=(a=We==null?void 0:We.env)==null?void 0:a["ProgramFiles(x86)"];if(e&&n.push(zi(e,"Programs","FreeCAD","bin","FreeCADCmd.exe")),t&&n.push(zi(t,"FreeCAD","bin","FreeCADCmd.exe")),e)for(let o of["1.2","1.1","1.0","0.22","0.21","0.20"])n.push(`${e}/Programs/FreeCAD ${o}/bin/FreeCADCmd.exe`);if(t)for(let o of["1.2","1.1","1.0","0.22","0.21","0.20"])n.push(`${t}/FreeCAD ${o}/bin/FreeCADCmd.exe`);return i&&n.push(`${i}/FreeCAD/bin/FreeCADCmd.exe`),n}function Rue(n){var a,o,l,c;if((We==null?void 0:We.platform)!=="win32")return[];let e=(a=We==null?void 0:We.env)==null?void 0:a.APPDATA,t=(o=We==null?void 0:We.env)==null?void 0:o.LOCALAPPDATA,i=(l=We==null?void 0:We.env)==null?void 0:l.npm_config_prefix,r=(c=We==null?void 0:We.env)==null?void 0:c.USERPROFILE,s=[i,e?zi(e,"npm"):void 0,t?zi(t,"npm"):void 0,r?zi(r,"AppData","Roaming","npm"):void 0].filter(f=>!!f);return Array.from(new Set(s.map(f=>zi(f,n))))}function bue(...n){var s,a,o;if((We==null?void 0:We.platform)!=="win32")return[];let e=(s=We==null?void 0:We.env)==null?void 0:s.ProgramFiles,t=(a=We==null?void 0:We.env)==null?void 0:a["ProgramFiles(x86)"],i=(o=We==null?void 0:We.env)==null?void 0:o.LOCALAPPDATA,r=[e,t,i?zi(i,"Programs"):void 0].filter(l=>!!l);return Array.from(new Set(r.flatMap(l=>n.map(c=>zi(l,c)))))}async function nN(n){try{return await cs(n,(We==null?void 0:We.platform)==="win32"?fs:JN),!0}catch(e){return!1}}function JO(n){let e=n==null?void 0:n.trim();if(e)return e}function rj(n){return Iue.test(n)?{ok:!1,reason:"Command contains unsafe shell metacharacters."}:{ok:!0}}async function Mue(n){try{return(await $N(n)).isFile()}catch(e){return!1}}function Cue(n){let e=[],t="",i=null;for(let r=0;rr.trim().toLowerCase()).filter(Boolean);return e!=null&&e.length?e:Aue}async function Lue(n){var r;let e=(r=We==null?void 0:We.env)==null?void 0:r.PATH;if(!e)return;let t=e.split(ew).map(s=>s.trim()).filter(Boolean),i=(We==null?void 0:We.platform)==="win32"?Due(n):[""];for(let s of t)for(let a of i){let o=zi(s,a?`${n}${a}`:n);if(await nN(o))return o}}function iN(n,e,t=15e3){let i=rj(n);return i.ok?new Promise((r,s)=>{aa(n,e,{timeout:t,windowsHide:!0,maxBuffer:4*1024*1024},(a,o,l)=>{if(a){s(new Error((l||o||a.message).toString().trim()||a.message));return}r({stdout:o!=null?o:"",stderr:l!=null?l:""})})}):Promise.reject(new Error(`Refusing to execute converter command: ${i.reason}`))}function rN(n){let t=(n instanceof Error?n.message:String(n)).replace(/\s+/g," ").trim();return t.length>180?`${t.slice(0,177)}...`:t}async function eN(n,e,t,i){let r="";for(let s of t)try{return await iN(n,[...e,...s]),{ok:!0,detail:""}}catch(a){let o=rN(a);if(i.test(o))return{ok:!0,detail:""};r=o}return{ok:!1,detail:r||"Command probe failed."}}async function Oue(n){var i;if(!n.available)return[];let e=(i=n.resolvedPath)!=null?i:n.executable,t=[...n.args];if(n.id==="freecad")try{return await iN(e,[...t,"-c","import cadquery, trimesh; print('ok')"]),[{kind:"cad-python",ok:!0,detail:""}]}catch(r){return[{kind:"cad-python",ok:!1,detail:rN(r)}]}if(n.id==="assimp")try{return await iN(e,[...t,"-c","import trimesh, numpy, networkx, collada; print('ok')"]),[{kind:"mesh-python",ok:!0,detail:""}]}catch(r){return[{kind:"mesh-python",ok:!1,detail:rN(r)}]}if(n.id==="freecadcmd"){let r=await eN(e,t,[["--version"],["--help"]],/freecad|usage|help|version/i);return[{kind:"freecadcmd-cli",ok:r.ok,detail:r.detail}]}if(n.id==="obj2gltf"){let r=await eN(e,t,[["--version"],["--help"]],/obj2gltf|usage|help|version/i);return[{kind:"obj2gltf-cli",ok:r.ok,detail:r.detail}]}if(n.id==="fbx2gltf"){let r=await eN(e,t,[["--version"],["--help"]],/fbx2gltf|usage|help|version/i);return[{kind:"fbx2gltf-cli",ok:r.ok,detail:r.detail}]}return[]}function Nue(n){let e=ij.find(t=>t.id===n);if(!e)throw new Error(`Unknown converter command id: ${n}`);return e}function wue(n){var s,a,o,l;let e=(a=(s=We==null?void 0:We.env)==null?void 0:s.ProgramFiles)==null?void 0:a.toLowerCase(),t=(l=(o=We==null?void 0:We.env)==null?void 0:o["ProgramFiles(x86)"])==null?void 0:l.toLowerCase(),i=[],r=[];for(let c of n.knownCandidates){let f=c.toLowerCase(),h=(We==null?void 0:We.platform)==="win32"&&((e?f.startsWith(e):!1)||(t?f.startsWith(t):!1)),d=(We==null?void 0:We.platform)!=="win32"&&(c.startsWith("/usr/bin/")||c.startsWith("/snap/freecad/current/usr/bin/"));h||d?r.push(c):i.push(c)}return{userCandidates:i,systemCandidates:r}}async function tj(n,e,t){for(let i of e)if(await nN(i))return{id:n.id,label:n.label,envVar:n.envVar,settingsKey:n.settingsKey,command:i,executable:i,args:[],resolvedPath:i,available:!0,source:"candidate",detail:t,checkedCandidates:[i]}}function Fue(n,e){let t=[];return n.length&&t.push(`Checked common user locations: ${n.join("; ")}`),e.length&&t.push(`Checked system fallback locations: ${e.join("; ")}`),t.join(". ")}async function nb(n,e,t,i){let r=yue(e),s=rj(r.executable);if(!s.ok)return{id:n.id,label:n.label,envVar:n.envVar,settingsKey:n.settingsKey,configuredCommand:i,command:e,executable:r.executable,args:r.args,resolvedPath:void 0,available:!1,source:t,detail:s.reason,checkedCandidates:[r.executable]};if(Pue(r.executable)){let[o,l]=await Promise.all([nN(r.executable),Mue(r.executable)]),c=o&&l;return{id:n.id,label:n.label,envVar:n.envVar,settingsKey:n.settingsKey,configuredCommand:i,command:e,executable:r.executable,args:r.args,resolvedPath:c?r.executable:void 0,available:c,source:t,detail:c?`Using ${sb(t)} path.`:"Configured path was not found or is not executable.",checkedCandidates:[r.executable]}}let a=await Lue(r.executable);return{id:n.id,label:n.label,envVar:n.envVar,settingsKey:n.settingsKey,configuredCommand:i,command:e,executable:r.executable,args:r.args,resolvedPath:a,available:!!a,source:t,detail:a?`Resolved from ${sb(t)} via PATH lookup.`:"Command name was not found on PATH.",checkedCandidates:[r.executable]}}function sb(n){switch(n){case"settings":return"plugin settings";case"env":return"environment variable";case"candidate":return"known install location";case"path":return"PATH fallback"}}async function nj(n,e){var d,u,m;let t=Nue(n),{userCandidates:i,systemCandidates:r}=wue(t),s=JO(e);if(s)return nb(t,s,"settings",s);let a=JO((d=We==null?void 0:We.env)==null?void 0:d[t.envVar]);if(a)return nb(t,a,"env");for(let p of(u=t.envVarAliases)!=null?u:[]){let _=JO((m=We==null?void 0:We.env)==null?void 0:m[p]);if(_)return nb(t,_,"env")}let o=await tj(t,i,"Detected at a common user-managed install location.");if(o)return o;let l=[];for(let p of t.fallbackCommands){let _=await nb(t,p,"path");if(l.push(_),_.available)return _}let c=await tj(t,r,"Detected at a system fallback install location.");if(c)return c;let f=l.flatMap(p=>p.checkedCandidates),h=Fue(i,r);return{...l[0],detail:h?`Command name was not found on PATH. ${h}`:"Command name was not found on PATH.",checkedCandidates:[...i,...f,...r]}}async function ab(n){let e=await Promise.all(ij.map(t=>nj(t.id,n[t.settingsKey])));return Promise.all(e.map(async t=>({...t,dependencyChecks:await Oue(t)})))}async function os(n,e){var i;let t=await nj(n,e);return{command:(i=t.resolvedPath)!=null?i:t.executable,args:[...t.args]}}var We,Aue,ij,Iue,Jf=C(()=>{"use strict";ar();ar();ar();We=dv(),Aue=[".exe",".cmd",".bat",".com"];ij=[{id:"freecad",label:"Python (CadQuery/OCCT)",settingsKey:"freecadCommand",envVar:"AI3D_FREECAD_CMD",fallbackCommands:(We==null?void 0:We.platform)==="win32"?["py","python"]:["python3","python"],knownCandidates:(We==null?void 0:We.platform)==="win32"?[]:["/usr/local/bin/python3","/opt/homebrew/bin/python3","/opt/local/bin/python3","/usr/bin/python3"]},{id:"obj2gltf",label:"obj2gltf",settingsKey:"obj2gltfCommand",envVar:"AI3D_OBJ2GLTF_CMD",fallbackCommands:(We==null?void 0:We.platform)==="win32"?["obj2gltf.cmd"]:["obj2gltf"],knownCandidates:(We==null?void 0:We.platform)==="win32"?Rue("obj2gltf.cmd"):tN("obj2gltf")},{id:"fbx2gltf",label:"FBX2glTF",settingsKey:"fbx2gltfCommand",envVar:"AI3D_FBX2GLTF_CMD",fallbackCommands:(We==null?void 0:We.platform)==="win32"?["FBX2glTF.exe"]:["FBX2glTF","fbx2gltf"],knownCandidates:(We==null?void 0:We.platform)==="win32"?bue(zi("FBX2glTF","FBX2glTF-windows-x64.exe"),zi("FBX2glTF","FBX2glTF.exe")):tN("FBX2glTF","fbx2gltf")},{id:"assimp",label:"Python (trimesh)",settingsKey:"assimpCommand",envVar:"AI3D_ASSIMP_CMD",fallbackCommands:(We==null?void 0:We.platform)==="win32"?["py","python"]:["python3","python"],knownCandidates:(We==null?void 0:We.platform)==="win32"?[]:["/usr/local/bin/python3","/opt/homebrew/bin/python3","/opt/local/bin/python3","/usr/bin/python3"]},{id:"freecadcmd",label:"FreeCAD (SLDPRT)",settingsKey:"freecadcmdCommand",envVar:"AI3D_FREECADCMD",envVarAliases:["AI3D_FREECMDCMD"],fallbackCommands:(We==null?void 0:We.platform)==="win32"?["FreeCADCmd.exe"]:["freecadcmd","FreeCADCmd"],knownCandidates:xue()}];Iue=/[;|&<>$`\r\n\t{}()[\]\\]/});function Ic(n){if(n.includes('"'))throw new Error(`File path contains double-quote character, not supported for Python conversion: ${n}`);return n.replace(/\\/g,"/")}var ob=C(()=>{"use strict"});async function Vue(n){try{return await cs(n,fs),!0}catch(e){return!1}}function Gue(n,e,t){return new Promise((i,r)=>{aa(n,e,{timeout:t,windowsHide:!0,maxBuffer:50*1024*1024},(s,a,o)=>{if(!s){i();return}let l=(a!=null?a:"").toString().trim(),c=(o!=null?o:"").toString().trim(),f=[`CAD conversion failed: ${s.message}`,l?`stdout: ${l}`:"",c?`stderr: ${c}`:""].filter(Boolean);r(new Error(f.join(" | ")))})})}function kue(n,e,t){let i=Ic(n),r=Ic(e),s=t.toLowerCase().replace(/^\./,""),a=s==="step"||s==="stp",o=s==="iges"||s==="igs",l=["import cadquery as cq","import trimesh","import trimesh.visual","import numpy as np","import sys","import os","import re","import shutil","import tempfile","",`src = r"${i}"`,`out = r"${r}"`,`source_ext = "${s}"`,"src_occt = src","try:"," src.encode('ascii')","except UnicodeEncodeError:"," safe_src = os.path.join(tempfile.gettempdir(), f'ai3d-occt-source-{os.getpid()}.{source_ext}')"," shutil.copyfile(src, safe_src)"," src_occt = safe_src",""];return a?l.push("from OCP.STEPCAFControl import STEPCAFControl_Reader","from OCP.STEPControl import STEPControl_Reader","from OCP.XCAFDoc import XCAFDoc_DocumentTool, XCAFDoc_ColorType, XCAFDoc_ShapeTool","from OCP.TDocStd import TDocStd_Document","from OCP.TCollection import TCollection_ExtendedString","from OCP.Quantity import Quantity_Color","from OCP.TDF import TDF_ChildIterator, TDF_LabelSequence","from OCP.TDataStd import TDataStd_Name"):o&&l.push("from OCP.IGESControl import IGESControl_Reader"),l.push("from OCP.TopoDS import TopoDS","from OCP.TopAbs import TopAbs_FACE","from OCP.TopExp import TopExp_Explorer","from OCP.BRep import BRep_Tool","from OCP.BRepMesh import BRepMesh_IncrementalMesh","from OCP.TopLoc import TopLoc_Location","from OCP.IFSelect import IFSelect_RetDone"),a||l.push("from OCP.BRepTools import BRepTools"),l.push("","DEFAULT_COLOR = [180, 180, 180, 255]","","def triangulate_face(face, linear=0.1, angular=0.5):"," BRepMesh_IncrementalMesh(face, linear, False, angular, True)"," loc = TopLoc_Location()"," tri = BRep_Tool.Triangulation_s(face, loc)"," if tri is None:"," return None, None"," n = tri.NbNodes()"," verts = []"," for i in range(1, n + 1):"," p = tri.Node(i)"," if not loc.IsIdentity():"," p = p.Transformed(loc.Transformation())"," verts.append([p.X(), p.Y(), p.Z()])"," ntri = tri.NbTriangles()"," faces = []"," for i in range(1, ntri + 1):"," t = tri.Triangle(i)"," n1, n2, n3 = t.Get()"," faces.append([n1 - 1, n2 - 1, n3 - 1])"," return verts, faces"),a&&l.push("","def build_xde_color_lookup(step_path):",' """Load XDE with STEPCAFControl, extract per-face colors via surface signature."""'," from OCP.BRepAdaptor import BRepAdaptor_Surface"," lookup = {}"," try:"," reader = STEPCAFControl_Reader()"," reader.SetColorMode(True)"," reader.SetNameMode(True)"," status = reader.ReadFile(step_path)"," if status != IFSelect_RetDone:"," return lookup"," doc = TDocStd_Document(TCollection_ExtendedString('XmlOcaf'))"," reader.Transfer(doc)"," shape_tool = XCAFDoc_DocumentTool.ShapeTool_s(doc.Main())"," color_tool = XCAFDoc_DocumentTool.ColorTool_s(doc.Main())",""," def walk(label):"," if XCAFDoc_ShapeTool.IsShape_s(label):"," s = XCAFDoc_ShapeTool.GetShape_s(label)"," if s is not None and s.ShapeType() == TopAbs_FACE:"," c = Quantity_Color()"," if color_tool.GetColor(s, XCAFDoc_ColorType.XCAFDoc_ColorSurf, c):"," face = TopoDS.Face_s(s)"," try:"," adaptor = BRepAdaptor_Surface(face)"," u_r = (adaptor.FirstUParameter(), adaptor.LastUParameter())"," v_r = (adaptor.FirstVParameter(), adaptor.LastVParameter())"," key = (adaptor.GetType(), tuple(round(x, 4) for x in u_r), tuple(round(x, 4) for x in v_r))"," color = (c.Red(), c.Green(), c.Blue())"," if key not in lookup:"," lookup[key] = color"," except Exception:"," pass"," children = TDF_ChildIterator(label)"," while children.More():"," walk(children.Value())"," children.Next()",""," walk(doc.Main())"," except Exception as e:",' print(f"XDE color extraction failed: {e}", file=sys.stderr)'," return lookup","","def get_face_color(face, color_lookup):",' """Match a geometry face to an XDE face via surface signature, return color."""'," from OCP.BRepAdaptor import BRepAdaptor_Surface"," try:"," adaptor = BRepAdaptor_Surface(face)"," u_r = (adaptor.FirstUParameter(), adaptor.LastUParameter())"," v_r = (adaptor.FirstVParameter(), adaptor.LastVParameter())"," key = (adaptor.GetType(), tuple(round(x, 4) for x in u_r), tuple(round(x, 4) for x in v_r))"," return color_lookup.get(key)"," except Exception:"," return None","","def label_name(label):"," name_attr = TDataStd_Name()"," try:"," if label.FindAttribute(TDataStd_Name.GetID_s(), name_attr):"," return name_attr.Get().ToExtString()"," except Exception:"," pass"," return ''","","def clean_component_name(value, fallback):"," text = re.sub(r'\\s+', ' ', str(value or '')).strip()"," if not text or text.startswith('=>'):"," text = fallback"," return text[:96]","","def count_shape_faces(shape):"," count = 0"," exp = TopExp_Explorer(shape, TopAbs_FACE)"," while exp.More():"," count += 1"," exp.Next()"," return count","","def unique_component_name(name, used):"," base = clean_component_name(name, f'component-{len(used) + 1:03d}')"," candidate = base"," suffix = 2"," while candidate in used:"," candidate = f'{base}-{suffix}'"," suffix += 1"," used.add(candidate)"," return candidate","","def collect_xde_components(step_path):"," components = []"," try:"," reader = STEPCAFControl_Reader()"," reader.SetColorMode(True)"," reader.SetNameMode(True)"," status = reader.ReadFile(step_path)"," if status != IFSelect_RetDone:"," return components"," doc = TDocStd_Document(TCollection_ExtendedString('XmlOcaf'))"," if not reader.Transfer(doc):"," return components"," shape_tool = XCAFDoc_DocumentTool.ShapeTool_s(doc.Main())"," free = TDF_LabelSequence()"," shape_tool.GetFreeShapes(free)"," used_names = set()",""," def walk(label, path_parts):"," if not XCAFDoc_ShapeTool.IsShape_s(label):"," child = TDF_ChildIterator(label)"," while child.More():"," walk(child.Value(), path_parts)"," child.Next()"," return"," raw_name = label_name(label)"," next_path = path_parts + ([raw_name] if raw_name and not raw_name.startswith('=>') else [])"," shape = XCAFDoc_ShapeTool.GetShape_s(label)"," face_count = 0 if shape is None or shape.IsNull() else count_shape_faces(shape)"," try:"," is_assembly = XCAFDoc_ShapeTool.IsAssembly_s(label)"," except Exception:"," is_assembly = False"," try:"," is_component = XCAFDoc_ShapeTool.IsComponent_s(label)"," except Exception:"," is_component = False"," if face_count > 0 and not is_assembly:"," name = unique_component_name(raw_name, used_names)"," component_path = '/'.join([part for part in next_path if part]) or name"," components.append({"," 'name': name,"," 'path': component_path,"," 'shape': shape,"," 'face_count': face_count,"," 'is_component': is_component,"," })"," return"," child = TDF_ChildIterator(label)"," while child.More():"," walk(child.Value(), next_path)"," child.Next()",""," for index in range(1, free.Length() + 1):"," walk(free.Value(index), [])"," except Exception as e:"," print(f'XDE component extraction failed: {e}', file=sys.stderr)"," return components","","def mesh_from_shape(shape, color_lookup, name, component_path):"," try:"," BRepMesh_IncrementalMesh(shape, 0.1, False, 0.5, True)"," except Exception:"," pass"," verts_acc = []"," faces_acc = []"," colors_acc = []"," matched = 0"," total = 0"," exp = TopExp_Explorer(shape, TopAbs_FACE)"," while exp.More():"," face = TopoDS.Face_s(exp.Current())"," total += 1"," verts, faces = triangulate_face(face)"," if verts and faces:"," offset = len(verts_acc)"," verts_acc.extend(verts)"," for tri in faces:"," faces_acc.append([tri[0] + offset, tri[1] + offset, tri[2] + offset])"," color = get_face_color(face, color_lookup)"," if color:"," matched += 1"," r, g, b = color"," rgba = [int(r * 255), int(g * 255), int(b * 255), 255]"," else:"," rgba = DEFAULT_COLOR"," colors_acc.extend([rgba] * len(verts))"," exp.Next()"," if not verts_acc or not faces_acc:"," return None, total, matched"," mesh = trimesh.Trimesh("," vertices=np.array(verts_acc, dtype=float),"," faces=np.array(faces_acc, dtype=int),"," visual=trimesh.visual.ColorVisuals(vertex_colors=np.array(colors_acc, dtype=np.uint8)),"," process=True,"," )"," mesh.fix_normals()"," mesh.metadata.update({"," 'name': name,"," 'ai3d': {"," 'partId': name,"," 'componentId': name,"," 'occurrenceId': component_path,"," 'componentPath': component_path,"," 'displayName': name,"," },"," })"," return mesh, total, matched"),l.push(""),a?l.push("# STEP: build XDE color lookup + load geometry","color_lookup = build_xde_color_lookup(src_occt)",'print(f"XDE color lookup: {len(color_lookup)} surface signatures")',"xde_components = collect_xde_components(src_occt)","component_meshes = []","component_faces = 0","component_matched = 0","for component in xde_components:"," mesh_result, total, matched = mesh_from_shape(component['shape'], color_lookup, component['name'], component['path'])"," component_faces += total"," component_matched += matched"," if mesh_result is not None:"," component_meshes.append((component, mesh_result))","if len(component_meshes) > 1:"," scene = trimesh.Scene()"," for component, mesh_result in component_meshes:"," scene.add_geometry(mesh_result, node_name=component['name'], geom_name=component['name'])"," result = scene.export(file_type='glb')"," if isinstance(result, bytes):"," data = result"," elif isinstance(result, str):"," with open(result, 'rb') as f:"," data = f.read()"," else:"," data = bytes(result)"," with open(out, 'wb') as f:"," f.write(data)"," print(f'Converted {src} -> {out} ({len(data)} bytes, {len(component_meshes)} XDE components, {component_matched}/{component_faces} colored faces)')"," sys.exit(0)",'print(f"XDE component export unavailable: {len(component_meshes)} usable components from {len(xde_components)} labels; falling back to whole-shape mesh")',"","sr = STEPControl_Reader()","status = sr.ReadFile(src_occt)","if status != IFSelect_RetDone:",' print(f"Failed to read STEP file: {src}", file=sys.stderr)'," sys.exit(1)","sr.TransferRoots()","shape = sr.OneShape()"):o?l.push("# IGES: load geometry (no XDE color support for IGES)","ir = IGESControl_Reader()","status = ir.ReadFile(src_occt)","if status != IFSelect_RetDone:",' print(f"Failed to read IGES file: {src}", file=sys.stderr)'," sys.exit(1)","ir.TransferRoots()","shape = ir.OneShape()"):l.push("# BREP: load geometry from native OpenCascade format","from OCP.TopoDS import TopoDS_Shape","from OCP.BRep import BRep_Builder","shape = TopoDS_Shape()","builder = BRep_Builder()","success = BRepTools.Read_s(shape, src_occt, builder)","if not success:",' print(f"Failed to read BREP file: {src}", file=sys.stderr)'," sys.exit(1)"),l.push("","all_verts = []","all_faces = []","all_colors = []","matched_count = 0","total_faces = 0","","exp = TopExp_Explorer(shape, TopAbs_FACE)","while exp.More():"," face = TopoDS.Face_s(exp.Current())"," total_faces += 1"," verts, faces = triangulate_face(face)"," if verts and faces:"," offset = len(all_verts)"," all_verts.extend(verts)"," for tri in faces:"," all_faces.append([tri[0] + offset, tri[1] + offset, tri[2] + offset])"),a?l.push(" color = get_face_color(face, color_lookup)"," if color:"," matched_count += 1"," r, g, b = color"," rgba = [int(r * 255), int(g * 255), int(b * 255), 255]"," else:"," rgba = DEFAULT_COLOR"):l.push(" rgba = DEFAULT_COLOR"),l.push(" n = len(verts)"," all_colors.extend([rgba] * n)"," exp.Next()","",'print(f"Triangulated: {total_faces} faces, {len(all_verts)} verts, {matched_count} colored ({matched_count*100//max(total_faces,1)}%)")',"","if not all_verts or not all_faces:"," # Fallback: use CadQuery import (works for STEP/IGES, not BREP)"),a?l.push(" cq_shape = cq.importers.importStep(src_occt)"):o?l.push(" cq_shape = cq.importers.importStep(src_occt) # CadQuery reads IGES via importStep"):l.push(" cq_shape = cq.importers.importStep(src_occt) # CadQuery BREP import"),l.push(" cq.exporters.export(cq_shape, out, exportType='STL')"," mesh = trimesh.load(out)"," data = mesh.export(file_type='glb')"," if isinstance(data, str):"," with open(data, 'rb') as f:"," data = f.read()"," with open(out, 'wb') as f:"," f.write(data)",' print(f"Fallback CadQuery STL->GLB: {out} ({len(data)} bytes)")'," sys.exit(0)","","verts_arr = np.array(all_verts, dtype=float)","faces_arr = np.array(all_faces, dtype=int)","colors_arr = np.array(all_colors, dtype=np.uint8)","","mesh = trimesh.Trimesh("," vertices=verts_arr,"," faces=faces_arr,"," visual=trimesh.visual.ColorVisuals(vertex_colors=colors_arr),"," process=True,",")","mesh.fix_normals()","scene = trimesh.Scene([mesh])","","result = scene.export(file_type='glb')","if isinstance(result, bytes):"," data = result","elif isinstance(result, str):"," with open(result, 'rb') as f:"," data = f.read()","else:"," data = bytes(result)","","with open(out, 'wb') as f:"," f.write(data)","","print(f'Converted {src} -> {out} ({len(data)} bytes, {matched_count}/{total_faces} colored faces)')"),l.join(` -`)}var Bue,Uue,lb,sj=C(()=>{"use strict";ar();ar();ar();ar();Tn();Jf();ob();Bue=ki("freecad-converter"),Uue=300*1e3;lb=class{constructor(e){this.configuredCommand=e;this.id="freecad";this.sourceExts=["step","stp","iges","igs","brep"];this.targetExt="glb"}async getCacheKey(){let e=await os(this.id,this.configuredCommand);return`${this.id}:${e.command} ${e.args.join(" ")}`.trim()}async convert(e){if(!Yn(e.sourcePath))throw new Error(`Converter '${this.id}' requires an absolute source path, got '${e.sourcePath}'. Pass a file-system path to the conversion pipeline when invoking CAD conversion.`);let t=await os(this.id,this.configuredCommand),i=Mo(e.sourcePath),r=Co(e.sourcePath,sa(e.sourcePath)),s=zi(i,`${r}.ai3d-converted.glb`),a=zi(wd(),"ai3d-freecad"),o=zi(a,`${r}-${Date.now()}.py`);await Od(a,{recursive:!0}),await Ld(o,kue(e.sourcePath,s,e.sourceExt),"utf8"),Bue.info("run CAD conversion (CadQuery/OCCT)",{sourcePath:e.sourcePath,outputPath:s,command:t.command,args:t.args});try{await Gue(t.command,[...t.args,o],Uue)}catch(c){throw new Error(`CAD conversion failed for '${e.sourcePath}'. Ensure Python with cadquery is installed: pip install cadquery trimesh. Set Python command path in plugin settings or AI3D_FREECAD_CMD if Python is not discoverable. ${c instanceof Error?c.message:String(c)}`)}finally{Nd(o,{force:!0})}if(!await Vue(s))throw new Error(`CAD conversion finished but output was not found: '${s}'. Check that CadQuery supports this CAD format.`);if((await na(s)).byteLength===0)throw new Error(`CAD conversion output is empty: '${s}'.`);return{outputPath:s,outputExt:"glb",fromCache:!1,warnings:["Converted by local Python/CadQuery(OCCT) bridge."]}}}});async function zue(n){try{return await cs(n,fs),!0}catch(e){return!1}}function Xue(n,e,t){return new Promise((i,r)=>{aa(n,e,{timeout:t,windowsHide:!0,maxBuffer:50*1024*1024},(s,a,o)=>{if(!s){i();return}let l=(a!=null?a:"").toString().trim(),c=(o!=null?o:"").toString().trim(),f=[`obj2gltf command failed: ${s.message}`,l?`stdout: ${l}`:"",c?`stderr: ${c}`:""].filter(Boolean);r(new Error(f.join(" | ")))})})}var Wue,Hue,cb,aj=C(()=>{"use strict";ar();ar();ar();Tn();Jf();Wue=ki("obj2gltf-converter"),Hue=180*1e3;cb=class{constructor(e){this.configuredCommand=e;this.id="obj2gltf";this.sourceExts=["obj"];this.targetExt="glb"}async getCacheKey(){let e=await os(this.id,this.configuredCommand);return`${this.id}:${e.command} ${e.args.join(" ")}`.trim()}async convert(e){if(!Yn(e.sourcePath))throw new Error(`Converter '${this.id}' requires an absolute source path, got '${e.sourcePath}'. Pass a file-system path to the conversion pipeline when invoking obj2gltf.`);let t=await os(this.id,this.configuredCommand),i=Mo(e.sourcePath),r=Co(e.sourcePath,sa(e.sourcePath)),s=zi(i,`${r}.ai3d-converted.glb`);Wue.info("run obj2gltf conversion",{sourcePath:e.sourcePath,outputPath:s,command:t.command,args:t.args});try{await Xue(t.command,[...t.args,"-i",e.sourcePath,"-o",s,"-b"],Hue)}catch(o){throw new Error(`obj2gltf conversion failed for '${e.sourcePath}'. Set obj2gltf command path in plugin settings or AI3D_OBJ2GLTF_CMD if obj2gltf is not discoverable. ${o instanceof Error?o.message:String(o)}`)}if(!await zue(s))throw new Error(`obj2gltf conversion finished but output was not found: '${s}'.`);if((await na(s)).byteLength===0)throw new Error(`obj2gltf output file is empty: '${s}'.`);return{outputPath:s,outputExt:"glb",fromCache:!1,warnings:["Converted by local obj2gltf CLI bridge."]}}}});async function jue(n){try{return await cs(n,fs),!0}catch(e){return!1}}function que(n,e,t){return new Promise((i,r)=>{aa(n,e,{timeout:t,windowsHide:!0,maxBuffer:50*1024*1024},(s,a,o)=>{if(!s){i();return}let l=(a!=null?a:"").toString().trim(),c=(o!=null?o:"").toString().trim(),f=[`FBX2glTF command failed: ${s.message}`,l?`stdout: ${l}`:"",c?`stderr: ${c}`:""].filter(Boolean);r(new Error(f.join(" | ")))})})}var Yue,Kue,fb,oj=C(()=>{"use strict";ar();ar();ar();Tn();Jf();Yue=ki("fbx2gltf-converter"),Kue=180*1e3;fb=class{constructor(e){this.configuredCommand=e;this.id="fbx2gltf";this.sourceExts=["fbx"];this.targetExt="glb"}async getCacheKey(){let e=await os(this.id,this.configuredCommand);return`${this.id}:${e.command} ${e.args.join(" ")}`.trim()}async convert(e){if(!Yn(e.sourcePath))throw new Error(`Converter '${this.id}' requires an absolute source path, got '${e.sourcePath}'. Pass a file-system path to the conversion pipeline when invoking FBX2glTF.`);let t=await os(this.id,this.configuredCommand),i=Mo(e.sourcePath),r=Co(e.sourcePath,sa(e.sourcePath)),s=zi(i,`${r}.ai3d-converted.glb`);Yue.info("run FBX2glTF conversion",{sourcePath:e.sourcePath,outputPath:s,command:t.command,args:t.args});try{await que(t.command,[...t.args,"-i",e.sourcePath,"-o",s,"-b"],Kue)}catch(o){throw new Error(`FBX2glTF conversion failed for '${e.sourcePath}'. Set FBX2glTF command path in plugin settings or AI3D_FBX2GLTF_CMD if FBX2glTF is not discoverable. ${o instanceof Error?o.message:String(o)}`)}if(!await jue(s))throw new Error(`FBX2glTF conversion finished but output was not found: '${s}'.`);if((await na(s)).byteLength===0)throw new Error(`FBX2glTF output file is empty: '${s}'.`);return{outputPath:s,outputExt:"glb",fromCache:!1,warnings:["Converted by local FBX2glTF CLI bridge."]}}}});async function $ue(n){try{return await cs(n,fs),!0}catch(e){return!1}}function Jue(n,e,t){return new Promise((i,r)=>{aa(n,e,{timeout:t,windowsHide:!0,maxBuffer:50*1024*1024},(s,a,o)=>{if(!s){i();return}let l=(a!=null?a:"").toString().trim(),c=(o!=null?o:"").toString().trim(),f=[`mesh conversion failed: ${s.message}`,l?`stdout: ${l}`:"",c?`stderr: ${c}`:""].filter(Boolean);r(new Error(f.join(" | ")))})})}function eme(n,e){let t=Ic(n),i=Ic(e);return["import trimesh","import sys","",`src = r"${t}"`,`out = r"${i}"`,"","try:"," loaded = trimesh.load(src, force=None)","except Exception as e:",' print(f"Failed to load {src}: {e}", file=sys.stderr)'," sys.exit(1)","","if isinstance(loaded, trimesh.Scene):"," scene = loaded","elif isinstance(loaded, trimesh.Trimesh):"," scene = trimesh.Scene([loaded])","else:",' print(f"Unsupported type: {type(loaded)}", file=sys.stderr)'," sys.exit(1)","","try:"," data = scene.export(file_type='glb')","except Exception as e:",' print(f"Failed to export GLB: {e}", file=sys.stderr)'," sys.exit(1)","","with open(out, 'wb') as f:"," f.write(data)","","print(f'Converted {src} -> {out} ({len(data)} bytes)')"].join(` -`)}var Zue,Que,hb,lj=C(()=>{"use strict";ar();ar();ar();ar();Tn();Jf();ob();Zue=ki("assimp-converter"),Que=300*1e3;hb=class{constructor(e){this.configuredCommand=e;this.id="assimp";this.sourceExts=["3mf","dae"];this.targetExt="glb"}async getCacheKey(){let e=await os(this.id,this.configuredCommand);return`${this.id}:${e.command} ${e.args.join(" ")}`.trim()}async convert(e){if(!Yn(e.sourcePath))throw new Error(`Converter '${this.id}' requires an absolute source path, got '${e.sourcePath}'. Pass a file-system path to the conversion pipeline when invoking mesh conversion.`);let t=await os(this.id,this.configuredCommand),i=Mo(e.sourcePath),r=Co(e.sourcePath,sa(e.sourcePath)),s=zi(i,`${r}.ai3d-converted.glb`),a=zi(wd(),"ai3d-mesh-convert"),o=zi(a,`${r}-${Date.now()}.py`);await Od(a,{recursive:!0}),await Ld(o,eme(e.sourcePath,s),"utf8"),Zue.info("run mesh conversion (trimesh)",{sourcePath:e.sourcePath,outputPath:s,command:t.command,args:t.args});try{await Jue(t.command,[...t.args,o],Que)}catch(c){throw new Error(`Mesh conversion failed for '${e.sourcePath}'. Ensure Python with trimesh is installed: pip install trimesh numpy networkx pycollada. Set Python command path in plugin settings or AI3D_ASSIMP_CMD if Python is not discoverable. ${c instanceof Error?c.message:String(c)}`)}finally{Nd(o,{force:!0})}if(!await $ue(s))throw new Error(`Mesh conversion finished but output was not found: '${s}'. Check that trimesh supports this format.`);if((await na(s)).byteLength===0)throw new Error(`Mesh conversion output is empty: '${s}'.`);return{outputPath:s,outputExt:"glb",fromCache:!1,warnings:["Converted by local Python/trimesh bridge."]}}}});async function ime(n){try{return await cs(n,fs),!0}catch(e){return!1}}function rme(n,e,t){return new Promise((i,r)=>{aa(n,e,{timeout:t,windowsHide:!0,maxBuffer:50*1024*1024},(s,a,o)=>{if(!s){i({stdout:a!=null?a:"",stderr:o!=null?o:""});return}let l=(a!=null?a:"").toString().trim(),c=(o!=null?o:"").toString().trim(),f=[`SLDPRT conversion failed: ${s.message}`,l?`stdout: ${l}`:"",c?`stderr: ${c}`:""].filter(Boolean);r(new Error(f.join(" | ")))})})}function nme(n,e){let t=Ic(n),i=Ic(e),r=i.replace(/\.glb$/i,".intermediate.step");return["import sys","import os","",`src = r"${t}"`,`out = r"${i}"`,`step_out = r"${r}"`,"","# Step 1: Import SLDPRT via FreeCAD","try:"," import FreeCAD"," import ImportGui"," import Mesh","except ImportError as e:",' print(f"FreeCAD modules not available: {e}", file=sys.stderr)',' print("Ensure this script runs under FreeCADCmd (not system Python).", file=sys.stderr)'," sys.exit(1)","","print(f'Opening SLDPRT: {src}')","try:"," doc = FreeCAD.newDocument('Convert')"," ImportGui.open(src, doc.Name)","except Exception as e:",' print(f"Failed to open SLDPRT file: {e}", file=sys.stderr)'," sys.exit(1)","","if not doc.Objects:",' print("SLDPRT file imported but contains no objects", file=sys.stderr)'," sys.exit(1)","",'print(f"Imported {len(doc.Objects)} object(s) from SLDPRT")',"","# Step 2: Export to STEP (intermediate)","try:"," import Import"," objs = [o for o in doc.Objects if hasattr(o, 'Shape')]"," if not objs:",' print("No shape objects found after import", file=sys.stderr)'," sys.exit(1)"," Import.export(objs, step_out)",' print(f"Exported intermediate STEP: {step_out}")',"except Exception as e:",' print(f"Failed to export STEP: {e}", file=sys.stderr)'," sys.exit(1)","","FreeCAD.closeDocument(doc.Name)","","# Step 3: Convert STEP to GLB using OCP (same pipeline as FreecadConverter)","import trimesh","import trimesh.visual","import numpy as np","","from OCP.STEPControl import STEPControl_Reader","from OCP.TopoDS import TopoDS","from OCP.TopAbs import TopAbs_FACE","from OCP.TopExp import TopExp_Explorer","from OCP.BRep import BRep_Tool","from OCP.BRepMesh import BRepMesh_IncrementalMesh","from OCP.TopLoc import TopLoc_Location","from OCP.IFSelect import IFSelect_RetDone","","DEFAULT_COLOR = [180, 180, 180, 255]","","def triangulate_face(face, linear=0.1, angular=0.5):"," BRepMesh_IncrementalMesh(face, linear, False, angular, True)"," loc = TopLoc_Location()"," tri = BRep_Tool.Triangulation_s(face, loc)"," if tri is None:"," return None, None"," n = tri.NbNodes()"," verts = []"," for i in range(1, n + 1):"," p = tri.Node(i)"," if not loc.IsIdentity():"," p = p.Transformed(loc.Transformation())"," verts.append([p.X(), p.Y(), p.Z()])"," ntri = tri.NbTriangles()"," faces = []"," for i in range(1, ntri + 1):"," t = tri.Triangle(i)"," n1, n2, n3 = t.Get()"," faces.append([n1 - 1, n2 - 1, n3 - 1])"," return verts, faces","","sr = STEPControl_Reader()","status = sr.ReadFile(step_out)","if status != IFSelect_RetDone:",' print(f"Failed to read intermediate STEP: {step_out}", file=sys.stderr)'," sys.exit(1)","sr.TransferRoots()","shape = sr.OneShape()","","all_verts = []","all_faces = []","all_colors = []","total_faces = 0","","exp = TopExp_Explorer(shape, TopAbs_FACE)","while exp.More():"," face = TopoDS.Face_s(exp.Current())"," total_faces += 1"," verts, faces = triangulate_face(face)"," if verts and faces:"," offset = len(all_verts)"," all_verts.extend(verts)"," for tri in faces:"," all_faces.append([tri[0] + offset, tri[1] + offset, tri[2] + offset])"," all_colors.extend([DEFAULT_COLOR] * len(verts))"," exp.Next()","","if not all_verts or not all_faces:",' print(f"No geometry extracted from STEP ({total_faces} faces scanned)", file=sys.stderr)'," sys.exit(1)","",'print(f"Triangulated: {total_faces} faces, {len(all_verts)} verts")',"","verts_arr = np.array(all_verts, dtype=float)","faces_arr = np.array(all_faces, dtype=int)","colors_arr = np.array(all_colors, dtype=np.uint8)","","mesh = trimesh.Trimesh("," vertices=verts_arr,"," faces=faces_arr,"," visual=trimesh.visual.ColorVisuals(vertex_colors=colors_arr),"," process=True,",")","mesh.fix_normals()","scene = trimesh.Scene([mesh])","","result = scene.export(file_type='glb')","if isinstance(result, bytes):"," data = result","elif isinstance(result, str):"," with open(result, 'rb') as f:"," data = f.read()","else:"," data = bytes(result)","","with open(out, 'wb') as f:"," f.write(data)","","# Cleanup intermediate STEP","try:"," os.remove(step_out)","except OSError:"," pass","","print(f'Converted {src} -> {out} ({len(data)} bytes, {total_faces} faces)')"].join(` -`)}var sN,tme,db,cj=C(()=>{"use strict";ar();ar();ar();ar();Tn();Jf();ob();sN=ki("sldprt-converter"),tme=600*1e3;db=class{constructor(e){this.configuredCommand=e;this.id="sldprt";this.sourceExts=["sldprt"];this.targetExt="glb"}async getCacheKey(){let e=await os("freecadcmd",this.configuredCommand);return`${this.id}:${e.command} ${e.args.join(" ")}`.trim()}async convert(e){if(!Yn(e.sourcePath))throw new Error(`Converter '${this.id}' requires an absolute source path, got '${e.sourcePath}'. Pass a file-system path to the conversion pipeline when invoking SLDPRT conversion.`);let t=await os("freecadcmd",this.configuredCommand),i=Mo(e.sourcePath),r=Co(e.sourcePath,sa(e.sourcePath)),s=zi(i,`${r}.ai3d-converted.glb`),a=zi(wd(),"ai3d-sldprt"),o=zi(a,`${r}-${Date.now()}.py`);await Od(a,{recursive:!0}),await Ld(o,nme(e.sourcePath,s),"utf8"),sN.info("run SLDPRT conversion (FreeCAD + OCP)",{sourcePath:e.sourcePath,outputPath:s,command:t.command,args:t.args});try{let{stdout:c,stderr:f}=await rme(t.command,[...t.args,o],tme);c&&sN.info("FreeCAD stdout",{stdout:c.trim().slice(0,500)}),f&&sN.warn("FreeCAD stderr",{stderr:f.trim().slice(0,500)})}catch(c){throw new Error(`SLDPRT conversion failed for '${e.sourcePath}'. Ensure FreeCAD is installed (https://www.freecad.org/downloads.php). Set FreeCADCmd path in plugin settings or AI3D_FREECADCMD env var. ${c instanceof Error?c.message:String(c)}`)}finally{Nd(o,{force:!0})}if(!await ime(s))throw new Error(`SLDPRT conversion finished but output was not found: '${s}'. Check that FreeCAD can import this SolidWorks file version.`);if((await na(s)).byteLength===0)throw new Error(`SLDPRT conversion output is empty: '${s}'.`);return{outputPath:s,outputExt:"glb",fromCache:!1,warnings:["Converted by local FreeCAD + OpenCASCADE bridge."]}}}});function gd(n){var r;let e=new rb,t=new Set((r=n==null?void 0:n.enabledConverterIds)!=null?r:[]);aN.debug("create conversion manager",{enabledConverterIds:[...t]});let i=[new lb(n==null?void 0:n.freecadCommand),new cb(n==null?void 0:n.obj2gltfCommand),new fb(n==null?void 0:n.fbx2gltfCommand),new hb(n==null?void 0:n.assimpCommand),new db(n==null?void 0:n.freecadcmdCommand)];for(let s of i)t.has(s.id)?(e.registerConverter(s),aN.info("enabled converter",{converterId:s.id})):aN.debug("converter disabled",{converterId:s.id});return e}var aN,ub=C(()=>{"use strict";ej();sj();aj();oj();lj();cj();Tn();aN=ki("conversion-factory")});function fj(n){let e=Ba(n.sourceExt),t=[];return e!==n.sourceExt&&t.push(`Normalized extension '${n.sourceExt}' -> '${e}'.`),sme.debug("prepare direct load",{path:n.path,sourceExt:n.sourceExt,normalizedExt:e,warningCount:t.length}),{effectivePath:n.path,effectiveExt:e,warnings:t}}var sme,hj=C(()=>{"use strict";Io();Tn();sme=ki("direct-load-service")});function mb(n){return`.${n.trim().toLowerCase()}`}function up(n){return n instanceof vd}function oN(n){var e;if(n instanceof vd){let t=(e=ame[n.converterId])!=null?e:n.converterId;return dr("modelLoad.warningMessage",{ext:mb(n.sourceExt),converterName:t})}return n instanceof dp?dr("modelLoad.mobileWarningMessage",{ext:mb(n.sourceExt)}):dr("modelLoad.errorMessage",{reason:n instanceof Error?n.message:String(n)})}function mp(n){return n instanceof vd?{level:"warning",title:J("modelLoad.warningTitle"),message:oN(n),hint:J("modelLoad.warningHint")}:n instanceof dp?{level:"warning",title:J("modelLoad.warningTitle"),message:oN(n),hint:J("modelLoad.mobileWarningHint")}:{level:"error",title:J("modelLoad.errorTitle"),message:oN(n),hint:J("modelLoad.errorHint")}}var ame,vd,dp,pp=C(()=>{"use strict";ra();ame={freecad:"FreeCAD",obj2gltf:"obj2gltf",fbx2gltf:"FBX2glTF",assimp:"mesh",sldprt:"SolidWorks"};vd=class extends Error{constructor(t,i){super(`Converter '${t}' is not registered for ${mb(i)}. Enable the matching converter in plugin settings before loading this format.`);this.converterId=t;this.sourceExt=i;this.name="MissingConverterError"}},dp=class extends Error{constructor(t){super(`Format ${mb(t)} requires local conversion tools that are unavailable on iOS, iPadOS, and Android.`);this.sourceExt=t;this.name="MobileConversionUnavailableError"}}});function lme(n,e,t){return n.converterId!==e?!1:t?n.converterId===t.converterId&&n.converterCacheKey===t.cacheKey:!0}async function cme(n){if(!n)return!1;try{return await cs(n,fs),!0}catch(e){return!1}}async function dj(n){var a,o,l,c,f,h,d;if(n.capability.strategy!=="convert")throw new Error(`Expected convert strategy, got '${n.capability.strategy}'.`);let e=n.capability.converterId,t=(a=n.capability.outputFormat)!=null?a:"glb";if(!e)throw new Error(`Format .${n.sourceExt} does not define a converter id.`);ev.info("prepare conversion route",{sourcePath:n.sourcePath,sourceExt:n.sourceExt,targetExt:t,converterId:e});let i=n.conversionManager.canConvert(n.sourceExt)?await n.conversionManager.getConverterCacheIdentity(n.sourceExt):void 0,r=(o=n.convertedAssetCache)==null?void 0:o.get(n.sourcePath,n.sourceExt,t);if(r)if(!await cme(r.outputPath))ev.warn("conversion cache stale",{sourcePath:n.sourcePath,sourceExt:n.sourceExt,targetExt:t,outputPath:r.outputPath}),(l=n.convertedAssetCache)==null||l.delete(n.sourcePath,n.sourceExt,t);else if(!lme(r,e,i))ev.warn("conversion cache identity mismatch",{sourcePath:n.sourcePath,sourceExt:n.sourceExt,targetExt:t,cachedConverterId:r.converterId,cachedConverterCacheKey:r.converterCacheKey,currentConverterId:(c=i==null?void 0:i.converterId)!=null?c:e,currentConverterCacheKey:i==null?void 0:i.cacheKey}),(f=n.convertedAssetCache)==null||f.delete(n.sourcePath,n.sourceExt,t);else return ev.info("conversion cache hit",{sourcePath:n.sourcePath,sourceExt:n.sourceExt,targetExt:t,outputPath:r.outputPath}),{effectivePath:r.outputPath,effectiveExt:r.outputExt,warnings:[...r.warnings,"Using cached conversion output."]};if(!n.conversionManager.canConvert(n.sourceExt))throw new vd(e,n.sourceExt);let s=await n.conversionManager.convert({sourcePath:n.sourcePath,sourceExt:n.sourceExt,targetExt:t});return(d=n.convertedAssetCache)==null||d.set({cacheVersion:2,converterId:e,converterCacheKey:(h=i==null?void 0:i.cacheKey)!=null?h:e,sourcePath:n.sourcePath,sourceExt:n.sourceExt,targetExt:t,outputPath:s.outputPath,outputExt:s.outputExt,warnings:s.warnings,createdAt:Date.now()}),ev.info("conversion route done",{sourcePath:n.sourcePath,outputPath:s.outputPath,warningCount:s.warnings.length}),{effectivePath:s.outputPath,effectiveExt:s.outputExt,warnings:s.warnings}}var ev,uj=C(()=>{"use strict";Nb();Tn();ar();pp();ev=ki("conversion-service")});function fme(n,e){var t;return!!((t=n.preferConversionExts)!=null&&t.includes(e))}async function Ed(n){var a,o;let e=Ba((a=n.path.split(".").pop())!=null?a:""),t=wb(e);if(Mc.info("prepare model input",{path:n.path,sourceExt:e}),!t||!t.enabled)throw Mc.warn("unsupported format",{sourceExt:e,path:n.path}),Ap(e)?new Error("SPLAT preview is disabled in packaged builds. Local-only .splat support is planned; .spz and .sog remain unavailable until their decoders can be bundled locally."):new Error(`Unsupported format: .${e}`);let i=fme(n,e);if(t.strategy==="convert"||i&&!!t.converterId){if(ur())throw Mc.warn("conversion unavailable on mobile",{sourceExt:e,path:n.path}),new dp(e);if(!n.absolutePath)throw Mc.error("filesystem path missing for conversion",{sourceExt:e,path:n.path}),new Error(`Format .${e} requires a local filesystem path for conversion, but none was resolved for '${n.path}'.`);if(!n.conversionManager)throw Mc.error("conversion manager missing",{sourceExt:e,path:n.path}),new Error(`Format .${e} requires conversion support, but no conversion manager is available.`);let l=t.strategy==="convert"?t:{...t,strategy:"convert",outputFormat:(o=t.outputFormat)!=null?o:"glb"};if(!l.converterId)throw Mc.error("preferred conversion route missing converter id",{sourceExt:e,path:n.path}),new Error(`Format .${e} is configured to prefer conversion, but no converter id is defined.`);i&&t.strategy==="direct"&&Mc.info("preferred conversion route",{sourceExt:e,path:n.path,converterId:l.converterId});let c=await dj({sourcePath:n.absolutePath,sourceExt:e,capability:l,conversionManager:n.conversionManager,convertedAssetCache:n.convertedAssetCache});return Mc.info("conversion completed",{sourceExt:e,outputExt:c.effectiveExt,outputPath:c.effectivePath,warningCount:c.warnings.length}),{sourcePath:n.path,sourceExt:e,strategy:"convert",effectivePath:c.effectivePath,effectiveExt:c.effectiveExt,warnings:c.warnings}}let s=fj({path:n.path,sourceExt:e});return Mc.debug("direct route",{sourceExt:e,path:n.path,warningCount:s.warnings.length}),{sourcePath:n.path,sourceExt:e,strategy:t.strategy,effectivePath:s.effectivePath,effectiveExt:s.effectiveExt,warnings:s.warnings}}var Mc,pb=C(()=>{"use strict";Io();hj();uj();pp();Tn();Ks();Mc=ki("model-pipeline")});function tv(n){return{path:n.effectivePath,ext:n.effectiveExt,strategy:n.strategy,sourcePath:n.sourcePath,sourceExt:n.sourceExt,warnings:n.warnings}}var lN=C(()=>{"use strict"});function Sd(n){let e=[];return n.preferObj2gltfForObj&&e.push("obj"),n.preferFbx2gltfForFbx&&e.push("fbx"),e}var _b=C(()=>{"use strict"});function iv(n){return n.replace(/\[\[([^\]|]+)\|([^\]]+)\]\]/g,"$2").replace(/\[\[([^\]]+)\]\]/g,"$1").replace(/\[([^\]]+)\]\([^)]*\)/g,"$1").replace(/[*_~`]+/g,"").replace(/==([^=]+)==/g,"$1").replace(/\s+/g," ").trim()}function hme(n,e){let t=e.toLowerCase().trim();if(!t)return[];let i=[],r=n.vault.getMarkdownFiles();for(let s of r){let a=n.metadataCache.getFileCache(s);if(a!=null&&a.headings)for(let o of a.headings)o.heading.toLowerCase().includes(t)&&i.push({notePath:s.path,heading:o.heading,level:o.level})}return i.slice(0,15)}function pj(n){return e=>hme(n,e)}async function dme(n,e,t){try{let i=n.vault.getAbstractFileByPath(e);if(!(i instanceof mj.TFile))return null;let s=(await n.vault.cachedRead(i)).split(` +}`;T.ShadersStore[GO]||(T.ShadersStore[GO]=IK);eue={name:GO,shader:IK}});var yK,MK,YR,tue,iue,CK,HO,PK=C(()=>{As();ki();_m();Ge();so();am();gy();Vn();Jy();zt();di();Gh();mf();zy();jo();Pt();Object.defineProperty(Jt.prototype,"forceShowBoundingBoxes",{get:function(){return this._forceShowBoundingBoxes||!1},set:function(n){this._forceShowBoundingBoxes=n,n&&this.getBoundingBoxRenderer()},enumerable:!0,configurable:!0});Jt.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer||(this._boundingBoxRenderer=new HO(this)),this._boundingBoxRenderer};Object.defineProperty(vr.prototype,"showBoundingBox",{get:function(){return this._showBoundingBox||!1},set:function(n){this._showBoundingBox=n,n&&this.getScene().getBoundingBoxRenderer()},enumerable:!0,configurable:!0});yK=K.Identity(),MK=new K,YR=new b,tue=new b,iue=yK.asArray(),CK=new Ef(YR,YR),HO=class{get shaderLanguage(){return this._shaderLanguage}constructor(e){this.name=et.NAME_BOUNDINGBOXRENDERER,this.frontColor=new ve(1,1,1),this.backColor=new ve(.1,.1,.1),this.showBackLines=!0,this.onBeforeBoxRenderingObservable=new ie,this.onAfterBoxRenderingObservable=new ie,this.onResourcesReadyObservable=new ie,this.enabled=!0,this._shaderLanguage=0,this.renderList=new Bi(32),this._vertexBuffers={},this._fillIndexBuffer=null,this._fillIndexData=null,this._matrixBuffer=null,this._matrices=null,this._useInstances=!1,this._drawWrapperFront=null,this._drawWrapperBack=null,this.scene=e,this.scene.getEngine().isWebGPU&&(this._shaderLanguage=1),e._addComponent(this),this._uniformBufferFront=new hr(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererFront",!0),this._buildUniformLayout(this._uniformBufferFront),this._uniformBufferBack=new hr(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererBack",!0),this._buildUniformLayout(this._uniformBufferBack)}_buildUniformLayout(e){e.addUniform("color",4),e.addUniform("world",16),e.addUniform("viewProjection",16),e.addUniform("viewProjectionR",16),e.create()}register(){this.scene._beforeEvaluateActiveMeshStage.registerStep(et.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER,this,this.reset),this.scene._preActiveMeshStage.registerStep(et.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER,this,this._preActiveMesh),this.scene._evaluateSubMeshStage.registerStep(et.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER,this,this._evaluateSubMesh),this.scene._afterRenderingGroupDrawStage.registerStep(et.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER,this,this.render)}async whenReadyAsync(e=16,t=3e4){return this._prepareResources(),await new Promise(i=>{Ko(()=>this._colorShader.isReady(),()=>{i()},(r,s)=>{s?(te.Error("BoundingBoxRenderer: Timeout while waiting for the renderer to be ready."),r&&te.Error(r)):(te.Error("BoundingBoxRenderer: An unexpected error occurred while waiting for the renderer to be ready."),r&&(te.Error(r),r.stack&&te.Error(r.stack)))},e,t)})}_evaluateSubMesh(e,t){if(e.showSubMeshesBoundingBox){let i=t.getBoundingInfo();i!=null&&(i.boundingBox._tag=e.renderingGroupId,this.renderList.push(i.boundingBox))}}_preActiveMesh(e){if(e.showBoundingBox||this.scene.forceShowBoundingBoxes){let t=e.getBoundingInfo();t.boundingBox._tag=e.renderingGroupId,this.renderList.push(t.boundingBox)}}_prepareResources(){if(this._colorShader)return;this._colorShader=new vo("colorShader",this.scene,"boundingBoxRenderer",{attributes:[L.PositionKind,"world0","world1","world2","world3"],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"],shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{this._shaderLanguage===1?await Promise.all([Promise.resolve().then(()=>(LO(),DO)),Promise.resolve().then(()=>(wO(),NO))]):await Promise.all([Promise.resolve().then(()=>(VO(),UO)),Promise.resolve().then(()=>(WO(),kO))])}},!1),this._colorShader.setDefine("INSTANCES",this._useInstances),this._colorShader.doNotSerialize=!0,this._colorShader.reservedDataStore={hidden:!0},this._colorShaderForOcclusionQuery=new vo("colorShaderOccQuery",this.scene,"boundingBoxRenderer",{attributes:[L.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"],shaderLanguage:this._shaderLanguage,extraInitializationsAsync:async()=>{this._shaderLanguage===1?await Promise.all([Promise.resolve().then(()=>(LO(),DO)),Promise.resolve().then(()=>(wO(),NO))]):await Promise.all([Promise.resolve().then(()=>(VO(),UO)),Promise.resolve().then(()=>(WO(),kO))])}},!0),this._colorShaderForOcclusionQuery.doNotSerialize=!0,this._colorShaderForOcclusionQuery.reservedDataStore={hidden:!0};let e=this.scene.getEngine(),t=HA({size:1});this._vertexBuffers[L.PositionKind]=new L(e,t.positions,L.PositionKind,!1),this._createIndexBuffer(),this._fillIndexData=t.indices,this.onResourcesReadyObservable.notifyObservers(this)}_createIndexBuffer(){let e=this.scene.getEngine();this._indexBuffer=e.createIndexBuffer([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,7,1,6,2,5,3,4])}rebuild(){let e=this._vertexBuffers[L.PositionKind];e&&e._rebuild(),this._createIndexBuffer(),this._matrixBuffer&&this._matrixBuffer._rebuild()}reset(){this.renderList.reset()}render(e){var r,s;if(this.renderList.length===0||!this.enabled)return;if(this._useInstances){this._renderInstanced(e);return}if(this._prepareResources(),!this._colorShader.isReady())return;let t=this.scene.getEngine();t.setDepthWrite(!1);let i=this.scene.getTransformMatrix();for(let a=0;ar*2)&&(i=new Float32Array(r),this._matrices=i),this.onBeforeBoxRenderingObservable.notifyObservers(CK);let s=0,a=this.scene.floatingOriginOffset;for(let g=0;g{"use strict";Ge();qP();zt();oo();PK();ws();rM();Qf=class Qf{constructor(e,t,i){this.occlusionDirection=b.Zero();this.occlusionRay=new Yr(b.Zero(),b.Zero(),1);this.lastOccluded=!1;this.selected=null;this.partPointerActive=!1;this.activePointerId=null;this.scene=e,this.camera=t,this.meshes=i,this.setBoundingBoxColor(Qf.BBOX_VISIBLE)}getParts(){return this.meshes}getPartId(e){return e.uniqueId}isDisposed(e){return e.isDisposed()}captureTransform(e){var t,i;return{parent:e.parent,position:e.position.clone(),rotation:e.rotation.clone(),rotationQuaternion:(i=(t=e.rotationQuaternion)==null?void 0:t.clone())!=null?i:null,scaling:e.scaling.clone()}}restoreTransform(e,t){var i,r;e.setParent(t.parent),e.position.copyFrom(t.position),e.rotation.copyFrom(t.rotation),e.rotationQuaternion=(r=(i=t.rotationQuaternion)==null?void 0:i.clone())!=null?r:null,e.scaling.copyFrom(t.scaling),e.computeWorldMatrix(!0)}subscribe(e){let t=this.scene.getEngine().getRenderingCanvas();t==null||t.classList.add("ai3d-disassembly-active");let i=this.scene.onPointerObservable.add(s=>{var o,l,c,f;let a=s.event;if(a.isPrimary!==!1){if(s.type===st.POINTERDOWN){if(a.button!==0)return;let h=(l=(o=s.pickInfo)==null?void 0:o.pickedMesh)!=null?l:null;if(this.partPointerActive=!!this.resolvePart(h),this.partPointerActive){a.preventDefault(),a.stopPropagation(),this.activePointerId=a.pointerId;try{(c=t==null?void 0:t.setPointerCapture)==null||c.call(t,a.pointerId)}catch(d){}this.camera.detachControl()}e.onPointerDown(h,a)}else if(s.type===st.POINTERMOVE){if(this.activePointerId!==null&&a.pointerId!==this.activePointerId)return;this.partPointerActive&&(a.preventDefault(),a.stopPropagation()),e.onPointerMove(a)}else if(s.type===st.POINTERUP){if(this.activePointerId!==null&&a.pointerId!==this.activePointerId)return;if(this.partPointerActive&&(a.preventDefault(),a.stopPropagation()),e.onPointerUp(a),this.activePointerId!==null&&((f=t==null?void 0:t.hasPointerCapture)!=null&&f.call(t,this.activePointerId)))try{t.releasePointerCapture(this.activePointerId)}catch(h){}this.partPointerActive=!1,this.activePointerId=null,this.camera.attachControl(this.scene.getEngine().getRenderingCanvas(),!0)}}}),r=this.scene.onAfterRenderCameraObservable.add(s=>{s===this.camera&&e.onRender()});return()=>{var s;if(this.scene.onPointerObservable.remove(i),this.scene.onAfterRenderCameraObservable.remove(r),t==null||t.classList.remove("ai3d-disassembly-active","ai3d-disassembly-dragging"),this.activePointerId!==null&&((s=t==null?void 0:t.hasPointerCapture)!=null&&s.call(t,this.activePointerId)))try{t.releasePointerCapture(this.activePointerId)}catch(a){}this.partPointerActive=!1,this.activePointerId=null,this.camera.attachControl(t,!0)}}resolvePart(e){if(!e||typeof e!="object")return null;if(this.isMeshInSet(e))return e;let t=e.parent;return t&&"uniqueId"in t&&this.isMeshInSet(t)?t:null}setSelected(e){this.selected&&!this.selected.isDisposed()&&(this.selected.showBoundingBox=!1),this.selected=e,this.lastOccluded=!1,this.setBoundingBoxColor(Qf.BBOX_VISIBLE),this.selected&&!this.selected.isDisposed()&&(this.selected.showBoundingBox=!0)}beginDrag(e,t){var o,l,c;let i=this.getPointOnDragPlane(e,t);if(!i)return null;t.preventDefault(),t.stopPropagation(),(o=this.scene.getEngine().getRenderingCanvas())==null||o.classList.add("ai3d-disassembly-dragging"),e.setParent(null),e.computeWorldMatrix(!0),t.shiftKey&&!e.rotationQuaternion&&(e.rotationQuaternion=Xe.FromEulerVector(e.rotation),e.rotation.set(0,0,0));let r=e.getBoundingInfo().boundingBox.centerWorld.clone(),s=Ud(Ht(i),Ht(this.camera.getForwardRay().direction));if(!s)return null;let a={mesh:e,mode:t.shiftKey?"rotate":"move",plane:s,startPoint:i,startPosition:e.position.clone(),startRotationQuaternion:(c=(l=e.rotationQuaternion)==null?void 0:l.clone())!=null?c:null,pivot:r,pointerX:t.clientX,pointerY:t.clientY};return this.camera.detachControl(),a}updateDrag(e,t){if(t.preventDefault(),t.stopPropagation(),e.mode==="rotate"){this.updateRotation(e,t);return}let i=this.getRayPlanePoint(t,e.plane);if(!i)return;let r=i.subtract(e.startPoint);e.mesh.position=e.startPosition.add(r),e.mesh.computeWorldMatrix(!0)}endDrag(e){var t;(t=this.scene.getEngine().getRenderingCanvas())==null||t.classList.remove("ai3d-disassembly-dragging"),this.camera.attachControl(this.scene.getEngine().getRenderingCanvas(),!0)}updateSelectionOcclusion(e){let t=e.getBoundingInfo().boundingBox.centerWorld,i=this.camera.position,r=Nc(Ht(i),Ht(t));if(!r)return;let s=this.occlusionDirection;s.set(r.direction.x,r.direction.y,r.direction.z),this.occlusionRay.origin=i,this.occlusionRay.direction=s,this.occlusionRay.length=r.distance;let a=this.scene.pickWithRay(this.occlusionRay),o=!!(a!=null&&a.hit)&&Oc(a.distance,r.distance,r.epsilon);o!==this.lastOccluded&&(this.lastOccluded=o,this.setBoundingBoxColor(o?Qf.BBOX_OCCLUDED:Qf.BBOX_VISIBLE))}isMeshInSet(e){return this.meshes.includes(e)}setBoundingBoxColor(e){var i,r;let t=(r=(i=this.scene).getBoundingBoxRenderer)==null?void 0:r.call(i);t&&(t.frontColor=e,t.backColor=e)}updateRotation(e,t){if(!e.startRotationQuaternion)return;let i=t.clientX-e.pointerX,r=t.clientY-e.pointerY,s=vv({startPosition:Ht(e.startPosition),pivot:Ht(e.pivot),startRotationQuaternion:gv(e.startRotationQuaternion),yawAxis:Ht(this.camera.getDirection(b.Up()).normalize()),pitchAxis:Ht(this.camera.getDirection(b.Right()).normalize()),deltaX:i,deltaY:r,sensitivity:.01});s&&(e.mesh.position=new b(s.position.x,s.position.y,s.position.z),e.mesh.rotationQuaternion=new Xe(s.rotationQuaternion.x,s.rotationQuaternion.y,s.rotationQuaternion.z,s.rotationQuaternion.w),e.mesh.rotation.set(0,0,0),e.mesh.computeWorldMatrix(!0))}getPointOnDragPlane(e,t){var s;let i=e.getBoundingInfo().boundingBox.centerWorld.clone(),r=Ud(Ht(i),Ht(this.camera.getForwardRay().direction));return r&&(s=this.getRayPlanePoint(t,r))!=null?s:i}getRayPlanePoint(e,t){let i=this.scene.getEngine().getRenderingCanvas();if(!i)return null;let r=i.getBoundingClientRect(),s=e.clientX-r.left,a=e.clientY-r.top,o=this.scene.createPickingRay(s,a,K.Identity(),this.camera),l=_v({origin:Ht(o.origin),direction:Ht(o.direction)},t);return l?new b(l.x,l.y,l.z):null}};Qf.BBOX_VISIBLE=new ve(.25,.7,1),Qf.BBOX_OCCLUDED=new ve(.1,.25,.4);zO=Qf});var BK={};tt(BK,{BabylonModelPreview:()=>qR,createBabylonModelPreview:()=>mue});function aue(n){let e=n.getClassName();return e==="DirectionalLight"||e==="PointLight"||e==="SpotLight"}function XO(n){return n.getClassName()==="GaussianSplattingMesh"}function jR(n,e){var i;return((i=rf(n.metadata,{name:n.name}).displayName)==null?void 0:i.trim())||n.name||e}function NK(n){let e=[],t=n;for(;t&&typeof t=="object"&&"name"in t;){let i=t,r=jR(i,"node");r.trim()&&e.push(r),t=i.parent}return e.reverse().join("/")}function wK(n,e){var t;return((t=n.displayName)==null?void 0:t.trim())||n.partNumber||n.componentId||e}function oue(n,e){try{if(e==="gltf")return JSON.parse(new TextDecoder().decode(new Uint8Array(n)));if(e!=="glb")return null;let t=new DataView(n);if(t.byteLength<20||t.getUint32(0,!0)!==1179937895)return null;let i=t.getUint32(12,!0);if(t.getUint32(16,!0)!==1313821514||20+i>t.byteLength)return null;let s=new Uint8Array(n,20,i);return JSON.parse(new TextDecoder().decode(s))}catch(t){return null}}function lue(n,e){let t=oue(n,e),i=new Map;if(!t)return i;let r=Array.isArray(t.nodes)?t.nodes:[];for(let a of r){if(!a||typeof a!="object")continue;let o=a,l=typeof o.name=="string"?o.name:"";l&&o.extras&&i.set(`node:${l}`,o.extras)}let s=Array.isArray(t.meshes)?t.meshes:[];for(let a of s){if(!a||typeof a!="object")continue;let o=a,l=typeof o.name=="string"?o.name:"";l&&o.extras&&i.set(`mesh:${l}`,o.extras)}return i}function FK(n,e){return e===void 0?n:n==null?e:{metadata:n,extras:e}}function cue(n){return!!n&&typeof n=="object"&&"getBoundingInfo"in n}function Qg(n){return new b(n.x,n.y,n.z)}function fue(n){let e=n.replace(/\s+#.*$/,"").trim();if(e.startsWith('"')){let t=e.indexOf('"',1);if(t>1)return e.slice(1,t)}return e}function hue(n){let e=n.trim().split(/\s+/),t=e.findIndex(i=>!i.startsWith("-")&&!/^[-+]?\d*\.?\d+$/.test(i));return e.slice(Math.max(0,t)).join(" ").replace(/^"|"$/g,"")}function due(n){var t,i;let e=(i=(t=n.split(".").pop())==null?void 0:t.toLowerCase())!=null?i:"png";return e==="jpg"||e==="jpeg"?"image/jpeg":e==="png"?"image/png":e==="bmp"?"image/bmp":e==="tga"?"image/x-tga":e==="webp"?"image/webp":`image/${e}`}function uue(n,e,t){let i=aa(e),r=i.replace(/\.[^.]+$/,""),s=jr(t),a=[Ns(n,e),Ns(n,i)];if(s)for(let o of OK)a.push(Ns(n,`${s}.${o}`));for(let o of OK){let l=`${r}.${o}`;l!==i&&a.push(Ns(n,l))}return a}function mue(n){return new qR(n)}var KR,OK,rue,nue,sue,ss,qR,UK=C(()=>{"use strict";dy();As();GA();kA();CG();yG();Fy();Ge();zt();Mi();TP();Sc();mz();qP();tR();bX();by();$m();qg();qg();dO();uO();V9();_K();BS();Ys();oa();gK();LK();FR();tf();VS();ws();XS();C_();tM();KR=null,OK=["jpg","jpeg","png","bmp","tga","webp","tif","tiff"],rue=/^\s*(map_Kd|map_Ka|map_Ks|map_Ns|map_d|map_bump|bump|disp|decal)\s+(.+)/i,nue=.242,sue=320;ss=class ss{constructor(e){this.rootMesh=null;this.loadedMeshes=[];this.loadedTransformNodes=[];this.loadedExt="";this.rendering=!1;this.contextLost=!1;this.viewportVisible=!0;this.viewportObserver=null;this.cleanupPicking=null;this.configLights=[];this.shadowGenerator=null;this.groundMesh=null;this.gridMesh=null;this.axisMeshes=[];this.autoRotateBehavior=null;this.wireframeEnabled=!1;this.gizmo=null;this.gizmoEnabled=!1;this.disassembly=null;this.focusSelectionEnabled=!1;this.focusedMesh=null;this.originalMeshVisibility=new Map;this.bboxMesh=null;this.bboxEnabled=!1;this.currentQuality="high";this.resourceWarnings=[];this.gltfComponentMetadata=new Map;this.animPlaying=!1;this.initialCamera={alpha:Math.PI/4,beta:Math.PI/3,radius:5,target:b.Zero()};this.focusWorldPointFrame=0;this._lastPickResult={mesh:null,pickedPoint:null,screenX:0,screenY:0};this._onPickCallbacks=[];this.measurementActive=!1;this.measurementScale={x:1,y:1,z:1};this.measurementUnit="mm";this.measurementSegments=[];this.measurementMarkers=[];this.pendingPoint=null;this.pendingMarker=null;this.hoveredMarkerIndex=-1;this.lastPointerClient={x:0,y:0};this.previewLine=null;this.handlePointerMove=e=>{if(this.lastPointerClient={x:e.clientX,y:e.clientY},!this.measurementActive||(this.pendingPoint&&this.updatePreviewLine(),this.measurementMarkers.length===0))return;let t=this.engine.getRenderingCanvas();if(!t)return;let i=t.getBoundingClientRect(),r=e.clientX-i.left,s=e.clientY-i.top,a=this.scene.pick(r,s,l=>this.measurementMarkers.includes(l)),o=a.hit?this.measurementMarkers.indexOf(a.pickedMesh):-1;if(o!==this.hoveredMarkerIndex){if(this.hoveredMarkerIndex>=0&&this.hoveredMarkerIndex=0&&o{e.preventDefault(),e.stopPropagation()};this.handleViewportIntersection=e=>{let t=e.some(i=>i.isIntersecting);t!==this.viewportVisible&&(this.viewportVisible=t,t?this.startRenderLoop():this.rendering&&(this.engine.stopRenderLoop(),this.rendering=!1))};this.handleContextLost=e=>{e.preventDefault(),this.contextLost=!0,this.rendering&&(this.engine.stopRenderLoop(),this.rendering=!1)};this.handleContextRestored=()=>{this.contextLost=!1,this.engine.resize(),this.startRenderLoop()};this.engine=new Ue(e,!0,{preserveDrawingBuffer:!0}),this.scene=new Jt(this.engine),this.scene.clearColor=new lt(.12,.12,.14,1),this.camera=new gi("cam",Math.PI/4,Math.PI/3,5,b.Zero(),this.scene),this.camera.attachControl(e,!0),this.camera.lowerRadiusLimit=.1,this.camera.wheelPrecision=30,e.addEventListener("wheel",this.preventCanvasWheelScroll,{passive:!1}),e.addEventListener("pointermove",this.handlePointerMove),e.addEventListener("webglcontextlost",this.handleContextLost),e.addEventListener("webglcontextrestored",this.handleContextRestored),this.scene.ambientColor=new ve(.3,.3,.3);let t=new Zs("default-light",new b(0,1,.5),this.scene);t.intensity=1.2,this.resizeObs=new ResizeObserver(()=>this.engine.resize()),this.resizeObs.observe(e),typeof IntersectionObserver!="undefined"&&(this.viewportObserver=new IntersectionObserver(this.handleViewportIntersection,{root:null,threshold:[0,.01]}),this.viewportObserver.observe(e)),window.requestAnimationFrame(()=>this.engine.resize())}canRender(){let e=this.engine.getRenderingCanvas();return!!(e!=null&&e.isConnected)&&e.clientWidth>0&&e.clientHeight>0}ensureDisassemblyController(){return this.rootMesh?(this.disassembly||(this.disassembly=DK(this.scene,this.camera,this.getRenderableMeshes(this.rootMesh))),this.disassembly):null}isDisassemblyActive(){var e,t;return(t=(e=this.disassembly)==null?void 0:e.isEnabled())!=null?t:!1}async loadModel(e,t,i,r){var h,d,u;if(await jg(),this.rootMesh){let m=this.rootMesh;m.dispose(!0,!0);for(let p of this.loadedMeshes)p!==m&&!p.isDisposed()&&p.dispose(!0,!0);this.rootMesh=null}this.loadedMeshes=[],this.loadedTransformNodes=[],this.clearMeasurements(),(h=this.disassembly)==null||h.dispose(),this.disassembly=null,this.clearFocusedMesh(),this.originalMeshVisibility.clear();let s=t.toLowerCase().replace(".","");this.loadedExt=s,this.resourceWarnings=[],this.gltfComponentMetadata=lue(e,s);let a=this.scene,l=(d={glb:".glb",gltf:".gltf",stl:".stl",obj:".obj",splat:".splat",ply:".ply"}[s])!=null?d:`.${s}`,c=`data:application/octet-stream;base64,${Ol(e)}`;if(s==="obj"&&i&&r){KR&&await KR;let m;KR=new Promise(p=>{m=p});try{let{OBJFileLoader:p}=await Promise.resolve().then(()=>(fO(),M9)),_=p.prototype;typeof _._loadMTL!="function"&&console.warn("[AI3D] OBJFileLoader._loadMTL not found \u2014 MTL vault resolution disabled");let g=_._loadMTL,x=new TextDecoder().decode(new Uint8Array(e)).match(/mtllib\s+(.+)/),A=null;if(x&&i&&r){let E=fue(x[1]),R=Ip(r),I=Ns(R,E);try{let y=await i(I),D=new TextDecoder().decode(new Uint8Array(y)).split(` +`);for(let N=0;NN!=="");if(!O.some(N=>/^\s*Kd\s+/i.test(N))){let N=O.findIndex(F=>/^\s*newmtl\s+/i.test(F));O.splice(N>=0?N+1:0,0,"Kd 0.80 0.80 0.80")}A=O.join(` +`)}catch(y){this.resourceWarnings.push(`OBJ material library not found: ${I}`)}}_._loadMTL=function(E,R,I){let y=A!=null?A:"";I(y)};let S=await Bg(c,a,{meshNames:"",pluginExtension:l});this.loadedMeshes=S.meshes,this.loadedTransformNodes=S.transformNodes,S.meshes.length>0&&(this.rootMesh=S.meshes[0]),_._loadMTL=g}catch(p){throw console.error("[AI3D] OBJ load error:",p),p}finally{m(),KR=null}}else if(s==="stl")this.rootMesh=D9(a,e),this.rootMesh&&(this.loadedMeshes=[this.rootMesh]);else if(s==="ply")this.rootMesh=O9(a,e),this.rootMesh&&(this.loadedMeshes=[this.rootMesh]);else{let m=await Bg(c,a,{meshNames:"",pluginExtension:l});this.loadedMeshes=m.meshes,this.loadedTransformNodes=m.transformNodes,m.meshes.length>0&&(this.rootMesh=m.meshes[0])}if(!this.rootMesh)throw new Error("No mesh found in model file");for(let m of this.getRenderableMeshes(this.rootMesh))m.material&&(m.material.backFaceCulling=!1);let f=US(this.getRenderableBounds(this.rootMesh));return this.camera.target=Qg(f.target),this.camera.radius=f.radius,this.camera.lowerRadiusLimit=f.lowerRadiusLimit,this.camera.upperRadiusLimit=f.upperRadiusLimit,this.camera.minZ=f.near,this.camera.maxZ=f.far,this.initialCamera={alpha:this.camera.alpha,beta:this.camera.beta,radius:this.camera.radius,target:this.camera.target.clone()},this.startRenderLoop(),this.engine.resize(),(u=this.cleanupPicking)==null||u.call(this),this.cleanupPicking=pK(this.scene,m=>{if(!this.isDisassemblyActive()){if(this.measurementActive&&m.pickedPoint){this.addMeasurementPoint(Qg(m.pickedPoint));return}this._lastPickResult=m,this.focusSelectionEnabled&&m.mesh&&this.setFocusedMesh(m.mesh),this._onPickCallbacks.forEach(p=>p(m))}},()=>!this.focusSelectionEnabled),this.ensureDisassemblyController(),this.computeSummary(this.rootMesh)}applyConfig(e){e.camera&&this.applyCameraConfig(e.camera),e.lights&&this.applyLightConfig(e.lights),e.scene&&this.applySceneConfig(e.scene),e.stl&&this.loadedExt==="stl"&&(e.stl.color&&this.setSTLColor(e.stl.color),e.stl.wireframe!==void 0&&this.setWireframe(e.stl.wireframe))}applyCameraConfig(e){var i;let t=this.engine.getRenderingCanvas();if(t){if(e.mode==="orthographic"){let r=this.camera.radius,s=t.clientWidth/t.clientHeight,a=(i=e.zoom)!=null?i:1,o=r/a;this.camera.mode=1,this.camera.orthoLeft=-o*s,this.camera.orthoRight=o*s,this.camera.orthoTop=o,this.camera.orthoBottom=-o}else this.camera.mode=0,e.fov&&(this.camera.fov=e.fov*Math.PI/180);if(e.position){let[r,s,a]=e.position;this.camera.setPosition(new b(r,s,a))}if(e.lookAt){let[r,s,a]=e.lookAt;this.camera.setTarget(new b(r,s,a))}e.near!==void 0&&(this.camera.minZ=e.near),e.far!==void 0&&(this.camera.maxZ=e.far)}}applyLightConfig(e){var i;for(let r of this.configLights)r.dispose();this.configLights=[],(i=this.shadowGenerator)==null||i.dispose(),this.shadowGenerator=null;let t=this.scene.getLightByName("default-light");t&&t.dispose();for(let r of e){let s=this.createLight(r);s&&this.configLights.push(s)}}createLight(e){var r,s;let t=e.color?ve.FromHexString(e.color):ve.White(),i=(r=e.intensity)!=null?r:1;switch(e.type){case"hemisphere":{let a=e.groundColor?ve.FromHexString(e.groundColor):new ve(.2,.2,.2),o=new Zs("hemi",new b(0,1,0),this.scene);return o.diffuse=t,o.groundColor=a,o.intensity=i,o}case"directional":{let a=e.position?new b(...e.position).normalize():new b(-1,-2,-1).normalize(),o=new Ms("dir",a,this.scene);return o.diffuse=t,o.intensity=i,e.castShadow&&this.rootMesh&&this.setupShadow(o),o}case"point":{let a=e.position?new b(...e.position):new b(0,5,0),o=new Pf("point",a,this.scene);return o.diffuse=t,o.intensity=i,e.decay!==void 0&&(o.decay=e.decay),o}case"spot":{let a=e.position?new b(...e.position):new b(0,5,0),l=(e.target?new b(...e.target):b.Zero()).subtract(a).normalize(),c=e.angle?e.angle*Math.PI/180:Math.PI/4,f=(s=e.penumbra)!=null?s:.5,h=new Ur("spot",a,l,c,f,this.scene);return h.diffuse=t,h.intensity=i,e.decay!==void 0&&(h.decay=e.decay),e.castShadow&&this.rootMesh&&this.setupShadow(h),h}case"attachToCam":{let a=new Pf("cam-light",b.Zero(),this.scene);return a.diffuse=t,a.intensity=i,a.parent=this.camera,a}default:return null}}setupShadow(e){if(!this.rootMesh)return;if(!aue(e)){console.warn("[AI3D] Light type does not support shadows:",e.name);return}let t=new Ci(1024,e);t.useBlurExponentialShadowMap=!0,t.blurKernel=32;for(let i of this.getRenderableMeshes(this.rootMesh))t.addShadowCaster(i),i.receiveShadows=!0;this.shadowGenerator=t}applySceneConfig(e){var t,i;if(e.background!==void 0){let r=lt.FromColor3(ve.FromHexString(e.background),e.transparent?0:1);this.scene.clearColor=r}e.autoRotate&&(this.autoRotateBehavior?this.autoRotateBehavior.idleRotationSpeed=(i=e.autoRotateSpeed)!=null?i:.5:(this.autoRotateBehavior=new Fm,this.autoRotateBehavior.idleRotationSpeed=(t=e.autoRotateSpeed)!=null?t:.5,this.autoRotateBehavior.idleRotationWaitTime=1e3,this.autoRotateBehavior.idleRotationSpinupTime=500,this.camera.addBehavior(this.autoRotateBehavior))),e.groundShadow&&this.rootMesh&&this.createGround(),e.grid&&this.createGrid(),e.axis&&this.createAxis()}createGround(){if(!this.rootMesh||this.groundMesh)return;let e=this.getRenderableBounds(this.rootMesh),t=Wr(e),i=Math.max(t.x,t.z)*3,r=e.min.y;this.groundMesh=ts.CreateGround("ground",{width:i,height:i},this.scene),this.groundMesh.position.y=r;let s=new ke("ground-mat",this.scene);s.diffuseColor=new ve(.15,.15,.15),s.specularColor=ve.Black(),s.alpha=.5,this.groundMesh.material=s,this.groundMesh.receiveShadows=!0}createGrid(){if(!this.rootMesh||this.gridMesh)return;let e=this.getRenderableBounds(this.rootMesh),t=Wr(e),i=Math.max(t.x,t.z)*2,r=e.min.y-.01;this.gridMesh=ts.CreateGround("grid",{width:i,height:i,subdivisions:20},this.scene),this.gridMesh.position.y=r;let s=new ke("grid-mat",this.scene);s.wireframe=!0,s.diffuseColor=new ve(.3,.3,.3),s.emissiveColor=new ve(.1,.1,.1),this.gridMesh.material=s}createAxis(){if(!this.rootMesh||this.axisMeshes.length>0)return;let e=this.getRenderableBounds(this.rootMesh),t=$1(e)*1.5,i=Qg(e.min),r=M_(e)*.01,s=[["x",ve.Red(),new b(t,0,0)],["y",ve.Green(),new b(0,t,0)],["z",ve.Blue(),new b(0,0,t)]];for(let[a,o,l]of s){let c=ts.CreateTube(`axis-${a}`,{path:[i,i.add(l)],radius:r,tessellation:8},this.scene),f=new ke(`axis-${a}-mat`,this.scene);f.emissiveColor=o,f.diffuseColor=ve.Black(),c.material=f,this.axisMeshes.push(c)}}setSTLColor(e){if(!this.rootMesh)return;let t=ve.FromHexString(e);for(let i of this.getRenderableMeshes(this.rootMesh))if(i.material&&i.material.name==="stl-mat"){let r=i.material;r.diffuseColor=t,r.emissiveColor=t.scale(.1)}}setWireframe(e){this.rootMesh&&(XO(this.rootMesh)||(this.wireframeEnabled=e,this.scene.forceWireframe=e))}toggleWireframe(){return this.setWireframe(!this.wireframeEnabled),this.wireframeEnabled}hasAnimations(){return this.scene.animationGroups.length>0}toggleAnimation(){let e=this.scene.animationGroups;if(e.length===0)return!1;this.animPlaying=!this.animPlaying;for(let t of e)this.animPlaying?t.play(!0):t.pause();return this.animPlaying}toggleMeasurement(){return this.measurementActive=!this.measurementActive,this.measurementActive||this.clearMeasurements(),this.measurementActive}isMeasurementActive(){return this.measurementActive}clearMeasurements(){this.measurementActive=!1,this.pendingPoint=null,this.pendingMarker=null,this.hoveredMarkerIndex=-1,this.removePreviewLine();for(let e of this.measurementSegments)e.line.dispose(),e.label.dispose();this.measurementSegments=[];for(let e of this.measurementMarkers)e.dispose();this.measurementMarkers=[]}setMeasurementScale(e){this.measurementScale={...e},this.updateMeasurementLabels()}getMeasurementScale(){return{...this.measurementScale}}getMeasurementBounds(){if(!this.rootMesh)return null;let e=this.getRenderableBounds(this.rootMesh);return e?{x:e.max.x-e.min.x,y:e.max.y-e.min.y,z:e.max.z-e.min.z}:null}getRealDistance(e,t){let i=(t.x-e.x)*this.measurementScale.x,r=(t.y-e.y)*this.measurementScale.y,s=(t.z-e.z)*this.measurementScale.z;return Math.sqrt(i*i+r*r+s*s)}formatMeasurementDistance(e){let t=this.measurementUnit;return t==="um"||t==="\u03BCm"?e<1e3?`${e.toFixed(2)} \u03BCm`:`${(e/1e3).toFixed(2)} mm`:t==="mm"?e<1?`${(e*1e3).toFixed(2)} \u03BCm`:e<1e3?`${e.toFixed(2)} mm`:`${(e/1e3).toFixed(3)} m`:t==="cm"?e<1?`${(e*10).toFixed(2)} mm`:e<100?`${e.toFixed(2)} cm`:`${(e/100).toFixed(3)} m`:t==="m"?e<.01?`${(e*1e3).toFixed(2)} mm`:e<1?`${e.toFixed(3)} m`:`${e.toFixed(2)} m`:`${e.toFixed(3)} ${t}`}updateMeasurementLabels(){if(this.measurementSegments.length===0)return;let e=this.getMeasurementMarkerSize()*4;for(let t of this.measurementSegments){let i=this.getRealDistance(t.start,t.end),r=this.formatMeasurementDistance(i);t.label.dispose(!1,!0);let s=b.Center(t.start,t.end);t.label=this.createMeasurementLabelMesh(r,s,e)}}setAnimationSpeed(e){for(let t of this.scene.animationGroups)t.speedRatio=e}captureSnapshot(){let e=this.engine.getRenderingCanvas();return e?(this.scene.render(),e.toDataURL("image/png")):null}toggleOrientationGizmo(){return this.gizmoEnabled=!this.gizmoEnabled,this.gizmoEnabled&&!this.gizmo&&(this.gizmo=new XR(this.engine,this.camera)),this.gizmoEnabled}isOrientationGizmoEnabled(){return this.gizmoEnabled}setRenderScale(e){let t=Math.max(.25,Math.min(e,2)),i={low:2,medium:1.33,high:1}[this.currentQuality],r=mr()?1.5:1;return this.engine.setHardwareScalingLevel(i*r/t),t}getPerformanceSnapshot(){return{backend:"babylon",renderScale:Number((1/this.engine.getHardwareScalingLevel()).toFixed(2)),quality:this.currentQuality,meshCount:this.rootMesh?this.getRenderableMeshes(this.rootMesh).length:0}}toggleBoundingBox(){var e;if(this.bboxEnabled=!this.bboxEnabled,this.bboxEnabled){if(!this.rootMesh)return this.bboxEnabled;this.bboxMesh&&this.bboxMesh.dispose();let t=this.getRenderableBounds(this.rootMesh),i=Qg(fn(t)),r=Qg(Wr(t));this.bboxMesh=ts.CreateBox("bbox",{width:r.x,height:r.y,depth:r.z},this.scene),this.bboxMesh.position=i;let s=new ke("bbox-mat",this.scene);s.wireframe=!0,s.emissiveColor=new ve(1,1,0),s.disableLighting=!0,s.alpha=.6,this.bboxMesh.material=s}else(e=this.bboxMesh)==null||e.dispose(),this.bboxMesh=null;return this.bboxEnabled}toggleFocusSelection(){var t;let e=!this.focusSelectionEnabled;return e&&this.isDisassemblyActive()&&((t=this.disassembly)==null||t.setEnabled(!1)),this.focusSelectionEnabled=e,this.focusSelectionEnabled?this._lastPickResult.mesh&&this.setFocusedMesh(this._lastPickResult.mesh):this.clearFocusedMesh(),this.focusSelectionEnabled}isFocusSelectionEnabled(){return this.focusSelectionEnabled}toggleDisassembly(){let e=this.ensureDisassemblyController();if(!e)return!1;let t=!e.isEnabled();return t&&(this.focusSelectionEnabled=!1,this.clearFocusedMesh()),e.setEnabled(t)}resetDisassembly(){var e;(e=this.disassembly)==null||e.reset()}isDisassemblyEnabled(){return this.isDisassemblyActive()}setExplode(e,t){this.rootMesh&&U9(this.rootMesh,e,t,this.loadedMeshes)}resetExplode(){this.rootMesh&&pO(this.rootMesh,this.loadedMeshes)}resetView(){this.rootMesh&&pO(this.rootMesh,this.loadedMeshes),this.resetDisassembly(),this.clearFocusedMesh(),this.camera.mode=0,this.camera.alpha=this.initialCamera.alpha,this.camera.beta=this.initialCamera.beta,this.camera.radius=this.initialCamera.radius,this.camera.target=this.initialCamera.target.clone()}exportModelInfo(e){if(!this.rootMesh)return"";let t=this.computeSummary(this.rootMesh),i=this.getRenderableMeshes(this.rootMesh),r=XO(this.rootMesh),s=e&&aa(e)||t.rootName;return HS({title:s,format:this.loadedExt.toUpperCase(),summary:t,meshBreakdown:i.map(a=>{var o,l;return{name:a.name,triangleCount:r?null:Zg(a),vertexCount:md(a),materialName:(l=(o=a.material)==null?void 0:o.name)!=null?l:null}}),materialNames:i.map(a=>{var o;return(o=a.material)==null?void 0:o.name})})}getModelEvidence(){var a;if(!this.rootMesh)return null;let e=this.getRenderableMeshes(this.rootMesh),t=this.computeComponentPartSummaries(e),i=e.filter(o=>!t.groupedMeshes.has(o)).map(o=>this.computePartSummary(o)),r=t.parts.length>0?[...t.parts,...i]:i,s=new Set;for(let o of e)(a=o.material)!=null&&a.name&&s.add(o.material.name);return{summary:this.computeSummary(this.rootMesh),parts:r,materialNames:Array.from(s).sort((o,l)=>o.localeCompare(l)),resourceWarnings:[...this.resourceWarnings],capturedAt:new Date().toISOString()}}getSelectedPartInfo(){var i;let e=(i=this.focusedMesh)!=null?i:this._lastPickResult.mesh,t=e?this.findRenderableMesh(e):null;return!t||t.isDisposed()?null:this.computePartSummary(t)}exportSelectedPartInfo(){let e=this.getSelectedPartInfo();return e?zS(e):""}getPickWorldPoint(e){if(e.pickedPoint&&typeof e.pickedPoint=="object")return Ht(e.pickedPoint);if(cue(e.mesh)){let t=e.mesh.getBoundingInfo().boundingBox.centerWorld;return Ht(t)}return null}focusWorldPoint(e){let t=new b(e.x,e.y,e.z),i=this.camera.target.clone(),r=performance.now();this.focusWorldPointFrame&&(activeWindow.cancelAnimationFrame(this.focusWorldPointFrame),this.focusWorldPointFrame=0);let s=a=>{let o=Math.min(1,Math.max(0,(a-r)/sue)),l=o<.5?4*o*o*o:1-Math.pow(-2*o+2,3)/2;if(this.camera.target=b.Lerp(i,t,l),o<1&&!this.scene.isDisposed){this.focusWorldPointFrame=window.requestAnimationFrame(s);return}this.focusWorldPointFrame=0};this.focusWorldPointFrame=window.requestAnimationFrame(s)}getAnnotationCameraStateKey(){return`${this.camera.alpha.toFixed(3)}_${this.camera.beta.toFixed(3)}_${this.camera.radius.toFixed(3)}_${this.camera.target.x.toFixed(2)}_${this.camera.target.y.toFixed(2)}_${this.camera.target.z.toFixed(2)}`}projectAnnotationWorldPoint(e,t){let i=this.engine.getRenderingCanvas();if(!i||this.scene.isDisposed)return!1;let r=this.engine.getRenderWidth(),s=this.engine.getRenderHeight();if(r===0||s===0||i.clientWidth===0||i.clientHeight===0)return!1;let a=ss.annotationWorldPoint;a.set(e.x,e.y,e.z),b.ProjectToRef(a,ss.annotationIdentity,this.scene.getTransformMatrix(),this.camera.viewport.toGlobal(r,s),ss.annotationProjection);let o=i.clientWidth/r,l=i.clientHeight/s;return t.screenX=ss.annotationProjection.x*o,t.screenY=ss.annotationProjection.y*l,t.depth=ss.annotationProjection.z,!0}isAnnotationWorldPointOccluded(e){if(this.scene.isDisposed)return!1;let t=Nc(Ht(this.camera.position),e);if(!t)return!1;let i=ss.annotationDirection,r=ss.annotationRay;i.set(t.direction.x,t.direction.y,t.direction.z),r.origin=this.camera.position,r.direction=i,r.length=t.distance;let s=this.scene.pickWithRay(r);return!!(s!=null&&s.hit)&&Oc(s.distance,t.distance,t.epsilon)}getAnnotationProvider(){let e=this.engine.getRenderingCanvas();if(!e)throw new Error("Preview canvas is unavailable");return{canvas:e,observeRender:t=>{let i=this.scene.onAfterRenderCameraObservable.add(r=>{r===this.camera&&t()});return{remove:()=>this.scene.onAfterRenderCameraObservable.remove(i)}},getCameraStateKey:()=>this.getAnnotationCameraStateKey(),projectWorldPoint:(t,i)=>this.projectAnnotationWorldPoint(t,i),isWorldPointOccluded:t=>this.isAnnotationWorldPointOccluded(t)}}getCanvas(){return this.engine.getRenderingCanvas()}getLastPickResult(){return this._lastPickResult}onPick(e){return this._onPickCallbacks.push(e),()=>{this._onPickCallbacks=this._onPickCallbacks.filter(t=>t!==e)}}setRenderQuality(e,t=1){this.currentQuality=e;let i={low:2,medium:1.33,high:1},r=mr()?1.5:1,s=i[e]*r/Math.max(t,.25);if(this.engine.setHardwareScalingLevel(s),this.shadowGenerator){let a={low:0,medium:16,high:32};this.shadowGenerator.blurKernel=a[e],e==="low"?(this.shadowGenerator.useBlurExponentialShadowMap=!1,this.shadowGenerator.useExponentialShadowMap=!0):(this.shadowGenerator.useBlurExponentialShadowMap=!0,this.shadowGenerator.useExponentialShadowMap=!1)}}destroy(){var t,i,r,s,a,o,l,c;this.engine.stopRenderLoop(),this.focusWorldPointFrame&&(activeWindow.cancelAnimationFrame(this.focusWorldPointFrame),this.focusWorldPointFrame=0),this._onPickCallbacks=[],(t=this.cleanupPicking)==null||t.call(this),this.cleanupPicking=null,(i=this.gizmo)==null||i.dispose(),this.gizmo=null,(r=this.disassembly)==null||r.dispose(),this.disassembly=null,this.clearMeasurements(),this.clearFocusedMesh(),this.originalMeshVisibility.clear(),(s=this.bboxMesh)==null||s.dispose(),this.bboxMesh=null,this.camera.detachControl();let e=this.engine.getRenderingCanvas();e==null||e.removeEventListener("wheel",this.preventCanvasWheelScroll),e==null||e.removeEventListener("pointermove",this.handlePointerMove),e==null||e.removeEventListener("webglcontextlost",this.handleContextLost),e==null||e.removeEventListener("webglcontextrestored",this.handleContextRestored),(a=this.viewportObserver)==null||a.disconnect(),this.viewportObserver=null,this.resizeObs.disconnect(),this.autoRotateBehavior&&(this.camera.removeBehavior(this.autoRotateBehavior),this.autoRotateBehavior=null);for(let f of this.configLights)f.dispose();this.configLights=[],(o=this.shadowGenerator)==null||o.dispose(),this.shadowGenerator=null,(l=this.groundMesh)==null||l.dispose(),this.groundMesh=null,(c=this.gridMesh)==null||c.dispose(),this.gridMesh=null;for(let f of this.axisMeshes)f.dispose();this.axisMeshes=[],this.scene.dispose(),this.engine.dispose()}startRenderLoop(){this.rendering||!this.viewportVisible||this.contextLost||(this.rendering=!0,this.engine.runRenderLoop(()=>{if(!this.canRender()||!this.viewportVisible||this.contextLost){this.engine.stopRenderLoop(),this.rendering=!1;return}this.scene.render(),this.gizmo&&this.gizmoEnabled&&(this.gizmo.syncWith(this.camera),this.gizmo.render())}))}getRenderableMeshes(e){return pd(e,this.loadedMeshes)}getRenderableBounds(e){return NR(e,this.loadedMeshes)}setFocusedMesh(e){if(!this.rootMesh)return;let t=e?this.findRenderableMesh(e):null;if(!t||t.isDisposed()){this.clearFocusedMesh();return}if(this.focusedMesh===t)return;let i=this.getRenderableMeshes(this.rootMesh);for(let r of i){this.originalMeshVisibility.has(r.uniqueId)||this.originalMeshVisibility.set(r.uniqueId,r.visibility);let s=r===t;r.visibility=s?1:nue,r.renderOutline=s,r.outlineColor=new ve(.18,.76,1),r.outlineWidth=s?.045:0}this.focusedMesh=t}clearFocusedMesh(){if(!this.rootMesh){this.focusedMesh=null;return}for(let e of this.getRenderableMeshes(this.rootMesh)){let t=this.originalMeshVisibility.get(e.uniqueId);t!==void 0&&(e.visibility=t),e.renderOutline=!1,e.outlineWidth=0}this.originalMeshVisibility.clear(),this.focusedMesh=null}findRenderableMesh(e){if(!this.rootMesh)return null;let t=this.getRenderableMeshes(this.rootMesh);if(t.includes(e))return e;let i=e.parent;for(;i&&"uniqueId"in i;){let r=i;if(t.includes(r))return r;i=i.parent}return null}computePartSummary(e){var s;let t=e.name||`mesh-${e.uniqueId}`,i=FK(e.metadata,(s=this.gltfComponentMetadata.get(`node:${t}`))!=null?s:this.gltfComponentMetadata.get(`mesh:${t}`)),r=rf(i,{name:t,path:NK(e)});return{...B9(e),name:wK(r,t),source:r.hasExplicitIdentity?"component":"mesh",meshNames:[t],childCount:1,componentId:r.componentId,occurrenceId:r.occurrenceId,partNumber:r.partNumber,componentPath:r.componentPath}}computeComponentPartSummaries(e){let t=new Set(e),i=[],r=new Set,s=[];for(let a of this.loadedTransformNodes){let o=a.getChildMeshes(!1).filter(h=>t.has(h)),l=jR(a,`component-${a.uniqueId}`),c=FK(a.metadata,this.gltfComponentMetadata.get(`node:${l}`)),f=rf(c,{name:jR(a,`component-${a.uniqueId}`),path:NK(a)});o.length<1||o.length===e.length||!f.hasExplicitIdentity&&(!a.name.trim()||o.length<2)||s.push({node:a,childMeshes:o,identity:f})}return s.sort((a,o)=>a.childMeshes.length-o.childMeshes.length).forEach(({node:a,childMeshes:o,identity:l})=>{var m;let c=o.filter(p=>!r.has(p));if(c.length<1||!l.hasExplicitIdentity&&c.length<2)return;for(let p of c)r.add(p);let f=cp(c);if(!f)return;let h=new Set,d=0,u=0;for(let p of c)d+=Zg(p),u+=md(p),(m=p.material)!=null&&m.name&&h.add(p.material.name);i.push(Ih({name:wK(l,jR(a,`component-${a.uniqueId}`)),triangleCount:d,vertexCount:u,materialName:h.size===0?null:h.size===1?Array.from(h)[0]:`${h.size} materials`,boundingSize:Wr(f),center:fn(f),source:l.hasExplicitIdentity?"component":"group",meshNames:c.map(p=>p.name||`mesh-${p.uniqueId}`),childCount:c.length,componentId:l.componentId,occurrenceId:l.occurrenceId,partNumber:l.partNumber,componentPath:l.componentPath}))}),{parts:i,groupedMeshes:r}}getMeasurementMarkerSize(){if(!this.rootMesh)return .02;let e=this.getRenderableBounds(this.rootMesh);return e?Math.max(e.max.x-e.min.x,e.max.y-e.min.y,e.max.z-e.min.z,.001)*.015:.02}findNearestMarkerIndex(e){let t=this.getMeasurementMarkerSize()*2.5;for(let i=0;i=0?this.measurementMarkers[t].position.clone():e;if(this.pendingPoint){if(b.Distance(i,this.pendingPoint)<1e-4)return;if(t<0){let r=this.getMeasurementMarkerSize(),s=ts.CreateSphere("measure-marker",{diameter:r},this.scene);s.position=i,s.isPickable=!1;let a=new ke("measure-marker-mat",this.scene);a.diffuseColor=new ve(1,.42,.42),a.emissiveColor=new ve(1,.42,.42),s.material=a,s.renderingGroupId=2,this.measurementMarkers.push(s)}this.createMeasurementSegment(this.pendingPoint,i),this.pendingMarker&&(this.pendingMarker.scaling.setAll(1),this.pendingMarker.material.diffuseColor=new ve(1,.42,.42),this.pendingMarker.material.emissiveColor=new ve(1,.42,.42)),this.pendingPoint=null,this.pendingMarker=null,this.removePreviewLine()}else{if(t<0){let r=this.getMeasurementMarkerSize(),s=ts.CreateSphere("measure-marker",{diameter:r},this.scene);s.position=i,s.isPickable=!1;let a=new ke("measure-marker-mat",this.scene);a.diffuseColor=new ve(1,.42,.42),a.emissiveColor=new ve(1,.42,.42),s.material=a,s.renderingGroupId=2,this.measurementMarkers.push(s),this.pendingMarker=s}else this.pendingMarker=this.measurementMarkers[t];this.pendingMarker.scaling.setAll(1.6),this.pendingMarker.material.diffuseColor=new ve(.32,.81,.4),this.pendingMarker.material.emissiveColor=new ve(.32,.81,.4),this.pendingPoint=i,this.ensurePreviewLine()}}createMeasurementSegment(e,t){let i=ts.CreateLines("measure-line",{points:[e,t]},this.scene);i.color=new ve(1,.42,.42),i.isPickable=!1,i.renderingGroupId=2;let r=this.getRealDistance(e,t),s=this.formatMeasurementDistance(r),a=b.Center(e,t),o=this.createMeasurementLabelMesh(s,a,this.getMeasurementMarkerSize()*4);this.measurementSegments.push({start:e,end:t,line:i,label:o})}createMeasurementLabelMesh(e,t,i){let r=ts.CreatePlane("measure-label",{width:i*4,height:i},this.scene);r.position=t,r.billboardMode=q.BILLBOARDMODE_ALL,r.isPickable=!1,r.renderingGroupId=2;let s=new Zx("measure-label-tex",{width:512,height:128},this.scene),a=s.getContext();a.fillStyle="rgba(32, 36, 46, 0.9)",a.fillRect(0,0,512,128),a.strokeStyle="#ff6b6b",a.lineWidth=4,a.strokeRect(0,0,512,128),a.fillStyle="#ffffff",a.font="bold 48px sans-serif",a.textAlign="center",a.textBaseline="middle",a.fillText(e,256,64),s.update();let o=new ke("measure-label-mat",this.scene);return o.diffuseTexture=s,o.emissiveColor=new ve(1,1,1),o.disableLighting=!0,o.opacityTexture=s,r.material=o,r}ensurePreviewLine(){this.previewLine||(this.previewLine=ts.CreateLines("measure-preview",{points:[b.Zero(),b.Zero()]},this.scene),this.previewLine.color=new ve(1,1,1),this.previewLine.alpha=.5,this.previewLine.isPickable=!1,this.previewLine.renderingGroupId=2)}updatePreviewLine(){if(!this.pendingPoint||!this.previewLine||!this.rootMesh)return;let e=this.engine.getRenderingCanvas();if(!e)return;let t=e.getBoundingClientRect(),i=this.lastPointerClient.x-t.left,r=this.lastPointerClient.y-t.top,s=this.scene.pick(i,r,o=>o!==this.previewLine&&!this.measurementMarkers.includes(o)),a;if(s.hit&&s.pickedPoint)a=s.pickedPoint;else{let o=this.scene.createPickingRay(i,r,K.Identity(),this.camera);a=this.pendingPoint.add(o.direction.scale(5))}this.previewLine.dispose(),this.previewLine=ts.CreateLines("measure-preview",{points:[this.pendingPoint,a]},this.scene),this.previewLine.color=new ve(1,1,1),this.previewLine.alpha=.5,this.previewLine.isPickable=!1,this.previewLine.renderingGroupId=2}removePreviewLine(){this.previewLine&&(this.previewLine.dispose(),this.previewLine=null)}computeSummary(e){let t=this.getRenderableMeshes(e),i=XO(e),r=t.reduce((s,a)=>s+md(a),0);return wR(e.name,this.getRenderableBounds(e),t,{splatCount:i?r:void 0,resourceWarnings:this.resourceWarnings})}};ss.annotationIdentity=K.Identity(),ss.annotationWorldPoint=b.Zero(),ss.annotationProjection=b.Zero(),ss.annotationDirection=b.Zero(),ss.annotationRay=new Yr(b.Zero(),b.Zero(),1);qR=ss});async function VK(n,e){if(kd(e).backend==="three"){let{createThreeModelPreview:r}=await Promise.resolve().then(()=>(p3(),m3));return r(n)}let{createBabylonModelPreview:i}=await Promise.resolve().then(()=>(UK(),BK));return i(n)}var GK=C(()=>{"use strict";Sv()});var kK={};tt(kK,{createBabylonGridRenderer:()=>_ue});function pue(n){return n.replace(/\|/g,"\\|").replace(/\r?\n/g," ")}function YO(n){return new b(n.x,n.y,n.z)}function _ue(n){return new KO(n)}var fp,KO,WK=C(()=>{"use strict";dy();As();GA();kA();Ge();zt();$u();$m();qh();Sc();qg();qg();FR();BS();Ys();tf();VS();fp=32;KO=class{constructor(e){this.cells=[];this.initialCameras=[];this.wireframeEnabled=!1;this.rendering=!1;this.dirty=!0;this.contextLost=!1;this.preventCanvasWheelScroll=e=>{e.preventDefault(),e.stopPropagation()};this.handleContextLost=e=>{e.preventDefault(),this.contextLost=!0,this.rendering&&(this.engine.stopRenderLoop(),this.rendering=!1)};this.handleContextRestored=()=>{this.contextLost=!1,this.engine.resize(),this.startRenderLoop(),this.markDirty()};e.className="ai3d-canvas-full",e.addEventListener("wheel",this.preventCanvasWheelScroll,{passive:!1}),this.engine=new Ue(e,!0,{preserveDrawingBuffer:!0}),e.addEventListener("webglcontextlost",this.handleContextLost),e.addEventListener("webglcontextrestored",this.handleContextRestored),this.scene=new Jt(this.engine),this.scene.clearColor=new lt(.12,.12,.14,1),this.scene.autoClear=!1,new Zs("default-light",new b(0,1,.5),this.scene),this.resizeObs=new ResizeObserver(()=>{this.engine.resize(),this.markDirty()}),this.resizeObs.observe(e),window.requestAnimationFrame(()=>this.engine.resize())}canRender(){let e=this.engine.getRenderingCanvas();return!!(e!=null&&e.isConnected)&&e.clientWidth>0&&e.clientHeight>0}markDirty(){this.dirty=!0}getCellBounds(e){let t=cp(e);if(!t)throw new Error("Grid cell has no renderable meshes");return t}async loadModels(e,t,i){var h,d,u;await jg();let r=e.length>fp?(console.warn(`[AI3D Grid] Capping ${e.length} models to ${fp} (layerMask limit)`),e.slice(0,fp)):e,s=(h=t.columns)!=null?h:Math.min(r.length,3),a=(d=t.gapX)!=null?d:.02,o=(u=t.gapY)!=null?u:.02,l=Math.ceil(r.length/s),c=(1-a*(s+1))/s,f=(1-o*(l+1))/l;for(let m=0;mfp?(console.warn(`[AI3D Preset] Capping ${e.placements.length} placements to ${fp} (layerMask limit)`),e.placements.slice(0,fp)):e.placements,r=[];for(let f=0;f0&&(d.push(...r[p]),u|=1<this.markDirty())),this.initialCameras.push({alpha:f.alpha,beta:f.beta,radius:f.radius,target:f.target.clone()}),f}async loadOne(e,t,i,r,s,a,o){var d,u;let l=await t(e.path),c=(u=(d=e.path.split(".").pop())==null?void 0:d.replace(".","").toLowerCase())!=null?u:"glb",{renderableMeshes:f}=await this.importMesh(e.path,l,o);if(c==="stl"&&e.color){let m=ve.FromHexString(e.color);for(let p of f)p.material instanceof ke&&p.material.name==="stl-mat"&&(p.material.diffuseColor=m)}if(c==="stl"&&e.wireframe!==void 0)for(let m of f)m.material instanceof ke&&(m.material.wireframe=e.wireframe);let h=this.createCellCamera(f,o,i,r,s,a);this.cells.push({meshes:f,camera:h})}createCellCamera(e,t,i,r,s,a){let o=US(this.getCellBounds(e)),l=new gi(`cell-cam-${t}`,Math.PI/4,Math.PI/3,o.radius,YO(o.target),this.scene);l.fov=45*Math.PI/180,l.minZ=o.near,l.maxZ=o.far,l.lowerRadiusLimit=o.lowerRadiusLimit,l.upperRadiusLimit=o.upperRadiusLimit,l.wheelPrecision=30,l.viewport=new io(i,r,s,a),l.layerMask=1<this.markDirty())),this.initialCameras.push({alpha:l.alpha,beta:l.beta,radius:l.radius,target:l.target.clone()}),l}renderFrame(){if(!this.canRender()||!this.dirty||this.contextLost)return;this.dirty=!1;let e=this.engine,t=this.scene;e.clear(t.clearColor,!0,!0);for(let i of this.cells){e.setViewport(i.camera.viewport);let r=i.camera.viewport,s=e.getRenderWidth(),a=e.getRenderHeight();e.enableScissor(r.x*s,r.y*a,r.width*s,r.height*a),t.activeCamera=i.camera,t.render(),e.disableScissor()}}startRenderLoop(){this.rendering||(this.rendering=!0,this.engine.runRenderLoop(()=>this.renderFrame()))}captureSnapshot(){let e=this.engine.getRenderingCanvas();return e?(this.renderFrame(),e.toDataURL("image/png")):null}getEngine(){return this.engine}getScene(){return this.scene}getCellCount(){return this.cells.length}getCanvas(){return this.engine.getRenderingCanvas()}getPrimaryCamera(){var e,t;return(t=(e=this.cells[0])==null?void 0:e.camera)!=null?t:null}setRenderScale(e){let t=Math.max(.25,Math.min(e,2)),i=mr()?1.5:1;return this.engine.setHardwareScalingLevel(i/t),t}resetView(){for(let e=0;e(WK(),kK));return e(n)}var zK=C(()=>{"use strict"});function gue(n,e,t){n.info("select preview backend",{...e,backend:t.backend,reason:t.reason,ext:t.ext,annotationMode:t.annotationMode,requireWorkbenchFeatures:t.requireWorkbenchFeatures,rendererRollout:t.rendererRollout})}async function _d(n,e,t,i){let r=kd(i);return gue(n,e,r),{preview:await VK(t,i),route:r}}function vue(n,e,t){n.info("select preview backend",{...e,backend:t.backend,reason:t.reason})}async function XK(n,e,t){let i=uw();return vue(n,e,i),{renderer:await HK(t),route:i}}var ZR=C(()=>{"use strict";GK();zK();Sv()});function jO(n){KK=n}function QR(n){return YK[n]>=YK[KK]}function $R(){return new Date().toISOString()}function JR(n){return n&&Object.keys(n).length>0?n:void 0}function Wi(n){let e=`[AI3D][${n}]`;return{debug(t,i){QR("debug")&&console.debug(e,$R(),t,JR(i))},info(t,i){QR("info")&&console.debug(e,$R(),t,JR(i))},warn(t,i){QR("warn")&&console.warn(e,$R(),t,JR(i))},error(t,i){QR("error")&&console.error(e,$R(),t,JR(i))}}}var YK,KK,Tn=C(()=>{"use strict";YK={debug:10,info:20,warn:30,error:40},KK="warn"});function an(n,e){return!!n&&typeof n=="object"&&e in n}function eb(n){return an(n,"getAnnotationProvider")}function jK(n){return an(n,"hasAnimations")&&an(n,"toggleAnimation")}function Ao(n){return an(n,"toggleMeasurement")&&an(n,"isMeasurementActive")&&an(n,"clearMeasurements")&&an(n,"setMeasurementScale")&&an(n,"getMeasurementScale")&&an(n,"getMeasurementBounds")&&an(n,"updateMeasurementLabels")}function tb(n){return an(n,"toggleDisassembly")&&an(n,"resetDisassembly")&&an(n,"isDisassemblyEnabled")}function ib(n){return an(n,"toggleFocusSelection")&&an(n,"isFocusSelectionEnabled")}function qK(n){return an(n,"toggleWireframe")}function qO(n){return an(n,"toggleOrientationGizmo")}function ZK(n){return an(n,"toggleBoundingBox")}function QK(n){return an(n,"setRenderScale")}var rb=C(()=>{"use strict"});function Cr(n){let e=createSvg("svg");e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("width","16"),e.setAttribute("height","16");let t=new DOMParser().parseFromString(`${n}`,"image/svg+xml");for(let i of Array.from(t.documentElement.childNodes))e.appendChild(activeDocument.importNode(i,!0));return e}function $K(n){var a,o;let[e,t]=n.split(","),i=(o=(a=e.match(/:(.*?);/))==null?void 0:a[1])!=null?o:"image/png",r=atob(t),s=new Uint8Array(r.length);for(let l=0;l{se.stopPropagation()};d.addEventListener("pointerdown",_),d.addEventListener("mousedown",_),d.addEventListener("click",_),f&&(d.classList.add("is-mobile"),JK(e,!1));let g=se=>(se.classList.add("is-secondary"),se),v=(se,Q)=>{se.classList.toggle("ai3d-btn-active",Q),se.setAttribute("aria-pressed",String(Q))},x=()=>{for(let se of[u,m,p]){let Q=Array.from(se.querySelectorAll(".ai3d-inline-btn")).filter(Je=>!Je.classList.contains("is-hidden")),Le=Q.length>0,Ae=Q.some(Je=>!Je.classList.contains("is-secondary"));se.classList.toggle("is-hidden",!Le),se.classList.toggle("has-primary-visible",Ae)}},A=!1,S=!1,E=f?u.createEl("button",{cls:"ai3d-inline-btn ai3d-mobile-mode-btn",attr:{"aria-label":J("helper.enableInteractionLabel"),"aria-pressed":"false"}}):null;E==null||E.appendChild(Cr(''));let R=(Wt=E==null?void 0:E.createSpan({cls:"ai3d-mobile-mode-btn-label"}))!=null?Wt:null,I=()=>{f&&E&&(JK(e,A),v(E,A),R==null||R.setText(A?J("helper.scrollAction"):J("helper.interactAction")),E.setAttribute("aria-label",A?J("helper.disableInteractionLabel"):J("helper.enableInteractionLabel"))),v($t,S),d.classList.toggle("show-secondary",S),x()},y=se=>{A=se,I()};E==null||E.addEventListener("click",()=>{let se=!A;l==null||l(se),y(se),Oi(E,se?J("helper.interactionOn"):J("helper.interactionOff"))});let M=(se,Q)=>{se.classList.toggle("is-hidden",!Q)},D=null,O=()=>{var Ae;let se=i(),Q=se&&ib(se)?se:null,Le=se&&tb(se)?se:null;v(Z,!!(Q!=null&&Q.isFocusSelectionEnabled())),v(X,!!(Le!=null&&Le.isDisassemblyEnabled())),se&&qO(se)&&v(ee,!!((Ae=se.isOrientationGizmoEnabled)!=null&&Ae.call(se)))},V=()=>{let se=i(),Q=se&&ib(se)?se:null,Le=se&&tb(se)?se:null,Ae=se&&jK(se)?se:null;se!==D&&(D=se,v(G,!1),v(j,!1),v(me,!1),me.replaceChildren(Cr('')),M(N,!!(se!=null&&se.resetView)),M(F,!!(se!=null&&se.exportModelInfo)),M(U,!!(se!=null&&se.exportSelectedPartInfo)),M(G,!!se&&qK(se)),M(ee,!!se&&qO(se)),M(j,!!se&&ZK(se)),M(Z,!!Q),M(X,!!Le),M(ae,!!se&&QK(se)),M(me,!!(Ae!=null&&Ae.hasAnimations()))),M(Y,!!(Le!=null&&Le.isDisassemblyEnabled())),M(re,!!se&&Ao(se)),M(de,!!se&&Ao(se)),M(De,!!se&&Ao(se)),O(),x()},N=u.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":J("helper.resetViewLabel")}});on(N,"reset-view"),N.appendChild(Cr('')),N.addEventListener("click",()=>{let se=i();se!=null&&se.resetView&&(se.resetView(),V(),Oi(N,J("helper.resetViewDone")))});let F=g(m.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":J("helper.copyModelInfoLabel")}}));on(F,"copy-model-info"),F.appendChild(Cr('')),F.addEventListener("click",()=>{let se=i();if(se!=null&&se.exportModelInfo)try{let Q=se.exportModelInfo(r());if(!Q)return;navigator.clipboard.writeText(Q).then(()=>{Oi(F,J("helper.copied"))}).catch(()=>{Oi(F,J("helper.failed"))})}catch(Q){console.error("[AI3D] Export model info failed:",Q),Oi(F,J("helper.failed"))}});let U=g(m.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":J("helper.copySelectedPartInfoLabel")}}));on(U,"copy-selected-part-info"),U.appendChild(Cr('')),U.addEventListener("click",()=>{let se=i();if(se!=null&&se.exportSelectedPartInfo)try{let Q=se.exportSelectedPartInfo();if(!Q){Oi(U,J("helper.noSelectedPart"));return}navigator.clipboard.writeText(Q).then(()=>{Oi(U,J("helper.copied"))}).catch(()=>{Oi(U,J("helper.failed"))})}catch(Q){console.error("[AI3D] Export selected part info failed:",Q),Oi(U,J("helper.failed"))}});let G=g(u.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":J("helper.toggleWireframeLabel"),"aria-pressed":"false"}}));on(G,"toggle-wireframe"),G.appendChild(Cr('')),G.addEventListener("click",()=>{let se=i();if(!(se!=null&&se.toggleWireframe))return;let Q=se.toggleWireframe();v(G,Q),Oi(G,Q?J("helper.wireframeOn"):J("helper.wireframeOff"))});let ee=g(u.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":J("helper.toggleAxesLabel"),"aria-pressed":"false"}}));on(ee,"toggle-axes"),ee.appendChild(Cr('')),ee.addEventListener("click",()=>{let se=i();if(!(se!=null&&se.toggleOrientationGizmo))return;let Q=se.toggleOrientationGizmo();v(ee,Q),Oi(ee,Q?J("helper.axesOn"):J("helper.axesOff"))});let j=g(u.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":J("helper.toggleBoundingBoxLabel"),"aria-pressed":"false"}}));on(j,"toggle-bounding-box"),j.appendChild(Cr('')),j.addEventListener("click",()=>{let se=i();if(!(se!=null&&se.toggleBoundingBox))return;let Q=se.toggleBoundingBox();v(j,Q),Oi(j,Q?J("helper.boundingBoxOn"):J("helper.boundingBoxOff"))});let Z=g(m.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":J("helper.toggleFocusSelectionLabel"),"aria-pressed":"false"}}));on(Z,"toggle-focus"),Z.appendChild(Cr('')),Z.addEventListener("click",()=>{let se=i();if(!se||!ib(se))return;let Q=se.toggleFocusSelection();V(),Oi(Z,Q?J("helper.focusSelectionOn"):J("helper.focusSelectionOff"))});let X=g(m.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":J("helper.toggleDisassemblyLabel"),"aria-pressed":"false"}}));on(X,"toggle-disassembly"),X.appendChild(Cr('')),X.addEventListener("click",()=>{let se=i();if(!se||!tb(se))return;let Q=se.toggleDisassembly();V(),Oi(X,Q?J("helper.disassemblyOn"):J("helper.disassemblyOff"))});let Y=g(m.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":J("helper.resetPartsLabel")}}));on(Y,"reset-parts"),Y.appendChild(Cr('')),Y.addEventListener("click",()=>{let se=i();se!=null&&se.resetDisassembly&&(se.resetDisassembly(),V(),Oi(Y,J("helper.partsReset")))});let ue=[.5,.75,1,1.5,2],Re=(jt=a==null?void 0:a().renderScale)!=null?jt:1,Be=ue.reduce((se,Q,Le)=>{let Ae=Math.abs(Q-Re),Je=Math.abs(ue[se]-Re);return Ae{let se=i();if(!(se!=null&&se.setRenderScale))return;Be=(Be+1)%ue.length;let Q=se.setRenderScale(ue[Be]);ae.textContent=`${Q.toFixed(1)}x`,Oi(ae,ur("helper.resolutionValue",{value:`${Q}x`}))});let me=g(u.createEl("button",{cls:"ai3d-inline-btn is-hidden",attr:{"aria-label":J("helper.toggleAnimationLabel"),"aria-pressed":"false"}}));on(me,"toggle-animation"),me.appendChild(Cr('')),me.addEventListener("click",()=>{let se=i();if(!(se!=null&&se.toggleAnimation))return;let Q=se.toggleAnimation();me.replaceChildren(Cr(Q?'':'')),v(me,Q),Oi(me,Q?J("helper.playing"):J("helper.paused"))});let re=g(m.createEl("button",{cls:"ai3d-inline-btn is-hidden",attr:{"aria-label":J("helper.toggleMeasurementLabel"),"aria-pressed":"false"}}));on(re,"toggle-measurement"),re.appendChild(Cr('')),re.addEventListener("click",()=>{let se=i();if(!se||!Ao(se))return;let Q=se.toggleMeasurement();v(re,Q),Oi(re,Q?J("helper.measurementOn"):J("helper.measurementOff")),Q||v(de,!1)});let de=g(m.createEl("button",{cls:"ai3d-inline-btn is-hidden",attr:{"aria-label":J("helper.clearMeasurementsLabel")}}));on(de,"clear-measurements"),de.appendChild(Cr('')),de.addEventListener("click",()=>{let se=i();!se||!Ao(se)||(se.clearMeasurements(),v(re,!1),Oi(de,J("helper.measurementsCleared")))});let De=g(m.createEl("button",{cls:"ai3d-inline-btn is-hidden",attr:{"aria-label":J("helper.calibrateLabel")}}));on(De,"toggle-calibration"),De.appendChild(Cr(''));let he=g(p.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":J("helper.removePreviewLabel")}}));on(he,"remove-preview"),he.appendChild(Cr('')),he.addEventListener("click",s);let Ie=p.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":J("helper.copySnapshotLabel")}});on(Ie,"copy-snapshot"),Ie.appendChild(Cr('')),Ie.addEventListener("click",()=>{let se=i();if(se)try{let Q=se.captureSnapshot();if(!Q)return;let Le=$K(Q);navigator.clipboard.write([new ClipboardItem({"image/png":Le})]).then(()=>{Oi(Ie,J("helper.copied"))}).catch(()=>{Oi(Ie,J("helper.failed"))})}catch(Q){console.error("[AI3D] Copy snapshot failed:",Q),Oi(Ie,J("helper.failed"))}});let ze=g(p.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":J("helper.saveSnapshotLabel")}}));on(ze,"save-snapshot"),ze.appendChild(Cr('')),ze.addEventListener("click",()=>{var Q,Le;let se=i();if(se)try{let Ae=se.captureSnapshot();if(!Ae)return;let Je=r(),Ke=jr(Je)||"model",Fe=a==null?void 0:a(),At=(Q=Fe==null?void 0:Fe.snapshotFolder)!=null?Q:"Media/3D Previews",qt=(Le=Fe==null?void 0:Fe.snapshotNaming)!=null?Le:"model-name",Ji=Date.now(),vi=qt==="timestamp"?`snapshot_${Ji}.png`:`${Ke}_snapshot_${Ji}.png`,xn=$K(Ae),ji=new FileReader;ji.onload=()=>{let Fa=ji.result;t.vault.adapter.exists(At).then(Tp=>Tp?Promise.resolve():t.vault.createFolder(At).catch(fv=>{Eue.warn("Failed to create vault folder",{path:At,error:String(fv)})})).then(()=>t.vault.createBinary(`${At}/${vi}`,Fa)).then(()=>{Oi(ze,J("helper.saved"))}).catch(Tp=>{console.error("[AI3D] Save snapshot failed:",Tp),Oi(ze,J("helper.failed"))})},ji.onerror=()=>{console.error("[AI3D] FileReader error"),Oi(ze,J("helper.failed"))},ji.onabort=()=>{console.error("[AI3D] FileReader aborted"),Oi(ze,J("helper.failed"))},ji.readAsArrayBuffer(xn)}catch(Ae){console.error("[AI3D] Save snapshot failed:",Ae),Oi(ze,J("helper.failed"))}});let St=g(p.createEl("button",{cls:"ai3d-inline-btn",attr:{"aria-label":J("helper.downloadSnapshotLabel")}}));on(St,"download-snapshot"),St.appendChild(Cr('')),St.addEventListener("click",()=>{let se=i();if(se)try{let Q=se.captureSnapshot();if(!Q)return;let Le=r(),Je=`${jr(Le)||"model"}_snapshot_${Date.now()}.png`,Ke=createEl("a");Ke.href=Q,Ke.download=Je,activeDocument.body.appendChild(Ke),Ke.click(),Ke.remove(),Oi(St,J("helper.downloaded"))}catch(Q){console.error("[AI3D] Download snapshot failed:",Q),Oi(St,J("helper.failed"))}});let Ye=g(m.createEl("button",{cls:"ai3d-inline-btn is-hidden ai3d-annot-btn",attr:{"aria-label":J(h.labelKey),"aria-pressed":"false"}}));on(Ye,"toggle-annotation"),Ye.appendChild(Cr(''));let je=Ye.createSpan({cls:"ai3d-pin-badge is-hidden"});Ye.addEventListener("click",()=>{if(!o)return;let se=o();v(Ye,se),Oi(Ye,se?J(h.activeTooltipKey):J(h.inactiveTooltipKey))});let $t=d.createEl("button",{cls:"ai3d-inline-btn ai3d-mobile-more-toggle",attr:{"aria-label":J("helper.showMoreActionsLabel"),"aria-pressed":"false"}});$t.appendChild(Cr('')),$t.addEventListener("click",()=>{S=!S,$t.setAttribute("aria-label",S?J("helper.hideMoreActionsLabel"):J("helper.showMoreActionsLabel")),I(),Oi($t,S?J("helper.moreActionsShown"):J("helper.moreActionsHidden"))}),n.insertBefore(d,e.nextSibling);let Lt=n.createDiv({cls:"ai3d-calibrate-panel is-hidden"});Lt.createDiv({cls:"ai3d-calibrate-title",text:J("helper.calibrateTitle")});let xi=Lt.createDiv({cls:"ai3d-calibrate-row"});xi.createSpan({cls:"ai3d-calibrate-label",text:J("helper.calibrateCurrent")});let oe=xi.createSpan({cls:"ai3d-calibrate-readonly"}),Ui=xi.createSpan({cls:"ai3d-calibrate-readonly"}),ti=xi.createSpan({cls:"ai3d-calibrate-readonly"}),Ni=Lt.createDiv({cls:"ai3d-calibrate-row"});Ni.createSpan({cls:"ai3d-calibrate-label",text:J("helper.calibrateReal")});let ot=Ni.createEl("input",{cls:"ai3d-calibrate-input",attr:{type:"number",step:"any",placeholder:"X"}}),yi=Ni.createEl("input",{cls:"ai3d-calibrate-input",attr:{type:"number",step:"any",placeholder:"Y"}}),z=Ni.createEl("input",{cls:"ai3d-calibrate-input",attr:{type:"number",step:"any",placeholder:"Z"}}),B=Lt.createDiv({cls:"ai3d-calibrate-row"}),pe=B.createEl("select",{cls:"ai3d-calibrate-select"});for(let se of[{v:"um",l:"\u03BCm"},{v:"mm",l:"mm"},{v:"cm",l:"cm"},{v:"m",l:"m"}])pe.createEl("option",{text:se.l,value:se.v});pe.value="mm";let Pe=B.createEl("label",{cls:"ai3d-calibrate-lock"}),Ve=Pe.createEl("input",{attr:{type:"checkbox",checked:"true"}});Pe.appendText(" "+J("helper.calibrateLock"));let $e=Lt.createDiv({cls:"ai3d-calibrate-row ai3d-calibrate-actions"}),rt=$e.createEl("button",{cls:"ai3d-inline-btn",text:J("helper.calibrateApply")}),ye=$e.createEl("button",{cls:"ai3d-inline-btn is-secondary",text:J("helper.calibrateReset")}),be=null;function ct(){var Le,Ae;let se=i();if(!se||!Ao(se))return;let Q=(Ae=(Le=se.getMeasurementBounds)==null?void 0:Le.call(se))!=null?Ae:null;be=Q,Q?(oe.textContent=`X: ${Q.x.toFixed(3)}`,Ui.textContent=`Y: ${Q.y.toFixed(3)}`,ti.textContent=`Z: ${Q.z.toFixed(3)}`):(oe.textContent="X: -",Ui.textContent="Y: -",ti.textContent="Z: -")}function Tt(){var Ke;let se=i();if(!se||!Ao(se)||!be)return;let Q=parseFloat(ot.value),Le=parseFloat(yi.value),Ae=parseFloat(z.value);if(!isFinite(Q)||!isFinite(Le)||!isFinite(Ae))return;let Je={x:be.x>1e-4?Q/be.x:1,y:be.y>1e-4?Le/be.y:1,z:be.z>1e-4?Ae/be.z:1};(Ke=se.setMeasurementScale)==null||Ke.call(se,Je),Oi(rt,J("helper.calibrated"))}function nt(){var Q;let se=i();!se||!Ao(se)||((Q=se.setMeasurementScale)==null||Q.call(se,{x:1,y:1,z:1}),ct(),be?(ot.value=be.x.toFixed(3),yi.value=be.y.toFixed(3),z.value=be.z.toFixed(3)):(ot.value="",yi.value="",z.value=""),Oi(ye,J("helper.calibrateResetDone")))}function Ze(se){if(!Ve.checked||!be)return;let Le=parseFloat((se==="x"?ot:se==="y"?yi:z).value);if(!isFinite(Le)||Le===0)return;let Ae=be[se];if(Ae<=1e-4)return;let Je=Le/Ae;se!=="x"&&(ot.value=(be.x*Je).toFixed(3)),se!=="y"&&(yi.value=(be.y*Je).toFixed(3)),se!=="z"&&(z.value=(be.z*Je).toFixed(3))}return ot.addEventListener("input",()=>Ze("x")),yi.addEventListener("input",()=>Ze("y")),z.addEventListener("input",()=>Ze("z")),rt.addEventListener("click",Tt),ye.addEventListener("click",nt),De.addEventListener("click",()=>{let se=Lt.classList.contains("is-hidden");se&&(ct(),be&&(ot.value=be.x.toFixed(3),yi.value=be.y.toFixed(3),z.value=be.z.toFixed(3))),Lt.classList.toggle("is-hidden",!se),v(De,se),Oi(De,se?J("helper.calibrateOpen"):J("helper.calibrateClose"))}),I(),V(),{showAnimButton(){me.classList.remove("is-hidden"),x()},showAnnotateButton(){Ye.classList.remove("is-hidden"),x()},updateAnnotationBadge(se){se>0?(je.textContent=String(se),je.classList.remove("is-hidden")):je.classList.add("is-hidden")},setMobileInteractionMode(se){f&&y(se)},syncCapabilities:V}}function Oi(n,e){var i;(i=ZO.get(n))==null||i.remove();let t=n.createSpan({cls:"ai3d-tooltip"});t.textContent=e,ZO.set(n,t),window.setTimeout(()=>{t.remove(),ZO.delete(n)},1500)}var Eue,ZO,QO=C(()=>{"use strict";ia();Tn();rb();Ys();oa();Eue=Wi("helper-buttons");ZO=new WeakMap});function Tue(n,e,t){let i=typeof activeWindow!="undefined"?activeWindow.setTimeout.bind(activeWindow):setTimeout,r=typeof activeWindow!="undefined"?activeWindow.clearTimeout.bind(activeWindow):clearTimeout,s=new Promise((a,o)=>{let l=i(()=>{o(new $O(`Conversion did not complete within ${e}ms`))},e);n.then(()=>r(l)).catch(()=>r(l))});return Promise.race([n,s])}var Jg,Sue,$O,nb,ej=C(()=>{"use strict";Io();Tn();Jg=Wi("conversion-manager"),Sue=12e4,$O=class extends Error{constructor(e="Conversion timed out"){super(e),this.name="ConversionTimeoutError"}};nb=class{constructor(){this.converters=new Map;this.pending=new Map}getConverter(e){return this.converters.get(Ba(e))}registerConverter(e){Jg.info("register converter",{converterId:e.id,sourceExts:[...e.sourceExts]});for(let t of e.sourceExts)this.converters.set(Ba(t),e)}canConvert(e){let t=Ba(e),i=this.converters.has(t);return Jg.debug("can convert",{ext:t,ok:i}),i}async getConverterCacheIdentity(e){let t=this.getConverter(e);if(t)return{converterId:t.id,cacheKey:await t.getCacheKey()}}async convert(e){var o;let t=Ba(e.sourceExt),i=this.getConverter(t);if(!i)throw Jg.error("converter missing",{ext:t,targetExt:e.targetExt}),new Error(`No converter registered for .${t}`);let r=`${e.sourcePath}::${t}::${e.targetExt}`,s=this.pending.get(r);if(s)return Jg.info("joining in-flight conversion",{key:r}),s;Jg.info("dispatch conversion",{converterId:i.id,ext:t,targetExt:e.targetExt});let a=Tue(i.convert({...e,sourceExt:t}),(o=e.timeoutMs)!=null?o:Sue,{converterId:i.id,ext:t,targetExt:e.targetExt});this.pending.set(r,a);try{return await a}finally{this.pending.delete(r)}}}});function tN(...n){let e=(We==null?void 0:We.platform)==="darwin"?["/opt/homebrew/bin","/usr/local/bin","/opt/local/bin","/usr/bin"]:["/usr/local/bin","/opt/homebrew/bin","/opt/local/bin","/usr/bin"];return Array.from(new Set(e.flatMap(t=>n.map(i=>`${t}/${i}`))))}function xue(){var r,s,a;if((We==null?void 0:We.platform)==="darwin")return["/Applications/FreeCAD.app/Contents/MacOS/FreeCADCmd","/Applications/FreeCAD.app/Contents/Resources/bin/FreeCADCmd","/Applications/FreeCAD.app/Contents/Resources/bin/freecadcmd",...tN("FreeCADCmd","freecadcmd")];if((We==null?void 0:We.platform)!=="win32")return["/usr/local/bin/freecadcmd","/opt/homebrew/bin/freecadcmd","/opt/local/bin/freecadcmd","/snap/freecad/current/usr/bin/freecadcmd","/usr/bin/freecadcmd"];let n=[],e=(r=We==null?void 0:We.env)==null?void 0:r.LOCALAPPDATA,t=(s=We==null?void 0:We.env)==null?void 0:s.ProgramFiles,i=(a=We==null?void 0:We.env)==null?void 0:a["ProgramFiles(x86)"];if(e&&n.push(zi(e,"Programs","FreeCAD","bin","FreeCADCmd.exe")),t&&n.push(zi(t,"FreeCAD","bin","FreeCADCmd.exe")),e)for(let o of["1.2","1.1","1.0","0.22","0.21","0.20"])n.push(`${e}/Programs/FreeCAD ${o}/bin/FreeCADCmd.exe`);if(t)for(let o of["1.2","1.1","1.0","0.22","0.21","0.20"])n.push(`${t}/FreeCAD ${o}/bin/FreeCADCmd.exe`);return i&&n.push(`${i}/FreeCAD/bin/FreeCADCmd.exe`),n}function Rue(n){var a,o,l,c;if((We==null?void 0:We.platform)!=="win32")return[];let e=(a=We==null?void 0:We.env)==null?void 0:a.APPDATA,t=(o=We==null?void 0:We.env)==null?void 0:o.LOCALAPPDATA,i=(l=We==null?void 0:We.env)==null?void 0:l.npm_config_prefix,r=(c=We==null?void 0:We.env)==null?void 0:c.USERPROFILE,s=[i,e?zi(e,"npm"):void 0,t?zi(t,"npm"):void 0,r?zi(r,"AppData","Roaming","npm"):void 0].filter(f=>!!f);return Array.from(new Set(s.map(f=>zi(f,n))))}function bue(...n){var s,a,o;if((We==null?void 0:We.platform)!=="win32")return[];let e=(s=We==null?void 0:We.env)==null?void 0:s.ProgramFiles,t=(a=We==null?void 0:We.env)==null?void 0:a["ProgramFiles(x86)"],i=(o=We==null?void 0:We.env)==null?void 0:o.LOCALAPPDATA,r=[e,t,i?zi(i,"Programs"):void 0].filter(l=>!!l);return Array.from(new Set(r.flatMap(l=>n.map(c=>zi(l,c)))))}async function nN(n){try{return await ls(n,(We==null?void 0:We.platform)==="win32"?cs:JN),!0}catch(e){return!1}}function JO(n){let e=n==null?void 0:n.trim();if(e)return e}function rj(n){return Iue.test(n)?{ok:!1,reason:"Command contains unsafe shell metacharacters."}:{ok:!0}}async function Mue(n){try{return(await $N(n)).isFile()}catch(e){return!1}}function Cue(n){let e=[],t="",i=null;for(let r=0;rr.trim().toLowerCase()).filter(Boolean);return e!=null&&e.length?e:Aue}async function Lue(n){var r;let e=(r=We==null?void 0:We.env)==null?void 0:r.PATH;if(!e)return;let t=e.split(ew).map(s=>s.trim()).filter(Boolean),i=(We==null?void 0:We.platform)==="win32"?Due(n):[""];for(let s of t)for(let a of i){let o=zi(s,a?`${n}${a}`:n);if(await nN(o))return o}}function iN(n,e,t=15e3){let i=rj(n);return i.ok?new Promise((r,s)=>{sa(n,e,{timeout:t,windowsHide:!0,maxBuffer:4*1024*1024},(a,o,l)=>{if(a){s(new Error((l||o||a.message).toString().trim()||a.message));return}r({stdout:o!=null?o:"",stderr:l!=null?l:""})})}):Promise.reject(new Error(`Refusing to execute converter command: ${i.reason}`))}function rN(n){let t=(n instanceof Error?n.message:String(n)).replace(/\s+/g," ").trim();return t.length>180?`${t.slice(0,177)}...`:t}async function eN(n,e,t,i){let r="";for(let s of t)try{return await iN(n,[...e,...s]),{ok:!0,detail:""}}catch(a){let o=rN(a);if(i.test(o))return{ok:!0,detail:""};r=o}return{ok:!1,detail:r||"Command probe failed."}}async function Oue(n){var i;if(!n.available)return[];let e=(i=n.resolvedPath)!=null?i:n.executable,t=[...n.args];if(n.id==="freecad")try{return await iN(e,[...t,"-c","import cadquery, trimesh; print('ok')"]),[{kind:"cad-python",ok:!0,detail:""}]}catch(r){return[{kind:"cad-python",ok:!1,detail:rN(r)}]}if(n.id==="assimp")try{return await iN(e,[...t,"-c","import trimesh, numpy, networkx, collada; print('ok')"]),[{kind:"mesh-python",ok:!0,detail:""}]}catch(r){return[{kind:"mesh-python",ok:!1,detail:rN(r)}]}if(n.id==="freecadcmd"){let r=await eN(e,t,[["--version"],["--help"]],/freecad|usage|help|version/i);return[{kind:"freecadcmd-cli",ok:r.ok,detail:r.detail}]}if(n.id==="obj2gltf"){let r=await eN(e,t,[["--version"],["--help"]],/obj2gltf|usage|help|version/i);return[{kind:"obj2gltf-cli",ok:r.ok,detail:r.detail}]}if(n.id==="fbx2gltf"){let r=await eN(e,t,[["--version"],["--help"]],/fbx2gltf|usage|help|version/i);return[{kind:"fbx2gltf-cli",ok:r.ok,detail:r.detail}]}return[]}function Nue(n){let e=ij.find(t=>t.id===n);if(!e)throw new Error(`Unknown converter command id: ${n}`);return e}function wue(n){var s,a,o,l;let e=(a=(s=We==null?void 0:We.env)==null?void 0:s.ProgramFiles)==null?void 0:a.toLowerCase(),t=(l=(o=We==null?void 0:We.env)==null?void 0:o["ProgramFiles(x86)"])==null?void 0:l.toLowerCase(),i=[],r=[];for(let c of n.knownCandidates){let f=c.toLowerCase(),h=(We==null?void 0:We.platform)==="win32"&&((e?f.startsWith(e):!1)||(t?f.startsWith(t):!1)),d=(We==null?void 0:We.platform)!=="win32"&&(c.startsWith("/usr/bin/")||c.startsWith("/snap/freecad/current/usr/bin/"));h||d?r.push(c):i.push(c)}return{userCandidates:i,systemCandidates:r}}async function tj(n,e,t){for(let i of e)if(await nN(i))return{id:n.id,label:n.label,envVar:n.envVar,settingsKey:n.settingsKey,command:i,executable:i,args:[],resolvedPath:i,available:!0,source:"candidate",detail:t,checkedCandidates:[i]}}function Fue(n,e){let t=[];return n.length&&t.push(`Checked common user locations: ${n.join("; ")}`),e.length&&t.push(`Checked system fallback locations: ${e.join("; ")}`),t.join(". ")}async function sb(n,e,t,i){let r=yue(e),s=rj(r.executable);if(!s.ok)return{id:n.id,label:n.label,envVar:n.envVar,settingsKey:n.settingsKey,configuredCommand:i,command:e,executable:r.executable,args:r.args,resolvedPath:void 0,available:!1,source:t,detail:s.reason,checkedCandidates:[r.executable]};if(Pue(r.executable)){let[o,l]=await Promise.all([nN(r.executable),Mue(r.executable)]),c=o&&l;return{id:n.id,label:n.label,envVar:n.envVar,settingsKey:n.settingsKey,configuredCommand:i,command:e,executable:r.executable,args:r.args,resolvedPath:c?r.executable:void 0,available:c,source:t,detail:c?`Using ${ab(t)} path.`:"Configured path was not found or is not executable.",checkedCandidates:[r.executable]}}let a=await Lue(r.executable);return{id:n.id,label:n.label,envVar:n.envVar,settingsKey:n.settingsKey,configuredCommand:i,command:e,executable:r.executable,args:r.args,resolvedPath:a,available:!!a,source:t,detail:a?`Resolved from ${ab(t)} via PATH lookup.`:"Command name was not found on PATH.",checkedCandidates:[r.executable]}}function ab(n){switch(n){case"settings":return"plugin settings";case"env":return"environment variable";case"candidate":return"known install location";case"path":return"PATH fallback"}}async function nj(n,e){var d,u,m;let t=Nue(n),{userCandidates:i,systemCandidates:r}=wue(t),s=JO(e);if(s)return sb(t,s,"settings",s);let a=JO((d=We==null?void 0:We.env)==null?void 0:d[t.envVar]);if(a)return sb(t,a,"env");for(let p of(u=t.envVarAliases)!=null?u:[]){let _=JO((m=We==null?void 0:We.env)==null?void 0:m[p]);if(_)return sb(t,_,"env")}let o=await tj(t,i,"Detected at a common user-managed install location.");if(o)return o;let l=[];for(let p of t.fallbackCommands){let _=await sb(t,p,"path");if(l.push(_),_.available)return _}let c=await tj(t,r,"Detected at a system fallback install location.");if(c)return c;let f=l.flatMap(p=>p.checkedCandidates),h=Fue(i,r);return{...l[0],detail:h?`Command name was not found on PATH. ${h}`:"Command name was not found on PATH.",checkedCandidates:[...i,...f,...r]}}async function ob(n){let e=await Promise.all(ij.map(t=>nj(t.id,n[t.settingsKey])));return Promise.all(e.map(async t=>({...t,dependencyChecks:await Oue(t)})))}async function as(n,e){var i;let t=await nj(n,e);return{command:(i=t.resolvedPath)!=null?i:t.executable,args:[...t.args]}}var We,Aue,ij,Iue,$f=C(()=>{"use strict";or();or();or();We=uv(),Aue=[".exe",".cmd",".bat",".com"];ij=[{id:"freecad",label:"Python (CadQuery/OCCT)",settingsKey:"freecadCommand",envVar:"AI3D_FREECAD_CMD",fallbackCommands:(We==null?void 0:We.platform)==="win32"?["py","python"]:["python3","python"],knownCandidates:(We==null?void 0:We.platform)==="win32"?[]:["/usr/local/bin/python3","/opt/homebrew/bin/python3","/opt/local/bin/python3","/usr/bin/python3"]},{id:"obj2gltf",label:"obj2gltf",settingsKey:"obj2gltfCommand",envVar:"AI3D_OBJ2GLTF_CMD",fallbackCommands:(We==null?void 0:We.platform)==="win32"?["obj2gltf.cmd"]:["obj2gltf"],knownCandidates:(We==null?void 0:We.platform)==="win32"?Rue("obj2gltf.cmd"):tN("obj2gltf")},{id:"fbx2gltf",label:"FBX2glTF",settingsKey:"fbx2gltfCommand",envVar:"AI3D_FBX2GLTF_CMD",fallbackCommands:(We==null?void 0:We.platform)==="win32"?["FBX2glTF.exe"]:["FBX2glTF","fbx2gltf"],knownCandidates:(We==null?void 0:We.platform)==="win32"?bue(zi("FBX2glTF","FBX2glTF-windows-x64.exe"),zi("FBX2glTF","FBX2glTF.exe")):tN("FBX2glTF","fbx2gltf")},{id:"assimp",label:"Python (trimesh)",settingsKey:"assimpCommand",envVar:"AI3D_ASSIMP_CMD",fallbackCommands:(We==null?void 0:We.platform)==="win32"?["py","python"]:["python3","python"],knownCandidates:(We==null?void 0:We.platform)==="win32"?[]:["/usr/local/bin/python3","/opt/homebrew/bin/python3","/opt/local/bin/python3","/usr/bin/python3"]},{id:"freecadcmd",label:"FreeCAD (SLDPRT)",settingsKey:"freecadcmdCommand",envVar:"AI3D_FREECADCMD",envVarAliases:["AI3D_FREECMDCMD"],fallbackCommands:(We==null?void 0:We.platform)==="win32"?["FreeCADCmd.exe"]:["freecadcmd","FreeCADCmd"],knownCandidates:xue()}];Iue=/[;|&<>$`\r\n\t{}()[\]\\]/});function bc(n){if(n.includes('"'))throw new Error(`File path contains double-quote character, not supported for Python conversion: ${n}`);return n.replace(/\\/g,"/")}var lb=C(()=>{"use strict"});async function Vue(n){try{return await ls(n,cs),!0}catch(e){return!1}}function Gue(n,e,t){return new Promise((i,r)=>{sa(n,e,{timeout:t,windowsHide:!0,maxBuffer:50*1024*1024},(s,a,o)=>{if(!s){i();return}let l=(a!=null?a:"").toString().trim(),c=(o!=null?o:"").toString().trim(),f=[`CAD conversion failed: ${s.message}`,l?`stdout: ${l}`:"",c?`stderr: ${c}`:""].filter(Boolean);r(new Error(f.join(" | ")))})})}function kue(n,e,t){let i=bc(n),r=bc(e),s=t.toLowerCase().replace(/^\./,""),a=s==="step"||s==="stp",o=s==="iges"||s==="igs",l=["import cadquery as cq","import trimesh","import trimesh.visual","import numpy as np","import sys","import os","import re","import shutil","import tempfile","",`src = r"${i}"`,`out = r"${r}"`,`source_ext = "${s}"`,"src_occt = src","try:"," src.encode('ascii')","except UnicodeEncodeError:"," safe_src = os.path.join(tempfile.gettempdir(), f'ai3d-occt-source-{os.getpid()}.{source_ext}')"," shutil.copyfile(src, safe_src)"," src_occt = safe_src",""];return a?l.push("from OCP.STEPCAFControl import STEPCAFControl_Reader","from OCP.STEPControl import STEPControl_Reader","from OCP.XCAFDoc import XCAFDoc_DocumentTool, XCAFDoc_ColorType, XCAFDoc_ShapeTool","from OCP.TDocStd import TDocStd_Document","from OCP.TCollection import TCollection_ExtendedString","from OCP.Quantity import Quantity_Color","from OCP.TDF import TDF_ChildIterator, TDF_LabelSequence","from OCP.TDataStd import TDataStd_Name"):o&&l.push("from OCP.IGESControl import IGESControl_Reader"),l.push("from OCP.TopoDS import TopoDS","from OCP.TopAbs import TopAbs_FACE","from OCP.TopExp import TopExp_Explorer","from OCP.BRep import BRep_Tool","from OCP.BRepMesh import BRepMesh_IncrementalMesh","from OCP.TopLoc import TopLoc_Location","from OCP.IFSelect import IFSelect_RetDone"),a||l.push("from OCP.BRepTools import BRepTools"),l.push("","DEFAULT_COLOR = [180, 180, 180, 255]","","def triangulate_face(face, linear=0.1, angular=0.5):"," BRepMesh_IncrementalMesh(face, linear, False, angular, True)"," loc = TopLoc_Location()"," tri = BRep_Tool.Triangulation_s(face, loc)"," if tri is None:"," return None, None"," n = tri.NbNodes()"," verts = []"," for i in range(1, n + 1):"," p = tri.Node(i)"," if not loc.IsIdentity():"," p = p.Transformed(loc.Transformation())"," verts.append([p.X(), p.Y(), p.Z()])"," ntri = tri.NbTriangles()"," faces = []"," for i in range(1, ntri + 1):"," t = tri.Triangle(i)"," n1, n2, n3 = t.Get()"," faces.append([n1 - 1, n2 - 1, n3 - 1])"," return verts, faces"),a&&l.push("","def build_xde_color_lookup(step_path):",' """Load XDE with STEPCAFControl, extract per-face colors via surface signature."""'," from OCP.BRepAdaptor import BRepAdaptor_Surface"," lookup = {}"," try:"," reader = STEPCAFControl_Reader()"," reader.SetColorMode(True)"," reader.SetNameMode(True)"," status = reader.ReadFile(step_path)"," if status != IFSelect_RetDone:"," return lookup"," doc = TDocStd_Document(TCollection_ExtendedString('XmlOcaf'))"," reader.Transfer(doc)"," shape_tool = XCAFDoc_DocumentTool.ShapeTool_s(doc.Main())"," color_tool = XCAFDoc_DocumentTool.ColorTool_s(doc.Main())",""," def walk(label):"," if XCAFDoc_ShapeTool.IsShape_s(label):"," s = XCAFDoc_ShapeTool.GetShape_s(label)"," if s is not None and s.ShapeType() == TopAbs_FACE:"," c = Quantity_Color()"," if color_tool.GetColor(s, XCAFDoc_ColorType.XCAFDoc_ColorSurf, c):"," face = TopoDS.Face_s(s)"," try:"," adaptor = BRepAdaptor_Surface(face)"," u_r = (adaptor.FirstUParameter(), adaptor.LastUParameter())"," v_r = (adaptor.FirstVParameter(), adaptor.LastVParameter())"," key = (adaptor.GetType(), tuple(round(x, 4) for x in u_r), tuple(round(x, 4) for x in v_r))"," color = (c.Red(), c.Green(), c.Blue())"," if key not in lookup:"," lookup[key] = color"," except Exception:"," pass"," children = TDF_ChildIterator(label)"," while children.More():"," walk(children.Value())"," children.Next()",""," walk(doc.Main())"," except Exception as e:",' print(f"XDE color extraction failed: {e}", file=sys.stderr)'," return lookup","","def get_face_color(face, color_lookup):",' """Match a geometry face to an XDE face via surface signature, return color."""'," from OCP.BRepAdaptor import BRepAdaptor_Surface"," try:"," adaptor = BRepAdaptor_Surface(face)"," u_r = (adaptor.FirstUParameter(), adaptor.LastUParameter())"," v_r = (adaptor.FirstVParameter(), adaptor.LastVParameter())"," key = (adaptor.GetType(), tuple(round(x, 4) for x in u_r), tuple(round(x, 4) for x in v_r))"," return color_lookup.get(key)"," except Exception:"," return None","","def label_name(label):"," name_attr = TDataStd_Name()"," try:"," if label.FindAttribute(TDataStd_Name.GetID_s(), name_attr):"," return name_attr.Get().ToExtString()"," except Exception:"," pass"," return ''","","def clean_component_name(value, fallback):"," text = re.sub(r'\\s+', ' ', str(value or '')).strip()"," if not text or text.startswith('=>'):"," text = fallback"," return text[:96]","","def count_shape_faces(shape):"," count = 0"," exp = TopExp_Explorer(shape, TopAbs_FACE)"," while exp.More():"," count += 1"," exp.Next()"," return count","","def unique_component_name(name, used):"," base = clean_component_name(name, f'component-{len(used) + 1:03d}')"," candidate = base"," suffix = 2"," while candidate in used:"," candidate = f'{base}-{suffix}'"," suffix += 1"," used.add(candidate)"," return candidate","","def collect_xde_components(step_path):"," components = []"," try:"," reader = STEPCAFControl_Reader()"," reader.SetColorMode(True)"," reader.SetNameMode(True)"," status = reader.ReadFile(step_path)"," if status != IFSelect_RetDone:"," return components"," doc = TDocStd_Document(TCollection_ExtendedString('XmlOcaf'))"," if not reader.Transfer(doc):"," return components"," shape_tool = XCAFDoc_DocumentTool.ShapeTool_s(doc.Main())"," free = TDF_LabelSequence()"," shape_tool.GetFreeShapes(free)"," used_names = set()",""," def walk(label, path_parts):"," if not XCAFDoc_ShapeTool.IsShape_s(label):"," child = TDF_ChildIterator(label)"," while child.More():"," walk(child.Value(), path_parts)"," child.Next()"," return"," raw_name = label_name(label)"," next_path = path_parts + ([raw_name] if raw_name and not raw_name.startswith('=>') else [])"," shape = XCAFDoc_ShapeTool.GetShape_s(label)"," face_count = 0 if shape is None or shape.IsNull() else count_shape_faces(shape)"," try:"," is_assembly = XCAFDoc_ShapeTool.IsAssembly_s(label)"," except Exception:"," is_assembly = False"," try:"," is_component = XCAFDoc_ShapeTool.IsComponent_s(label)"," except Exception:"," is_component = False"," if face_count > 0 and not is_assembly:"," name = unique_component_name(raw_name, used_names)"," component_path = '/'.join([part for part in next_path if part]) or name"," components.append({"," 'name': name,"," 'path': component_path,"," 'shape': shape,"," 'face_count': face_count,"," 'is_component': is_component,"," })"," return"," child = TDF_ChildIterator(label)"," while child.More():"," walk(child.Value(), next_path)"," child.Next()",""," for index in range(1, free.Length() + 1):"," walk(free.Value(index), [])"," except Exception as e:"," print(f'XDE component extraction failed: {e}', file=sys.stderr)"," return components","","def mesh_from_shape(shape, color_lookup, name, component_path):"," try:"," BRepMesh_IncrementalMesh(shape, 0.1, False, 0.5, True)"," except Exception:"," pass"," verts_acc = []"," faces_acc = []"," colors_acc = []"," matched = 0"," total = 0"," exp = TopExp_Explorer(shape, TopAbs_FACE)"," while exp.More():"," face = TopoDS.Face_s(exp.Current())"," total += 1"," verts, faces = triangulate_face(face)"," if verts and faces:"," offset = len(verts_acc)"," verts_acc.extend(verts)"," for tri in faces:"," faces_acc.append([tri[0] + offset, tri[1] + offset, tri[2] + offset])"," color = get_face_color(face, color_lookup)"," if color:"," matched += 1"," r, g, b = color"," rgba = [int(r * 255), int(g * 255), int(b * 255), 255]"," else:"," rgba = DEFAULT_COLOR"," colors_acc.extend([rgba] * len(verts))"," exp.Next()"," if not verts_acc or not faces_acc:"," return None, total, matched"," mesh = trimesh.Trimesh("," vertices=np.array(verts_acc, dtype=float),"," faces=np.array(faces_acc, dtype=int),"," visual=trimesh.visual.ColorVisuals(vertex_colors=np.array(colors_acc, dtype=np.uint8)),"," process=True,"," )"," mesh.fix_normals()"," mesh.metadata.update({"," 'name': name,"," 'ai3d': {"," 'partId': name,"," 'componentId': name,"," 'occurrenceId': component_path,"," 'componentPath': component_path,"," 'displayName': name,"," },"," })"," return mesh, total, matched"),l.push(""),a?l.push("# STEP: build XDE color lookup + load geometry","color_lookup = build_xde_color_lookup(src_occt)",'print(f"XDE color lookup: {len(color_lookup)} surface signatures")',"xde_components = collect_xde_components(src_occt)","component_meshes = []","component_faces = 0","component_matched = 0","for component in xde_components:"," mesh_result, total, matched = mesh_from_shape(component['shape'], color_lookup, component['name'], component['path'])"," component_faces += total"," component_matched += matched"," if mesh_result is not None:"," component_meshes.append((component, mesh_result))","if len(component_meshes) > 1:"," scene = trimesh.Scene()"," for component, mesh_result in component_meshes:"," scene.add_geometry(mesh_result, node_name=component['name'], geom_name=component['name'])"," result = scene.export(file_type='glb')"," if isinstance(result, bytes):"," data = result"," elif isinstance(result, str):"," with open(result, 'rb') as f:"," data = f.read()"," else:"," data = bytes(result)"," with open(out, 'wb') as f:"," f.write(data)"," print(f'Converted {src} -> {out} ({len(data)} bytes, {len(component_meshes)} XDE components, {component_matched}/{component_faces} colored faces)')"," sys.exit(0)",'print(f"XDE component export unavailable: {len(component_meshes)} usable components from {len(xde_components)} labels; falling back to whole-shape mesh")',"","sr = STEPControl_Reader()","status = sr.ReadFile(src_occt)","if status != IFSelect_RetDone:",' print(f"Failed to read STEP file: {src}", file=sys.stderr)'," sys.exit(1)","sr.TransferRoots()","shape = sr.OneShape()"):o?l.push("# IGES: load geometry (no XDE color support for IGES)","ir = IGESControl_Reader()","status = ir.ReadFile(src_occt)","if status != IFSelect_RetDone:",' print(f"Failed to read IGES file: {src}", file=sys.stderr)'," sys.exit(1)","ir.TransferRoots()","shape = ir.OneShape()"):l.push("# BREP: load geometry from native OpenCascade format","from OCP.TopoDS import TopoDS_Shape","from OCP.BRep import BRep_Builder","shape = TopoDS_Shape()","builder = BRep_Builder()","success = BRepTools.Read_s(shape, src_occt, builder)","if not success:",' print(f"Failed to read BREP file: {src}", file=sys.stderr)'," sys.exit(1)"),l.push("","all_verts = []","all_faces = []","all_colors = []","matched_count = 0","total_faces = 0","","exp = TopExp_Explorer(shape, TopAbs_FACE)","while exp.More():"," face = TopoDS.Face_s(exp.Current())"," total_faces += 1"," verts, faces = triangulate_face(face)"," if verts and faces:"," offset = len(all_verts)"," all_verts.extend(verts)"," for tri in faces:"," all_faces.append([tri[0] + offset, tri[1] + offset, tri[2] + offset])"),a?l.push(" color = get_face_color(face, color_lookup)"," if color:"," matched_count += 1"," r, g, b = color"," rgba = [int(r * 255), int(g * 255), int(b * 255), 255]"," else:"," rgba = DEFAULT_COLOR"):l.push(" rgba = DEFAULT_COLOR"),l.push(" n = len(verts)"," all_colors.extend([rgba] * n)"," exp.Next()","",'print(f"Triangulated: {total_faces} faces, {len(all_verts)} verts, {matched_count} colored ({matched_count*100//max(total_faces,1)}%)")',"","if not all_verts or not all_faces:"," # Fallback: use CadQuery import (works for STEP/IGES, not BREP)"),a?l.push(" cq_shape = cq.importers.importStep(src_occt)"):o?l.push(" cq_shape = cq.importers.importStep(src_occt) # CadQuery reads IGES via importStep"):l.push(" cq_shape = cq.importers.importStep(src_occt) # CadQuery BREP import"),l.push(" cq.exporters.export(cq_shape, out, exportType='STL')"," mesh = trimesh.load(out)"," data = mesh.export(file_type='glb')"," if isinstance(data, str):"," with open(data, 'rb') as f:"," data = f.read()"," with open(out, 'wb') as f:"," f.write(data)",' print(f"Fallback CadQuery STL->GLB: {out} ({len(data)} bytes)")'," sys.exit(0)","","verts_arr = np.array(all_verts, dtype=float)","faces_arr = np.array(all_faces, dtype=int)","colors_arr = np.array(all_colors, dtype=np.uint8)","","mesh = trimesh.Trimesh("," vertices=verts_arr,"," faces=faces_arr,"," visual=trimesh.visual.ColorVisuals(vertex_colors=colors_arr),"," process=True,",")","mesh.fix_normals()","scene = trimesh.Scene([mesh])","","result = scene.export(file_type='glb')","if isinstance(result, bytes):"," data = result","elif isinstance(result, str):"," with open(result, 'rb') as f:"," data = f.read()","else:"," data = bytes(result)","","with open(out, 'wb') as f:"," f.write(data)","","print(f'Converted {src} -> {out} ({len(data)} bytes, {matched_count}/{total_faces} colored faces)')"),l.join(` +`)}var Bue,Uue,cb,sj=C(()=>{"use strict";or();or();or();or();Tn();$f();lb();Bue=Wi("freecad-converter"),Uue=300*1e3;cb=class{constructor(e){this.configuredCommand=e;this.id="freecad";this.sourceExts=["step","stp","iges","igs","brep"];this.targetExt="glb"}async getCacheKey(){let e=await as(this.id,this.configuredCommand);return`${this.id}:${e.command} ${e.args.join(" ")}`.trim()}async convert(e){if(!Xn(e.sourcePath))throw new Error(`Converter '${this.id}' requires an absolute source path, got '${e.sourcePath}'. Pass a file-system path to the conversion pipeline when invoking CAD conversion.`);let t=await as(this.id,this.configuredCommand),i=Mo(e.sourcePath),r=Co(e.sourcePath,na(e.sourcePath)),s=zi(i,`${r}.ai3d-converted.glb`),a=zi(Nd(),"ai3d-freecad"),o=zi(a,`${r}-${Date.now()}.py`);await Ld(a,{recursive:!0}),await Dd(o,kue(e.sourcePath,s,e.sourceExt),"utf8"),Bue.info("run CAD conversion (CadQuery/OCCT)",{sourcePath:e.sourcePath,outputPath:s,command:t.command,args:t.args});try{await Gue(t.command,[...t.args,o],Uue)}catch(c){throw new Error(`CAD conversion failed for '${e.sourcePath}'. Ensure Python with cadquery is installed: pip install cadquery trimesh. Set Python command path in plugin settings or AI3D_FREECAD_CMD if Python is not discoverable. ${c instanceof Error?c.message:String(c)}`)}finally{Od(o,{force:!0})}if(!await Vue(s))throw new Error(`CAD conversion finished but output was not found: '${s}'. Check that CadQuery supports this CAD format.`);if((await ra(s)).byteLength===0)throw new Error(`CAD conversion output is empty: '${s}'.`);return{outputPath:s,outputExt:"glb",fromCache:!1,warnings:["Converted by local Python/CadQuery(OCCT) bridge."]}}}});async function zue(n){try{return await ls(n,cs),!0}catch(e){return!1}}function Xue(n,e,t){return new Promise((i,r)=>{sa(n,e,{timeout:t,windowsHide:!0,maxBuffer:50*1024*1024},(s,a,o)=>{if(!s){i();return}let l=(a!=null?a:"").toString().trim(),c=(o!=null?o:"").toString().trim(),f=[`obj2gltf command failed: ${s.message}`,l?`stdout: ${l}`:"",c?`stderr: ${c}`:""].filter(Boolean);r(new Error(f.join(" | ")))})})}var Wue,Hue,fb,aj=C(()=>{"use strict";or();or();or();Tn();$f();Wue=Wi("obj2gltf-converter"),Hue=180*1e3;fb=class{constructor(e){this.configuredCommand=e;this.id="obj2gltf";this.sourceExts=["obj"];this.targetExt="glb"}async getCacheKey(){let e=await as(this.id,this.configuredCommand);return`${this.id}:${e.command} ${e.args.join(" ")}`.trim()}async convert(e){if(!Xn(e.sourcePath))throw new Error(`Converter '${this.id}' requires an absolute source path, got '${e.sourcePath}'. Pass a file-system path to the conversion pipeline when invoking obj2gltf.`);let t=await as(this.id,this.configuredCommand),i=Mo(e.sourcePath),r=Co(e.sourcePath,na(e.sourcePath)),s=zi(i,`${r}.ai3d-converted.glb`);Wue.info("run obj2gltf conversion",{sourcePath:e.sourcePath,outputPath:s,command:t.command,args:t.args});try{await Xue(t.command,[...t.args,"-i",e.sourcePath,"-o",s,"-b"],Hue)}catch(o){throw new Error(`obj2gltf conversion failed for '${e.sourcePath}'. Set obj2gltf command path in plugin settings or AI3D_OBJ2GLTF_CMD if obj2gltf is not discoverable. ${o instanceof Error?o.message:String(o)}`)}if(!await zue(s))throw new Error(`obj2gltf conversion finished but output was not found: '${s}'.`);if((await ra(s)).byteLength===0)throw new Error(`obj2gltf output file is empty: '${s}'.`);return{outputPath:s,outputExt:"glb",fromCache:!1,warnings:["Converted by local obj2gltf CLI bridge."]}}}});async function jue(n){try{return await ls(n,cs),!0}catch(e){return!1}}function que(n,e,t){return new Promise((i,r)=>{sa(n,e,{timeout:t,windowsHide:!0,maxBuffer:50*1024*1024},(s,a,o)=>{if(!s){i();return}let l=(a!=null?a:"").toString().trim(),c=(o!=null?o:"").toString().trim(),f=[`FBX2glTF command failed: ${s.message}`,l?`stdout: ${l}`:"",c?`stderr: ${c}`:""].filter(Boolean);r(new Error(f.join(" | ")))})})}var Yue,Kue,hb,oj=C(()=>{"use strict";or();or();or();Tn();$f();Yue=Wi("fbx2gltf-converter"),Kue=180*1e3;hb=class{constructor(e){this.configuredCommand=e;this.id="fbx2gltf";this.sourceExts=["fbx"];this.targetExt="glb"}async getCacheKey(){let e=await as(this.id,this.configuredCommand);return`${this.id}:${e.command} ${e.args.join(" ")}`.trim()}async convert(e){if(!Xn(e.sourcePath))throw new Error(`Converter '${this.id}' requires an absolute source path, got '${e.sourcePath}'. Pass a file-system path to the conversion pipeline when invoking FBX2glTF.`);let t=await as(this.id,this.configuredCommand),i=Mo(e.sourcePath),r=Co(e.sourcePath,na(e.sourcePath)),s=zi(i,`${r}.ai3d-converted.glb`);Yue.info("run FBX2glTF conversion",{sourcePath:e.sourcePath,outputPath:s,command:t.command,args:t.args});try{await que(t.command,[...t.args,"-i",e.sourcePath,"-o",s,"-b"],Kue)}catch(o){throw new Error(`FBX2glTF conversion failed for '${e.sourcePath}'. Set FBX2glTF command path in plugin settings or AI3D_FBX2GLTF_CMD if FBX2glTF is not discoverable. ${o instanceof Error?o.message:String(o)}`)}if(!await jue(s))throw new Error(`FBX2glTF conversion finished but output was not found: '${s}'.`);if((await ra(s)).byteLength===0)throw new Error(`FBX2glTF output file is empty: '${s}'.`);return{outputPath:s,outputExt:"glb",fromCache:!1,warnings:["Converted by local FBX2glTF CLI bridge."]}}}});async function $ue(n){try{return await ls(n,cs),!0}catch(e){return!1}}function Jue(n,e,t){return new Promise((i,r)=>{sa(n,e,{timeout:t,windowsHide:!0,maxBuffer:50*1024*1024},(s,a,o)=>{if(!s){i();return}let l=(a!=null?a:"").toString().trim(),c=(o!=null?o:"").toString().trim(),f=[`mesh conversion failed: ${s.message}`,l?`stdout: ${l}`:"",c?`stderr: ${c}`:""].filter(Boolean);r(new Error(f.join(" | ")))})})}function eme(n,e){let t=bc(n),i=bc(e);return["import trimesh","import sys","",`src = r"${t}"`,`out = r"${i}"`,"","try:"," loaded = trimesh.load(src, force=None)","except Exception as e:",' print(f"Failed to load {src}: {e}", file=sys.stderr)'," sys.exit(1)","","if isinstance(loaded, trimesh.Scene):"," scene = loaded","elif isinstance(loaded, trimesh.Trimesh):"," scene = trimesh.Scene([loaded])","else:",' print(f"Unsupported type: {type(loaded)}", file=sys.stderr)'," sys.exit(1)","","try:"," data = scene.export(file_type='glb')","except Exception as e:",' print(f"Failed to export GLB: {e}", file=sys.stderr)'," sys.exit(1)","","with open(out, 'wb') as f:"," f.write(data)","","print(f'Converted {src} -> {out} ({len(data)} bytes)')"].join(` +`)}var Zue,Que,db,lj=C(()=>{"use strict";or();or();or();or();Tn();$f();lb();Zue=Wi("assimp-converter"),Que=300*1e3;db=class{constructor(e){this.configuredCommand=e;this.id="assimp";this.sourceExts=["3mf","dae"];this.targetExt="glb"}async getCacheKey(){let e=await as(this.id,this.configuredCommand);return`${this.id}:${e.command} ${e.args.join(" ")}`.trim()}async convert(e){if(!Xn(e.sourcePath))throw new Error(`Converter '${this.id}' requires an absolute source path, got '${e.sourcePath}'. Pass a file-system path to the conversion pipeline when invoking mesh conversion.`);let t=await as(this.id,this.configuredCommand),i=Mo(e.sourcePath),r=Co(e.sourcePath,na(e.sourcePath)),s=zi(i,`${r}.ai3d-converted.glb`),a=zi(Nd(),"ai3d-mesh-convert"),o=zi(a,`${r}-${Date.now()}.py`);await Ld(a,{recursive:!0}),await Dd(o,eme(e.sourcePath,s),"utf8"),Zue.info("run mesh conversion (trimesh)",{sourcePath:e.sourcePath,outputPath:s,command:t.command,args:t.args});try{await Jue(t.command,[...t.args,o],Que)}catch(c){throw new Error(`Mesh conversion failed for '${e.sourcePath}'. Ensure Python with trimesh is installed: pip install trimesh numpy networkx pycollada. Set Python command path in plugin settings or AI3D_ASSIMP_CMD if Python is not discoverable. ${c instanceof Error?c.message:String(c)}`)}finally{Od(o,{force:!0})}if(!await $ue(s))throw new Error(`Mesh conversion finished but output was not found: '${s}'. Check that trimesh supports this format.`);if((await ra(s)).byteLength===0)throw new Error(`Mesh conversion output is empty: '${s}'.`);return{outputPath:s,outputExt:"glb",fromCache:!1,warnings:["Converted by local Python/trimesh bridge."]}}}});async function ime(n){try{return await ls(n,cs),!0}catch(e){return!1}}function rme(n,e,t){return new Promise((i,r)=>{sa(n,e,{timeout:t,windowsHide:!0,maxBuffer:50*1024*1024},(s,a,o)=>{if(!s){i({stdout:a!=null?a:"",stderr:o!=null?o:""});return}let l=(a!=null?a:"").toString().trim(),c=(o!=null?o:"").toString().trim(),f=[`SLDPRT conversion failed: ${s.message}`,l?`stdout: ${l}`:"",c?`stderr: ${c}`:""].filter(Boolean);r(new Error(f.join(" | ")))})})}function nme(n,e){let t=bc(n),i=bc(e),r=i.replace(/\.glb$/i,".intermediate.step");return["import sys","import os","",`src = r"${t}"`,`out = r"${i}"`,`step_out = r"${r}"`,"","# Step 1: Import SLDPRT via FreeCAD","try:"," import FreeCAD"," import ImportGui"," import Mesh","except ImportError as e:",' print(f"FreeCAD modules not available: {e}", file=sys.stderr)',' print("Ensure this script runs under FreeCADCmd (not system Python).", file=sys.stderr)'," sys.exit(1)","","print(f'Opening SLDPRT: {src}')","try:"," doc = FreeCAD.newDocument('Convert')"," ImportGui.open(src, doc.Name)","except Exception as e:",' print(f"Failed to open SLDPRT file: {e}", file=sys.stderr)'," sys.exit(1)","","if not doc.Objects:",' print("SLDPRT file imported but contains no objects", file=sys.stderr)'," sys.exit(1)","",'print(f"Imported {len(doc.Objects)} object(s) from SLDPRT")',"","# Step 2: Export to STEP (intermediate)","try:"," import Import"," objs = [o for o in doc.Objects if hasattr(o, 'Shape')]"," if not objs:",' print("No shape objects found after import", file=sys.stderr)'," sys.exit(1)"," Import.export(objs, step_out)",' print(f"Exported intermediate STEP: {step_out}")',"except Exception as e:",' print(f"Failed to export STEP: {e}", file=sys.stderr)'," sys.exit(1)","","FreeCAD.closeDocument(doc.Name)","","# Step 3: Convert STEP to GLB using OCP (same pipeline as FreecadConverter)","import trimesh","import trimesh.visual","import numpy as np","","from OCP.STEPControl import STEPControl_Reader","from OCP.TopoDS import TopoDS","from OCP.TopAbs import TopAbs_FACE","from OCP.TopExp import TopExp_Explorer","from OCP.BRep import BRep_Tool","from OCP.BRepMesh import BRepMesh_IncrementalMesh","from OCP.TopLoc import TopLoc_Location","from OCP.IFSelect import IFSelect_RetDone","","DEFAULT_COLOR = [180, 180, 180, 255]","","def triangulate_face(face, linear=0.1, angular=0.5):"," BRepMesh_IncrementalMesh(face, linear, False, angular, True)"," loc = TopLoc_Location()"," tri = BRep_Tool.Triangulation_s(face, loc)"," if tri is None:"," return None, None"," n = tri.NbNodes()"," verts = []"," for i in range(1, n + 1):"," p = tri.Node(i)"," if not loc.IsIdentity():"," p = p.Transformed(loc.Transformation())"," verts.append([p.X(), p.Y(), p.Z()])"," ntri = tri.NbTriangles()"," faces = []"," for i in range(1, ntri + 1):"," t = tri.Triangle(i)"," n1, n2, n3 = t.Get()"," faces.append([n1 - 1, n2 - 1, n3 - 1])"," return verts, faces","","sr = STEPControl_Reader()","status = sr.ReadFile(step_out)","if status != IFSelect_RetDone:",' print(f"Failed to read intermediate STEP: {step_out}", file=sys.stderr)'," sys.exit(1)","sr.TransferRoots()","shape = sr.OneShape()","","all_verts = []","all_faces = []","all_colors = []","total_faces = 0","","exp = TopExp_Explorer(shape, TopAbs_FACE)","while exp.More():"," face = TopoDS.Face_s(exp.Current())"," total_faces += 1"," verts, faces = triangulate_face(face)"," if verts and faces:"," offset = len(all_verts)"," all_verts.extend(verts)"," for tri in faces:"," all_faces.append([tri[0] + offset, tri[1] + offset, tri[2] + offset])"," all_colors.extend([DEFAULT_COLOR] * len(verts))"," exp.Next()","","if not all_verts or not all_faces:",' print(f"No geometry extracted from STEP ({total_faces} faces scanned)", file=sys.stderr)'," sys.exit(1)","",'print(f"Triangulated: {total_faces} faces, {len(all_verts)} verts")',"","verts_arr = np.array(all_verts, dtype=float)","faces_arr = np.array(all_faces, dtype=int)","colors_arr = np.array(all_colors, dtype=np.uint8)","","mesh = trimesh.Trimesh("," vertices=verts_arr,"," faces=faces_arr,"," visual=trimesh.visual.ColorVisuals(vertex_colors=colors_arr),"," process=True,",")","mesh.fix_normals()","scene = trimesh.Scene([mesh])","","result = scene.export(file_type='glb')","if isinstance(result, bytes):"," data = result","elif isinstance(result, str):"," with open(result, 'rb') as f:"," data = f.read()","else:"," data = bytes(result)","","with open(out, 'wb') as f:"," f.write(data)","","# Cleanup intermediate STEP","try:"," os.remove(step_out)","except OSError:"," pass","","print(f'Converted {src} -> {out} ({len(data)} bytes, {total_faces} faces)')"].join(` +`)}var sN,tme,ub,cj=C(()=>{"use strict";or();or();or();or();Tn();$f();lb();sN=Wi("sldprt-converter"),tme=600*1e3;ub=class{constructor(e){this.configuredCommand=e;this.id="sldprt";this.sourceExts=["sldprt"];this.targetExt="glb"}async getCacheKey(){let e=await as("freecadcmd",this.configuredCommand);return`${this.id}:${e.command} ${e.args.join(" ")}`.trim()}async convert(e){if(!Xn(e.sourcePath))throw new Error(`Converter '${this.id}' requires an absolute source path, got '${e.sourcePath}'. Pass a file-system path to the conversion pipeline when invoking SLDPRT conversion.`);let t=await as("freecadcmd",this.configuredCommand),i=Mo(e.sourcePath),r=Co(e.sourcePath,na(e.sourcePath)),s=zi(i,`${r}.ai3d-converted.glb`),a=zi(Nd(),"ai3d-sldprt"),o=zi(a,`${r}-${Date.now()}.py`);await Ld(a,{recursive:!0}),await Dd(o,nme(e.sourcePath,s),"utf8"),sN.info("run SLDPRT conversion (FreeCAD + OCP)",{sourcePath:e.sourcePath,outputPath:s,command:t.command,args:t.args});try{let{stdout:c,stderr:f}=await rme(t.command,[...t.args,o],tme);c&&sN.info("FreeCAD stdout",{stdout:c.trim().slice(0,500)}),f&&sN.warn("FreeCAD stderr",{stderr:f.trim().slice(0,500)})}catch(c){throw new Error(`SLDPRT conversion failed for '${e.sourcePath}'. Ensure FreeCAD is installed (https://www.freecad.org/downloads.php). Set FreeCADCmd path in plugin settings or AI3D_FREECADCMD env var. ${c instanceof Error?c.message:String(c)}`)}finally{Od(o,{force:!0})}if(!await ime(s))throw new Error(`SLDPRT conversion finished but output was not found: '${s}'. Check that FreeCAD can import this SolidWorks file version.`);if((await ra(s)).byteLength===0)throw new Error(`SLDPRT conversion output is empty: '${s}'.`);return{outputPath:s,outputExt:"glb",fromCache:!1,warnings:["Converted by local FreeCAD + OpenCASCADE bridge."]}}}});function gd(n){var r;let e=new nb,t=new Set((r=n==null?void 0:n.enabledConverterIds)!=null?r:[]);aN.debug("create conversion manager",{enabledConverterIds:[...t]});let i=[new cb(n==null?void 0:n.freecadCommand),new fb(n==null?void 0:n.obj2gltfCommand),new hb(n==null?void 0:n.fbx2gltfCommand),new db(n==null?void 0:n.assimpCommand),new ub(n==null?void 0:n.freecadcmdCommand)];for(let s of i)t.has(s.id)?(e.registerConverter(s),aN.info("enabled converter",{converterId:s.id})):aN.debug("converter disabled",{converterId:s.id});return e}var aN,mb=C(()=>{"use strict";ej();sj();aj();oj();lj();cj();Tn();aN=Wi("conversion-factory")});function fj(n){let e=Ba(n.sourceExt),t=[];return e!==n.sourceExt&&t.push(`Normalized extension '${n.sourceExt}' -> '${e}'.`),sme.debug("prepare direct load",{path:n.path,sourceExt:n.sourceExt,normalizedExt:e,warningCount:t.length}),{effectivePath:n.path,effectiveExt:e,warnings:t}}var sme,hj=C(()=>{"use strict";Io();Tn();sme=Wi("direct-load-service")});function pb(n){return`.${n.trim().toLowerCase()}`}function dp(n){return n instanceof vd}function oN(n){var e;if(n instanceof vd){let t=(e=ame[n.converterId])!=null?e:n.converterId;return ur("modelLoad.warningMessage",{ext:pb(n.sourceExt),converterName:t})}return n instanceof hp?ur("modelLoad.mobileWarningMessage",{ext:pb(n.sourceExt)}):ur("modelLoad.errorMessage",{reason:n instanceof Error?n.message:String(n)})}function up(n){return n instanceof vd?{level:"warning",title:J("modelLoad.warningTitle"),message:oN(n),hint:J("modelLoad.warningHint")}:n instanceof hp?{level:"warning",title:J("modelLoad.warningTitle"),message:oN(n),hint:J("modelLoad.mobileWarningHint")}:{level:"error",title:J("modelLoad.errorTitle"),message:oN(n),hint:J("modelLoad.errorHint")}}var ame,vd,hp,mp=C(()=>{"use strict";ia();ame={freecad:"FreeCAD",obj2gltf:"obj2gltf",fbx2gltf:"FBX2glTF",assimp:"mesh",sldprt:"SolidWorks"};vd=class extends Error{constructor(t,i){super(`Converter '${t}' is not registered for ${pb(i)}. Enable the matching converter in plugin settings before loading this format.`);this.converterId=t;this.sourceExt=i;this.name="MissingConverterError"}},hp=class extends Error{constructor(t){super(`Format ${pb(t)} requires local conversion tools that are unavailable on iOS, iPadOS, and Android.`);this.sourceExt=t;this.name="MobileConversionUnavailableError"}}});function lme(n,e,t){return n.converterId!==e?!1:t?n.converterId===t.converterId&&n.converterCacheKey===t.cacheKey:!0}async function cme(n){if(!n)return!1;try{return await ls(n,cs),!0}catch(e){return!1}}async function dj(n){var a,o,l,c,f,h,d;if(n.capability.strategy!=="convert")throw new Error(`Expected convert strategy, got '${n.capability.strategy}'.`);let e=n.capability.converterId,t=(a=n.capability.outputFormat)!=null?a:"glb";if(!e)throw new Error(`Format .${n.sourceExt} does not define a converter id.`);ev.info("prepare conversion route",{sourcePath:n.sourcePath,sourceExt:n.sourceExt,targetExt:t,converterId:e});let i=n.conversionManager.canConvert(n.sourceExt)?await n.conversionManager.getConverterCacheIdentity(n.sourceExt):void 0,r=(o=n.convertedAssetCache)==null?void 0:o.get(n.sourcePath,n.sourceExt,t);if(r)if(!await cme(r.outputPath))ev.warn("conversion cache stale",{sourcePath:n.sourcePath,sourceExt:n.sourceExt,targetExt:t,outputPath:r.outputPath}),(l=n.convertedAssetCache)==null||l.delete(n.sourcePath,n.sourceExt,t);else if(!lme(r,e,i))ev.warn("conversion cache identity mismatch",{sourcePath:n.sourcePath,sourceExt:n.sourceExt,targetExt:t,cachedConverterId:r.converterId,cachedConverterCacheKey:r.converterCacheKey,currentConverterId:(c=i==null?void 0:i.converterId)!=null?c:e,currentConverterCacheKey:i==null?void 0:i.cacheKey}),(f=n.convertedAssetCache)==null||f.delete(n.sourcePath,n.sourceExt,t);else return ev.info("conversion cache hit",{sourcePath:n.sourcePath,sourceExt:n.sourceExt,targetExt:t,outputPath:r.outputPath}),{effectivePath:r.outputPath,effectiveExt:r.outputExt,warnings:[...r.warnings,"Using cached conversion output."]};if(!n.conversionManager.canConvert(n.sourceExt))throw new vd(e,n.sourceExt);let s=await n.conversionManager.convert({sourcePath:n.sourcePath,sourceExt:n.sourceExt,targetExt:t});return(d=n.convertedAssetCache)==null||d.set({cacheVersion:2,converterId:e,converterCacheKey:(h=i==null?void 0:i.cacheKey)!=null?h:e,sourcePath:n.sourcePath,sourceExt:n.sourceExt,targetExt:t,outputPath:s.outputPath,outputExt:s.outputExt,warnings:s.warnings,createdAt:Date.now()}),ev.info("conversion route done",{sourcePath:n.sourcePath,outputPath:s.outputPath,warningCount:s.warnings.length}),{effectivePath:s.outputPath,effectiveExt:s.outputExt,warnings:s.warnings}}var ev,uj=C(()=>{"use strict";Nb();Tn();or();mp();ev=Wi("conversion-service")});function fme(n,e){var t;return!!((t=n.preferConversionExts)!=null&&t.includes(e))}async function Ed(n){var a,o;let e=Ba((a=n.path.split(".").pop())!=null?a:""),t=wb(e);if(Ic.info("prepare model input",{path:n.path,sourceExt:e}),!t||!t.enabled)throw Ic.warn("unsupported format",{sourceExt:e,path:n.path}),Ap(e)?new Error("SPLAT preview is disabled in packaged builds. Local-only .splat support is planned; .spz and .sog remain unavailable until their decoders can be bundled locally."):new Error(`Unsupported format: .${e}`);let i=fme(n,e);if(t.strategy==="convert"||i&&!!t.converterId){if(mr())throw Ic.warn("conversion unavailable on mobile",{sourceExt:e,path:n.path}),new hp(e);if(!n.absolutePath)throw Ic.error("filesystem path missing for conversion",{sourceExt:e,path:n.path}),new Error(`Format .${e} requires a local filesystem path for conversion, but none was resolved for '${n.path}'.`);if(!n.conversionManager)throw Ic.error("conversion manager missing",{sourceExt:e,path:n.path}),new Error(`Format .${e} requires conversion support, but no conversion manager is available.`);let l=t.strategy==="convert"?t:{...t,strategy:"convert",outputFormat:(o=t.outputFormat)!=null?o:"glb"};if(!l.converterId)throw Ic.error("preferred conversion route missing converter id",{sourceExt:e,path:n.path}),new Error(`Format .${e} is configured to prefer conversion, but no converter id is defined.`);i&&t.strategy==="direct"&&Ic.info("preferred conversion route",{sourceExt:e,path:n.path,converterId:l.converterId});let c=await dj({sourcePath:n.absolutePath,sourceExt:e,capability:l,conversionManager:n.conversionManager,convertedAssetCache:n.convertedAssetCache});return Ic.info("conversion completed",{sourceExt:e,outputExt:c.effectiveExt,outputPath:c.effectivePath,warningCount:c.warnings.length}),{sourcePath:n.path,sourceExt:e,strategy:"convert",effectivePath:c.effectivePath,effectiveExt:c.effectiveExt,warnings:c.warnings}}let s=fj({path:n.path,sourceExt:e});return Ic.debug("direct route",{sourceExt:e,path:n.path,warningCount:s.warnings.length}),{sourcePath:n.path,sourceExt:e,strategy:t.strategy,effectivePath:s.effectivePath,effectiveExt:s.effectiveExt,warnings:s.warnings}}var Ic,_b=C(()=>{"use strict";Io();hj();uj();mp();Tn();Ys();Ic=Wi("model-pipeline")});function tv(n){return{path:n.effectivePath,ext:n.effectiveExt,strategy:n.strategy,sourcePath:n.sourcePath,sourceExt:n.sourceExt,warnings:n.warnings}}var lN=C(()=>{"use strict"});function Sd(n){let e=[];return n.preferObj2gltfForObj&&e.push("obj"),n.preferFbx2gltfForFbx&&e.push("fbx"),e}var gb=C(()=>{"use strict"});function iv(n){return n.replace(/\[\[([^\]|]+)\|([^\]]+)\]\]/g,"$2").replace(/\[\[([^\]]+)\]\]/g,"$1").replace(/\[([^\]]+)\]\([^)]*\)/g,"$1").replace(/[*_~`]+/g,"").replace(/==([^=]+)==/g,"$1").replace(/\s+/g," ").trim()}function hme(n,e){let t=e.toLowerCase().trim();if(!t)return[];let i=[],r=n.vault.getMarkdownFiles();for(let s of r){let a=n.metadataCache.getFileCache(s);if(a!=null&&a.headings)for(let o of a.headings)o.heading.toLowerCase().includes(t)&&i.push({notePath:s.path,heading:o.heading,level:o.level})}return i.slice(0,15)}function pj(n){return e=>hme(n,e)}async function dme(n,e,t){try{let i=n.vault.getAbstractFileByPath(e);if(!(i instanceof mj.TFile))return null;let s=(await n.vault.cachedRead(i)).split(` `),a=-1,o=0,l=iv(t);for(let f=0;fdme(n,e,t)}var mj,rv=C(()=>{"use strict";mj=require("obsidian")});function Td(n){let e=n.createDiv({cls:"ai3d-loading-overlay"}),t=e.createDiv({cls:"ai3d-loading-skeleton"});t.createDiv({cls:"ai3d-loading-skeleton-canvas"});let i=t.createDiv({cls:"ai3d-loading-skeleton-meta"});i.createDiv({cls:"ai3d-loading-skeleton-line"}),i.createDiv({cls:"ai3d-loading-skeleton-line is-short"}),e.createDiv({cls:"ai3d-loading-spinner"});let r=e.createDiv({cls:"ai3d-loading-text"}),s="loading.default",a="",o=()=>{r.textContent=s?J(s):a};o();let c=e.createDiv({cls:"ai3d-loading-bar-track"}).createDiv({cls:"ai3d-loading-bar-fill is-indeterminate"}),f=!1,h=jN(()=>{!f&&s&&o()});return{el:e,setPhase(d){s=null,a=d,f||o()},setPhaseKey(d){s=d,f||o()},setProgress(d){f||(d<0?(c.className="ai3d-loading-bar-fill is-indeterminate",c.style.removeProperty("--bar-width")):(c.className="ai3d-loading-bar-fill",c.style.setProperty("--bar-width",`${Math.min(100,Math.max(0,d))}%`)))},hide(){f||(f=!0,h(),e.classList.add("is-hiding"),window.setTimeout(()=>e.remove(),300))}}}var gb=C(()=>{"use strict";ra()});function gp(n,e){let t=n.createDiv({cls:"ai3d-inline-empty ai3d-load-feedback-shell"});ur()&&t.classList.add("is-mobile");let i=t.createDiv({cls:`ai3d-load-feedback is-${e.level}`});return i.createDiv({cls:"ai3d-load-feedback-title",text:e.title}),i.createDiv({cls:"ai3d-load-feedback-message",text:e.message}),i.createDiv({cls:"ai3d-load-feedback-hint",text:e.hint}),t}function vp(n,e){var o,l,c,f,h,d,u;if((!e.performanceTier||e.performanceTier==="light")&&!((o=e.resourceWarnings)!=null&&o.length))return null;let t=(l=e.performanceTier)!=null?l:"light",i=((c=e.splatCount)!=null?c:e.triangleCount).toLocaleString(),r=e.splatCount!==void 0?"splats":"triangles",s=n.createDiv({cls:`ai3d-performance-feedback is-${t}`});s.createDiv({cls:"ai3d-performance-feedback-tier",text:(f=e.resourceWarnings)!=null&&f.length?"assets":(h=e.performanceTier)!=null?h:"light"}),s.createDiv({cls:"ai3d-performance-feedback-meta",text:(d=e.resourceWarnings)!=null&&d.length?e.resourceWarnings[0]:`${i} ${r} \xB7 ${e.materialCount.toLocaleString()} materials`});let a=[...(u=e.resourceWarnings)!=null?u:[],...e.performanceHint?[e.performanceHint]:[]];return a.length>0&&(s.title=a.join(` -`)),window.setTimeout(()=>s.classList.add("is-subtle"),4200),s}var vb=C(()=>{"use strict";Ks()});function vj(){return typeof performance!="undefined"?performance.now():Date.now()}function Ad(n,e,t=`${e}s`){return`${n.toLocaleString()} ${n===1?e:t}`}function _me(n){return{stage:"reason",durationMs:Math.max(0,Math.round(vj()-n)),status:"success"}}function gme(n,e){let t=n[0]-e[0],i=n[1]-e[1],r=n[2]-e[2];return Math.sqrt(t*t+i*i+r*r)}function Ej(n){var t;let e=(t=n.split(".").pop())==null?void 0:t.trim().toLowerCase();return pme.has(e)?e:"glb"}function fN(n){return[n.x,n.y,n.z]}function _j(n){return n.trim().replace(/[\\/:*?"<>|#[\]^]+/g,"-").replace(/\s+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,96)}function vme(n,e,t,i){var c,f;let r=_j(jr(n)||"model")||"model",s=(f=(c=e.occurrenceId)!=null?c:e.componentId)!=null?f:e.partNumber,a=s?`${r}:component:${_j(s)||t+1}`:`${r}:part:${t+1}`,o=a,l=2;for(;i.has(o);)o=`${a}:${l}`,l++;return i.add(o),o}function nv(n){return(n!=null?n:"").toLowerCase().replace(/[_\-./\\]+/g," ").replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim()}function Eb(n){return new Set(nv(n).split(" ").filter(e=>e.length>=2))}function gj(n,e){if(n.size===0||e.size===0)return 0;let t=0;for(let i of n)e.has(i)&&(t+=1);return t/Math.max(n.size,e.size)}function Eme(n,e){if(!n||!e||n.length<3||e.length<3)return 0;let t=[...n].slice(0,3).map(s=>Math.max(1e-4,Math.abs(s))).sort((s,a)=>s-a),i=[...e].slice(0,3).map(s=>Math.max(1e-4,Math.abs(s))).sort((s,a)=>s-a),r=0;for(let s=0;s<3;s++)r+=Math.min(t[s],i[s])/Math.max(t[s],i[s]);return r/3}function Sme(n,e){let t=nv(n),i=nv(e);return!!t&&!!i&&t===i}function cN(n,e){let t=nv(n),i=nv(e);return!!t&&!!i&&t===i}function Tme(n,e){let t=Eb(n.name),i=Eb(n.meshRefs.join(" "));return e.filter(s=>s.assetId!==n.assetId||s.partId!==n.partId).flatMap(s=>{let a=[],o=gj(t,Eb(s.name)),l=gj(i,Eb(s.meshRefs.join(" "))),c=Eme(n.bbox,s.bbox),f=!!n.category&&!!s.category&&n.category===s.category,h=Sme(n.materialName,s.materialName),d=cN(n.componentId,s.componentId),u=cN(n.partNumber,s.partNumber),m=cN(n.occurrenceId,s.occurrenceId),p=o*.38+l*.22+c*.22;return d&&(p+=.5),u&&(p+=.4),m&&(p+=.25),f&&(p+=.1),h&&(p+=.08),d&&a.push(`same component id: ${n.componentId}`),u&&a.push(`same part number: ${n.partNumber}`),m&&a.push("same occurrence id"),o>=.5&&a.push("similar part name"),l>=.5&&a.push("similar mesh names"),c>=.72&&a.push("similar bounding size"),f&&a.push(`same category: ${n.category}`),h&&n.materialName&&a.push(`same material: ${n.materialName}`),p=Math.min(1,p),pa.matchScore-s.matchScore).slice(0,ume)}function Ame(n,e){return e.length===0?n.map(t=>({...t})):n.map(t=>{let i=Tme(t,e);return i.length>0?{...t,registeredMatches:i}:{...t}})}function xme(n){var t;let e=n.name.toLowerCase();return n.source==="component"?"component":n.source==="group"?"group":e.includes("wheel")||e.includes("gear")||e.includes("axle")?"mechanical":e.includes("shell")||e.includes("case")||e.includes("cover")||e.includes("housing")?"enclosure":e.includes("button")||e.includes("key")||e.includes("switch")?"control":e.includes("glass")||e.includes("screen")||e.includes("lens")?"surface":(t=n.materialName)!=null&&t.toLowerCase().includes("metal")?"material-driven":"unclassified"}function Rme(n){var t,i,r,s,a,o;let e=[];return n.source==="group"&&e.push(`Registered from model group with ${Ad((r=(i=n.childCount)!=null?i:(t=n.meshNames)==null?void 0:t.length)!=null?r:0,"child mesh","child meshes")}.`),n.source==="component"&&e.push(`Registered from model component metadata with ${Ad((o=(a=n.childCount)!=null?a:(s=n.meshNames)==null?void 0:s.length)!=null?o:1,"child mesh","child meshes")}.`),n.componentId&&e.push(`Component ID: ${n.componentId}.`),n.occurrenceId&&e.push(`Occurrence ID: ${n.occurrenceId}.`),n.partNumber&&e.push(`Part number: ${n.partNumber}.`),n.componentPath&&e.push(`Component path: ${n.componentPath}.`),e.push(`${Ad(n.triangleCount,"triangle")} and ${Ad(n.vertexCount,"vertex")}.`,`Bounding size ${n.boundingSize.x.toFixed(3)} x ${n.boundingSize.y.toFixed(3)} x ${n.boundingSize.z.toFixed(3)}.`),n.materialName&&e.push(`Uses material "${n.materialName}".`),e}function hN(n,e){let t=new Set;return e.map((i,r)=>{var s;return{partId:vme(n,i,r,t),assetId:n,name:i.name||`Part ${r+1}`,source:i.source,componentId:i.componentId,occurrenceId:i.occurrenceId,partNumber:i.partNumber,componentPath:i.componentPath,category:xme(i),meshRefs:(s=i.meshNames)!=null&&s.length?[...i.meshNames]:[i.name||`mesh-${r+1}`],childCount:i.childCount,materialRefs:i.materialName?[i.materialName]:[],bbox:fN(i.boundingSize),center:fN(i.center),triangleCount:i.triangleCount,vertexCount:i.vertexCount,materialName:i.materialName,confidence:i.source==="component"?.82:i.source==="group"?.72:i.name?.55:.35,observations:Rme(i),inferredFunctions:[],knowledgeTags:[],reviewed:!1}})}function bme(n,e,t,i,r){var o;let s=[],a=t==null?void 0:t.summary;a&&s.push({id:`${n}:geometry`,title:"Geometry overview",domain:"geometry",summary:`${Ad(a.meshCount,"mesh")}, ${Ad(a.triangleCount,"triangle")}, ${Ad(a.materialCount,"material slot")}.`,relatedPartIds:i.slice(0,12).map(l=>l.partId),relatedAssetIds:[n],confidence:.72,source:"rule"});for(let l of(o=e==null?void 0:e.annotations)!=null?o:[]){let c=r.find(f=>f.annotationId===l.id);s.push({id:`${n}:annotation:${l.id}`,title:l.label||"Annotation focus",domain:"assembly",summary:[l.headingRef?`Pinned focus area linked to heading "${l.headingRef}".`:"Pinned focus area marked by the user for follow-up analysis.",c!=null&&c.nearestPartName?`Nearest part candidate: ${c.nearestPartName}.`:""].filter(Boolean).join(" "),relatedPartIds:c!=null&&c.nearestPartId?[c.nearestPartId]:[],relatedAssetIds:[n],confidence:.8,source:"user"})}return s}function Ime(n,e){var i;return((i=n==null?void 0:n.annotations)!=null?i:[]).map(r=>{let s=r.position,a=null,o=Number.POSITIVE_INFINITY;for(let c of e){if(!c.center)continue;let f=gme(s,c.center);f{var l;return{partId:o.partId,name:o.name,notePath:o.notePath,source:o.source,componentId:o.componentId,occurrenceId:o.occurrenceId,partNumber:o.partNumber,componentPath:o.componentPath,category:o.category,meshRefs:[...o.meshRefs],childCount:o.childCount,triangleCount:o.triangleCount,materialName:o.materialName,registeredMatches:(l=o.registeredMatches)==null?void 0:l.map(c=>({...c,reasons:[...c.reasons]})),observations:o.observations}}),annotationLinks:[...n.annotationLinks],knowledgeNodes:[...n.knowledgeNodes]}}function Cme(n,e){var t,i;return Array.from(new Set([...(t=n==null?void 0:n.resourceWarnings)!=null?t:[],...(i=e==null?void 0:e.resourceWarnings)!=null?i:[]]))}function Sb(n){var f,h,d,u,m,p,_,g,v,x;let e=(f=n.startedAt)!=null?f:vj(),t=(d=(h=n.evidence)==null?void 0:h.summary)!=null?d:n.preview,i=Ame(hN(n.modelPath,(m=(u=n.evidence)==null?void 0:u.parts)!=null?m:[]),(p=n.registeredParts)!=null?p:[]),r=new Date().toISOString(),s=Cme(n.preview,n.evidence),a=Ime(n.profile,i),o=bme(n.modelPath,n.profile,n.evidence,i,a),l=(_=n.previewImages)!=null?_:[],c=Mme({modelPath:n.modelPath,profile:n.profile,preview:t,parts:i,knowledgeNodes:o,annotationLinks:a,previewImages:l,warnings:s});return{asset:{assetId:n.modelPath,title:jr(n.modelPath)||n.modelPath,sourcePath:n.modelPath,format:Ej(n.modelPath),importedAt:r,updatedAt:r,status:t?"ready":"processing",vertexCount:t==null?void 0:t.vertexCount,triangleCount:t==null?void 0:t.triangleCount,materialCount:t==null?void 0:t.materialCount,boundingBox:t?fN(t.boundingSize):void 0,analysisVersion:Ep},parts:i,knowledgeNodes:o,previewImages:l,annotationLinks:a,draftingInput:c,evidence:(g=n.evidence)!=null?g:void 0,warnings:s,pipeline:[{stage:"stats",durationMs:0,status:t?"success":"skipped"},{stage:"split",durationMs:0,status:(x=(v=n.evidence)==null?void 0:v.parts)!=null&&x.length?"success":"skipped"},{stage:"map",durationMs:0,status:a.length>0?"success":"skipped"},_me(e)]}}var Ep,ume,mme,pme,dN=C(()=>{"use strict";la();Ep="local-evidence-v1",ume=3,mme=.58,pme=new Set(["glb","gltf","stl","obj","splat","ply","fbx","step","stp","iges","igs","brep","sldprt","3mf","dae"])});function xd(n){let e=n.trim();return e.length>Tj?lr(e.slice(0,Tj))+"\u2026":lr(e)}function Aj(n){if(!n||typeof n!="object")return null;let e=n,t=typeof e.summary=="string"?e.summary.trim():"",i=xd(t);if(!i)return null;let r=Array.isArray(e.sections)?e.sections.flatMap(o=>{if(!o||typeof o!="object")return[];let l=o,c=typeof l.heading=="string"?l.heading.trim():"",f=typeof l.body=="string"?l.body.trim():"",h=xd(c),d=xd(f);return h&&d?[{heading:h,body:d}]:[]}):void 0,s=Array.isArray(e.suggestedTags)?e.suggestedTags.filter(o=>typeof o=="string"&&o.trim().length>0).map(o=>xd(o)):void 0,a=Array.isArray(e.warnings)?e.warnings.filter(o=>typeof o=="string"&&o.trim().length>0).map(o=>xd(o)):void 0;return{title:typeof e.title=="string"?xd(e.title):void 0,summary:i,sections:r,suggestedTags:s,warnings:a,model:typeof e.model=="string"?xd(e.model):void 0}}var Tj,xj=C(()=>{"use strict";VS();Tj=8e3});function Pme(n){let e=n.trim().replace(/\/+$/,"");if(!e)return"";let t=/^[a-z][a-z\d+\-.]*:\/\//i.test(e)?e:`http://${e}`;try{let i=new URL(t);return i.protocol!=="http:"&&i.protocol!=="https:"||i.search||i.hash?null:i.toString().replace(/\/+$/,"")}catch(i){return null}}function Dme(n){return{...n,evidence:{...n.evidence,previewImages:[]}}}function Lme(n){return{...n,model:{...n.model,summary:void 0},partCandidates:[],annotationLinks:n.annotationLinks.map(e=>({...e,notePath:void 0,position:[0,0,0],nearestPartId:void 0,nearestPartName:void 0,distance:void 0,confidence:Math.min(e.confidence,.25)})),knowledgeNodes:n.knowledgeNodes.map(e=>({...e,summary:"Geometry details were withheld by privacy settings.",relatedPartIds:[]}))}}function Ome(n,e){let t=e;return n.sendPreviewImagesToRemote||(t=Dme(t)),n.sendGeometrySummaryToRemote||(t=Lme(t)),{...t,evidence:{...t.evidence,rawModelIncluded:!1}}}function bj(n,e,t){if(n.analysisMode==="local")return{enabled:!1,reason:"analysisMode=local"};let i=Pme(n.serviceBaseUrl);return i===""?{enabled:!1,reason:"serviceBaseUrl is empty"}:i===null?{enabled:!1,reason:"serviceBaseUrl must be a valid http(s) URL"}:n.sendRawModelToRemote?{enabled:!1,reason:"raw model upload is not supported by this draft client"}:e?{enabled:!0,endpoint:`${i}/draft-note`,request:{analysisVersion:t,draftingInput:Ome(n,e)}}:{enabled:!1,reason:"drafting input is unavailable"}}async function Ij(n){if(!n.enabled||!n.endpoint||!n.request)return null;let e=await(0,Rj.requestUrl)({url:n.endpoint,method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n.request)});if(e.status<200||e.status>=300)throw new Error(`Remote draft request failed: HTTP ${e.status}`);return Aj(e.json)}var Rj,Mj=C(()=>{"use strict";Rj=require("obsidian");xj()});var Tb={};tt(Tb,{buildKnowledgeIndexContent:()=>Xj,buildKnowledgeIndexManagedSection:()=>TN,buildKnowledgeNoteContent:()=>Vj,collectRegisteredPartsFromProfiles:()=>Hj,generateKnowledgeNote:()=>cpe,replaceManagedSection:()=>zj});function Oj(n){var t;let e=(t=n.split(".").pop())==null?void 0:t.trim().toLowerCase();return e&&e.length>0?e:"unknown"}function _N(n){return n.filter(e=>e.length>0).join(", ")}function uN(n){return Array.from(new Set(n.map(e=>e.trim()).filter(Boolean)))}function EN(n){return n.replace(/\\/g,"/").replace(/^\/+|\/+$/g,"").trim()}function gN(n,e){return n.replace(/[\\/:*?"<>|#[\]^]/g," ").replace(/\s+/g," ").trim().slice(0,80)||e}function vN(n){var e;return(e=n==null?void 0:n.map(t=>t.toFixed(2)).join(", "))!=null?e:"-"}function wme(n,e=12){if(n.length===0)return"-";let t=n.slice(0,e).join(", "),i=n.length-e;return i>0?`${t}, +${i.toLocaleString()} more`:t}function Nj(n){var e;return n.source==="component"?n.childCount&&n.childCount>1?`component (${n.childCount})`:"component":n.source==="group"?`group (${(e=n.childCount)!=null?e:n.meshRefs.length})`:"mesh"}function Fme(n){let e=n.sourceNotePath?`[[${n.sourceNotePath}|${n.sourcePartName}]]`:n.sourcePartName,t=n.reasons.length>0?` - ${n.reasons.join(", ")}`:"";return`${e} (${Math.round(n.confidence*100)}%${t})`}function wj(n){var t;let e=[];if(n.headingRef&&e.push(`heading: ${lr(n.headingRef)}`),n.notePath){let i=(t=oa(n.notePath))!=null?t:n.notePath;e.push(`note: [[${n.notePath}|${i}]]`)}return e}function Bme(n){return[{axis:"x",value:Math.max(0,n.boundingSize.x)},{axis:"y",value:Math.max(0,n.boundingSize.y)},{axis:"z",value:Math.max(0,n.boundingSize.z)}].sort((e,t)=>t.value-e.value)}function Fj(n){let[e,t,i]=Bme(n);if(!e||e.value<=0)return"Bounding information is incomplete, so scale and orientation still need manual review.";let r=i.value>0?e.value/i.value:Number.POSITIVE_INFINITY,s=e.value>0?t.value/e.value:0;return(e.value>0?i.value/e.value:0)<=.18&&s>=.45?`The bounding box is strongly planar, with a thin ${i.axis.toUpperCase()} dimension compared with ${e.axis.toUpperCase()}.`:r>=3&&s<=.55?`The model is strongly elongated along ${e.axis.toUpperCase()}, which suggests a directional or axial structure.`:"The overall bounding volume is fairly balanced, so semantic grouping is more likely to come from mesh and material boundaries than from one dominant axis."}function Bj(n){if(n.splatCount!==void 0)return`This is a splat-based asset with ${n.splatCount.toLocaleString()} splats; review should focus on capture coverage, density, and viewpoint clarity instead of triangle topology.`;let e=0;return n.triangleCount>=5e5?e+=3:n.triangleCount>=1e5?e+=2:n.triangleCount>=2e4&&(e+=1),n.meshCount>=100?e+=2:n.meshCount>=25&&(e+=1),n.materialCount>=8&&(e+=1),e>=5?"The mesh and material counts point to a high-complexity asset; expect semantic cleanup, regrouping, or naming review before turning it into stable knowledge notes.":e>=3?"The asset sits in a medium-complexity range: it already contains useful structure, but some meshes or materials may still reflect export convenience rather than real-world parts.":"The asset is structurally compact, so a lightweight local pass can usually produce usable first-draft notes without a heavier analysis pipeline."}function Ume(n){var t;let e=(t=n==null?void 0:n.tags)!=null?t:[];return e.length===0?"No knowledge tags are stored yet, so the note should establish the first stable vocabulary for this model.":`Current tags already suggest a working taxonomy: ${_N(e)}.`}function Cj(n){var t;let e=(t=n==null?void 0:n.annotations)!=null?t:[];return e.length===0?"No annotation pins are stored yet, so the next useful pass is to mark semantically important regions before splitting the model into part notes.":e.length===1?"There is 1 saved annotation pin, which already gives this report a concrete user-selected focus area.":`There are ${e.length} saved annotation pins, which provide a useful first-pass map of user-relevant regions.`}function Vme(n,e){var r;if(!n)return["Preview statistics were not available when this note was generated, so the next step is to reload the model and regenerate the report.",Cj(e)];let t=[`${n.meshCount.toLocaleString()} mesh(es), ${((r=n.splatCount)!=null?r:n.triangleCount).toLocaleString()} ${n.splatCount!==void 0?"splats":"triangles"}, and ${n.materialCount.toLocaleString()} material slot(s) are currently visible in the preview pipeline.`,Bj(n),Fj(n),Cj(e)],i=Ume(e);return i&&t.push(i),t}function Gme(n){var i;let e=(i=n==null?void 0:n.annotations)!=null?i:[];if(e.length===0)return["## Focus Areas","","- No focus areas have been pinned yet.",""];let t=["## Focus Areas",""];for(let r of e){let s=wj(r),a=s.length>0?` (${s.join("; ")})`:"";t.push(`- **${r.label||"Untitled pin"}**${a}`)}return t.push(""),t}function kme(n){var i,r;let e=(i=n==null?void 0:n.annotationLinks)!=null?i:[];if(e.length===0)return["## Annotation Links","","- No annotation-to-part links were produced in this pass.",""];let t=["## Annotation Links","","| Annotation | Nearest Part | Linked Note | Distance | Confidence |","|------------|--------------|-------------|----------|------------|"];for(let s of e){let a=s.notePath?`[[${s.notePath}]]`:"-";t.push(`| ${ta(s.label)} | ${ta((r=s.nearestPartName)!=null?r:"-")} | ${ta(a)} | ${s.distance===void 0?"-":s.distance.toFixed(3)} | ${Math.round(s.confidence*100)}% |`)}return t.push(""),t}function Wme(n){var i,r,s,a;let e=((i=n==null?void 0:n.parts)!=null?i:[]).filter(o=>o.notePath);if(e.length===0)return["## Suggested Part Notes","","- No part note drafts were created in this pass.",""];let t=["## Suggested Part Notes",""];for(let o of e.slice(0,Dj)){let l=lr((s=oa((r=o.notePath)!=null?r:""))!=null?s:o.name),c=[(a=o.category)!=null?a:"unclassified",xo(o.triangleCount,"triangle"),o.materialName?`material ${lr(o.materialName)}`:""].filter(Boolean).join(", ");t.push(`- [[${o.notePath}|${l}]] - ${lr(o.name)} (${c})`)}return t.push(""),t}function xo(n,e){return`${(n!=null?n:0).toLocaleString()} ${e}${n===1?"":"s"}`}function Hme(n){return n.length===0?"No per-part evidence was captured yet, so the first useful editing pass is to reload the model and regenerate this note from the workbench.":n.slice(0,6).map((e,t)=>{var r;let i=e.materialName?`, material ${lr(e.materialName)}`:"";return`${t+1}. ${lr(e.name)} (${(r=e.category)!=null?r:"unclassified"}, ${xo(e.triangleCount,"triangle")}${i})`}).join(` -`)}function zme(n){let e=n.filter(t=>{var i;return(i=t.registeredMatches)==null?void 0:i.length});return e.length===0?"No previously registered parts were matched across other analyzed models in this pass.":e.slice(0,6).map(t=>{var r;let i=(r=t.registeredMatches)==null?void 0:r[0];return i?`- ${lr(t.name)}: possible reuse of ${lr(i.sourcePartName)} from ${lr(i.sourceAssetId)} (${Math.round(i.confidence*100)}% confidence).`:""}).filter(Boolean).join(` -`)}function Uj(n){var _,g,v,x,A,S,E,R,I;let e=Oj(n.sourcePath).toUpperCase(),t=n.preview,i=[...(g=(_=n.analysis)==null?void 0:_.parts)!=null?g:[]].sort((y,M)=>{var D,O;return((D=M.triangleCount)!=null?D:0)-((O=y.triangleCount)!=null?O:0)}),r=(x=(v=n.profile)==null?void 0:v.annotations)!=null?x:[],s=(S=(A=n.analysis)==null?void 0:A.annotationLinks)!=null?S:[],a=uN(i.map(y=>{var M;return(M=y.category)!=null?M:"unclassified"})).slice(0,6),o=uN(i.flatMap(y=>y.materialName?[lr(y.materialName)]:[])).slice(0,6),l=Hme(i),c=zme(i),f=t?Fj(t):"Geometry statistics are not available yet, so this draft should stay provisional.",h=t?Bj(t):"Reload the preview to capture mesh, triangle, vertex, and material evidence.",d=(E=n.profile)==null?void 0:E.notes.trim(),u=t?`${n.baseName} is a ${e} asset with ${xo(t.meshCount,"mesh")}, ${xo(t.triangleCount,"triangle")}, ${xo(t.vertexCount,"vertex")}, and ${xo(t.materialCount,"material slot")}.`:`${n.baseName} is a ${e} asset that still needs a refreshed preview pass before its geometry can be summarized confidently.`,m=r.length>0?r.map(y=>{let M=s.find(V=>V.annotationId===y.id),D=M!=null&&M.nearestPartName?` Nearest captured part: ${lr(M.nearestPartName)}.`:"",O=y.headingRef?` Linked heading: ${lr(y.headingRef)}.`:"";return`- ${lr(y.label||"Untitled pin")}.${D}${O}`}).join(` -`):"- No pins are saved yet. Add pins for the regions that should become standalone notes, questions, or review checkpoints.",p=[i.length>0?"Rename the strongest part candidates so their mesh names match real semantic parts.":"Regenerate after the model preview has captured per-part evidence.",r.length>0?"Turn each saved pin into a short linked note or heading-level review item.":"Place at least one pin on the most important region before treating this as a finished note.","Review scale, orientation, materials, and whether mesh boundaries represent real assembly boundaries."];return{title:`${n.baseName} local knowledge draft`,summary:[u,f,d?`User notes add this context: ${d}`:"No user notes are stored yet, so the draft stays grounded in renderer evidence and saved pins."].join(" "),sections:[{heading:"Evidence-backed description",body:[h,a.length>0?`Detected part categories: ${_N(a)}.`:"No part categories were inferred yet.",o.length>0?`Visible materials include ${_N(o)}.`:"No material names were captured from the renderer evidence."].join(" ")},{heading:"Candidate structure",body:l},{heading:"Registered part reuse",body:c},{heading:"Focus areas",body:m},{heading:"Suggested note shape",body:[`Start with a short purpose paragraph for ${n.baseName}.`,"Then split the note into geometry evidence, meaningful part candidates, saved focus areas, and unresolved review questions.","Only promote a mesh into a standalone part note after a human confirms its function or assembly role."].join(" ")}],suggestedTags:uN([...(I=(R=n.profile)==null?void 0:R.tags)!=null?I:[],`format/${e.toLowerCase()}`,...a.map(y=>`part/${y}`)]).slice(0,12),nextActions:p,generatedAt:new Date().toISOString()}}function Xme(n){var i,r;let e=(r=(i=n.analysis)==null?void 0:i.localDraft)!=null?r:Uj(n),t=["## Local Draft Metadata","",`- Generated at: ${e.generatedAt}`,`- Sections: ${e.sections.length.toLocaleString()}`];return e.suggestedTags.length>0&&t.push("Suggested tags:","",...e.suggestedTags.map(s=>`- ${s}`),""),e.nextActions.length>0&&t.push("Next actions:","",...e.nextActions.map(s=>`- ${s}`),""),t}function An(n){return JSON.stringify(n)}function Yme(n){return n!=null&&n.draftingInput?["## AI Drafting Input","","- Grounded drafting input is available in the sidecar JSON under `draftingInput`.",`- Part candidates included: ${n.draftingInput.partCandidates.length.toLocaleString()}`,`- Annotation links included: ${n.draftingInput.annotationLinks.length.toLocaleString()}`,"- Raw model included: false",""]:["## AI Drafting Input","","- No drafting input was prepared in this pass.",""]}function Kme(n){var i,r,s,a;let e=n==null?void 0:n.remoteDraft;if(!e)return["## Remote Draft","","- No remote draft was requested or returned for this pass.",""];let t=["## Remote Draft","",e.title?`### ${e.title}`:"### Draft Summary","",e.summary,""];for(let o of(i=e.sections)!=null?i:[])t.push(`### ${o.heading}`,"",o.body,"");(r=e.suggestedTags)!=null&&r.length&&t.push("Suggested tags:","",...e.suggestedTags.map(o=>`- ${o}`),"");for(let o of(s=e.warnings)!=null?s:[])t.push(`- Remote warning: ${o}`);return(a=e.warnings)!=null&&a.length&&t.push(""),t}function jme(n){var i,r;let e=(i=n==null?void 0:n.remoteDraft)!=null?i:n==null?void 0:n.localDraft;if(!e)return["## Editable Draft","","- No draft body was produced in this pass.",""];let t=["## Editable Draft","",n!=null&&n.remoteDraft?"- Source: optional remote draft, grounded by the local evidence sidecar.":"- Source: local evidence draft, generated without a remote service.","",e.summary,""];for(let s of(r=e.sections)!=null?r:[])t.push(`### ${s.heading}`,"",s.body,"");return t}function qme(n){var t;let e=(t=n==null?void 0:n.previewImages)!=null?t:[];return e.length===0?["## Evidence Snapshots","","- No preview snapshot was captured for this generation pass.",""]:["## Evidence Snapshots","",...e.map(i=>`![[${i}]]`),""]}function Zme(n){var i,r,s,a;let e=(i=n==null?void 0:n.parts)!=null?i:[];if(e.length===0)return["## Part Candidates","","- No per-mesh evidence was available. Reload the model in the workbench and regenerate the note to capture part candidates.",""];let t=["## Part Candidates","","| # | Part | Part Note | Source | Category | Triangles | Material | Center | Evidence |","|---|------|-----------|--------|----------|-----------|----------|--------|----------|"];for(let[o,l]of e.slice(0,32).entries()){let c=vN(l.center),f=l.observations.slice(0,2).join(" "),h=l.notePath?`[[${l.notePath}]]`:"-",d=Nj(l);t.push(`| ${o+1} | ${ta(l.name)} | ${ta(h)} | ${ta(d)} | ${ta((r=l.category)!=null?r:"unclassified")} | ${((s=l.triangleCount)!=null?s:0).toLocaleString()} | ${ta((a=l.materialName)!=null?a:"-")} | ${c} | ${ta(f)} |`)}return e.length>32&&t.push(`| ... | ${e.length-32} more candidate parts omitted from this note | - | - | - | - | - | - | See sidecar JSON |`),t.push(""),t}function Qme(n){var i,r;let e=((i=n==null?void 0:n.parts)!=null?i:[]).filter(s=>{var a;return(a=s.registeredMatches)==null?void 0:a.length});if(e.length===0)return["## Registered Part Matches","","- No previously registered parts were matched across other analyzed models in this pass.",""];let t=["## Registered Part Matches","","| Current Part | Best Existing Part | Source Model | Confidence | Reasons |","|--------------|--------------------|--------------|------------|---------|"];for(let s of e.slice(0,32)){let a=(r=s.registeredMatches)==null?void 0:r[0];if(!a)continue;let o=a.sourceNotePath?`[[${a.sourceNotePath}|${a.sourcePartName}]]`:a.sourcePartName;t.push(`| ${ta(s.name)} | ${ta(o)} | ${ta(a.sourceAssetId)} | ${Math.round(a.confidence*100)}% | ${ta(a.reasons.join(", "))} |`)}return e.length>32&&t.push(`| ... | ${e.length-32} more matched parts omitted | - | - | See sidecar JSON |`),t.push(""),t}function $me(n){var i;let e=(i=n==null?void 0:n.knowledgeNodes)!=null?i:[];if(e.length===0)return["## Knowledge Nodes","","- No knowledge nodes were produced in this pass.",""];let t=["## Knowledge Nodes",""];for(let r of e)t.push(`- **${r.title}** (${r.domain}, ${Math.round(r.confidence*100)}%, ${r.source}): ${r.summary}`);return t.push(""),t}function Jme(n,e){var i,r;let t=["## Evidence Health","",`- Analysis version: ${Ep}`,e?`- Sidecar: [[${e}|Analysis JSON]]`:"- Sidecar: not written",n!=null&&n.knowledgeIndexPath?`- Knowledge index: [[${n.knowledgeIndexPath}|Model index]]`:"- Knowledge index: not written"];for(let s of(i=n==null?void 0:n.warnings)!=null?i:[])t.push(`- Warning: ${s}`);return((r=n==null?void 0:n.warnings)!=null?r:[]).length===0&&t.push("- Warnings: none"),t.push(""),t}function epe(n,e){var r;let t=(r=e==null?void 0:e.annotations)!=null?r:[],i=["## Draft Knowledge Points",""];if(n?(i.push(`- Geometry overview: explain how ${n.meshCount.toLocaleString()} mesh(es) and ${n.materialCount.toLocaleString()} material slot(s) map to real semantic parts instead of export-only fragments.`),n.splatCount!==void 0?i.push(`- Capture quality: review whether the ${n.splatCount.toLocaleString()} splats preserve enough silhouette and depth detail for note-taking from multiple angles.`):i.push(`- Structural density: verify whether ${(n.triangleCount/Math.max(n.meshCount,1)).toLocaleString(void 0,{maximumFractionDigits:0})} average triangles per mesh reflects deliberate detail or accidental over-segmentation.`)):i.push("- Geometry overview: reload the model and capture preview statistics before turning this into a stable knowledge note."),t.length>0)for(let s of t.slice(0,8)){let a=wj(s),o=a.length>0?` (${a.join("; ")})`:"";i.push(`- **${s.label||"Untitled pin"}**${o}: describe what this region does, why it matters, and whether it deserves its own linked part note.`)}else i.push("- Focus mapping: add pins for the regions that should become standalone part notes or review checkpoints.");return i.push("- Review pass: confirm scale, orientation, and whether material boundaries reflect actual function, assembly, or simply renderer setup."),i.push(""),i}function Vj(n){var c,f,h,d;let e=n.profile,t=n.preview,i=n.analysis,r=Oj(n.sourcePath),s=(c=e==null?void 0:e.tags)!=null?c:[],a=(f=e==null?void 0:e.annotations)!=null?f:[],o=(h=i==null?void 0:i.previewImages)!=null?h:[];return[["---",`source_model: ${An(n.sourcePath)}`,`format: ${r}`,"status: ready","analysis_mode: local",`analysis_version: ${Ep}`,`report_note_path: ${An(n.notePath)}`,...n.analysisSidecarPath?[`analysis_sidecar_path: ${An(n.analysisSidecarPath)}`]:[],...n.knowledgeIndexPath?[`knowledge_index_path: ${An(n.knowledgeIndexPath)}`]:[],`annotation_count: ${a.length}`,`updated_at: ${new Date().toISOString()}`,...o.length>0?["preview_images:",...o.map(u=>` - ${An(u)}`)]:[],...s.length>0?["knowledge_tags:",...s.map(u=>` - ${An(u)}`)]:[],"---"].join(` +`).trim()||null}catch(i){return null}}function pp(n){return(e,t)=>dme(n,e,t)}var mj,rv=C(()=>{"use strict";mj=require("obsidian")});function Td(n){let e=n.createDiv({cls:"ai3d-loading-overlay"}),t=e.createDiv({cls:"ai3d-loading-skeleton"});t.createDiv({cls:"ai3d-loading-skeleton-canvas"});let i=t.createDiv({cls:"ai3d-loading-skeleton-meta"});i.createDiv({cls:"ai3d-loading-skeleton-line"}),i.createDiv({cls:"ai3d-loading-skeleton-line is-short"}),e.createDiv({cls:"ai3d-loading-spinner"});let r=e.createDiv({cls:"ai3d-loading-text"}),s="loading.default",a="",o=()=>{r.textContent=s?J(s):a};o();let c=e.createDiv({cls:"ai3d-loading-bar-track"}).createDiv({cls:"ai3d-loading-bar-fill is-indeterminate"}),f=!1,h=jN(()=>{!f&&s&&o()});return{el:e,setPhase(d){s=null,a=d,f||o()},setPhaseKey(d){s=d,f||o()},setProgress(d){f||(d<0?(c.className="ai3d-loading-bar-fill is-indeterminate",c.style.removeProperty("--bar-width")):(c.className="ai3d-loading-bar-fill",c.style.setProperty("--bar-width",`${Math.min(100,Math.max(0,d))}%`)))},hide(){f||(f=!0,h(),e.classList.add("is-hiding"),window.setTimeout(()=>e.remove(),300))}}}var vb=C(()=>{"use strict";ia()});function _p(n,e){let t=n.createDiv({cls:"ai3d-inline-empty ai3d-load-feedback-shell"});mr()&&t.classList.add("is-mobile");let i=t.createDiv({cls:`ai3d-load-feedback is-${e.level}`});return i.createDiv({cls:"ai3d-load-feedback-title",text:e.title}),i.createDiv({cls:"ai3d-load-feedback-message",text:e.message}),i.createDiv({cls:"ai3d-load-feedback-hint",text:e.hint}),t}function gp(n,e){var o,l,c,f,h,d,u;if((!e.performanceTier||e.performanceTier==="light")&&!((o=e.resourceWarnings)!=null&&o.length))return null;let t=(l=e.performanceTier)!=null?l:"light",i=((c=e.splatCount)!=null?c:e.triangleCount).toLocaleString(),r=e.splatCount!==void 0?"splats":"triangles",s=n.createDiv({cls:`ai3d-performance-feedback is-${t}`});s.createDiv({cls:"ai3d-performance-feedback-tier",text:(f=e.resourceWarnings)!=null&&f.length?"assets":(h=e.performanceTier)!=null?h:"light"}),s.createDiv({cls:"ai3d-performance-feedback-meta",text:(d=e.resourceWarnings)!=null&&d.length?e.resourceWarnings[0]:`${i} ${r} \xB7 ${e.materialCount.toLocaleString()} materials`});let a=[...(u=e.resourceWarnings)!=null?u:[],...e.performanceHint?[e.performanceHint]:[]];return a.length>0&&(s.title=a.join(` +`)),window.setTimeout(()=>s.classList.add("is-subtle"),4200),s}var Eb=C(()=>{"use strict";Ys()});function vj(){return typeof performance!="undefined"?performance.now():Date.now()}function Ad(n,e,t=`${e}s`){return`${n.toLocaleString()} ${n===1?e:t}`}function _me(n){return{stage:"reason",durationMs:Math.max(0,Math.round(vj()-n)),status:"success"}}function gme(n,e){let t=n[0]-e[0],i=n[1]-e[1],r=n[2]-e[2];return Math.sqrt(t*t+i*i+r*r)}function Ej(n){var t;let e=(t=n.split(".").pop())==null?void 0:t.trim().toLowerCase();return pme.has(e)?e:"glb"}function fN(n){return[n.x,n.y,n.z]}function _j(n){return n.trim().replace(/[\\/:*?"<>|#[\]^]+/g,"-").replace(/\s+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,96)}function vme(n,e,t,i){var c,f;let r=_j(jr(n)||"model")||"model",s=(f=(c=e.occurrenceId)!=null?c:e.componentId)!=null?f:e.partNumber,a=s?`${r}:component:${_j(s)||t+1}`:`${r}:part:${t+1}`,o=a,l=2;for(;i.has(o);)o=`${a}:${l}`,l++;return i.add(o),o}function nv(n){return(n!=null?n:"").toLowerCase().replace(/[_\-./\\]+/g," ").replace(/[^\p{L}\p{N}\s]+/gu," ").replace(/\s+/g," ").trim()}function Sb(n){return new Set(nv(n).split(" ").filter(e=>e.length>=2))}function gj(n,e){if(n.size===0||e.size===0)return 0;let t=0;for(let i of n)e.has(i)&&(t+=1);return t/Math.max(n.size,e.size)}function Eme(n,e){if(!n||!e||n.length<3||e.length<3)return 0;let t=[...n].slice(0,3).map(s=>Math.max(1e-4,Math.abs(s))).sort((s,a)=>s-a),i=[...e].slice(0,3).map(s=>Math.max(1e-4,Math.abs(s))).sort((s,a)=>s-a),r=0;for(let s=0;s<3;s++)r+=Math.min(t[s],i[s])/Math.max(t[s],i[s]);return r/3}function Sme(n,e){let t=nv(n),i=nv(e);return!!t&&!!i&&t===i}function cN(n,e){let t=nv(n),i=nv(e);return!!t&&!!i&&t===i}function Tme(n,e){let t=Sb(n.name),i=Sb(n.meshRefs.join(" "));return e.filter(s=>s.assetId!==n.assetId||s.partId!==n.partId).flatMap(s=>{let a=[],o=gj(t,Sb(s.name)),l=gj(i,Sb(s.meshRefs.join(" "))),c=Eme(n.bbox,s.bbox),f=!!n.category&&!!s.category&&n.category===s.category,h=Sme(n.materialName,s.materialName),d=cN(n.componentId,s.componentId),u=cN(n.partNumber,s.partNumber),m=cN(n.occurrenceId,s.occurrenceId),p=o*.38+l*.22+c*.22;return d&&(p+=.5),u&&(p+=.4),m&&(p+=.25),f&&(p+=.1),h&&(p+=.08),d&&a.push(`same component id: ${n.componentId}`),u&&a.push(`same part number: ${n.partNumber}`),m&&a.push("same occurrence id"),o>=.5&&a.push("similar part name"),l>=.5&&a.push("similar mesh names"),c>=.72&&a.push("similar bounding size"),f&&a.push(`same category: ${n.category}`),h&&n.materialName&&a.push(`same material: ${n.materialName}`),p=Math.min(1,p),pa.matchScore-s.matchScore).slice(0,ume)}function Ame(n,e){return e.length===0?n.map(t=>({...t})):n.map(t=>{let i=Tme(t,e);return i.length>0?{...t,registeredMatches:i}:{...t}})}function xme(n){var t;let e=n.name.toLowerCase();return n.source==="component"?"component":n.source==="group"?"group":e.includes("wheel")||e.includes("gear")||e.includes("axle")?"mechanical":e.includes("shell")||e.includes("case")||e.includes("cover")||e.includes("housing")?"enclosure":e.includes("button")||e.includes("key")||e.includes("switch")?"control":e.includes("glass")||e.includes("screen")||e.includes("lens")?"surface":(t=n.materialName)!=null&&t.toLowerCase().includes("metal")?"material-driven":"unclassified"}function Rme(n){var t,i,r,s,a,o;let e=[];return n.source==="group"&&e.push(`Registered from model group with ${Ad((r=(i=n.childCount)!=null?i:(t=n.meshNames)==null?void 0:t.length)!=null?r:0,"child mesh","child meshes")}.`),n.source==="component"&&e.push(`Registered from model component metadata with ${Ad((o=(a=n.childCount)!=null?a:(s=n.meshNames)==null?void 0:s.length)!=null?o:1,"child mesh","child meshes")}.`),n.componentId&&e.push(`Component ID: ${n.componentId}.`),n.occurrenceId&&e.push(`Occurrence ID: ${n.occurrenceId}.`),n.partNumber&&e.push(`Part number: ${n.partNumber}.`),n.componentPath&&e.push(`Component path: ${n.componentPath}.`),e.push(`${Ad(n.triangleCount,"triangle")} and ${Ad(n.vertexCount,"vertex")}.`,`Bounding size ${n.boundingSize.x.toFixed(3)} x ${n.boundingSize.y.toFixed(3)} x ${n.boundingSize.z.toFixed(3)}.`),n.materialName&&e.push(`Uses material "${n.materialName}".`),e}function hN(n,e){let t=new Set;return e.map((i,r)=>{var s;return{partId:vme(n,i,r,t),assetId:n,name:i.name||`Part ${r+1}`,source:i.source,componentId:i.componentId,occurrenceId:i.occurrenceId,partNumber:i.partNumber,componentPath:i.componentPath,category:xme(i),meshRefs:(s=i.meshNames)!=null&&s.length?[...i.meshNames]:[i.name||`mesh-${r+1}`],childCount:i.childCount,materialRefs:i.materialName?[i.materialName]:[],bbox:fN(i.boundingSize),center:fN(i.center),triangleCount:i.triangleCount,vertexCount:i.vertexCount,materialName:i.materialName,confidence:i.source==="component"?.82:i.source==="group"?.72:i.name?.55:.35,observations:Rme(i),inferredFunctions:[],knowledgeTags:[],reviewed:!1}})}function bme(n,e,t,i,r){var o;let s=[],a=t==null?void 0:t.summary;a&&s.push({id:`${n}:geometry`,title:"Geometry overview",domain:"geometry",summary:`${Ad(a.meshCount,"mesh")}, ${Ad(a.triangleCount,"triangle")}, ${Ad(a.materialCount,"material slot")}.`,relatedPartIds:i.slice(0,12).map(l=>l.partId),relatedAssetIds:[n],confidence:.72,source:"rule"});for(let l of(o=e==null?void 0:e.annotations)!=null?o:[]){let c=r.find(f=>f.annotationId===l.id);s.push({id:`${n}:annotation:${l.id}`,title:l.label||"Annotation focus",domain:"assembly",summary:[l.headingRef?`Pinned focus area linked to heading "${l.headingRef}".`:"Pinned focus area marked by the user for follow-up analysis.",c!=null&&c.nearestPartName?`Nearest part candidate: ${c.nearestPartName}.`:""].filter(Boolean).join(" "),relatedPartIds:c!=null&&c.nearestPartId?[c.nearestPartId]:[],relatedAssetIds:[n],confidence:.8,source:"user"})}return s}function Ime(n,e){var i;return((i=n==null?void 0:n.annotations)!=null?i:[]).map(r=>{let s=r.position,a=null,o=Number.POSITIVE_INFINITY;for(let c of e){if(!c.center)continue;let f=gme(s,c.center);f{var l;return{partId:o.partId,name:o.name,notePath:o.notePath,source:o.source,componentId:o.componentId,occurrenceId:o.occurrenceId,partNumber:o.partNumber,componentPath:o.componentPath,category:o.category,meshRefs:[...o.meshRefs],childCount:o.childCount,triangleCount:o.triangleCount,materialName:o.materialName,registeredMatches:(l=o.registeredMatches)==null?void 0:l.map(c=>({...c,reasons:[...c.reasons]})),observations:o.observations}}),annotationLinks:[...n.annotationLinks],knowledgeNodes:[...n.knowledgeNodes]}}function Cme(n,e){var t,i;return Array.from(new Set([...(t=n==null?void 0:n.resourceWarnings)!=null?t:[],...(i=e==null?void 0:e.resourceWarnings)!=null?i:[]]))}function Tb(n){var f,h,d,u,m,p,_,g,v,x;let e=(f=n.startedAt)!=null?f:vj(),t=(d=(h=n.evidence)==null?void 0:h.summary)!=null?d:n.preview,i=Ame(hN(n.modelPath,(m=(u=n.evidence)==null?void 0:u.parts)!=null?m:[]),(p=n.registeredParts)!=null?p:[]),r=new Date().toISOString(),s=Cme(n.preview,n.evidence),a=Ime(n.profile,i),o=bme(n.modelPath,n.profile,n.evidence,i,a),l=(_=n.previewImages)!=null?_:[],c=Mme({modelPath:n.modelPath,profile:n.profile,preview:t,parts:i,knowledgeNodes:o,annotationLinks:a,previewImages:l,warnings:s});return{asset:{assetId:n.modelPath,title:jr(n.modelPath)||n.modelPath,sourcePath:n.modelPath,format:Ej(n.modelPath),importedAt:r,updatedAt:r,status:t?"ready":"processing",vertexCount:t==null?void 0:t.vertexCount,triangleCount:t==null?void 0:t.triangleCount,materialCount:t==null?void 0:t.materialCount,boundingBox:t?fN(t.boundingSize):void 0,analysisVersion:vp},parts:i,knowledgeNodes:o,previewImages:l,annotationLinks:a,draftingInput:c,evidence:(g=n.evidence)!=null?g:void 0,warnings:s,pipeline:[{stage:"stats",durationMs:0,status:t?"success":"skipped"},{stage:"split",durationMs:0,status:(x=(v=n.evidence)==null?void 0:v.parts)!=null&&x.length?"success":"skipped"},{stage:"map",durationMs:0,status:a.length>0?"success":"skipped"},_me(e)]}}var vp,ume,mme,pme,dN=C(()=>{"use strict";oa();vp="local-evidence-v1",ume=3,mme=.58,pme=new Set(["glb","gltf","stl","obj","splat","ply","fbx","step","stp","iges","igs","brep","sldprt","3mf","dae"])});function xd(n){let e=n.trim();return e.length>Tj?cr(e.slice(0,Tj))+"\u2026":cr(e)}function Aj(n){if(!n||typeof n!="object")return null;let e=n,t=typeof e.summary=="string"?e.summary.trim():"",i=xd(t);if(!i)return null;let r=Array.isArray(e.sections)?e.sections.flatMap(o=>{if(!o||typeof o!="object")return[];let l=o,c=typeof l.heading=="string"?l.heading.trim():"",f=typeof l.body=="string"?l.body.trim():"",h=xd(c),d=xd(f);return h&&d?[{heading:h,body:d}]:[]}):void 0,s=Array.isArray(e.suggestedTags)?e.suggestedTags.filter(o=>typeof o=="string"&&o.trim().length>0).map(o=>xd(o)):void 0,a=Array.isArray(e.warnings)?e.warnings.filter(o=>typeof o=="string"&&o.trim().length>0).map(o=>xd(o)):void 0;return{title:typeof e.title=="string"?xd(e.title):void 0,summary:i,sections:r,suggestedTags:s,warnings:a,model:typeof e.model=="string"?xd(e.model):void 0}}var Tj,xj=C(()=>{"use strict";GS();Tj=8e3});function Pme(n){let e=n.trim().replace(/\/+$/,"");if(!e)return"";let t=/^[a-z][a-z\d+\-.]*:\/\//i.test(e)?e:`http://${e}`;try{let i=new URL(t);return i.protocol!=="http:"&&i.protocol!=="https:"||i.search||i.hash?null:i.toString().replace(/\/+$/,"")}catch(i){return null}}function Dme(n){return{...n,evidence:{...n.evidence,previewImages:[]}}}function Lme(n){return{...n,model:{...n.model,summary:void 0},partCandidates:[],annotationLinks:n.annotationLinks.map(e=>({...e,notePath:void 0,position:[0,0,0],nearestPartId:void 0,nearestPartName:void 0,distance:void 0,confidence:Math.min(e.confidence,.25)})),knowledgeNodes:n.knowledgeNodes.map(e=>({...e,summary:"Geometry details were withheld by privacy settings.",relatedPartIds:[]}))}}function Ome(n,e){let t=e;return n.sendPreviewImagesToRemote||(t=Dme(t)),n.sendGeometrySummaryToRemote||(t=Lme(t)),{...t,evidence:{...t.evidence,rawModelIncluded:!1}}}function bj(n,e,t){if(n.analysisMode==="local")return{enabled:!1,reason:"analysisMode=local"};let i=Pme(n.serviceBaseUrl);return i===""?{enabled:!1,reason:"serviceBaseUrl is empty"}:i===null?{enabled:!1,reason:"serviceBaseUrl must be a valid http(s) URL"}:n.sendRawModelToRemote?{enabled:!1,reason:"raw model upload is not supported by this draft client"}:e?{enabled:!0,endpoint:`${i}/draft-note`,request:{analysisVersion:t,draftingInput:Ome(n,e)}}:{enabled:!1,reason:"drafting input is unavailable"}}async function Ij(n){if(!n.enabled||!n.endpoint||!n.request)return null;let e=await(0,Rj.requestUrl)({url:n.endpoint,method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n.request)});if(e.status<200||e.status>=300)throw new Error(`Remote draft request failed: HTTP ${e.status}`);return Aj(e.json)}var Rj,Mj=C(()=>{"use strict";Rj=require("obsidian");xj()});var Ab={};tt(Ab,{buildKnowledgeIndexContent:()=>Xj,buildKnowledgeIndexManagedSection:()=>TN,buildKnowledgeNoteContent:()=>Vj,collectRegisteredPartsFromProfiles:()=>Hj,generateKnowledgeNote:()=>cpe,replaceManagedSection:()=>zj});function Oj(n){var t;let e=(t=n.split(".").pop())==null?void 0:t.trim().toLowerCase();return e&&e.length>0?e:"unknown"}function _N(n){return n.filter(e=>e.length>0).join(", ")}function uN(n){return Array.from(new Set(n.map(e=>e.trim()).filter(Boolean)))}function EN(n){return n.replace(/\\/g,"/").replace(/^\/+|\/+$/g,"").trim()}function gN(n,e){return n.replace(/[\\/:*?"<>|#[\]^]/g," ").replace(/\s+/g," ").trim().slice(0,80)||e}function vN(n){var e;return(e=n==null?void 0:n.map(t=>t.toFixed(2)).join(", "))!=null?e:"-"}function wme(n,e=12){if(n.length===0)return"-";let t=n.slice(0,e).join(", "),i=n.length-e;return i>0?`${t}, +${i.toLocaleString()} more`:t}function Nj(n){var e;return n.source==="component"?n.childCount&&n.childCount>1?`component (${n.childCount})`:"component":n.source==="group"?`group (${(e=n.childCount)!=null?e:n.meshRefs.length})`:"mesh"}function Fme(n){let e=n.sourceNotePath?`[[${n.sourceNotePath}|${n.sourcePartName}]]`:n.sourcePartName,t=n.reasons.length>0?` - ${n.reasons.join(", ")}`:"";return`${e} (${Math.round(n.confidence*100)}%${t})`}function wj(n){var t;let e=[];if(n.headingRef&&e.push(`heading: ${cr(n.headingRef)}`),n.notePath){let i=(t=aa(n.notePath))!=null?t:n.notePath;e.push(`note: [[${n.notePath}|${i}]]`)}return e}function Bme(n){return[{axis:"x",value:Math.max(0,n.boundingSize.x)},{axis:"y",value:Math.max(0,n.boundingSize.y)},{axis:"z",value:Math.max(0,n.boundingSize.z)}].sort((e,t)=>t.value-e.value)}function Fj(n){let[e,t,i]=Bme(n);if(!e||e.value<=0)return"Bounding information is incomplete, so scale and orientation still need manual review.";let r=i.value>0?e.value/i.value:Number.POSITIVE_INFINITY,s=e.value>0?t.value/e.value:0;return(e.value>0?i.value/e.value:0)<=.18&&s>=.45?`The bounding box is strongly planar, with a thin ${i.axis.toUpperCase()} dimension compared with ${e.axis.toUpperCase()}.`:r>=3&&s<=.55?`The model is strongly elongated along ${e.axis.toUpperCase()}, which suggests a directional or axial structure.`:"The overall bounding volume is fairly balanced, so semantic grouping is more likely to come from mesh and material boundaries than from one dominant axis."}function Bj(n){if(n.splatCount!==void 0)return`This is a splat-based asset with ${n.splatCount.toLocaleString()} splats; review should focus on capture coverage, density, and viewpoint clarity instead of triangle topology.`;let e=0;return n.triangleCount>=5e5?e+=3:n.triangleCount>=1e5?e+=2:n.triangleCount>=2e4&&(e+=1),n.meshCount>=100?e+=2:n.meshCount>=25&&(e+=1),n.materialCount>=8&&(e+=1),e>=5?"The mesh and material counts point to a high-complexity asset; expect semantic cleanup, regrouping, or naming review before turning it into stable knowledge notes.":e>=3?"The asset sits in a medium-complexity range: it already contains useful structure, but some meshes or materials may still reflect export convenience rather than real-world parts.":"The asset is structurally compact, so a lightweight local pass can usually produce usable first-draft notes without a heavier analysis pipeline."}function Ume(n){var t;let e=(t=n==null?void 0:n.tags)!=null?t:[];return e.length===0?"No knowledge tags are stored yet, so the note should establish the first stable vocabulary for this model.":`Current tags already suggest a working taxonomy: ${_N(e)}.`}function Cj(n){var t;let e=(t=n==null?void 0:n.annotations)!=null?t:[];return e.length===0?"No annotation pins are stored yet, so the next useful pass is to mark semantically important regions before splitting the model into part notes.":e.length===1?"There is 1 saved annotation pin, which already gives this report a concrete user-selected focus area.":`There are ${e.length} saved annotation pins, which provide a useful first-pass map of user-relevant regions.`}function Vme(n,e){var r;if(!n)return["Preview statistics were not available when this note was generated, so the next step is to reload the model and regenerate the report.",Cj(e)];let t=[`${n.meshCount.toLocaleString()} mesh(es), ${((r=n.splatCount)!=null?r:n.triangleCount).toLocaleString()} ${n.splatCount!==void 0?"splats":"triangles"}, and ${n.materialCount.toLocaleString()} material slot(s) are currently visible in the preview pipeline.`,Bj(n),Fj(n),Cj(e)],i=Ume(e);return i&&t.push(i),t}function Gme(n){var i;let e=(i=n==null?void 0:n.annotations)!=null?i:[];if(e.length===0)return["## Focus Areas","","- No focus areas have been pinned yet.",""];let t=["## Focus Areas",""];for(let r of e){let s=wj(r),a=s.length>0?` (${s.join("; ")})`:"";t.push(`- **${r.label||"Untitled pin"}**${a}`)}return t.push(""),t}function kme(n){var i,r;let e=(i=n==null?void 0:n.annotationLinks)!=null?i:[];if(e.length===0)return["## Annotation Links","","- No annotation-to-part links were produced in this pass.",""];let t=["## Annotation Links","","| Annotation | Nearest Part | Linked Note | Distance | Confidence |","|------------|--------------|-------------|----------|------------|"];for(let s of e){let a=s.notePath?`[[${s.notePath}]]`:"-";t.push(`| ${ea(s.label)} | ${ea((r=s.nearestPartName)!=null?r:"-")} | ${ea(a)} | ${s.distance===void 0?"-":s.distance.toFixed(3)} | ${Math.round(s.confidence*100)}% |`)}return t.push(""),t}function Wme(n){var i,r,s,a;let e=((i=n==null?void 0:n.parts)!=null?i:[]).filter(o=>o.notePath);if(e.length===0)return["## Suggested Part Notes","","- No part note drafts were created in this pass.",""];let t=["## Suggested Part Notes",""];for(let o of e.slice(0,Dj)){let l=cr((s=aa((r=o.notePath)!=null?r:""))!=null?s:o.name),c=[(a=o.category)!=null?a:"unclassified",xo(o.triangleCount,"triangle"),o.materialName?`material ${cr(o.materialName)}`:""].filter(Boolean).join(", ");t.push(`- [[${o.notePath}|${l}]] - ${cr(o.name)} (${c})`)}return t.push(""),t}function xo(n,e){return`${(n!=null?n:0).toLocaleString()} ${e}${n===1?"":"s"}`}function Hme(n){return n.length===0?"No per-part evidence was captured yet, so the first useful editing pass is to reload the model and regenerate this note from the workbench.":n.slice(0,6).map((e,t)=>{var r;let i=e.materialName?`, material ${cr(e.materialName)}`:"";return`${t+1}. ${cr(e.name)} (${(r=e.category)!=null?r:"unclassified"}, ${xo(e.triangleCount,"triangle")}${i})`}).join(` +`)}function zme(n){let e=n.filter(t=>{var i;return(i=t.registeredMatches)==null?void 0:i.length});return e.length===0?"No previously registered parts were matched across other analyzed models in this pass.":e.slice(0,6).map(t=>{var r;let i=(r=t.registeredMatches)==null?void 0:r[0];return i?`- ${cr(t.name)}: possible reuse of ${cr(i.sourcePartName)} from ${cr(i.sourceAssetId)} (${Math.round(i.confidence*100)}% confidence).`:""}).filter(Boolean).join(` +`)}function Uj(n){var _,g,v,x,A,S,E,R,I;let e=Oj(n.sourcePath).toUpperCase(),t=n.preview,i=[...(g=(_=n.analysis)==null?void 0:_.parts)!=null?g:[]].sort((y,M)=>{var D,O;return((D=M.triangleCount)!=null?D:0)-((O=y.triangleCount)!=null?O:0)}),r=(x=(v=n.profile)==null?void 0:v.annotations)!=null?x:[],s=(S=(A=n.analysis)==null?void 0:A.annotationLinks)!=null?S:[],a=uN(i.map(y=>{var M;return(M=y.category)!=null?M:"unclassified"})).slice(0,6),o=uN(i.flatMap(y=>y.materialName?[cr(y.materialName)]:[])).slice(0,6),l=Hme(i),c=zme(i),f=t?Fj(t):"Geometry statistics are not available yet, so this draft should stay provisional.",h=t?Bj(t):"Reload the preview to capture mesh, triangle, vertex, and material evidence.",d=(E=n.profile)==null?void 0:E.notes.trim(),u=t?`${n.baseName} is a ${e} asset with ${xo(t.meshCount,"mesh")}, ${xo(t.triangleCount,"triangle")}, ${xo(t.vertexCount,"vertex")}, and ${xo(t.materialCount,"material slot")}.`:`${n.baseName} is a ${e} asset that still needs a refreshed preview pass before its geometry can be summarized confidently.`,m=r.length>0?r.map(y=>{let M=s.find(V=>V.annotationId===y.id),D=M!=null&&M.nearestPartName?` Nearest captured part: ${cr(M.nearestPartName)}.`:"",O=y.headingRef?` Linked heading: ${cr(y.headingRef)}.`:"";return`- ${cr(y.label||"Untitled pin")}.${D}${O}`}).join(` +`):"- No pins are saved yet. Add pins for the regions that should become standalone notes, questions, or review checkpoints.",p=[i.length>0?"Rename the strongest part candidates so their mesh names match real semantic parts.":"Regenerate after the model preview has captured per-part evidence.",r.length>0?"Turn each saved pin into a short linked note or heading-level review item.":"Place at least one pin on the most important region before treating this as a finished note.","Review scale, orientation, materials, and whether mesh boundaries represent real assembly boundaries."];return{title:`${n.baseName} local knowledge draft`,summary:[u,f,d?`User notes add this context: ${d}`:"No user notes are stored yet, so the draft stays grounded in renderer evidence and saved pins."].join(" "),sections:[{heading:"Evidence-backed description",body:[h,a.length>0?`Detected part categories: ${_N(a)}.`:"No part categories were inferred yet.",o.length>0?`Visible materials include ${_N(o)}.`:"No material names were captured from the renderer evidence."].join(" ")},{heading:"Candidate structure",body:l},{heading:"Registered part reuse",body:c},{heading:"Focus areas",body:m},{heading:"Suggested note shape",body:[`Start with a short purpose paragraph for ${n.baseName}.`,"Then split the note into geometry evidence, meaningful part candidates, saved focus areas, and unresolved review questions.","Only promote a mesh into a standalone part note after a human confirms its function or assembly role."].join(" ")}],suggestedTags:uN([...(I=(R=n.profile)==null?void 0:R.tags)!=null?I:[],`format/${e.toLowerCase()}`,...a.map(y=>`part/${y}`)]).slice(0,12),nextActions:p,generatedAt:new Date().toISOString()}}function Xme(n){var i,r;let e=(r=(i=n.analysis)==null?void 0:i.localDraft)!=null?r:Uj(n),t=["## Local Draft Metadata","",`- Generated at: ${e.generatedAt}`,`- Sections: ${e.sections.length.toLocaleString()}`];return e.suggestedTags.length>0&&t.push("Suggested tags:","",...e.suggestedTags.map(s=>`- ${s}`),""),e.nextActions.length>0&&t.push("Next actions:","",...e.nextActions.map(s=>`- ${s}`),""),t}function An(n){return JSON.stringify(n)}function Yme(n){return n!=null&&n.draftingInput?["## AI Drafting Input","","- Grounded drafting input is available in the sidecar JSON under `draftingInput`.",`- Part candidates included: ${n.draftingInput.partCandidates.length.toLocaleString()}`,`- Annotation links included: ${n.draftingInput.annotationLinks.length.toLocaleString()}`,"- Raw model included: false",""]:["## AI Drafting Input","","- No drafting input was prepared in this pass.",""]}function Kme(n){var i,r,s,a;let e=n==null?void 0:n.remoteDraft;if(!e)return["## Remote Draft","","- No remote draft was requested or returned for this pass.",""];let t=["## Remote Draft","",e.title?`### ${e.title}`:"### Draft Summary","",e.summary,""];for(let o of(i=e.sections)!=null?i:[])t.push(`### ${o.heading}`,"",o.body,"");(r=e.suggestedTags)!=null&&r.length&&t.push("Suggested tags:","",...e.suggestedTags.map(o=>`- ${o}`),"");for(let o of(s=e.warnings)!=null?s:[])t.push(`- Remote warning: ${o}`);return(a=e.warnings)!=null&&a.length&&t.push(""),t}function jme(n){var i,r;let e=(i=n==null?void 0:n.remoteDraft)!=null?i:n==null?void 0:n.localDraft;if(!e)return["## Editable Draft","","- No draft body was produced in this pass.",""];let t=["## Editable Draft","",n!=null&&n.remoteDraft?"- Source: optional remote draft, grounded by the local evidence sidecar.":"- Source: local evidence draft, generated without a remote service.","",e.summary,""];for(let s of(r=e.sections)!=null?r:[])t.push(`### ${s.heading}`,"",s.body,"");return t}function qme(n){var t;let e=(t=n==null?void 0:n.previewImages)!=null?t:[];return e.length===0?["## Evidence Snapshots","","- No preview snapshot was captured for this generation pass.",""]:["## Evidence Snapshots","",...e.map(i=>`![[${i}]]`),""]}function Zme(n){var i,r,s,a;let e=(i=n==null?void 0:n.parts)!=null?i:[];if(e.length===0)return["## Part Candidates","","- No per-mesh evidence was available. Reload the model in the workbench and regenerate the note to capture part candidates.",""];let t=["## Part Candidates","","| # | Part | Part Note | Source | Category | Triangles | Material | Center | Evidence |","|---|------|-----------|--------|----------|-----------|----------|--------|----------|"];for(let[o,l]of e.slice(0,32).entries()){let c=vN(l.center),f=l.observations.slice(0,2).join(" "),h=l.notePath?`[[${l.notePath}]]`:"-",d=Nj(l);t.push(`| ${o+1} | ${ea(l.name)} | ${ea(h)} | ${ea(d)} | ${ea((r=l.category)!=null?r:"unclassified")} | ${((s=l.triangleCount)!=null?s:0).toLocaleString()} | ${ea((a=l.materialName)!=null?a:"-")} | ${c} | ${ea(f)} |`)}return e.length>32&&t.push(`| ... | ${e.length-32} more candidate parts omitted from this note | - | - | - | - | - | - | See sidecar JSON |`),t.push(""),t}function Qme(n){var i,r;let e=((i=n==null?void 0:n.parts)!=null?i:[]).filter(s=>{var a;return(a=s.registeredMatches)==null?void 0:a.length});if(e.length===0)return["## Registered Part Matches","","- No previously registered parts were matched across other analyzed models in this pass.",""];let t=["## Registered Part Matches","","| Current Part | Best Existing Part | Source Model | Confidence | Reasons |","|--------------|--------------------|--------------|------------|---------|"];for(let s of e.slice(0,32)){let a=(r=s.registeredMatches)==null?void 0:r[0];if(!a)continue;let o=a.sourceNotePath?`[[${a.sourceNotePath}|${a.sourcePartName}]]`:a.sourcePartName;t.push(`| ${ea(s.name)} | ${ea(o)} | ${ea(a.sourceAssetId)} | ${Math.round(a.confidence*100)}% | ${ea(a.reasons.join(", "))} |`)}return e.length>32&&t.push(`| ... | ${e.length-32} more matched parts omitted | - | - | See sidecar JSON |`),t.push(""),t}function $me(n){var i;let e=(i=n==null?void 0:n.knowledgeNodes)!=null?i:[];if(e.length===0)return["## Knowledge Nodes","","- No knowledge nodes were produced in this pass.",""];let t=["## Knowledge Nodes",""];for(let r of e)t.push(`- **${r.title}** (${r.domain}, ${Math.round(r.confidence*100)}%, ${r.source}): ${r.summary}`);return t.push(""),t}function Jme(n,e){var i,r;let t=["## Evidence Health","",`- Analysis version: ${vp}`,e?`- Sidecar: [[${e}|Analysis JSON]]`:"- Sidecar: not written",n!=null&&n.knowledgeIndexPath?`- Knowledge index: [[${n.knowledgeIndexPath}|Model index]]`:"- Knowledge index: not written"];for(let s of(i=n==null?void 0:n.warnings)!=null?i:[])t.push(`- Warning: ${s}`);return((r=n==null?void 0:n.warnings)!=null?r:[]).length===0&&t.push("- Warnings: none"),t.push(""),t}function epe(n,e){var r;let t=(r=e==null?void 0:e.annotations)!=null?r:[],i=["## Draft Knowledge Points",""];if(n?(i.push(`- Geometry overview: explain how ${n.meshCount.toLocaleString()} mesh(es) and ${n.materialCount.toLocaleString()} material slot(s) map to real semantic parts instead of export-only fragments.`),n.splatCount!==void 0?i.push(`- Capture quality: review whether the ${n.splatCount.toLocaleString()} splats preserve enough silhouette and depth detail for note-taking from multiple angles.`):i.push(`- Structural density: verify whether ${(n.triangleCount/Math.max(n.meshCount,1)).toLocaleString(void 0,{maximumFractionDigits:0})} average triangles per mesh reflects deliberate detail or accidental over-segmentation.`)):i.push("- Geometry overview: reload the model and capture preview statistics before turning this into a stable knowledge note."),t.length>0)for(let s of t.slice(0,8)){let a=wj(s),o=a.length>0?` (${a.join("; ")})`:"";i.push(`- **${s.label||"Untitled pin"}**${o}: describe what this region does, why it matters, and whether it deserves its own linked part note.`)}else i.push("- Focus mapping: add pins for the regions that should become standalone part notes or review checkpoints.");return i.push("- Review pass: confirm scale, orientation, and whether material boundaries reflect actual function, assembly, or simply renderer setup."),i.push(""),i}function Vj(n){var c,f,h,d;let e=n.profile,t=n.preview,i=n.analysis,r=Oj(n.sourcePath),s=(c=e==null?void 0:e.tags)!=null?c:[],a=(f=e==null?void 0:e.annotations)!=null?f:[],o=(h=i==null?void 0:i.previewImages)!=null?h:[];return[["---",`source_model: ${An(n.sourcePath)}`,`format: ${r}`,"status: ready","analysis_mode: local",`analysis_version: ${vp}`,`report_note_path: ${An(n.notePath)}`,...n.analysisSidecarPath?[`analysis_sidecar_path: ${An(n.analysisSidecarPath)}`]:[],...n.knowledgeIndexPath?[`knowledge_index_path: ${An(n.knowledgeIndexPath)}`]:[],`annotation_count: ${a.length}`,`updated_at: ${new Date().toISOString()}`,...o.length>0?["preview_images:",...o.map(u=>` - ${An(u)}`)]:[],...s.length>0?["knowledge_tags:",...s.map(u=>` - ${An(u)}`)]:[],"---"].join(` `),"",`# ${n.baseName}`,"","## Summary","",...t?[...r3(t,{decimals:2}),""]:["(No preview data available)",""],...jme(i),...Xme(n),...n.knowledgeIndexPath?["## Knowledge Index","",`- [[${n.knowledgeIndexPath}|Open model knowledge index]]`,""]:[],"## Local Observations","",...Vme(t,e).map(u=>`- ${u}`),"",...Jme(i,n.analysisSidecarPath),...qme(i),...Gme(e),...kme(i),...Wme(i),...Zme(i),...Qme(i),...$me(i),...Yme(i),...Kme(i),...epe(t,e),"## Review Notes","",(d=e==null?void 0:e.notes)!=null&&d.trim()?e.notes.trim():"-",""].join(` -`)}function tpe(n,e){let t=new Date().toISOString();return{tags:Array.isArray(n==null?void 0:n.tags)?n.tags:[],notes:typeof(n==null?void 0:n.notes)=="string"?n.notes:"",annotations:Array.isArray(n==null?void 0:n.annotations)?n.annotations:[],registeredParts:Array.isArray(n==null?void 0:n.registeredParts)?n.registeredParts.map(i=>Wj(i,e)).filter(i=>!!i):void 0,analysisVersion:typeof(n==null?void 0:n.analysisVersion)=="string"?n.analysisVersion:void 0,reportNotePath:typeof(n==null?void 0:n.reportNotePath)=="string"?n.reportNotePath:void 0,analysisSidecarPath:typeof(n==null?void 0:n.analysisSidecarPath)=="string"?n.analysisSidecarPath:void 0,knowledgeIndexPath:typeof(n==null?void 0:n.knowledgeIndexPath)=="string"?n.knowledgeIndexPath:void 0,previewImagePaths:Array.isArray(n==null?void 0:n.previewImagePaths)?n.previewImagePaths.filter(i=>typeof i=="string"):void 0,createdAt:typeof(n==null?void 0:n.createdAt)=="string"?n.createdAt:t,updatedAt:typeof(n==null?void 0:n.updatedAt)=="string"?n.updatedAt:t}}function ta(n){return lr(n).replace(/\|/g,"\\|").replace(/\r?\n/g," ")}function ipe(n){let[,e=""]=n.split(",",2),t=atob(e),i=new Uint8Array(t.length);for(let r=0;r{Nme.warn("Failed to create vault folder",{path:i,error:String(s)})})}async function Gj(n,e,t){let i=n.vault.getAbstractFileByPath(e);if(i instanceof Cc.TFile)return i;try{return await n.vault.create(e,t)}catch(r){let s=n.vault.getAbstractFileByPath(e);return s instanceof Cc.TFile?s:null}}async function yj(n,e,t){let i=n.vault.getAbstractFileByPath(e);if(i instanceof Cc.TFile)return await n.vault.modify(i,t),i;try{return await n.vault.create(e,t)}catch(r){let s=n.vault.getAbstractFileByPath(e);if(s instanceof Cc.TFile)return await n.vault.modify(s,t),s}return null}async function rpe(n,e,t,i){var s;let r=(s=e==null?void 0:e.captureSnapshot)==null?void 0:s.call(e);if(!(r!=null&&r.startsWith("data:image/png;base64,")))return{paths:[]};try{await SN(n,t);let a=`${t}/${i}_evidence_${Date.now()}.png`;return await n.vault.createBinary(a,ipe(r)),{paths:[a]}}catch(a){let o=a instanceof Error?a.message:String(a);return{paths:[],warning:`Evidence snapshot failed: ${o}`}}}function kj(n){return!!n&&typeof n=="object"}function sv(n){return Array.isArray(n)?n.filter(e=>typeof e=="string"):[]}function Pj(n){if(!Array.isArray(n)||n.length<3)return;let e=n.slice(0,3).map(t=>Number(t));return e.every(Number.isFinite)?[e[0],e[1],e[2]]:void 0}function Wj(n,e){if(!kj(n))return null;let t=typeof n.partId=="string"?n.partId:"",i=typeof n.name=="string"?n.name:"";if(!t||!i)return null;let r=typeof n.assetId=="string"&&n.assetId?n.assetId:e;return{partId:t,assetId:r,parentPartId:typeof n.parentPartId=="string"?n.parentPartId:void 0,name:i,source:n.source==="group"||n.source==="mesh"||n.source==="component"?n.source:void 0,componentId:typeof n.componentId=="string"?n.componentId:void 0,occurrenceId:typeof n.occurrenceId=="string"?n.occurrenceId:void 0,partNumber:typeof n.partNumber=="string"?n.partNumber:void 0,componentPath:typeof n.componentPath=="string"?n.componentPath:void 0,category:typeof n.category=="string"?n.category:void 0,meshRefs:sv(n.meshRefs),childCount:Number.isFinite(n.childCount)?Number(n.childCount):void 0,materialRefs:sv(n.materialRefs),bbox:Pj(n.bbox),center:Pj(n.center),triangleCount:Number.isFinite(n.triangleCount)?Number(n.triangleCount):void 0,vertexCount:Number.isFinite(n.vertexCount)?Number(n.vertexCount):void 0,materialName:typeof n.materialName=="string"?n.materialName:null,confidence:Number.isFinite(n.confidence)?Number(n.confidence):.5,observations:sv(n.observations),inferredFunctions:sv(n.inferredFunctions),knowledgeTags:sv(n.knowledgeTags),notePath:typeof n.notePath=="string"?n.notePath:void 0,reviewed:n.reviewed===!0}}async function Hj(n,e,t){var a;let i=[],r=new Set,s=(o,l)=>{let c=Wj(o,l);if(!c)return;let f=`${c.assetId}:${c.partId}`;r.has(f)||(r.add(f),i.push(c))};for(let[o,l]of Object.entries(e))if(o!==t){if(l.analysisSidecarPath){let c=n.vault.getAbstractFileByPath(l.analysisSidecarPath);if(c instanceof Cc.TFile)try{let f=await n.vault.read(c),h=JSON.parse(f);if(kj(h)&&Array.isArray(h.parts))for(let d of h.parts)s(d,o)}catch(f){console.warn("[AI3D] Failed to read registered part sidecar:",l.analysisSidecarPath,f)}}for(let c of(a=l.registeredParts)!=null?a:[])s(c,o)}return i}function npe(n){var t;let e=new Set(((t=n.annotationLinks)!=null?t:[]).flatMap(i=>i.nearestPartId?[i.nearestPartId]:[]));return new Set([...n.parts].sort((i,r)=>{var c,f,h,d;let s=e.has(i.partId)?1:0,a=e.has(r.partId)?1:0;if(s!==a)return a-s;let o=(c=i.registeredMatches)!=null&&c.length?1:0,l=(f=r.registeredMatches)!=null&&f.length?1:0;return o!==l?l-o:((h=r.triangleCount)!=null?h:0)-((d=i.triangleCount)!=null?d:0)}).slice(0,Dj).map(i=>i.partId))}function spe(n,e,t,i){let r=EN(n)||"Parts/3D Components",s=gN(e,"model"),a=gN(t.name,`Part ${i+1}`);return`${r}/${s}/${String(i+1).padStart(2,"0")} ${a}.md`}function ape(n){var i,r,s,a,o,l;let e=((i=n.analysis.annotationLinks)!=null?i:[]).filter(c=>c.nearestPartId===n.part.partId);return[["---",`source_model: ${An(n.sourcePath)}`,`parent_report: ${An(n.notePath)}`,`part_id: ${An(n.part.partId)}`,`asset_id: ${An(n.part.assetId)}`,...n.part.componentId?[`component_id: ${An(n.part.componentId)}`]:[],...n.part.occurrenceId?[`occurrence_id: ${An(n.part.occurrenceId)}`]:[],...n.part.partNumber?[`part_number: ${An(n.part.partNumber)}`]:[],`category: ${An((r=n.part.category)!=null?r:"unclassified")}`,"status: draft","generated_by: ai-model-workbench",`updated_at: ${new Date().toISOString()}`,"---"].join(` -`),"",`# ${lr(n.part.name)}`,"","## Evidence","",`- Source model: [[${n.sourcePath}|${n.baseName}]]`,`- Parent report: [[${n.notePath}|${n.baseName} Report]]`,`- Source: ${Nj(n.part)}`,`- Category: ${(s=n.part.category)!=null?s:"unclassified"}`,...n.part.componentId?[`- Component ID: ${n.part.componentId}`]:[],...n.part.occurrenceId?[`- Occurrence ID: ${n.part.occurrenceId}`]:[],...n.part.partNumber?[`- Part number: ${n.part.partNumber}`]:[],...n.part.componentPath?[`- Component path: ${n.part.componentPath}`]:[],...n.part.source==="group"||n.part.source==="component"?[`- Child meshes: ${wme(n.part.meshRefs)}`]:[],`- Triangles: ${((a=n.part.triangleCount)!=null?a:0).toLocaleString()}`,`- Vertices: ${((o=n.part.vertexCount)!=null?o:0).toLocaleString()}`,`- Material: ${n.part.materialName?lr(n.part.materialName):"-"}`,`- Bounding size: ${vN(n.part.bbox)}`,`- Center: ${vN(n.part.center)}`,...(l=n.part.registeredMatches)!=null&&l.length?[`- Possible registered match: ${Fme(n.part.registeredMatches[0])}`]:[],"","## Renderer Observations","",...n.part.observations.length>0?n.part.observations.map(c=>`- ${c}`):["- No renderer observations were captured for this part."],"","## Linked Focus Areas","",...e.length>0?e.map(c=>`- ${c.label} (${Math.round(c.confidence*100)}% confidence, distance ${c.distance===void 0?"-":c.distance.toFixed(3)})`):["- No saved annotation pin is linked to this part yet."],"","## Working Notes","","- ",""].join(` -`)}async function ope(n){var a;let e=npe(n.analysis);if(e.size===0)return n.analysis.pipeline.push({stage:"partNotes",durationMs:0,status:"skipped"}),[];let t=[],i=typeof performance!="undefined"?performance.now():Date.now(),s=`${EN(n.partFolder)||"Parts/3D Components"}/${gN(n.baseName,"model")}`;await SN(n.app,s);for(let[o,l]of n.analysis.parts.entries()){if(!e.has(l.partId))continue;let c=spe(n.partFolder,n.baseName,l,o),f={...l,notePath:c},h=ape({baseName:n.baseName,notePath:n.notePath,sourcePath:n.sourcePath,part:f,analysis:n.analysis}),d=await Gj(n.app,c,h);d&&(l.notePath=d.path,t.push(d.path))}n.analysis.partNotePaths=t;for(let o of(a=n.analysis.annotationLinks)!=null?a:[]){let l=n.analysis.parts.find(c=>c.partId===o.nearestPartId);l!=null&&l.notePath&&!o.notePath&&(o.notePath=l.notePath)}return n.analysis.pipeline.push({stage:"partNotes",durationMs:Math.max(0,Math.round((typeof performance!="undefined"?performance.now():Date.now())-i)),status:t.length>0?"success":"skipped"}),t}function TN(n){var r,s,a,o,l,c;let e=((r=n.analysis.parts)!=null?r:[]).filter(f=>f.notePath),t=(a=(s=n.profile)==null?void 0:s.annotations)!=null?a:[],i=(l=(o=n.analysis.localDraft)==null?void 0:o.nextActions)!=null?l:[];return[Lj,"","## Entry Points","",`- Model report: [[${n.notePath}|${n.baseName} Report]]`,`- Analysis sidecar: [[${n.analysisSidecarPath}|Analysis JSON]]`,`- Source model: [[${n.sourcePath}|${n.baseName}]]`,"","## Model Snapshot","",n.preview?`- ${xo(n.preview.meshCount,"mesh")}, ${xo(n.preview.triangleCount,"triangle")}, ${xo(n.preview.vertexCount,"vertex")}, ${xo(n.preview.materialCount,"material slot")}.`:"- No preview statistics were available for this index.",`- Evidence images: ${((c=n.analysis.previewImages)!=null?c:[]).length.toLocaleString()}`,`- Part drafts: ${e.length.toLocaleString()}`,`- Saved annotations: ${t.length.toLocaleString()}`,"","## Part Notes","",...e.length>0?e.map(f=>{var u,m;let h=(u=f.registeredMatches)==null?void 0:u[0],d=h?`, matches ${lr(h.sourcePartName)} (${Math.round(h.confidence*100)}%)`:"";return`- [[${f.notePath}|${lr(f.name)}]] - ${(m=f.category)!=null?m:"unclassified"}, ${xo(f.triangleCount,"triangle")}${d}`}):["- No part note drafts were created in this pass."],"","## Evidence Images","",...n.analysis.previewImages.length>0?n.analysis.previewImages.map(f=>`- ![[${f}]]`):["- No evidence image was captured in this pass."],"","## Focus Areas","",...t.length>0?t.map(f=>{var u;let h=(u=n.analysis.annotationLinks)==null?void 0:u.find(m=>m.annotationId===f.id),d=h!=null&&h.notePath?` -> [[${h.notePath}|part note]]`:"";return`- ${f.label||"Untitled pin"}${d}`}):["- No saved annotation pins yet."],"","## Next Actions","",...i.length?i.map(f=>`- ${f}`):["- Review generated part drafts and promote confirmed components into stable notes."],"",pN,""].join(` +`)}function tpe(n,e){let t=new Date().toISOString();return{tags:Array.isArray(n==null?void 0:n.tags)?n.tags:[],notes:typeof(n==null?void 0:n.notes)=="string"?n.notes:"",annotations:Array.isArray(n==null?void 0:n.annotations)?n.annotations:[],registeredParts:Array.isArray(n==null?void 0:n.registeredParts)?n.registeredParts.map(i=>Wj(i,e)).filter(i=>!!i):void 0,analysisVersion:typeof(n==null?void 0:n.analysisVersion)=="string"?n.analysisVersion:void 0,reportNotePath:typeof(n==null?void 0:n.reportNotePath)=="string"?n.reportNotePath:void 0,analysisSidecarPath:typeof(n==null?void 0:n.analysisSidecarPath)=="string"?n.analysisSidecarPath:void 0,knowledgeIndexPath:typeof(n==null?void 0:n.knowledgeIndexPath)=="string"?n.knowledgeIndexPath:void 0,previewImagePaths:Array.isArray(n==null?void 0:n.previewImagePaths)?n.previewImagePaths.filter(i=>typeof i=="string"):void 0,createdAt:typeof(n==null?void 0:n.createdAt)=="string"?n.createdAt:t,updatedAt:typeof(n==null?void 0:n.updatedAt)=="string"?n.updatedAt:t}}function ea(n){return cr(n).replace(/\|/g,"\\|").replace(/\r?\n/g," ")}function ipe(n){let[,e=""]=n.split(",",2),t=atob(e),i=new Uint8Array(t.length);for(let r=0;r{Nme.warn("Failed to create vault folder",{path:i,error:String(s)})})}async function Gj(n,e,t){let i=n.vault.getAbstractFileByPath(e);if(i instanceof Mc.TFile)return i;try{return await n.vault.create(e,t)}catch(r){let s=n.vault.getAbstractFileByPath(e);return s instanceof Mc.TFile?s:null}}async function yj(n,e,t){let i=n.vault.getAbstractFileByPath(e);if(i instanceof Mc.TFile)return await n.vault.modify(i,t),i;try{return await n.vault.create(e,t)}catch(r){let s=n.vault.getAbstractFileByPath(e);if(s instanceof Mc.TFile)return await n.vault.modify(s,t),s}return null}async function rpe(n,e,t,i){var s;let r=(s=e==null?void 0:e.captureSnapshot)==null?void 0:s.call(e);if(!(r!=null&&r.startsWith("data:image/png;base64,")))return{paths:[]};try{await SN(n,t);let a=`${t}/${i}_evidence_${Date.now()}.png`;return await n.vault.createBinary(a,ipe(r)),{paths:[a]}}catch(a){let o=a instanceof Error?a.message:String(a);return{paths:[],warning:`Evidence snapshot failed: ${o}`}}}function kj(n){return!!n&&typeof n=="object"}function sv(n){return Array.isArray(n)?n.filter(e=>typeof e=="string"):[]}function Pj(n){if(!Array.isArray(n)||n.length<3)return;let e=n.slice(0,3).map(t=>Number(t));return e.every(Number.isFinite)?[e[0],e[1],e[2]]:void 0}function Wj(n,e){if(!kj(n))return null;let t=typeof n.partId=="string"?n.partId:"",i=typeof n.name=="string"?n.name:"";if(!t||!i)return null;let r=typeof n.assetId=="string"&&n.assetId?n.assetId:e;return{partId:t,assetId:r,parentPartId:typeof n.parentPartId=="string"?n.parentPartId:void 0,name:i,source:n.source==="group"||n.source==="mesh"||n.source==="component"?n.source:void 0,componentId:typeof n.componentId=="string"?n.componentId:void 0,occurrenceId:typeof n.occurrenceId=="string"?n.occurrenceId:void 0,partNumber:typeof n.partNumber=="string"?n.partNumber:void 0,componentPath:typeof n.componentPath=="string"?n.componentPath:void 0,category:typeof n.category=="string"?n.category:void 0,meshRefs:sv(n.meshRefs),childCount:Number.isFinite(n.childCount)?Number(n.childCount):void 0,materialRefs:sv(n.materialRefs),bbox:Pj(n.bbox),center:Pj(n.center),triangleCount:Number.isFinite(n.triangleCount)?Number(n.triangleCount):void 0,vertexCount:Number.isFinite(n.vertexCount)?Number(n.vertexCount):void 0,materialName:typeof n.materialName=="string"?n.materialName:null,confidence:Number.isFinite(n.confidence)?Number(n.confidence):.5,observations:sv(n.observations),inferredFunctions:sv(n.inferredFunctions),knowledgeTags:sv(n.knowledgeTags),notePath:typeof n.notePath=="string"?n.notePath:void 0,reviewed:n.reviewed===!0}}async function Hj(n,e,t){var a;let i=[],r=new Set,s=(o,l)=>{let c=Wj(o,l);if(!c)return;let f=`${c.assetId}:${c.partId}`;r.has(f)||(r.add(f),i.push(c))};for(let[o,l]of Object.entries(e))if(o!==t){if(l.analysisSidecarPath){let c=n.vault.getAbstractFileByPath(l.analysisSidecarPath);if(c instanceof Mc.TFile)try{let f=await n.vault.read(c),h=JSON.parse(f);if(kj(h)&&Array.isArray(h.parts))for(let d of h.parts)s(d,o)}catch(f){console.warn("[AI3D] Failed to read registered part sidecar:",l.analysisSidecarPath,f)}}for(let c of(a=l.registeredParts)!=null?a:[])s(c,o)}return i}function npe(n){var t;let e=new Set(((t=n.annotationLinks)!=null?t:[]).flatMap(i=>i.nearestPartId?[i.nearestPartId]:[]));return new Set([...n.parts].sort((i,r)=>{var c,f,h,d;let s=e.has(i.partId)?1:0,a=e.has(r.partId)?1:0;if(s!==a)return a-s;let o=(c=i.registeredMatches)!=null&&c.length?1:0,l=(f=r.registeredMatches)!=null&&f.length?1:0;return o!==l?l-o:((h=r.triangleCount)!=null?h:0)-((d=i.triangleCount)!=null?d:0)}).slice(0,Dj).map(i=>i.partId))}function spe(n,e,t,i){let r=EN(n)||"Parts/3D Components",s=gN(e,"model"),a=gN(t.name,`Part ${i+1}`);return`${r}/${s}/${String(i+1).padStart(2,"0")} ${a}.md`}function ape(n){var i,r,s,a,o,l;let e=((i=n.analysis.annotationLinks)!=null?i:[]).filter(c=>c.nearestPartId===n.part.partId);return[["---",`source_model: ${An(n.sourcePath)}`,`parent_report: ${An(n.notePath)}`,`part_id: ${An(n.part.partId)}`,`asset_id: ${An(n.part.assetId)}`,...n.part.componentId?[`component_id: ${An(n.part.componentId)}`]:[],...n.part.occurrenceId?[`occurrence_id: ${An(n.part.occurrenceId)}`]:[],...n.part.partNumber?[`part_number: ${An(n.part.partNumber)}`]:[],`category: ${An((r=n.part.category)!=null?r:"unclassified")}`,"status: draft","generated_by: ai-model-workbench",`updated_at: ${new Date().toISOString()}`,"---"].join(` +`),"",`# ${cr(n.part.name)}`,"","## Evidence","",`- Source model: [[${n.sourcePath}|${n.baseName}]]`,`- Parent report: [[${n.notePath}|${n.baseName} Report]]`,`- Source: ${Nj(n.part)}`,`- Category: ${(s=n.part.category)!=null?s:"unclassified"}`,...n.part.componentId?[`- Component ID: ${n.part.componentId}`]:[],...n.part.occurrenceId?[`- Occurrence ID: ${n.part.occurrenceId}`]:[],...n.part.partNumber?[`- Part number: ${n.part.partNumber}`]:[],...n.part.componentPath?[`- Component path: ${n.part.componentPath}`]:[],...n.part.source==="group"||n.part.source==="component"?[`- Child meshes: ${wme(n.part.meshRefs)}`]:[],`- Triangles: ${((a=n.part.triangleCount)!=null?a:0).toLocaleString()}`,`- Vertices: ${((o=n.part.vertexCount)!=null?o:0).toLocaleString()}`,`- Material: ${n.part.materialName?cr(n.part.materialName):"-"}`,`- Bounding size: ${vN(n.part.bbox)}`,`- Center: ${vN(n.part.center)}`,...(l=n.part.registeredMatches)!=null&&l.length?[`- Possible registered match: ${Fme(n.part.registeredMatches[0])}`]:[],"","## Renderer Observations","",...n.part.observations.length>0?n.part.observations.map(c=>`- ${c}`):["- No renderer observations were captured for this part."],"","## Linked Focus Areas","",...e.length>0?e.map(c=>`- ${c.label} (${Math.round(c.confidence*100)}% confidence, distance ${c.distance===void 0?"-":c.distance.toFixed(3)})`):["- No saved annotation pin is linked to this part yet."],"","## Working Notes","","- ",""].join(` +`)}async function ope(n){var a;let e=npe(n.analysis);if(e.size===0)return n.analysis.pipeline.push({stage:"partNotes",durationMs:0,status:"skipped"}),[];let t=[],i=typeof performance!="undefined"?performance.now():Date.now(),s=`${EN(n.partFolder)||"Parts/3D Components"}/${gN(n.baseName,"model")}`;await SN(n.app,s);for(let[o,l]of n.analysis.parts.entries()){if(!e.has(l.partId))continue;let c=spe(n.partFolder,n.baseName,l,o),f={...l,notePath:c},h=ape({baseName:n.baseName,notePath:n.notePath,sourcePath:n.sourcePath,part:f,analysis:n.analysis}),d=await Gj(n.app,c,h);d&&(l.notePath=d.path,t.push(d.path))}n.analysis.partNotePaths=t;for(let o of(a=n.analysis.annotationLinks)!=null?a:[]){let l=n.analysis.parts.find(c=>c.partId===o.nearestPartId);l!=null&&l.notePath&&!o.notePath&&(o.notePath=l.notePath)}return n.analysis.pipeline.push({stage:"partNotes",durationMs:Math.max(0,Math.round((typeof performance!="undefined"?performance.now():Date.now())-i)),status:t.length>0?"success":"skipped"}),t}function TN(n){var r,s,a,o,l,c;let e=((r=n.analysis.parts)!=null?r:[]).filter(f=>f.notePath),t=(a=(s=n.profile)==null?void 0:s.annotations)!=null?a:[],i=(l=(o=n.analysis.localDraft)==null?void 0:o.nextActions)!=null?l:[];return[Lj,"","## Entry Points","",`- Model report: [[${n.notePath}|${n.baseName} Report]]`,`- Analysis sidecar: [[${n.analysisSidecarPath}|Analysis JSON]]`,`- Source model: [[${n.sourcePath}|${n.baseName}]]`,"","## Model Snapshot","",n.preview?`- ${xo(n.preview.meshCount,"mesh")}, ${xo(n.preview.triangleCount,"triangle")}, ${xo(n.preview.vertexCount,"vertex")}, ${xo(n.preview.materialCount,"material slot")}.`:"- No preview statistics were available for this index.",`- Evidence images: ${((c=n.analysis.previewImages)!=null?c:[]).length.toLocaleString()}`,`- Part drafts: ${e.length.toLocaleString()}`,`- Saved annotations: ${t.length.toLocaleString()}`,"","## Part Notes","",...e.length>0?e.map(f=>{var u,m;let h=(u=f.registeredMatches)==null?void 0:u[0],d=h?`, matches ${cr(h.sourcePartName)} (${Math.round(h.confidence*100)}%)`:"";return`- [[${f.notePath}|${cr(f.name)}]] - ${(m=f.category)!=null?m:"unclassified"}, ${xo(f.triangleCount,"triangle")}${d}`}):["- No part note drafts were created in this pass."],"","## Evidence Images","",...n.analysis.previewImages.length>0?n.analysis.previewImages.map(f=>`- ![[${f}]]`):["- No evidence image was captured in this pass."],"","## Focus Areas","",...t.length>0?t.map(f=>{var u;let h=(u=n.analysis.annotationLinks)==null?void 0:u.find(m=>m.annotationId===f.id),d=h!=null&&h.notePath?` -> [[${h.notePath}|part note]]`:"";return`- ${f.label||"Untitled pin"}${d}`}):["- No saved annotation pins yet."],"","## Next Actions","",...i.length?i.map(f=>`- ${f}`):["- Review generated part drafts and promote confirmed components into stable notes."],"",pN,""].join(` `)}function zj(n,e){let t=n.indexOf(Lj),i=n.indexOf(pN);if(t>=0&&i>t){let r=n.slice(0,t).replace(/\s+$/,""),s=n.slice(i+pN.length).replace(/^\s+/,"");return[r,e.trim(),s].filter(Boolean).join(` `)+` @@ -23835,7 +23835,7 @@ gl_FragColor=color; ${e.trim()} `}function Xj(n){var r;let e=TN(n),t=((r=n.analysis.parts)!=null?r:[]).filter(s=>s.notePath).length;return[["---",`source_model: ${An(n.sourcePath)}`,`report_note_path: ${An(n.notePath)}`,`analysis_sidecar_path: ${An(n.analysisSidecarPath)}`,`part_note_count: ${t}`,"status: index","generated_by: ai-model-workbench",`updated_at: ${new Date().toISOString()}`,"---"].join(` `),"",`# ${n.baseName} Knowledge Index`,"","## User Notes","","- ","",e].join(` -`)}async function lpe(n){let e=typeof performance!="undefined"?performance.now():Date.now(),t=n.app.vault.getAbstractFileByPath(n.indexPath),i=null;if(t instanceof Cc.TFile){let r=await n.app.vault.read(t),s=TN(n);await n.app.vault.modify(t,zj(r,s)),i=t}else i=await Gj(n.app,n.indexPath,Xj(n));return i&&(n.analysis.knowledgeIndexPath=i.path),n.analysis.pipeline.push({stage:"index",durationMs:Math.max(0,Math.round((typeof performance!="undefined"?performance.now():Date.now())-e)),status:i?"success":"failed"}),i}async function cpe(n,e,t={}){var r,s,a,o,l,c;if(mN!==null)return;let i;mN=new Promise(f=>{i=f});try{let f=e.store.getState(),h=f.currentModelPath;if(!h)return;let d=f.modelAssetProfiles[h],u=f.modelPreview,m=jr(h)||"model",p=f.settings.reportFolder,_=`${p}/${m} Report.md`,g=`${p}/${m} Analysis.json`,v=`${p}/${m} Index.md`,x=(a=(s=(r=t.preview)==null?void 0:r.getModelEvidence)==null?void 0:s.call(r))!=null?a:null,A=await rpe(n,t.preview,f.settings.previewFolder,m),S=await Hj(n,f.modelAssetProfiles,h),E=Sb({modelPath:h,profile:d,preview:u,evidence:x,previewImages:A.paths,registeredParts:S});A.warning&&(E.warnings=[...E.warnings,A.warning],E.draftingInput&&(E.draftingInput={...E.draftingInput,evidence:{...E.draftingInput.evidence,warnings:[...E.draftingInput.evidence.warnings,A.warning]}})),E.localDraft=Uj({baseName:m,sourcePath:h,profile:d,preview:u,analysis:E}),E.pipeline.push({stage:"draft",durationMs:0,status:"success"}),await ope({app:n,partFolder:f.settings.partFolder,baseName:m,notePath:_,sourcePath:h,analysis:E}),E.draftingInput&&(E.draftingInput={...E.draftingInput,partCandidates:E.draftingInput.partCandidates.map(O=>{let V=E.parts.find(N=>N.partId===O.partId);return V!=null&&V.notePath?{...O,notePath:V.notePath}:O}),annotationLinks:[...(o=E.annotationLinks)!=null?o:[]]});let R=bj(f.settings,E.draftingInput,Ep);if(R.enabled)try{let O=await Ij(R);O?(E.remoteDraft=O,E.pipeline.push({stage:"remoteDraft",durationMs:0,status:"success"})):E.pipeline.push({stage:"remoteDraft",durationMs:0,status:"skipped"})}catch(O){let V=O instanceof Error?O.message:String(O);E.warnings=[...E.warnings,`Remote draft failed: ${V}`],E.pipeline.push({stage:"remoteDraft",durationMs:0,status:"failed"})}else E.pipeline.push({stage:"remoteDraft",durationMs:0,status:"skipped"});await SN(n,p),await lpe({app:n,baseName:m,notePath:_,sourcePath:h,analysisSidecarPath:g,indexPath:v,analysis:E,preview:u,profile:d});let I=Vj({baseName:m,notePath:_,sourcePath:h,profile:d,preview:u,analysis:E,analysisSidecarPath:g,knowledgeIndexPath:E.knowledgeIndexPath});await yj(n,g,`${JSON.stringify(E,null,2)} -`);let y=await yj(n,_,I);if(!y)return;let M=e.store.getState().modelAssetProfiles,D=tpe(M[h],h);e.store.setState({modelAssetProfiles:{...M,[h]:{...D,analysisVersion:Ep,registeredParts:E.parts,reportNotePath:y.path,analysisSidecarPath:g,knowledgeIndexPath:E.knowledgeIndexPath,previewImagePaths:A.paths,updatedAt:new Date().toISOString()}},lastKnowledgeGeneration:{modelPath:h,reportNotePath:y.path,analysisSidecarPath:g,knowledgeIndexPath:E.knowledgeIndexPath,partNoteCount:(c=(l=E.partNotePaths)==null?void 0:l.length)!=null?c:0,previewImageCount:E.previewImages.length,generatedAt:new Date().toISOString(),status:"success",warningCount:E.warnings.length}}),await n.workspace.getLeaf(!0).openFile(y,{active:!0}),new Cc.Notice(`Knowledge note updated: ${y.path}`)}finally{i(),mN=null}}var Cc,Nme,Dj,Lj,pN,mN,Ab=C(()=>{"use strict";Cc=require("obsidian");zS();VS();Tn();la();dN();Mj();Nme=ki("knowledge-note"),Dj=8,Lj="",pN="";mN=null});function Ro(n,e,t=2.5){var i;if(typeof n=="string"){let r=(i=RN[n])!=null?i:RN.iso;return{alpha:r.alpha,beta:r.beta,radiusMultiplier:t}}return{alpha:n,beta:e!=null?e:Math.PI/3,radiusMultiplier:t}}function pl(n,e,t=.02){let i=(1-t*(n+1))/n,r=(1-t*(e+1))/e,s=[];for(let a=0;a({path:i.path,position:[-t/2+r*e,0,0],color:i.color,wireframe:i.wireframe}))}function IN(n,e){return n.map((t,i)=>{let r=2*Math.PI*i/n.length;return{path:t.path,position:[Math.cos(r)*e,0,Math.sin(r)*e],color:t.color,wireframe:t.wireframe}})}var RN,Rd=C(()=>{"use strict";RN={iso:{alpha:Math.PI/4,beta:Math.PI/3},front:{alpha:0,beta:Math.PI/2},side:{alpha:Math.PI/2,beta:Math.PI/2},top:{alpha:0,beta:.01},back:{alpha:Math.PI,beta:Math.PI/2},"3/4":{alpha:Math.PI/6,beta:Math.PI/3.5}}});var Zj,Qj=C(()=>{"use strict";Rd();Zj={name:"compare",description:"Side-by-side model comparison (2-4 models)",minModels:2,maxModels:4,compute(n,e){if(n.length<2||n.length>4)return null;let t=Number(e.spacing)||6,i=e.angle||"iso",r=av(n,t),s=n.length<=3?n.length:2,a=Math.ceil(n.length/s),o=pl(s,a),l=n.map((c,f)=>({modelIndex:f,camera:Ro(i),viewport:o[f]}));return{placements:r,cells:l}}}});var $j,Jj=C(()=>{"use strict";Rd();$j={name:"showcase",description:"Single model viewed from multiple angles",minModels:1,maxModels:1,compute(n,e){if(n.length<1)return null;let t=Number(e.angles)||4,i=Number(e.radius)||2.5,r=[{path:n[0].path,position:[0,0,0],color:n[0].color,wireframe:n[0].wireframe}],s=t>=6?["front","side","top","back","iso","3/4"]:["iso","front","side","top"],a=s.length<=4?2:3,o=Math.ceil(s.length/a),l=pl(a,o),c=s.map((f,h)=>({modelIndex:0,camera:Ro(f,void 0,i),viewport:l[h]}));return{placements:r,cells:c}}}});var eq,tq=C(()=>{"use strict";Rd();eq={name:"explode",description:"Spatial arrangement of parts (3-8 models in a ring)",minModels:3,maxModels:8,compute(n,e){if(n.length<3||n.length>8)return null;let t=Number(e.radius)||8,i=e.angle||"iso",r=IN(n,t),s=Math.min(n.length,4),a=Math.ceil(n.length/s),o=pl(s,a),l=n.map((c,f)=>({modelIndex:f,camera:Ro(i),viewport:o[f]}));return{placements:r,cells:l}}}});var iq,rq=C(()=>{"use strict";Rd();iq={name:"timeline",description:"Horizontal progression of models (2-6 models in a strip)",minModels:2,maxModels:6,compute(n,e){if(n.length<2||n.length>6)return null;let t=Number(e.spacing)||6,i=e.angle||"3/4",r=av(n,t),s=bN(n.length),a=n.map((o,l)=>({modelIndex:l,camera:Ro(i),viewport:s[l]}));return{placements:r,cells:a}}}});function MN(n,e,t,i,r){var f,h;if(!n||n.length===0)return null;let s=n.reduce((d,u)=>{var m;return d+((m=u.weight)!=null?m:1)},0);if(s<=0)return null;let a=[],o=0;for(let d of n){let m=((f=d.weight)!=null?f:1)/s*(1-t*(n.length+1));e==="horizontal"?a.push({x:t+o,y:t,w:m,h:1-2*t}):a.push({x:t,y:t+o,w:1-2*t,h:m}),o+=m+t}let l=[],c=[];for(let d=0;d{"use strict";nq={name:"compose",description:"Combine multiple presets into one layout",minModels:1,maxModels:32,compute(n,e,t){return null}}});var sq,aq=C(()=>{"use strict";Rd();sq={name:"gallery",description:"All models in one scene, single camera (no cell limit)",minModels:1,maxModels:32,compute(n,e){if(n.length===0)return null;let t=Number(e.spacing)||6,i=e.angle||"iso",r=Number(e.cols)||0,s=r>0?r:Math.ceil(Math.sqrt(n.length)),a=Math.ceil(n.length/s),o=n.map((f,h)=>{let d=h%s,u=Math.floor(h/s),m=(d-(s-1)/2)*t,p=(u-(a-1)/2)*t;return{path:f.path,position:[m,0,p],color:f.color,wireframe:f.wireframe}}),l=pl(1,1,0),c=[{modelIndex:0,camera:Ro(i,void 0,3+Math.max(s,a)*.5),viewport:l[0]}];return{placements:o,cells:c}}}});function Sp(n){oq.set(n.name,n)}function yN(n){return oq.get(n)}var oq,lq=C(()=>{"use strict";Qj();Jj();tq();rq();CN();aq();Rd();CN();oq=new Map;Sp(Zj);Sp($j);Sp(eq);Sp(iq);Sp(nq);Sp(sq)});var dq={};tt(dq,{registerCodeBlockProcessor:()=>vpe,registerGridCodeBlockProcessor:()=>Spe});async function fq(n,e,t,i){var h,d,u;let r=typeof e=="string"?{path:e}:e,s=Bd(n,r.path);if(!s)throw new Error(dr("workbench.fileNotFound",{path:r.path}));let a=(d=(h=s.split(".").pop())==null?void 0:h.toLowerCase())!=null?d:"";if(!gl(a))throw Ap(a)?new Error(J("codeBlock.splatDisabled")):new Error(dr("codeBlock.unsupportedFormat",{ext:`.${a}`,formats:vl().join(", ")}));let o=(u=eh(n,s))!=null?u:void 0,l=gd(t),c=await Ed({path:s,absolutePath:o,preferConversionExts:Sd(t),conversionManager:l,convertedAssetCache:i}),f=tv(c);return{sourcePath:s,effectivePath:f.path,effectiveExt:f.ext,warnings:f.warnings,model:{...r,path:f.path}}}async function gpe(n,e,t,i){let r=[];for(let s of e.models){let a=await fq(n,s,t,i);r.push(a.model)}return{...e,models:r}}function hq(n){ur()&&n.createDiv({cls:"ai3d-mobile-mode-hint ai3d-mobile-mode-hint--inline",text:J("codeBlock.mobileHint")})}function vpe(n,e,t,i){return{id:"3d",handler:(r,s,a)=>{var y,M;let o=r.trim();if(!o){s.createDiv({cls:"ai3d-inline-empty",text:J("codeBlock.noModelPathOrConfig")});return}let l;if(o.startsWith("{")||o.startsWith("["))try{let D=JSON.parse(o);l=Epe(D)}catch(D){let O=s.createDiv({cls:"ai3d-json-error"}),V=String(D).match(/position\s+(\d+)/),N=dr("codeBlock.jsonParseError",{error:String(D)});if(V){let F=parseInt(V[1],10),U=o.substring(0,F).split(` -`);N+=dr("codeBlock.jsonParseLine",{line:String(U.length)})}O.createEl("pre",{text:N});return}else l={models:[{path:o}]};if(!l.models||l.models.length===0){s.createDiv({cls:"ai3d-inline-empty",text:J("codeBlock.noModelsInConfig")});return}l.models.length>1&&console.warn(`[AI3D] \`\`\`3d only supports one model; ${l.models.length-1} additional models ignored. Use \`\`\`3dgrid for multi-model.`);let f=l.models[0],h=Bd(n,f.path);if(!h){s.createDiv({cls:"ai3d-inline-empty",text:dr("workbench.fileNotFound",{path:f.path})});return}let d=(M=(y=h.split(".").pop())==null?void 0:y.toLowerCase())!=null?M:"";if(!gl(d)){s.createDiv({cls:"ai3d-inline-empty",text:Ap(d)?J("codeBlock.splatDisabled"):dr("codeBlock.unsupportedFormat",{ext:`.${d}`,formats:vl().join(", ")})});return}let u=e(),m=s.createDiv({cls:"ai3d-preview-host"});l.height&&m.style.setProperty("--min-height",typeof l.height=="number"?`${l.height}px`:l.height),l.width&&m.style.setProperty("--max-width",typeof l.width=="number"?`${l.width}px`:l.width);let p=m.createEl("canvas",{cls:"ai3d-canvas-full"});p.tabIndex=0,p.addEventListener("keydown",D=>{var V,N,F,U,k;if(x||!_)return;let O=D.key.toLowerCase();O==="r"?((V=_.resetView)==null||V.call(_),D.preventDefault()):O==="w"?((N=_.toggleWireframe)==null||N.call(_),D.preventDefault()):O==="g"?((F=_.toggleOrientationGizmo)==null||F.call(_),D.preventDefault()):O==="b"?((U=_.toggleBoundingBox)==null||U.call(_),D.preventDefault()):O===" "?((k=_.toggleAnimation)==null||k.call(_),D.preventDefault()):O==="m"&&(Ao(_)&&_.toggleMeasurement(),D.preventDefault())}),m.appendChild(p);let _=null,g=null,v=!0,x=!1,A=!1,S=$g(s,m,n,()=>_,()=>h,()=>{x||(x=!0,E.disconnect(),I.disconnect(),g==null||g.destroy(),g=null,_==null||_.destroy(),_=null,m.remove())},e,()=>{if(v=!v,g){let D=m.querySelector(".ai3d-annotation-overlay");D&&D.classList.toggle("is-hidden",!v)}return v},void 0,{labelKey:"helper.toggleAnnotationsVisibilityLabel",activeTooltipKey:"helper.annotationsVisible",inactiveTooltipKey:"helper.annotationsHidden"});hq(s);let E=new MutationObserver(()=>{x||s.contains(m)||(x=!0,E.disconnect(),I.disconnect(),g==null||g.destroy(),g=null,_==null||_.destroy(),_=null)});E.observe(s,{childList:!0});async function R(){var O,V,N,F,U,k,ee;if(A||x||!h)return;A=!0;let D=Td(m);try{let q=(O=eh(n,h))!=null?O:void 0,Q=gd(u);D.setPhaseKey("loading.preparingModel");let Y=await Ed({path:h,absolutePath:q,preferConversionExts:Sd(u),conversionManager:Q,convertedAssetCache:t}),K=tv(Y),de=(V=i==null?void 0:i(h))!=null?V:[],Re={ext:K.ext,annotationMode:de.length>0?"readonly":"none",rendererRollout:u.previewRendererRollout,useThreeRenderer:u.useThreeRenderer},{preview:Fe}=await _d(cq,{surface:"code-block",modelPath:h},p,Re);_=Fe,S.syncCapabilities(),D.setPhaseKey("loading.loadingModel");let se=await Ua(n,K.path),ue=async he=>Ua(n,he);if(x){D.hide();return}let re=await _.loadModel(se,K.ext,ue,K.path);if(D.setProgress(100),vp(m,re),x){D.hide();return}if(((N=l.scene)==null?void 0:N.autoRotate)===void 0&&u.autoRotateDefault&&(l.scene={...l.scene,autoRotate:!0,autoRotateSpeed:u.autoRotateSpeed}),_.applyConfig(l),(F=_.setRenderQuality)==null||F.call(_,u.renderQuality,u.renderScale),S.syncCapabilities(),de.length>0&&JR(_)){let he=_.getAnnotationProvider();he.canvas&&(g=new Fc(he,m,"readonly",de,void 0,_p(n),void 0,{app:n,previewMode:u.annotationPreviewMode,displayMode:u.annotationDisplayMode}),S.showAnnotateButton(),S.updateAnnotationBadge(de.length))}d==="stl"&&f.color&&((U=_.setSTLColor)==null||U.call(_,f.color)),d==="stl"&&f.wireframe!==void 0&&((k=_.setWireframe)==null||k.call(_,f.wireframe)),(ee=_.hasAnimations)!=null&&ee.call(_)&&S.showAnimButton(),D.hide()}catch(q){x=!0,E.disconnect(),I.disconnect(),D.hide(),_==null||_.destroy(),_=null,m.replaceChildren();let Q=mp(q);up(q)?console.warn("[AI3D] Inline preview blocked by converter settings:",Q.message):console.error("[AI3D] Inline preview failed:",q),gp(m,Q)}}let I=new IntersectionObserver(D=>{for(let O of D)O.isIntersecting&&(I.disconnect(),R())},{rootMargin:"200px"});I.observe(m)}}}function Epe(n){if(typeof n=="string")return{models:[{path:n}]};if(typeof n!="object"||n===null)return{models:[]};let e=n;return typeof e.path=="string"?{models:[{path:e.path,color:e.color,wireframe:e.wireframe}],camera:e.camera,lights:e.lights,scene:e.scene,stl:e.stl,width:e.width,height:e.height}:{models:Array.isArray(e.models)?e.models.filter(i=>{let r=typeof i=="string"?i:i&&typeof i=="object"&&"path"in i?i.path:void 0;return typeof r=="string"&&r.length>0}).map(i=>{if(typeof i=="string")return{path:i};let r=i;return{path:r.path,color:r.color,wireframe:r.wireframe}}):[],camera:e.camera,lights:e.lights,scene:e.scene,stl:e.stl,width:e.width,height:e.height}}function Spe(n,e,t){return{id:"3dgrid",handler:(i,r,s)=>{let a=i.trim();if(!a){r.createDiv({cls:"ai3d-inline-empty",text:J("codeBlock.noConfigSpecified")});return}let o;try{o=JSON.parse(a)}catch(f){r.createDiv({cls:"ai3d-json-error"}).createEl("pre",{text:`JSON parse error: ${String(f)}`});return}if(o.preset!=="compose"&&(!o.models||o.models.length===0)){r.createDiv({cls:"ai3d-inline-empty",text:J("codeBlock.noModelsSpecified")});return}let l=e(),c=Td(r);(async()=>{var E,R,I,y;let f=[];for(let M of(E=o.models)!=null?E:[])try{let D=await fq(n,M,l,t);f.push(D)}catch(D){c.hide(),r.createDiv({cls:"ai3d-inline-empty",text:D instanceof Error?D.message:String(D)});return}let h=f.map(M=>M.model),d=(I=(R=f[0])==null?void 0:R.sourcePath)!=null?I:"",u=r.createDiv({cls:"ai3d-grid-host"}),m=u.createEl("canvas");if(m.tabIndex=0,m.addEventListener("keydown",M=>{var O,V;if(_||!p)return;let D=M.key.toLowerCase();D==="r"?((O=p.resetView)==null||O.call(p),M.preventDefault()):D==="w"&&((V=p.toggleWireframe)==null||V.call(p),M.preventDefault())}),u.appendChild(m),typeof o.rowHeight=="number"){let M=o.preset==="compose"?1:Math.ceil(h.length/((y=o.columns)!=null?y:Math.min(h.length,3)));u.style.setProperty("--grid-height",`${o.rowHeight*M}px`)}let p=null,_=!1,g=!1,v=$g(r,u,n,()=>p,()=>d,()=>{_||(_=!0,x.disconnect(),S.disconnect(),p==null||p.destroy(),p=null,u.remove())},e);hq(r);let x=new MutationObserver(()=>{_||r.contains(u)||(_=!0,x.disconnect(),S.disconnect(),p==null||p.destroy(),p=null)});x.observe(r,{childList:!0});async function A(){var M,D,O,V,N,F,U;if(!(g||_)){g=!0,c.setPhaseKey("codeBlock.renderingGrid"),c.setProgress(-1);try{let{renderer:k}=await XK(cq,{surface:"3dgrid",preset:(M=o.preset)!=null?M:"compare",modelCount:(O=(D=o.models)==null?void 0:D.length)!=null?O:0},m);p=k,v.syncCapabilities();let ee=p,q=async Q=>Ua(n,Q);if(o.preset==="compose"){if(!o.sections||o.sections.length===0){c.hide(),u.createDiv({cls:"ai3d-inline-empty",text:J("codeBlock.composeRequiresSections")}),p.destroy(),p=null;return}let Q=[];for(let K of o.sections)try{if(!d){let Re=K.models[0];if(Re){let Fe=typeof Re=="string"?Re:Re.path;d=(V=Bd(n,Fe))!=null?V:Fe}}let de=await gpe(n,K,l,t);Q.push(de)}catch(de){c.hide(),u.createDiv({cls:"ai3d-inline-empty",text:de instanceof Error?de.message:String(de)}),ee.destroy(),p=null;return}let Y=MN(Q,(N=o.direction)!=null?N:"horizontal",Number((F=o.params)==null?void 0:F.gap)||.02,K=>typeof K=="string"?null:K,yN);if(!Y){c.hide(),u.createDiv({cls:"ai3d-inline-empty",text:J("codeBlock.composeNoValidSections")}),ee.destroy(),p=null;return}await ee.loadWithPreset(Y,q)}else if(o.preset){let Q=yN(o.preset);if(!Q){c.hide(),u.createDiv({cls:"ai3d-inline-empty",text:dr("codeBlock.unknownPreset",{preset:o.preset})}),ee.destroy(),p=null;return}let Y=Q.compute(h,(U=o.params)!=null?U:{});if(!Y){c.hide(),u.createDiv({cls:"ai3d-inline-empty",text:dr("codeBlock.presetRequiresModels",{preset:o.preset,min:String(Q.minModels),max:String(Q.maxModels),count:String(h.length)})}),ee.destroy(),p=null;return}await ee.loadWithPreset(Y,q)}else await ee.loadModels(h,o,q);if(_){c.hide();return}c.hide()}catch(k){_=!0,x.disconnect(),S.disconnect(),c.hide(),p==null||p.destroy(),p=null,console.error("[AI3D Grid] Failed:",k),u.createDiv({cls:"ai3d-inline-empty",text:dr("codeBlock.gridFailed",{reason:String(k)})})}}}let S=new IntersectionObserver(M=>{for(let D of M)D.isIntersecting&&(S.disconnect(),A())},{rootMargin:"200px"});S.observe(u)})()}}}var cq,uq=C(()=>{"use strict";Io();vv();qR();ib();la();lq();QO();ub();pb();lN();_b();gb();rv();pp();ra();vb();Ks();Tn();cq=ki("inline-code-block")});function ov(n){return createDiv().createDiv(n?{cls:n}:void 0)}function PN(n,e){return createDiv().createEl(n,e?{cls:e}:void 0)}var mq=C(()=>{"use strict"});var gq={};tt(gq,{registerLivePreviewExtension:()=>Ape});function pq(n,e,t,i,r,s,a,o,l,c,f,h,d,u,m,p){var v,x;let _="state"in n?n.state.doc:n.doc,g=[];for(let A=1;A<=_.lines;A++){let S=_.line(A),E=S.text;if(!E.includes("!["))continue;let R=0;for(;R0&&E[I-1]==="\\"){R=I+3;continue}let y=E.indexOf("]]",I+3);if(y===-1)break;let D=E.slice(I+3,y).split("|"),O=D[0].trim(),V=(x=(v=O.split(".").pop())==null?void 0:v.toLowerCase())!=null?x:"";if(!gl(V)){R=y+2;continue}let N=400,F=300;if(D.length>1){let q=D[1].trim().match(/^(\d+)\s*x\s*(\d+)$/);q&&(N=parseInt(q[1],10),F=parseInt(q[2],10))}let U=Bd(e,O);if(!U){R=y+2;continue}let k=S.from+I,ee=S.from+y+2;g.push(Tp.Decoration.replace({widget:new DN(e,U,N,F,t,i,r,s,a,o,l,c,f,h,d,u,m,p),block:!0}).range(k,ee)),R=y+2}}return g}function _q(n){return n.length===0?bd.RangeSet.empty:bd.RangeSet.of(n,!0)}function Ape(n,e,t,i){let r=bd.StateField.define({create(s){let a=e(),o=pq(s,n,a.autoRotateDefault,a.enabledConverterIds,a.freecadCommand,a.obj2gltfCommand,a.fbx2gltfCommand,a.freecadcmdCommand,a.preferObj2gltfForObj,a.preferFbx2gltfForFbx,a.annotationPreviewMode,a.annotationDisplayMode,a.previewRendererRollout,a.useThreeRenderer,t,i);return _q(o)},update(s,a){if(a.docChanged){let o=e(),l=pq(a.state,n,o.autoRotateDefault,o.enabledConverterIds,o.freecadCommand,o.obj2gltfCommand,o.fbx2gltfCommand,o.freecadcmdCommand,o.preferObj2gltfForObj,o.preferFbx2gltfForFbx,o.annotationPreviewMode,o.annotationDisplayMode,o.previewRendererRollout,o.useThreeRenderer,t,i);return _q(l)}return s.map(a.changes)},provide:s=>Tp.EditorView.decorations.from(s)});return[bd.Prec.highest(r)]}var Tp,bd,Tpe,DN,vq=C(()=>{"use strict";Tp=require("@codemirror/view"),bd=require("@codemirror/state");Io();vv();qR();ib();la();ub();pb();_b();gb();rv();mq();pp();Ks();vb();ra();Tn();Tpe=ki("inline-live-preview"),DN=class extends Tp.WidgetType{constructor(t,i,r,s,a,o,l,c,f,h,d,u,m,p,_,g,v,x){super();this.app=t;this.modelPath=i;this.width=r;this.height=s;this.autoRotate=a;this.enabledConverterIds=o;this.freecadCommand=l;this.obj2gltfCommand=c;this.fbx2gltfCommand=f;this.freecadcmdCommand=h;this.preferObj2gltfForObj=d;this.preferFbx2gltfForFbx=u;this.annotationPreviewMode=m;this.annotationDisplayMode=p;this.previewRendererRollout=_;this.useThreeRenderer=g;this.convertedAssetCache=v;this.getAnnotations=x;this.preview=null;this.annotationMgr=null;this.readyObs=null;this.pollId=0;this.initStarted=!1;this.destroyed=!1;this.initGeneration=0}eq(t){return this.modelPath===t.modelPath&&this.width===t.width&&this.height===t.height&&this.autoRotate===t.autoRotate&&this.enabledConverterIds.join("|")===t.enabledConverterIds.join("|")&&this.freecadCommand===t.freecadCommand&&this.obj2gltfCommand===t.obj2gltfCommand&&this.fbx2gltfCommand===t.fbx2gltfCommand&&this.freecadcmdCommand===t.freecadcmdCommand&&this.preferObj2gltfForObj===t.preferObj2gltfForObj&&this.preferFbx2gltfForFbx===t.preferFbx2gltfForFbx&&this.annotationPreviewMode===t.annotationPreviewMode&&this.annotationDisplayMode===t.annotationDisplayMode&&this.previewRendererRollout===t.previewRendererRollout&&this.convertedAssetCache===t.convertedAssetCache}toDOM(){let t=ur(),i=ov("ai3d-embed-preview ai3d-cm-widget");i.setAttribute("contenteditable","false"),t&&i.classList.add("is-mobile","is-mobile-scroll-mode");let r=PN("canvas","ai3d-embed-canvas"),s=t?Math.min(this.height,220):this.height;r.style.setProperty("--ai3d-embed-height",`${s}px`),i.appendChild(r);let a=Td(i),o=ov("ai3d-embed-error is-hidden");if(i.appendChild(o),t){let h=!1,d=ov("ai3d-mobile-mode-bar"),u=ov("ai3d-mobile-mode-hint");u.textContent=J("livePreview.mobileHint");let m=PN("button","ai3d-mobile-mode-btn");m.type="button";let p=()=>{i.classList.toggle("is-mobile-interactive",h),i.classList.toggle("is-mobile-scroll-mode",!h),m.textContent=h?J("helper.scrollAction"):J("helper.interactAction"),m.classList.toggle("ai3d-btn-active",h),m.setAttribute("aria-label",h?J("helper.disableInteractionLabel"):J("helper.enableInteractionLabel"))};m.addEventListener("click",()=>{h=!h,p()}),p(),d.append(u,m),i.appendChild(d)}let l=()=>{this.destroyed||this.initStarted||!i.isConnected||r.clientWidth<=0||r.clientHeight<=0||(this.initStarted=!0,this.stopReadyWatch(),this.initPreview(i,r,a,o,++this.initGeneration))};this.readyObs=new ResizeObserver(()=>l()),this.readyObs.observe(i),this.readyObs.observe(r);let c=0,f=()=>{this.destroyed||this.initStarted||(l(),!this.initStarted&&(++c>240||(this.pollId=window.requestAnimationFrame(f))))};return this.pollId=window.requestAnimationFrame(f),i}async initPreview(t,i,r,s,a){var o,l,c,f,h,d;try{let u=(o=eh(this.app,this.modelPath))!=null?o:void 0,m=gd({enabledConverterIds:this.enabledConverterIds,freecadCommand:this.freecadCommand,obj2gltfCommand:this.obj2gltfCommand,fbx2gltfCommand:this.fbx2gltfCommand,freecadcmdCommand:this.freecadcmdCommand});r.setPhaseKey("loading.preparingModel");let p=await Ed({path:this.modelPath,absolutePath:u,preferConversionExts:Sd({preferObj2gltfForObj:this.preferObj2gltfForObj,preferFbx2gltfForFbx:this.preferFbx2gltfForFbx}),conversionManager:m,convertedAssetCache:this.convertedAssetCache}),_=(c=(l=this.getAnnotations)==null?void 0:l.call(this,this.modelPath))!=null?c:[],g={ext:p.effectiveExt,annotationMode:_.length>0?"readonly":"none",rendererRollout:this.previewRendererRollout,useThreeRenderer:this.useThreeRenderer},{preview:v}=await _d(Tpe,{surface:"live-preview",modelPath:this.modelPath},i,g);if(this.destroyed||a!==this.initGeneration){v.destroy();return}this.preview=v,r.setPhaseKey("loading.loadingModel");let x=await Ua(this.app,p.effectivePath);if(this.destroyed||a!==this.initGeneration){(f=this.preview)==null||f.destroy(),this.preview=null;return}let A=await this.preview.loadModel(x,p.effectiveExt,S=>Ua(this.app,S),p.effectivePath);if(this.destroyed||a!==this.initGeneration){(h=this.preview)==null||h.destroy(),this.preview=null;return}if(vp(t,A),this.autoRotate&&this.preview.applyConfig({models:[],scene:{autoRotate:!0,autoRotateSpeed:.5}}),_.length>0&&JR(this.preview)){let S=this.preview.getAnnotationProvider();S.canvas&&(this.annotationMgr=new Fc(S,t,"readonly",_,void 0,_p(this.app),void 0,{app:this.app,previewMode:this.annotationPreviewMode,displayMode:this.annotationDisplayMode}))}r.setProgress(100),r.hide()}catch(u){if(this.destroyed||a!==this.initGeneration)return;(d=this.preview)==null||d.destroy(),this.preview=null,r.hide(),s.remove(),t.replaceChildren();let m=mp(u);up(u)?console.warn("[AI3D] Live Preview blocked by converter settings:",m.message):console.error("[AI3D] Live Preview failed:",u),gp(t,m)}}destroy(){var t;this.destroyed=!0,window.cancelAnimationFrame(this.pollId),this.pollId=0,this.stopReadyWatch(),(t=this.annotationMgr)==null||t.destroy(),this.annotationMgr=null,this.preview&&(this.preview.destroy(),this.preview=null),this.initStarted=!1}stopReadyWatch(){var t;(t=this.readyObs)==null||t.disconnect(),this.readyObs=null}ignoreEvent(){return!0}}});var Sq={};tt(Sq,{buildDiagnosticsReport:()=>bpe});function Cb(n){return typeof n=="boolean"?n?"on":"off":typeof n=="number"?Number.isFinite(n)?String(n):"unknown":typeof n=="string"?n.length>0?n:"empty":"unknown"}function lv(n){return n?`set (${n})`:"not set"}function xpe(n){let e=n.settings;return e.analysisMode==="local"?"local only":[e.analysisMode,e.serviceBaseUrl.trim()?"service configured":"service missing",`geometry ${Cb(e.sendGeometrySummaryToRemote)}`,`preview refs ${Cb(e.sendPreviewImagesToRemote)}`,`raw model ${e.sendRawModelToRemote?"blocked if requested":"off"}`].join(", ")}function Rpe(n){let e=n.currentModelPath;return e?n.modelAssetProfiles[e]:void 0}function bpe(n){var o,l,c,f,h,d,u,m,p,_;let{manifest:e,state:t}=n,i=t.settings,r=Rpe(t),s=t.currentModelPath?Wd({ext:(o=t.currentModelPath.split(".").pop())!=null?o:"",annotationMode:r!=null&&r.annotations.length?"readonly":"none",allowEditModeOnThree:!0,allowWorkbenchFeaturesOnThree:i.experimentalThreeWorkbench,rendererRollout:i.previewRendererRollout,useThreeRenderer:i.useThreeRenderer}):null,a=t.lastKnowledgeGeneration;return["# AI Model Workbench Diagnostics","",`Generated: ${(l=n.generatedAt)!=null?l:new Date().toISOString()}`,"","## Runtime","",`- Plugin version: ${e.version}`,`- Minimum Obsidian version: ${e.minAppVersion}`,`- Obsidian API version: ${Eq.apiVersion}`,`- Platform: ${ur()?"mobile":"desktop"}`,`- Locale: ${i.locale}`,"","## Renderer","",`- Use Three renderer: ${Cb(i.useThreeRenderer)}`,`- Preview rollout: ${i.previewRendererRollout}`,`- Experimental Three workbench: ${Cb(i.experimentalThreeWorkbench)}`,`- Current route: ${s?`${s.backend} (${s.reason})`:"no current model"}`,`- Render quality: ${i.renderQuality}`,`- Render scale: ${i.renderScale}`,"","## Current Model","",`- Path: ${(c=t.currentModelPath)!=null?c:"none"}`,`- Preview summary: ${t.modelPreview?`${t.modelPreview.meshCount} mesh(es), ${t.modelPreview.triangleCount.toLocaleString()} triangle(s), ${t.modelPreview.materialCount} material(s)`:"not captured"}`,`- Annotation count: ${(f=r==null?void 0:r.annotations.length)!=null?f:0}`,`- Registered part candidates: ${(d=(h=r==null?void 0:r.registeredParts)==null?void 0:h.length)!=null?d:0}`,`- Report note: ${lv(r==null?void 0:r.reportNotePath)}`,`- Analysis sidecar: ${lv(r==null?void 0:r.analysisSidecarPath)}`,`- Knowledge index: ${lv(r==null?void 0:r.knowledgeIndexPath)}`,"","## Knowledge Generation","",`- Mode: ${xpe(t)}`,`- Report folder: ${i.reportFolder}`,`- Part notes folder: ${i.partFolder}`,`- Snapshot folder: ${i.previewFolder}`,`- Last generation: ${a?`${a.status} at ${a.generatedAt}`:"none"}`,`- Last generated model: ${(u=a==null?void 0:a.modelPath)!=null?u:"none"}`,`- Last report: ${lv(a==null?void 0:a.reportNotePath)}`,`- Last index: ${lv(a==null?void 0:a.knowledgeIndexPath)}`,`- Last part notes: ${(m=a==null?void 0:a.partNoteCount)!=null?m:0}`,`- Last preview images: ${(p=a==null?void 0:a.previewImageCount)!=null?p:0}`,`- Last warning count: ${(_=a==null?void 0:a.warningCount)!=null?_:0}`,"","## Conversion","",`- Enabled converters: ${i.enabledConverterIds.length?i.enabledConverterIds.join(", "):"none"}`,`- Cached conversions: ${t.convertedAssetRecords.length}`,`- Supported direct/model extensions: ${vl().join(", ")}`,"","## Notes","","- Draft service URL and command paths are intentionally omitted from this report.","- Attach this report with the model format, console error, and reproduction steps when filing a bug.",""].join(` -`)}var Eq,Tq=C(()=>{"use strict";Eq=require("obsidian");Io();Ev();Ks()});var Ipe={};tt(Ipe,{default:()=>yb});module.exports=Nq(Ipe);var Os=require("obsidian");Nb();Io();Io();var Dpe=new Set(vl());var Oc={analysisMode:"local",serviceBaseUrl:"",copySourceModelToVault:!1,sourceModelFolder:"Assets/3D",reportFolder:"Analysis/3D Reports",partFolder:"Parts/3D Components",previewFolder:"Media/3D Previews",maxFileSizeMb:50,autoGenerateKnowledgeNotes:!0,annotationPreviewMode:"plain-text",annotationDisplayMode:"surface",previewRendererRollout:"three-direct-glb",useThreeRenderer:!0,experimentalThreeWorkbench:!1,sendRawModelToRemote:!1,sendPreviewImagesToRemote:!1,sendGeometrySummaryToRemote:!1,defaultKnowledgeTaxonomy:"default-v1",defaultCanvasHeight:400,autoRotateDefault:!1,autoRotateSpeed:.5,renderQuality:"high",renderScale:1,snapshotFolder:"Media/3D Previews",snapshotNaming:"model-name",enabledConverterIds:[],freecadCommand:"",obj2gltfCommand:"",fbx2gltfCommand:"",assimpCommand:"",freecadcmdCommand:"",preferObj2gltfForObj:!1,preferFbx2gltfForFbx:!1,logLevel:"warn",locale:"en"};function kN(n){let e={...n},t=new Set;return{getState:()=>e,setState(i){e={...e,...i};let r=[...t];for(let s of r)s()},subscribe(i){return t.add(i),()=>{t.delete(i)}}}}var Uq={settings:{...Oc},currentModelPath:null,convertedAssetRecords:[],modelAssetProfiles:{},agentDraft:"",agentPlan:null,modelPreview:null,selectedPart:null,lastKnowledgeGeneration:null};function HN(n){let e=kN(Uq),t=null;function i(){t&&window.clearTimeout(t),t=window.setTimeout(()=>{t=null,r().catch(a=>console.error("[AI3D] Auto-save failed:",a))},500)}async function r(){let a=e.getState(),o={settings:a.settings,convertedAssetRecords:a.convertedAssetRecords,modelAssetProfiles:a.modelAssetProfiles,agentDraft:a.agentDraft,agentPlan:a.agentPlan,lastKnowledgeGeneration:a.lastKnowledgeGeneration};await n.saveData(o)}e.subscribe(()=>i());let s=!1;return{store:e,get localeLoadedFromSaved(){return s},async load(){var o,l,c,f,h;let a=await n.loadData();a&&(s=!!((o=a.settings)!=null&&o.locale),e.setState({settings:{...Oc,...(l=a.settings)!=null?l:{}},convertedAssetRecords:(c=a.convertedAssetRecords)!=null?c:[],modelAssetProfiles:Vq(a.modelAssetProfiles),agentDraft:(f=a.agentDraft)!=null?f:"",agentPlan:(h=a.agentPlan)!=null?h:null,lastKnowledgeGeneration:kq(a.lastKnowledgeGeneration)}))},async save(){t&&(window.clearTimeout(t),t=null),await r()},dispose(){t&&(window.clearTimeout(t),t=null),r().catch(a=>console.error("[AI3D] Final save on dispose failed:",a))}}}function Vq(n){if(!n||typeof n!="object")return{};let e={};for(let[t,i]of Object.entries(n)){if(!i||typeof i!="object")continue;let r=new Date().toISOString();e[t]={tags:Array.isArray(i.tags)?i.tags:[],notes:typeof i.notes=="string"?i.notes:"",annotations:Array.isArray(i.annotations)?i.annotations:[],registeredParts:Gq(i.registeredParts,t),analysisVersion:typeof i.analysisVersion=="string"?i.analysisVersion:void 0,reportNotePath:typeof i.reportNotePath=="string"?i.reportNotePath:void 0,analysisSidecarPath:typeof i.analysisSidecarPath=="string"?i.analysisSidecarPath:void 0,previewImagePaths:Array.isArray(i.previewImagePaths)?i.previewImagePaths.filter(s=>typeof s=="string"):void 0,knowledgeIndexPath:typeof i.knowledgeIndexPath=="string"?i.knowledgeIndexPath:void 0,createdAt:typeof i.createdAt=="string"?i.createdAt:r,updatedAt:typeof i.updatedAt=="string"?i.updatedAt:r}}return e}function xp(n){return Array.isArray(n)?n.filter(e=>typeof e=="string"&&e.trim().length>0):[]}function WN(n){if(!Array.isArray(n)||n.length<3)return;let e=n.slice(0,3).map(t=>Number(t));return e.every(Number.isFinite)?[e[0],e[1],e[2]]:void 0}function Gq(n,e){if(!Array.isArray(n))return;let t=[],i=new Set;for(let r of n){if(!r||typeof r!="object")continue;let s=r,a=typeof s.partId=="string"?s.partId:"",o=typeof s.name=="string"?s.name:"";if(!a||!o)continue;let l=typeof s.assetId=="string"&&s.assetId?s.assetId:e,c=`${l}:${a}`;i.has(c)||(i.add(c),t.push({partId:a,assetId:l,parentPartId:typeof s.parentPartId=="string"?s.parentPartId:void 0,name:o,source:s.source==="group"||s.source==="mesh"||s.source==="component"?s.source:void 0,componentId:typeof s.componentId=="string"?s.componentId:void 0,occurrenceId:typeof s.occurrenceId=="string"?s.occurrenceId:void 0,partNumber:typeof s.partNumber=="string"?s.partNumber:void 0,componentPath:typeof s.componentPath=="string"?s.componentPath:void 0,category:typeof s.category=="string"?s.category:void 0,meshRefs:xp(s.meshRefs),childCount:Number.isFinite(s.childCount)?Math.max(0,Math.floor(Number(s.childCount))):void 0,materialRefs:xp(s.materialRefs),bbox:WN(s.bbox),center:WN(s.center),triangleCount:Number.isFinite(s.triangleCount)?Math.max(0,Math.floor(Number(s.triangleCount))):void 0,vertexCount:Number.isFinite(s.vertexCount)?Math.max(0,Math.floor(Number(s.vertexCount))):void 0,materialName:typeof s.materialName=="string"?s.materialName:null,confidence:Number.isFinite(s.confidence)?Math.max(0,Math.min(1,Number(s.confidence))):.5,observations:xp(s.observations),inferredFunctions:xp(s.inferredFunctions),knowledgeTags:xp(s.knowledgeTags),notePath:typeof s.notePath=="string"?s.notePath:void 0,registeredMatches:Array.isArray(s.registeredMatches)?s.registeredMatches:void 0,reviewed:s.reviewed===!0}))}return t.length>0?t:void 0}function kq(n){if(!n||typeof n!="object")return null;let e=typeof n.modelPath=="string"?n.modelPath:"";return e?{modelPath:e,reportNotePath:typeof n.reportNotePath=="string"?n.reportNotePath:void 0,analysisSidecarPath:typeof n.analysisSidecarPath=="string"?n.analysisSidecarPath:void 0,knowledgeIndexPath:typeof n.knowledgeIndexPath=="string"?n.knowledgeIndexPath:void 0,partNoteCount:Number.isFinite(n.partNoteCount)?Math.max(0,Math.floor(n.partNoteCount)):0,previewImageCount:Number.isFinite(n.previewImageCount)?Math.max(0,Math.floor(n.previewImageCount)):0,generatedAt:typeof n.generatedAt=="string"?n.generatedAt:new Date().toISOString(),status:n.status==="failed"?"failed":"success",warningCount:Number.isFinite(n.warningCount)?Math.max(0,Math.floor(n.warningCount)):0}:null}var yc=require("obsidian");vv();qR();QO();ub();pb();lN();la();_b();rv();gb();pp();ra();vb();Ks();Tn();dN();ra();function yme(n){if(!n)return"";let e=n.split("/");return e[e.length-1]||n}function Sj(n,e,t){var o,l;let i=n.createDiv({cls:"ai3d-direct-workbench-match"}),r=i.createDiv({cls:"ai3d-direct-workbench-match-main"});r.createDiv({cls:"ai3d-direct-workbench-match-title",text:e}),r.createDiv({cls:"ai3d-direct-workbench-match-source",text:t.sourcePartName||t.sourcePartId}),t.sourceModelPath&&r.createDiv({cls:"ai3d-direct-workbench-match-model",text:dr("directWorkbench.registeredSourceModel",{model:yme(t.sourceModelPath)})}),r.createDiv({cls:"ai3d-direct-workbench-match-target",text:t.sourceNotePath?J("directWorkbench.registeredTargetPartNote"):t.sourceModelPath?J("directWorkbench.registeredTargetSourceModel"):J("directWorkbench.registeredTargetUnavailable")}),t.reasons.length>0&&r.createDiv({cls:"ai3d-direct-workbench-match-reasons",text:t.reasons.slice(0,2).join(" / ")});let s=i.createDiv({cls:"ai3d-direct-workbench-match-side"});s.createDiv({cls:"ai3d-direct-workbench-match-score",text:`${Math.round(t.matchScore*100)}%`});let a=s.createEl("button",{cls:"ai3d-direct-workbench-action ai3d-direct-workbench-match-open",text:t.sourceNotePath?J("directWorkbench.registeredOpenNote"):J("directWorkbench.registeredOpenModel"),attr:{type:"button","data-ai3d-action":"open-registered-part","data-ai3d-target-path":(l=(o=t.sourceNotePath)!=null?o:t.sourceModelPath)!=null?l:""}});return a.disabled=!t.sourceNotePath&&!t.sourceModelPath,i}var bb="ai3d-direct-view",AN=ki("direct-view"),Yj=new Set(["glb","gltf"]);function Kj(){return{tags:[],notes:"",annotations:[],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}}function fpe(n,e){return n.experimentalThreeWorkbench&&n.useThreeRenderer&&e.strategy==="direct"&&Yj.has(e.ext)&&Yj.has(e.sourceExt)}function xb(n){return Math.round(n!=null?n:0).toLocaleString()}function hpe(n){return[n.boundingSize.x,n.boundingSize.y,n.boundingSize.z].map(e=>e.toFixed(2)).join(" x ")}function dpe(n){return n==="three"?"Three.js":"Babylon.js"}function upe(n){return n instanceof Error&&n.message.includes("Missing external model resource:")}function jj(n){var i,r,s;let e=(r=(i=n.occurrenceId)!=null?i:n.componentId)!=null?r:n.partNumber;if(e!=null&&e.trim())return`component:${e.trim().toLowerCase()}`;let t=n.meshRefs.map(a=>a.trim().toLowerCase()).filter(Boolean).sort().join("|");return`${(s=n.source)!=null?s:"mesh"}:${n.name.trim().toLowerCase()}:${t}`}function mpe(n,e){return n?{...e,notePath:n.notePath,reviewed:n.reviewed,inferredFunctions:n.inferredFunctions.length>0?n.inferredFunctions:e.inferredFunctions,knowledgeTags:n.knowledgeTags.length>0?n.knowledgeTags:e.knowledgeTags}:e}var Rb=class extends yc.FileView{constructor(t,i,r,s){super(t);this.preview=null;this.annotationMgr=null;this.annotationMode=!1;this.loadGeneration=0;this.escHandler=null;this.workbenchPanel=null;this.workbenchSummary=null;this.workbenchRoute=null;this.workbenchModelPath=null;this.sidebarContent=null;this.getSettings=i,this.convertedAssetCache=r,this.ps=s}getViewType(){return bb}getDisplayText(){var t,i;return(i=(t=this.file)==null?void 0:t.name)!=null?i:J("workbench.modelTitle")}getIcon(){return"box"}async onOpen(){this.contentEl.empty(),this.contentEl.addClass("ai3d-direct-view"),this.file&&await this.loadModel(this.file)}async onLoadFile(t){this.contentEl.empty(),await this.loadModel(t)}onClose(){var t,i;return this.escHandler&&(activeDocument.removeEventListener("keydown",this.escHandler),this.escHandler=null),(t=this.annotationMgr)==null||t.destroy(),this.annotationMgr=null,(i=this.preview)==null||i.destroy(),this.preview=null,Promise.resolve()}async loadModel(t){var A,S,E,R,I,y,M,D,O;let i=++this.loadGeneration,r=ur();(A=this.annotationMgr)==null||A.destroy(),this.annotationMgr=null,this.workbenchPanel=null,this.workbenchSummary=null,this.workbenchRoute=null,this.workbenchModelPath=null,this.sidebarContent=null,(S=this.preview)==null||S.destroy(),this.preview=null,this.ps.store.setState({currentModelPath:t.path,modelPreview:null,selectedPart:null});let s=this.contentEl.createDiv({cls:"ai3d-workspace"}),a=s.createDiv({cls:"ai3d-workspace-track-top"}),o=a.createDiv({cls:"ai3d-workspace-main"}),l=a.createDiv({cls:"ai3d-resize-handle ai3d-resize-handle-h"}),c=a.createDiv({cls:"ai3d-workspace-sidebar"}),f=createDiv(),h=f.createDiv({cls:"ai3d-preview-host"}),d=f.createEl("canvas");d.className="ai3d-canvas-full",h.appendChild(d);let u=f.createDiv();u.className="ai3d-annot-mode-overlay is-hidden",h.appendChild(u),o.appendChild(h);let m=null,p=V=>{var N;this.annotationMode=V,r&&V&&(m==null||m.setMobileInteractionMode(!0)),(N=this.annotationMgr)==null||N.hideEditor(),u.classList.toggle("is-hidden",!V)};this.escHandler&&activeDocument.removeEventListener("keydown",this.escHandler),this.escHandler=V=>{V.key==="Escape"&&this.annotationMode&&p(!1)},activeDocument.addEventListener("keydown",this.escHandler),m=$g(o,h,this.app,()=>this.preview,()=>t.path,()=>{this.leaf.detach()},this.getSettings,()=>(p(!this.annotationMode),this.annotationMode),V=>{!V&&this.annotationMode&&p(!1)});let _=c.createDiv({cls:"ai3d-sidebar-content"});this.sidebarContent=_;let g=s.createDiv({cls:"ai3d-resize-handle ai3d-resize-handle-v"}),v=s.createDiv({cls:"ai3d-direct-workbench-panel is-hidden"});this.workbenchPanel=v,this.setupResizeHandles(l,g,a,s),r&&o.createDiv({cls:"ai3d-mobile-mode-hint ai3d-mobile-mode-hint--inline",text:J("directView.mobileHint")});let x=Td(h);try{let V=this.getSettings(),N=gd(V),F=(E=eh(this.app,t.path))!=null?E:void 0;x.setPhaseKey("loading.preparingModel");let U=await Ed({path:t.path,absolutePath:F,preferConversionExts:Sd(V),conversionManager:N,convertedAssetCache:this.convertedAssetCache});if(i!==this.loadGeneration){new yc.Notice(J("directWorkbench.modelLoadInterrupted"));return}let k=tv(U),ee={ext:k.ext,annotationMode:"edit",allowEditModeOnThree:!0,allowWorkbenchFeaturesOnThree:fpe(V,k),requireWorkbenchFeatures:!0,rendererRollout:V.previewRendererRollout,useThreeRenderer:V.useThreeRenderer};m==null||m.syncCapabilities(),x.setPhaseKey("loading.loadingModel");let q=await Ua(this.app,k.path),Q=await this.createPreviewWithFallback(d,q,k,ee,t.path);if(i!==this.loadGeneration){Q.preview.destroy(),new yc.Notice(J("directWorkbench.modelLoadInterrupted"));return}this.preview=Q.preview,h.dataset.ai3dBackend=Q.route.backend,h.dataset.ai3dRouteReason=Q.route.reason,m==null||m.syncCapabilities();let Y=Q.summary,K=(y=(I=(R=this.preview).getModelEvidence)==null?void 0:I.call(R))!=null?y:null;this.registerModelPartsFromEvidence(t.path,K),vp(h,Y),this.workbenchPanel=v,this.workbenchSummary=Y,this.workbenchRoute=Q.route,this.workbenchModelPath=t.path,this.renderWorkbenchPanel(v,Y,Q.route,t.path),this.renderSidebarContent(t.path,Y),this.ps.store.setState({currentModelPath:t.path,modelPreview:Y,selectedPart:null}),AN.info("direct view model loaded",{path:t.path,effectivePath:k.path,effectiveExt:k.ext,strategy:k.strategy,backend:Q.route.backend,routeReason:Q.route.reason,meshCount:Y.meshCount,triangleCount:Y.triangleCount}),x.setProgress(100);let de=this.preview.getAnnotationProvider();if(de.canvas){let Re=this.ps.store.getState().modelAssetProfiles[t.path],Fe=(M=Re==null?void 0:Re.annotations)!=null?M:[],se=_p(this.app),ue=pj(this.app);this.annotationMgr=new Fc(de,h,"edit",Fe,re=>{var fe;let he=this.ps.store.getState().modelAssetProfiles,De=(fe=he[t.path])!=null?fe:Kj();this.ps.store.setState({modelAssetProfiles:{...he,[t.path]:{...De,annotations:re,updatedAt:new Date().toISOString()}}}),m.updateAnnotationBadge(re.length)},se,ue,{app:this.app,previewMode:this.getSettings().annotationPreviewMode,displayMode:this.getSettings().annotationDisplayMode}),m.showAnnotateButton(),m.updateAnnotationBadge(Fe.length),this.preview.onPick(re=>{var be,Xe;if(!this.annotationMode||!this.annotationMgr)return;let he=re.screenX,De=re.screenY,fe=(Xe=(be=this.preview)==null?void 0:be.getPickWorldPoint(re))!=null?Xe:null;fe&&this.annotationMgr.showEditor(he,De,fe)})}x.hide()}catch(V){if(i!==this.loadGeneration)return;x.hide(),(D=this.preview)==null||D.destroy(),this.preview=null,h.replaceChildren(),(O=this.workbenchPanel)==null||O.addClass("is-hidden");let N=mp(V);up(V)?console.warn("[AI3D] Direct view blocked by converter settings:",N.message):console.error("[AI3D] Direct view failed:",V),this.ps.store.getState().currentModelPath===t.path&&this.ps.store.setState({modelPreview:null,selectedPart:null}),gp(h,N)}}registerModelPartsFromEvidence(t,i){var c,f;if(!(i!=null&&i.parts.length))return;let r=hN(t,i.parts);if(r.length===0)return;let s=this.ps.store.getState().modelAssetProfiles,a=(c=s[t])!=null?c:Kj(),o=new Map(((f=a.registeredParts)!=null?f:[]).map(h=>[jj(h),h])),l=r.map(h=>mpe(o.get(jj(h)),h));this.ps.store.setState({modelAssetProfiles:{...s,[t]:{...a,registeredParts:l,updatedAt:new Date().toISOString()}}})}renderWorkbenchPanel(t,i,r,s){var h,d,u,m;t.empty(),t.removeClass("is-hidden"),t.dataset.ai3dBackend=r.backend,t.dataset.ai3dRouteReason=r.reason;let a=t.createDiv({cls:"ai3d-direct-workbench-overview"}),o=a.createDiv({cls:"ai3d-direct-workbench-status"}),l=o.createDiv({cls:"ai3d-direct-workbench-line"});l.createSpan({cls:"ai3d-direct-workbench-label",text:J("directWorkbench.backendLabel")}),l.createSpan({cls:"ai3d-direct-workbench-value",text:dpe(r.backend)});let c=o.createDiv({cls:"ai3d-direct-workbench-line ai3d-direct-workbench-route"});c.createSpan({cls:"ai3d-direct-workbench-label",text:J("directWorkbench.routeLabel")}),c.createSpan({cls:"ai3d-direct-workbench-value",text:r.reason});let f=a.createDiv({cls:"ai3d-direct-workbench-metrics"});this.renderMetric(f,J("workbench.meshesLabel"),xb(i.meshCount)),this.renderMetric(f,J("directWorkbench.partCandidatesLabel"),xb((d=(h=this.ps.store.getState().modelAssetProfiles[s])==null?void 0:h.registeredParts)==null?void 0:d.length)),this.renderMetric(f,i.splatCount!==void 0?J("workbench.splatsLabel"):J("workbench.trianglesLabel"),xb((u=i.splatCount)!=null?u:i.triangleCount)),this.renderMetric(f,J("workbench.materialsLabel"),xb(i.materialCount)),this.renderMetric(f,J("workbench.boundingSizeLabel"),hpe(i)),this.renderMetric(f,J("directWorkbench.performanceLabel"),(m=i.performanceTier)!=null?m:"light")}renderSidebarContent(t,i){this.sidebarContent&&(this.sidebarContent.empty(),this.renderKnowledgeControls(this.sidebarContent,t),this.renderRegisteredPartMatches(this.sidebarContent,t,i))}refreshWorkbenchPanel(){!this.workbenchPanel||!this.workbenchSummary||!this.workbenchRoute||!this.workbenchModelPath||(this.renderWorkbenchPanel(this.workbenchPanel,this.workbenchSummary,this.workbenchRoute,this.workbenchModelPath),this.renderSidebarContent(this.workbenchModelPath,this.workbenchSummary))}setupResizeHandles(t,i,r,s){let a=(c,f,h)=>{let d=0,u=0,m=_=>{f(_.clientX-d,_.clientY-u),d=_.clientX,u=_.clientY},p=()=>{activeDocument.removeEventListener("mousemove",m),activeDocument.removeEventListener("mouseup",p),h()};c.addEventListener("mousedown",_=>{_.preventDefault(),d=_.clientX,u=_.clientY,activeDocument.addEventListener("mousemove",m),activeDocument.addEventListener("mouseup",p)})},o=200;a(t,c=>{o=Math.max(48,Math.min(400,o-c)),r.style.gridTemplateColumns=`1fr 4px ${o}px`},()=>{});let l=220;a(i,(c,f)=>{l=Math.max(120,Math.min(500,l-f)),s.style.gridTemplateRows=`1fr 4px ${l}px`},()=>{})}renderMetric(t,i,r){let s=t.createDiv({cls:"ai3d-direct-workbench-metric"});s.createSpan({cls:"ai3d-direct-workbench-label",text:i}),s.createSpan({cls:"ai3d-direct-workbench-value",text:r})}renderKnowledgeControls(t,i){let r=this.ps.store.getState().modelAssetProfiles[i],s=t.createDiv({cls:"ai3d-direct-workbench-control ai3d-direct-workbench-knowledge"});s.createDiv({cls:"ai3d-direct-workbench-label",text:J("directWorkbench.knowledgeTitle")}),s.createDiv({cls:"ai3d-direct-workbench-value",text:r!=null&&r.knowledgeIndexPath?J("workbench.indexReady"):r!=null&&r.reportNotePath?J("workbench.noteReady"):J("workbench.noReportYet")});let a=s.createDiv({cls:"ai3d-direct-workbench-actions"}),o=a.createEl("button",{cls:"ai3d-direct-workbench-action",text:J("workbench.generateNoteAction"),attr:{type:"button","data-ai3d-action":"generate-note"}});o.addEventListener("click",()=>{o.disabled=!0,Promise.resolve().then(()=>(Ab(),Tb)).then(({generateKnowledgeNote:f})=>f(this.app,this.ps,{preview:this.preview})).catch(f=>{console.error("[AI3D] Generate knowledge note failed:",f)}).finally(()=>{o.disabled=!1,this.refreshWorkbenchPanel()})});let l=a.createEl("button",{cls:"ai3d-direct-workbench-action",text:J("workbench.openNoteAction"),attr:{type:"button","data-ai3d-action":"open-note"}});l.disabled=!(r!=null&&r.reportNotePath),l.addEventListener("click",()=>{var d;let f=(d=this.ps.store.getState().modelAssetProfiles[i])==null?void 0:d.reportNotePath;if(!f)return;let h=this.app.vault.getAbstractFileByPath(f);h instanceof yc.TFile&&this.app.workspace.getLeaf(!0).openFile(h,{active:!0})});let c=a.createEl("button",{cls:"ai3d-direct-workbench-action",text:J("workbench.openIndexAction"),attr:{type:"button","data-ai3d-action":"open-index"}});c.disabled=!(r!=null&&r.knowledgeIndexPath),c.addEventListener("click",()=>{var d;let f=(d=this.ps.store.getState().modelAssetProfiles[i])==null?void 0:d.knowledgeIndexPath;if(!f)return;let h=this.app.vault.getAbstractFileByPath(f);h instanceof yc.TFile&&this.app.workspace.getLeaf(!0).openFile(h,{active:!0})})}renderRegisteredPartMatches(t,i,r){var d,u,m;let s=this.loadGeneration,a=t.createDiv({cls:"ai3d-direct-workbench-control ai3d-direct-workbench-registered"}),o=a.createDiv({cls:"ai3d-direct-workbench-control-head"});o.createSpan({cls:"ai3d-direct-workbench-label",text:J("directWorkbench.registeredTitle")});let l=o.createSpan({cls:"ai3d-direct-workbench-value",text:J("directWorkbench.registeredLoading")}),c=a.createDiv({cls:"ai3d-direct-workbench-registered-body"}),f=p=>{l.setText(""),c.empty(),c.createDiv({cls:"ai3d-direct-workbench-empty",text:J(p)})},h=(m=(u=(d=this.preview)==null?void 0:d.getModelEvidence)==null?void 0:u.call(d))!=null?m:null;if(!(h!=null&&h.parts.length)){f("directWorkbench.registeredUnavailable");return}Promise.resolve().then(()=>(Ab(),Tb)).then(async({collectRegisteredPartsFromProfiles:p})=>{var E;let _=this.ps.store.getState(),g=await p(this.app,_.modelAssetProfiles,i);if(s!==this.loadGeneration||this.workbenchModelPath!==i||!a.isConnected)return;if(g.length===0){f("directWorkbench.registeredEmpty");return}let v=this.ps.store.getState().modelAssetProfiles[i],A=Sb({modelPath:i,profile:v,preview:r,evidence:h,registeredParts:g}).parts.filter(R=>{var I;return(I=R.registeredMatches)==null?void 0:I.length}).sort((R,I)=>{var y,M,D,O,V,N;return((D=(M=(y=I.registeredMatches)==null?void 0:y[0])==null?void 0:M.matchScore)!=null?D:0)-((N=(V=(O=R.registeredMatches)==null?void 0:O[0])==null?void 0:V.matchScore)!=null?N:0)}).slice(0,5);if(A.length===0){f("directWorkbench.registeredEmpty");return}l.setText(dr("directWorkbench.registeredCount",{count:String(A.length)})),c.empty();let S=c.createDiv({cls:"ai3d-direct-workbench-match-list"});for(let R of A){let I=(E=R.registeredMatches)==null?void 0:E[0];if(!I)continue;let M=Sj(S,R.name,I).querySelector("[data-ai3d-action='open-registered-part']");M instanceof HTMLButtonElement&&M.addEventListener("click",()=>{let D=M.getAttribute("data-ai3d-target-path")||void 0;if(!D)return;let O=this.app.vault.getAbstractFileByPath(D);O instanceof yc.TFile&&this.app.workspace.getLeaf(!0).openFile(O,{active:!0})})}}).catch(p=>{console.warn("[AI3D] Registered part match preview failed:",p),s===this.loadGeneration&&this.workbenchModelPath===i&&a.isConnected&&f("directWorkbench.registeredUnavailable")})}async createPreviewWithFallback(t,i,r,s,a){let o=await _d(AN,{surface:"direct-view",modelPath:a},t,s);try{let l=await o.preview.loadModel(i.slice(0),r.ext,c=>Ua(this.app,c),r.path);return{preview:o.preview,summary:l,route:o.route}}catch(l){if(o.preview.destroy(),o.route.backend!=="three"||!s.allowWorkbenchFeaturesOnThree)throw l;console.warn("[AI3D] Experimental Three workbench failed; falling back to Babylon:",l);let c={...s,allowWorkbenchFeaturesOnThree:!1},f=await _d(AN,{surface:"direct-view-fallback",modelPath:a},t,c);try{let h=await f.preview.loadModel(i.slice(0),r.ext,d=>Ua(this.app,d),r.path);return{preview:f.preview,summary:h,route:f.route}}catch(h){throw f.preview.destroy(),upe(l)?l:h}}}};var qj=require("obsidian");Io();ra();var Ib=class extends qj.FuzzySuggestModal{constructor(e,t){super(e),this.onChoose=t,this.setPlaceholder(J("modal.selectModel"))}getItems(){return this.app.vault.getFiles().filter(e=>{let t=e.extension.toLowerCase();return gl(t)})}getItemText(e){return e.path}onChooseItem(e){this.onChoose(e)}};var Zt=require("obsidian");Jf();ra();Ks();ar();var xN=dv();function ppe(){switch(xN==null?void 0:xN.platform){case"win32":return{python:"Path to python executable",freecad:"Path to FreeCADCmd.exe",obj2gltf:"Path to obj2gltf.cmd",fbx2gltf:"Path to FBX2glTF.exe"};case"darwin":return{python:"Path to python3",freecad:"Path to FreeCADCmd",obj2gltf:"Path to obj2gltf",fbx2gltf:"Path to FBX2glTF"};case"linux":return{python:"Path to python3",freecad:"Path to freecadcmd",obj2gltf:"Path to obj2gltf",fbx2gltf:"Path to FBX2glTF"};default:return{python:"Path to python executable",freecad:"Path to FreeCAD command",obj2gltf:"Path to obj2gltf",fbx2gltf:"Path to FBX2glTF"}}}var Mb=class extends Zt.PluginSettingTab{constructor(t,i){super(t,i);this.diagnosticsRunId=0;this.plugin=i}display(){let{containerEl:t}=this;t.empty(),Rp(this.plugin.getSettings().locale);let i=ppe(),r=ur(),s=null,a=(l,c,f)=>{let h=l.createEl("details",{cls:"ai3d-settings-secondary-menu"});h.createEl("summary",{cls:"ai3d-settings-secondary-menu-summary",text:c});let d=h.createDiv({cls:"ai3d-settings-secondary-menu-body"});return d.createEl("p",{cls:"setting-item-description",text:f}),d},o=()=>{s&&(this.diagnosticsRunId++,s.empty(),s.createEl("p",{text:J("settings.diagnostics.idle")}))};if(new Zt.Setting(t).setName(J("settings.title")).setHeading(),new Zt.Setting(t).setName(J("settings.language")).setDesc(J("settings.language.desc")).addDropdown(l=>l.addOption("en","English").addOption("zh-CN","\u7B80\u4F53\u4E2D\u6587").setValue(this.plugin.getSettings().locale).onChange(c=>{this.plugin.updateSettings({locale:c}),this.display()})),new Zt.Setting(t).setName(J("settings.folders")).setHeading(),new Zt.Setting(t).setName(J("settings.sourceModelFolder")).setDesc(J("settings.sourceModelFolder.desc")).addText(l=>l.setPlaceholder(Oc.sourceModelFolder).setValue(this.plugin.getSettings().sourceModelFolder).onChange(c=>{this.plugin.updateSettings({sourceModelFolder:c})})),new Zt.Setting(t).setName(J("settings.reportFolder")).setDesc(J("settings.reportFolder.desc")).addText(l=>l.setPlaceholder(Oc.reportFolder).setValue(this.plugin.getSettings().reportFolder).onChange(c=>{this.plugin.updateSettings({reportFolder:c})})),new Zt.Setting(t).setName(J("settings.partFolder")).setDesc(J("settings.partFolder.desc")).addText(l=>l.setPlaceholder(Oc.partFolder).setValue(this.plugin.getSettings().partFolder).onChange(c=>{this.plugin.updateSettings({partFolder:c})})),new Zt.Setting(t).setName(J("settings.snapshotFolder")).setDesc(J("settings.snapshotFolder.desc")).addText(l=>l.setPlaceholder(Oc.snapshotFolder).setValue(this.plugin.getSettings().snapshotFolder).onChange(c=>{this.plugin.updateSettings({snapshotFolder:c})})),new Zt.Setting(t).setName(J("settings.behavior")).setHeading(),new Zt.Setting(t).setName(J("settings.autoGenerateKnowledgeNotes")).setDesc(J("settings.autoGenerateKnowledgeNotes.desc")).addToggle(l=>l.setValue(this.plugin.getSettings().autoGenerateKnowledgeNotes).onChange(c=>{this.plugin.updateSettings({autoGenerateKnowledgeNotes:c})})),new Zt.Setting(t).setName(J("settings.annotationPreviewMode")).setDesc(J("settings.annotationPreviewMode.desc")).addDropdown(l=>l.addOption("plain-text",J("settings.annotationPreviewMode.plainText")).addOption("markdown",J("settings.annotationPreviewMode.markdown")).setValue(this.plugin.getSettings().annotationPreviewMode).onChange(c=>{this.plugin.updateSettings({annotationPreviewMode:c})})),new Zt.Setting(t).setName(J("settings.annotationDisplayMode")).setDesc(J("settings.annotationDisplayMode.desc")).addDropdown(l=>l.addOption("snippet",J("settings.annotationDisplayMode.snippet")).addOption("surface",J("settings.annotationDisplayMode.surface")).addOption("dot",J("settings.annotationDisplayMode.dot")).setValue(this.plugin.getSettings().annotationDisplayMode).onChange(c=>{this.plugin.updateSettings({annotationDisplayMode:c})})),new Zt.Setting(t).setName(J("settings.previewRendererRollout")).setDesc(J("settings.previewRendererRollout.desc")).addDropdown(l=>l.addOption("babylon-safe",J("settings.previewRendererRollout.babylonSafe")).addOption("three-readonly-glb",J("settings.previewRendererRollout.readonly")).addOption("three-direct-glb",J("settings.previewRendererRollout.direct")).setValue(this.plugin.getSettings().previewRendererRollout).onChange(c=>{this.plugin.updateSettings({previewRendererRollout:c})})),new Zt.Setting(t).setName(J("settings.useThreeRenderer")).setDesc(J("settings.useThreeRenderer.desc")).addToggle(l=>l.setValue(this.plugin.getSettings().useThreeRenderer).onChange(c=>{this.plugin.updateSettings({useThreeRenderer:c})})),new Zt.Setting(t).setName(J("settings.experimentalThreeWorkbench")).setDesc(J("settings.experimentalThreeWorkbench.desc")).addToggle(l=>l.setValue(this.plugin.getSettings().experimentalThreeWorkbench).onChange(c=>{this.plugin.updateSettings({experimentalThreeWorkbench:c})})),new Zt.Setting(t).setName(J("settings.autoRotateDefault")).setDesc(J("settings.autoRotateDefault.desc")).addToggle(l=>l.setValue(this.plugin.getSettings().autoRotateDefault).onChange(c=>{this.plugin.updateSettings({autoRotateDefault:c})})),new Zt.Setting(t).setName(J("settings.snapshotNaming")).setDesc(J("settings.snapshotNaming.desc")).addDropdown(l=>l.addOption("model-name",J("settings.snapshotNaming.modelName")).addOption("timestamp",J("settings.snapshotNaming.timestamp")).setValue(this.plugin.getSettings().snapshotNaming).onChange(c=>{this.plugin.updateSettings({snapshotNaming:c})})),new Zt.Setting(t).setName(J("settings.logLevel")).setDesc(J("settings.logLevel.desc")).addDropdown(l=>l.addOption("debug","Debug").addOption("info","Info").addOption("warn","Warn").addOption("error","Error").setValue(this.plugin.getSettings().logLevel).onChange(c=>{this.plugin.updateSettings({logLevel:c})})),new Zt.Setting(t).setName(J("settings.knowledgeGeneration")).setHeading(),new Zt.Setting(t).setName(J("settings.analysisMode")).setDesc(J("settings.analysisMode.desc")).addDropdown(l=>l.addOption("local",J("settings.analysisMode.local")).addOption("hybrid",J("settings.analysisMode.hybrid")).addOption("remote",J("settings.analysisMode.remote")).setValue(this.plugin.getSettings().analysisMode).onChange(c=>{this.plugin.updateSettings({analysisMode:c})})),new Zt.Setting(t).setName(J("settings.serviceBaseUrl")).setDesc(J("settings.serviceBaseUrl.desc")).addText(l=>l.setPlaceholder("Local draft service URL").setValue(this.plugin.getSettings().serviceBaseUrl).onChange(c=>{this.plugin.updateSettings({serviceBaseUrl:c.trim()})})),new Zt.Setting(t).setName(J("settings.sendGeometrySummaryToRemote")).setDesc(J("settings.sendGeometrySummaryToRemote.desc")).addToggle(l=>l.setValue(this.plugin.getSettings().sendGeometrySummaryToRemote).onChange(c=>{this.plugin.updateSettings({sendGeometrySummaryToRemote:c})})),new Zt.Setting(t).setName(J("settings.sendPreviewImagesToRemote")).setDesc(J("settings.sendPreviewImagesToRemote.desc")).addToggle(l=>l.setValue(this.plugin.getSettings().sendPreviewImagesToRemote).onChange(c=>{this.plugin.updateSettings({sendPreviewImagesToRemote:c})})),new Zt.Setting(t).setName(J("settings.sendRawModelToRemote")).setDesc(J("settings.sendRawModelToRemote.desc")).addToggle(l=>l.setValue(this.plugin.getSettings().sendRawModelToRemote).onChange(c=>{this.plugin.updateSettings({sendRawModelToRemote:c})})),new Zt.Setting(t).setName(J("settings.converters")).setHeading(),r)t.createEl("p",{cls:"setting-item-description",text:J("settings.mobileSupport.desc")});else{let l=a(t,J("settings.converterMenu"),J("settings.converterMenu.desc"));new Zt.Setting(l).setName(J("settings.enableCad")).setDesc(J("settings.enableCad.desc")).addToggle(h=>{let d=this.plugin.getSettings().enabledConverterIds.includes("freecad");return h.setValue(d).onChange(u=>{let m=this.plugin.getSettings().enabledConverterIds,p=u?Array.from(new Set([...m,"freecad"])):m.filter(_=>_!=="freecad");this.plugin.updateSettings({enabledConverterIds:p})})}),new Zt.Setting(l).setName(J("settings.enableObj2gltf")).setDesc(J("settings.enableObj2gltf.desc")).addToggle(h=>{let d=this.plugin.getSettings().enabledConverterIds.includes("obj2gltf");return h.setValue(d).onChange(u=>{let m=this.plugin.getSettings().enabledConverterIds,p=u?Array.from(new Set([...m,"obj2gltf"])):m.filter(_=>_!=="obj2gltf");this.plugin.updateSettings({enabledConverterIds:p})})}),new Zt.Setting(l).setName(J("settings.preferObj2gltf")).setDesc(J("settings.preferObj2gltf.desc")).addToggle(h=>h.setValue(this.plugin.getSettings().preferObj2gltfForObj).onChange(d=>{this.plugin.updateSettings({preferObj2gltfForObj:d})})),new Zt.Setting(l).setName(J("settings.enableFbx2gltf")).setDesc(J("settings.enableFbx2gltf.desc")).addToggle(h=>{let d=this.plugin.getSettings().enabledConverterIds.includes("fbx2gltf");return h.setValue(d).onChange(u=>{let m=this.plugin.getSettings().enabledConverterIds,p=u?Array.from(new Set([...m,"fbx2gltf"])):m.filter(_=>_!=="fbx2gltf");this.plugin.updateSettings({enabledConverterIds:p})})}),new Zt.Setting(l).setName(J("settings.enableMesh")).setDesc(J("settings.enableMesh.desc")).addToggle(h=>{let d=this.plugin.getSettings().enabledConverterIds.includes("assimp");return h.setValue(d).onChange(u=>{let m=this.plugin.getSettings().enabledConverterIds,p=u?Array.from(new Set([...m,"assimp"])):m.filter(_=>_!=="assimp");this.plugin.updateSettings({enabledConverterIds:p})})}),new Zt.Setting(l).setName(J("settings.enableSldprt")).setDesc(J("settings.enableSldprt.desc")).addToggle(h=>{let d=this.plugin.getSettings().enabledConverterIds.includes("sldprt");return h.setValue(d).onChange(u=>{let m=this.plugin.getSettings().enabledConverterIds,p=u?Array.from(new Set([...m,"sldprt"])):m.filter(_=>_!=="sldprt");this.plugin.updateSettings({enabledConverterIds:p})})});let c=a(t,J("settings.environmentInspector"),J("settings.environmentInspector.desc"));new Zt.Setting(c).setName(J("settings.paths")).setHeading(),new Zt.Setting(c).setName(J("settings.pythonCmd")).setDesc(J("settings.pythonCmd.desc")).addText(h=>h.setPlaceholder(i.python).setValue(this.plugin.getSettings().freecadCommand).onChange(d=>{this.plugin.updateSettings({freecadCommand:d.trim()}),o()})),new Zt.Setting(c).setName(J("settings.freecadCmd")).setDesc(J("settings.freecadCmd.desc")).addText(h=>h.setPlaceholder(i.freecad).setValue(this.plugin.getSettings().freecadcmdCommand).onChange(d=>{this.plugin.updateSettings({freecadcmdCommand:d.trim()}),o()})),new Zt.Setting(c).setName(J("settings.obj2gltfCmd")).setDesc(J("settings.obj2gltfCmd.desc")).addText(h=>h.setPlaceholder(i.obj2gltf).setValue(this.plugin.getSettings().obj2gltfCommand).onChange(d=>{this.plugin.updateSettings({obj2gltfCommand:d.trim()}),o()})),new Zt.Setting(c).setName(J("settings.fbx2gltfCmd")).setDesc(J("settings.fbx2gltfCmd.desc")).addText(h=>h.setPlaceholder(i.fbx2gltf).setValue(this.plugin.getSettings().fbx2gltfCommand).onChange(d=>{this.plugin.updateSettings({fbx2gltfCommand:d.trim()}),o()})),new Zt.Setting(c).setName(J("settings.assimpCmd")).setDesc(J("settings.assimpCmd.desc")).addText(h=>h.setPlaceholder(i.python).setValue(this.plugin.getSettings().assimpCommand).onChange(d=>{this.plugin.updateSettings({assimpCommand:d.trim()}),o()})),new Zt.Setting(c).setName(J("settings.diagnostics")).setDesc(J("settings.diagnostics.desc")).addButton(h=>h.setButtonText(J("settings.diagnostics.checkNow")).onClick(async()=>{h.setDisabled(!0),h.setButtonText(J("settings.diagnostics.checking")),s&&await this.renderCommandDiagnostics(s),h.setButtonText(J("settings.diagnostics.checkNow")),h.setDisabled(!1),new Zt.Notice(J("settings.diagnostics.refreshed"))})),s=c.createDiv({cls:"ai3d-settings-diagnostics"}),o()}new Zt.Setting(t).setName(J("settings.performance")).setHeading(),new Zt.Setting(t).setName(J("settings.canvasHeight")).setDesc(J("settings.canvasHeight.desc")).addSlider(l=>l.setLimits(200,800,25).setValue(this.plugin.getSettings().defaultCanvasHeight).setDynamicTooltip().onChange(c=>{this.plugin.updateSettings({defaultCanvasHeight:c})})),new Zt.Setting(t).setName(J("settings.autoRotateSpeed")).setDesc(J("settings.autoRotateSpeed.desc")).addSlider(l=>l.setLimits(.1,2,.1).setValue(this.plugin.getSettings().autoRotateSpeed).setDynamicTooltip().onChange(c=>{this.plugin.updateSettings({autoRotateSpeed:c})})),new Zt.Setting(t).setName(J("settings.renderQuality")).setDesc(J("settings.renderQuality.desc")).addDropdown(l=>l.addOption("low","Low").addOption("medium","Medium").addOption("high","High").setValue(this.plugin.getSettings().renderQuality).onChange(c=>{this.plugin.updateSettings({renderQuality:c})})),new Zt.Setting(t).setName(J("settings.renderScale")).setDesc(J("settings.renderScale.desc")).addSlider(l=>l.setLimits(.25,2,.25).setValue(this.plugin.getSettings().renderScale).setDynamicTooltip().onChange(c=>{this.plugin.updateSettings({renderScale:c})}))}async renderCommandDiagnostics(t){let i=++this.diagnosticsRunId;t.empty(),t.createEl("p",{text:J("settings.diagnostics.checkingAvailability")});let r=await ab(this.plugin.getSettings());if(i===this.diagnosticsRunId){t.empty();for(let s of r)this.renderCommandStatus(t,s)}}renderCommandStatus(t,i){var a;let r=t.createDiv({cls:"ai3d-settings-status-block"});r.createEl("strong",{text:`${i.label}: ${i.available?J("settings.diagnostics.available"):J("settings.diagnostics.notFound")}`});let s=[`${J("settings.diagnostics.sourceLabel")}: ${sb(i.source)}`,`${J("settings.diagnostics.commandLabel")}: ${i.command}`,i.resolvedPath&&i.resolvedPath!==i.command?`${J("settings.diagnostics.resolvedPathLabel")}: ${i.resolvedPath}`:"",i.detail].filter(Boolean);for(let o of s)r.createDiv({text:o});for(let o of(a=i.dependencyChecks)!=null?a:[])this.renderDependencyCheck(r,o)}renderDependencyCheck(t,i){let r=(()=>{switch(i.kind){case"cad-python":return J("settings.diagnostics.cadPythonCheck");case"mesh-python":return J("settings.diagnostics.meshPythonCheck");case"freecadcmd-cli":return J("settings.diagnostics.freecadCmdCheck");case"obj2gltf-cli":return J("settings.diagnostics.obj2gltfCheck");case"fbx2gltf-cli":return J("settings.diagnostics.fbx2gltfCheck")}})(),s=i.ok?J("settings.diagnostics.selfCheckOk"):J("settings.diagnostics.selfCheckFailed");t.createDiv({text:`${J("settings.diagnostics.selfCheckLabel")}: ${r} - ${s}`}),i.detail&&t.createDiv({text:i.detail})}};Jf();Tn();ra();rv();Ks();la();var Aq=ki("main");function cv(n,e){return()=>{n().catch(t=>{Aq.error(`Command ${e} failed`,{error:String(t)}),new Os.Notice(`AI3D: ${e} failed \u2014 ${String(t)}`,5e3)})}}var yb=class extends Os.Plugin{getSettings(){return this.ps.store.getState().settings}updateSettings(e){let i={...this.ps.store.getState().settings,...e};this.ps.store.setState({settings:i}),jO(i.logLevel),Rp(i.locale)}async onload(){var l;if(this.ps=HN(this),await this.ps.load(),this.convertedAssetCache=VN(this.ps.store.getState().convertedAssetRecords,c=>this.ps.store.setState({convertedAssetRecords:c})),jO(this.getSettings().logLevel),!this.ps.localeLoadedFromSaved){let f=((l=navigator.language)!=null?l:"en").startsWith("zh")?"zh-CN":"en";this.updateSettings({locale:f})}Rp(this.getSettings().locale),this.addRibbonIcon("box",J("main.commandImportModel"),()=>this.importModel()),this.addCommand({id:"import-model",name:J("main.commandImportModel"),callback:()=>this.importModel()}),this.addCommand({id:"generate-note",name:J("main.commandGenerateNote"),callback:cv(()=>this.generateNote(),"generate note")}),this.addCommand({id:"open-knowledge-index",name:J("main.commandOpenKnowledgeIndex"),callback:cv(()=>this.openKnowledgeIndex(),"open knowledge index")}),this.addCommand({id:"clear-conversion-cache",name:J("main.commandClearConversionCache"),callback:cv(()=>Promise.resolve(this.clearConversionCache()),"clear conversion cache")}),this.addCommand({id:"check-converters",name:J("main.commandCheckConverters"),callback:cv(()=>this.checkConverterCommands(),"check converters")}),this.addCommand({id:"copy-diagnostics-report",name:J("main.commandCopyDiagnostics"),callback:cv(()=>this.copyDiagnosticsReport(),"copy diagnostics")}),this.addSettingTab(new Mb(this.app,this)),this.registerView(bb,c=>new Rb(c,()=>this.getSettings(),this.convertedAssetCache,this.ps)),this.registerExtensions(vl(),bb);let{registerCodeBlockProcessor:e,registerGridCodeBlockProcessor:t}=await Promise.resolve().then(()=>(uq(),dq)),i=c=>{var f,h;return(h=(f=this.ps.store.getState().modelAssetProfiles[c])==null?void 0:f.annotations)!=null?h:[]},r=e(this.app,()=>this.getSettings(),this.convertedAssetCache,i);this.registerMarkdownCodeBlockProcessor(r.id,r.handler);let s=t(this.app,()=>this.getSettings(),this.convertedAssetCache);this.registerMarkdownCodeBlockProcessor(s.id,s.handler);let{registerLivePreviewExtension:a}=await Promise.resolve().then(()=>(vq(),gq)),o=a(this.app,()=>this.getSettings(),this.convertedAssetCache,i);for(let c of o)this.registerEditorExtension(c);this.setupHeadingPinObserver()}onunload(){this.ps.save().catch(e=>console.error("[AI3D] unload save failed:",e))}setupHeadingPinObserver(){let e=".markdown-preview-view, .markdown-source-view",t=[".markdown-preview-view h1",".markdown-preview-view h2",".markdown-preview-view h3",".markdown-preview-view h4",".markdown-preview-view h5",".markdown-preview-view h6",".cm-heading-1",".cm-heading-2",".cm-heading-3",".cm-heading-4",".cm-heading-5",".cm-heading-6",".cm-header-1",".cm-header-2",".cm-header-3",".cm-header-4",".cm-header-5",".cm-header-6"].join(", "),i=new Map,r=M=>{if(M.length===0)return"var(--interactive-accent)";if(M.length===1)return M[0];let D=100/M.length;return`linear-gradient(135deg, ${M.map((O,V)=>{let N=Math.round(V*D),F=Math.round((V+1)*D);return`${O} ${N}% ${F}%`}).join(", ")})`},s=()=>{let M=new Map,D=this.ps.store.getState().modelAssetProfiles;for(let[O,V]of Object.entries(D))for(let N of V.annotations)if(N.headingRef&&N.id){let F=iv(N.headingRef);if(!F)continue;let U=M.get(F);U||(U=[],M.set(F,U)),U.push({pinId:N.id,modelPath:O,color:N.color})}return M},a=M=>M.map(D=>`${D.pinId}:${D.modelPath}:${D.color}`).sort().join("|"),o=M=>Array.from(M.entries()).map(([D,O])=>`${D}=>${a(O)}`).sort().join("||"),l=M=>iv(Array.from(M.childNodes).map(D=>{var O;return D.instanceOf(Element)&&D.classList.contains("ai3d-heading-pin-badge")?"":(O=D.textContent)!=null?O:""}).join(" ")),c=M=>{let D=i.get(M);D&&(M.removeEventListener("mouseover",D.handler),D.badge.remove(),delete M.dataset.pinBound,i.delete(M))},f=(M,D)=>{if(D.length===0){c(M);return}let O=a(D),V=i.get(M);if((V==null?void 0:V.signature)===O)return;V&&c(M),M.dataset.pinBound=O;let N=M.createSpan({cls:"ai3d-heading-pin-badge"}),F=[...new Set(D.map(Q=>Q.color).filter(Boolean))],U=N.createSpan({cls:"ai3d-heading-pin-badge-swatch"});if(U.style.background=r(F),U.title=D.length>1?J("headingPin.showMultiple"):J("headingPin.showSingle"),U.setAttribute("role","button"),U.setAttribute("tabindex","0"),D.length>1){let Q=N.createSpan({cls:"ai3d-heading-pin-badge-count"});Q.textContent=`\xD7${D.length}`}let k=[...new Set(D.map(Q=>jr(Q.modelPath)))];N.title=dr("headingPin.linkedTo",{models:k.join(", ")});let ee=Q=>{Q==null||Q.stopPropagation(),Q==null||Q.preventDefault();for(let Y of D)activeDocument.dispatchEvent(new CustomEvent("ai3d-pin-highlight",{detail:{pinId:Y.pinId}}))};U.addEventListener("click",Q=>{ee(Q)}),U.addEventListener("keydown",Q=>{Q.instanceOf(KeyboardEvent)&&(Q.key!=="Enter"&&Q.key!==" "||ee(Q))}),N.addEventListener("click",Q=>{Q.stopPropagation()}),M.appendChild(N);let q=()=>{for(let Q of D)activeDocument.dispatchEvent(new CustomEvent("ai3d-pin-highlight",{detail:{pinId:Q.pinId}}))};M.addEventListener("mouseover",q),i.set(M,{badge:N,handler:q,signature:O})},h=(M,D)=>{var V;let O=l(M);f(M,(V=D.get(O))!=null?V:[])},d=M=>{var D;for(let[O,V]of Array.from(i.entries())){if(!O.isConnected){c(O);continue}let N=(D=M.get(l(O)))!=null?D:[],F=a(N);(N.length===0||V.signature!==F)&&f(O,N)}},u=(M,D)=>{M.querySelectorAll(t).forEach(O=>h(O,D))},m=()=>{let M=s();d(M),activeDocument.querySelectorAll(e).forEach(O=>u(O,M))},p=o(s()),_=0,g=(M=0)=>{_&&window.clearTimeout(_),_=window.setTimeout(()=>{_=0,m()},M)},v=this.ps.store.subscribe(()=>{let M=s(),D=o(M);D!==p&&(p=D,g())});this.registerEvent(this.app.workspace.on("layout-change",()=>{g(200)}));let x=M=>M.matches(e)||M.matches(t)?!0:!!M.querySelector(e)||!!M.querySelector(t),A=M=>M.isConnected&&x(M),S=M=>x(M),E=new Set,R=0,I=()=>{var O,V,N,F,U,k;let M=Array.from(E);E.clear(),R=0;let D=s();d(D);for(let ee of M)ee.isConnected&&((O=ee.matches)!=null&&O.call(ee,t)&&h(ee,D),(N=(V=ee.querySelectorAll)==null?void 0:V.call(ee,t))==null||N.forEach(q=>h(q,D)),(F=ee.matches)!=null&&F.call(ee,e)&&u(ee,D),(k=(U=ee.querySelectorAll)==null?void 0:U.call(ee,e))==null||k.forEach(q=>u(q,D)));p=o(D)},y=new MutationObserver(M=>{let D=!1;for(let O of M){for(let V of Array.from(O.addedNodes))V.instanceOf(HTMLElement)&&A(V)&&(E.add(V),D=!0);for(let V of Array.from(O.removedNodes))V.instanceOf(HTMLElement)&&S(V)&&(D=!0)}D&&!R&&(R=window.setTimeout(I,100))});y.observe(activeDocument.body,{childList:!0,subtree:!0}),this.register(()=>{v(),y.disconnect(),R&&(window.clearTimeout(R),R=0),_&&(window.clearTimeout(_),_=0);for(let M of Array.from(i.keys()))c(M)}),g(500)}importModel(){new Ib(this.app,e=>{let t=e.extension.toLowerCase();gl(t)&&this.openModelFile(e)}).open()}async openModelFile(e){this.ps.store.setState({currentModelPath:e.path,modelPreview:null,selectedPart:null}),await this.app.workspace.getLeaf(!0).openFile(e,{active:!0})}async generateNote(){let{generateKnowledgeNote:e}=await Promise.resolve().then(()=>(Ab(),Tb));await e(this.app,this.ps)}async openKnowledgeIndex(){let e=this.resolveKnowledgeIndexPath();if(!e){new Os.Notice(J("workbench.noIndexYet"));return}let t=this.app.vault.getAbstractFileByPath(e);t instanceof Os.TFile?await this.app.workspace.getLeaf(!0).openFile(t,{active:!0}):new Os.Notice(dr("workbench.fileNotFound",{path:e}))}resolveKnowledgeIndexPath(){var s,a,o;let e=this.ps.store.getState(),t=e.currentModelPath,i=t?(s=e.modelAssetProfiles[t])==null?void 0:s.knowledgeIndexPath:void 0;return i||((a=e.lastKnowledgeGeneration)!=null&&a.knowledgeIndexPath?e.lastKnowledgeGeneration.knowledgeIndexPath:(o=Object.values(e.modelAssetProfiles).filter(l=>!!l.knowledgeIndexPath).sort((l,c)=>Date.parse(c.updatedAt)-Date.parse(l.updatedAt))[0])==null?void 0:o.knowledgeIndexPath)}clearConversionCache(){this.convertedAssetCache.clear(),new Os.Notice("AI 3d conversion cache cleared.")}async checkConverterCommands(){if(ur()){new Os.Notice(J("main.converterDiagnosticsMobileUnavailable"),8e3);return}let e=await ab(this.getSettings()),t=e.filter(r=>r.available).map(r=>r.label),i=e.filter(r=>!r.available).map(r=>r.label);if(i.length===0){new Os.Notice(`AI 3D converter diagnostics: all commands available (${t.join(", ")}).`,8e3);return}new Os.Notice(`AI 3D converter diagnostics: available ${t.join(", ")||"none"}; missing ${i.join(", ")}.`,1e4)}async copyDiagnosticsReport(){let{buildDiagnosticsReport:e}=await Promise.resolve().then(()=>(Tq(),Sq)),t=e({manifest:this.manifest,state:this.ps.store.getState()});try{await navigator.clipboard.writeText(t),new Os.Notice(J("main.diagnosticsCopied"),8e3)}catch(i){let r=this.getSettings().reportFolder.replace(/\\/g,"/").replace(/^\/+|\/+$/g,"").trim()||"Analysis/3D Reports";await this.ensureVaultFolder(r);let s=`AI Model Workbench Diagnostics ${new Date().toISOString().replace(/[:.]/g,"-")}.md`,a=await this.app.vault.create(`${r}/${s}`,t);await this.app.workspace.getLeaf(!0).openFile(a,{active:!0}),new Os.Notice(J("main.diagnosticsCopyFailed"),1e4)}}async ensureVaultFolder(e){let t="";for(let i of e.split("/").filter(Boolean))t=t?`${t}/${i}`:i,this.app.vault.getAbstractFileByPath(t)||await this.app.vault.createFolder(t).catch(r=>{Aq.warn("Failed to create vault folder",{path:t,error:String(r)})})}}; +`)}async function lpe(n){let e=typeof performance!="undefined"?performance.now():Date.now(),t=n.app.vault.getAbstractFileByPath(n.indexPath),i=null;if(t instanceof Mc.TFile){let r=await n.app.vault.read(t),s=TN(n);await n.app.vault.modify(t,zj(r,s)),i=t}else i=await Gj(n.app,n.indexPath,Xj(n));return i&&(n.analysis.knowledgeIndexPath=i.path),n.analysis.pipeline.push({stage:"index",durationMs:Math.max(0,Math.round((typeof performance!="undefined"?performance.now():Date.now())-e)),status:i?"success":"failed"}),i}async function cpe(n,e,t={}){var r,s,a,o,l,c;if(mN!==null)return;let i;mN=new Promise(f=>{i=f});try{let f=e.store.getState(),h=f.currentModelPath;if(!h)return;let d=f.modelAssetProfiles[h],u=f.modelPreview,m=jr(h)||"model",p=f.settings.reportFolder,_=`${p}/${m} Report.md`,g=`${p}/${m} Analysis.json`,v=`${p}/${m} Index.md`,x=(a=(s=(r=t.preview)==null?void 0:r.getModelEvidence)==null?void 0:s.call(r))!=null?a:null,A=await rpe(n,t.preview,f.settings.previewFolder,m),S=await Hj(n,f.modelAssetProfiles,h),E=Tb({modelPath:h,profile:d,preview:u,evidence:x,previewImages:A.paths,registeredParts:S});A.warning&&(E.warnings=[...E.warnings,A.warning],E.draftingInput&&(E.draftingInput={...E.draftingInput,evidence:{...E.draftingInput.evidence,warnings:[...E.draftingInput.evidence.warnings,A.warning]}})),E.localDraft=Uj({baseName:m,sourcePath:h,profile:d,preview:u,analysis:E}),E.pipeline.push({stage:"draft",durationMs:0,status:"success"}),await ope({app:n,partFolder:f.settings.partFolder,baseName:m,notePath:_,sourcePath:h,analysis:E}),E.draftingInput&&(E.draftingInput={...E.draftingInput,partCandidates:E.draftingInput.partCandidates.map(O=>{let V=E.parts.find(N=>N.partId===O.partId);return V!=null&&V.notePath?{...O,notePath:V.notePath}:O}),annotationLinks:[...(o=E.annotationLinks)!=null?o:[]]});let R=bj(f.settings,E.draftingInput,vp);if(R.enabled)try{let O=await Ij(R);O?(E.remoteDraft=O,E.pipeline.push({stage:"remoteDraft",durationMs:0,status:"success"})):E.pipeline.push({stage:"remoteDraft",durationMs:0,status:"skipped"})}catch(O){let V=O instanceof Error?O.message:String(O);E.warnings=[...E.warnings,`Remote draft failed: ${V}`],E.pipeline.push({stage:"remoteDraft",durationMs:0,status:"failed"})}else E.pipeline.push({stage:"remoteDraft",durationMs:0,status:"skipped"});await SN(n,p),await lpe({app:n,baseName:m,notePath:_,sourcePath:h,analysisSidecarPath:g,indexPath:v,analysis:E,preview:u,profile:d});let I=Vj({baseName:m,notePath:_,sourcePath:h,profile:d,preview:u,analysis:E,analysisSidecarPath:g,knowledgeIndexPath:E.knowledgeIndexPath});await yj(n,g,`${JSON.stringify(E,null,2)} +`);let y=await yj(n,_,I);if(!y)return;let M=e.store.getState().modelAssetProfiles,D=tpe(M[h],h);e.store.setState({modelAssetProfiles:{...M,[h]:{...D,analysisVersion:vp,registeredParts:E.parts,reportNotePath:y.path,analysisSidecarPath:g,knowledgeIndexPath:E.knowledgeIndexPath,previewImagePaths:A.paths,updatedAt:new Date().toISOString()}},lastKnowledgeGeneration:{modelPath:h,reportNotePath:y.path,analysisSidecarPath:g,knowledgeIndexPath:E.knowledgeIndexPath,partNoteCount:(c=(l=E.partNotePaths)==null?void 0:l.length)!=null?c:0,previewImageCount:E.previewImages.length,generatedAt:new Date().toISOString(),status:"success",warningCount:E.warnings.length}}),await n.workspace.getLeaf(!0).openFile(y,{active:!0}),new Mc.Notice(`Knowledge note updated: ${y.path}`)}finally{i(),mN=null}}var Mc,Nme,Dj,Lj,pN,mN,xb=C(()=>{"use strict";Mc=require("obsidian");XS();GS();Tn();oa();dN();Mj();Nme=Wi("knowledge-note"),Dj=8,Lj="",pN="";mN=null});function Ro(n,e,t=2.5){var i;if(typeof n=="string"){let r=(i=RN[n])!=null?i:RN.iso;return{alpha:r.alpha,beta:r.beta,radiusMultiplier:t}}return{alpha:n,beta:e!=null?e:Math.PI/3,radiusMultiplier:t}}function pl(n,e,t=.02){let i=(1-t*(n+1))/n,r=(1-t*(e+1))/e,s=[];for(let a=0;a({path:i.path,position:[-t/2+r*e,0,0],color:i.color,wireframe:i.wireframe}))}function IN(n,e){return n.map((t,i)=>{let r=2*Math.PI*i/n.length;return{path:t.path,position:[Math.cos(r)*e,0,Math.sin(r)*e],color:t.color,wireframe:t.wireframe}})}var RN,Rd=C(()=>{"use strict";RN={iso:{alpha:Math.PI/4,beta:Math.PI/3},front:{alpha:0,beta:Math.PI/2},side:{alpha:Math.PI/2,beta:Math.PI/2},top:{alpha:0,beta:.01},back:{alpha:Math.PI,beta:Math.PI/2},"3/4":{alpha:Math.PI/6,beta:Math.PI/3.5}}});var Zj,Qj=C(()=>{"use strict";Rd();Zj={name:"compare",description:"Side-by-side model comparison (2-4 models)",minModels:2,maxModels:4,compute(n,e){if(n.length<2||n.length>4)return null;let t=Number(e.spacing)||6,i=e.angle||"iso",r=av(n,t),s=n.length<=3?n.length:2,a=Math.ceil(n.length/s),o=pl(s,a),l=n.map((c,f)=>({modelIndex:f,camera:Ro(i),viewport:o[f]}));return{placements:r,cells:l}}}});var $j,Jj=C(()=>{"use strict";Rd();$j={name:"showcase",description:"Single model viewed from multiple angles",minModels:1,maxModels:1,compute(n,e){if(n.length<1)return null;let t=Number(e.angles)||4,i=Number(e.radius)||2.5,r=[{path:n[0].path,position:[0,0,0],color:n[0].color,wireframe:n[0].wireframe}],s=t>=6?["front","side","top","back","iso","3/4"]:["iso","front","side","top"],a=s.length<=4?2:3,o=Math.ceil(s.length/a),l=pl(a,o),c=s.map((f,h)=>({modelIndex:0,camera:Ro(f,void 0,i),viewport:l[h]}));return{placements:r,cells:c}}}});var eq,tq=C(()=>{"use strict";Rd();eq={name:"explode",description:"Spatial arrangement of parts (3-8 models in a ring)",minModels:3,maxModels:8,compute(n,e){if(n.length<3||n.length>8)return null;let t=Number(e.radius)||8,i=e.angle||"iso",r=IN(n,t),s=Math.min(n.length,4),a=Math.ceil(n.length/s),o=pl(s,a),l=n.map((c,f)=>({modelIndex:f,camera:Ro(i),viewport:o[f]}));return{placements:r,cells:l}}}});var iq,rq=C(()=>{"use strict";Rd();iq={name:"timeline",description:"Horizontal progression of models (2-6 models in a strip)",minModels:2,maxModels:6,compute(n,e){if(n.length<2||n.length>6)return null;let t=Number(e.spacing)||6,i=e.angle||"3/4",r=av(n,t),s=bN(n.length),a=n.map((o,l)=>({modelIndex:l,camera:Ro(i),viewport:s[l]}));return{placements:r,cells:a}}}});function MN(n,e,t,i,r){var f,h;if(!n||n.length===0)return null;let s=n.reduce((d,u)=>{var m;return d+((m=u.weight)!=null?m:1)},0);if(s<=0)return null;let a=[],o=0;for(let d of n){let m=((f=d.weight)!=null?f:1)/s*(1-t*(n.length+1));e==="horizontal"?a.push({x:t+o,y:t,w:m,h:1-2*t}):a.push({x:t,y:t+o,w:1-2*t,h:m}),o+=m+t}let l=[],c=[];for(let d=0;d{"use strict";nq={name:"compose",description:"Combine multiple presets into one layout",minModels:1,maxModels:32,compute(n,e,t){return null}}});var sq,aq=C(()=>{"use strict";Rd();sq={name:"gallery",description:"All models in one scene, single camera (no cell limit)",minModels:1,maxModels:32,compute(n,e){if(n.length===0)return null;let t=Number(e.spacing)||6,i=e.angle||"iso",r=Number(e.cols)||0,s=r>0?r:Math.ceil(Math.sqrt(n.length)),a=Math.ceil(n.length/s),o=n.map((f,h)=>{let d=h%s,u=Math.floor(h/s),m=(d-(s-1)/2)*t,p=(u-(a-1)/2)*t;return{path:f.path,position:[m,0,p],color:f.color,wireframe:f.wireframe}}),l=pl(1,1,0),c=[{modelIndex:0,camera:Ro(i,void 0,3+Math.max(s,a)*.5),viewport:l[0]}];return{placements:o,cells:c}}}});function Ep(n){oq.set(n.name,n)}function yN(n){return oq.get(n)}var oq,lq=C(()=>{"use strict";Qj();Jj();tq();rq();CN();aq();Rd();CN();oq=new Map;Ep(Zj);Ep($j);Ep(eq);Ep(iq);Ep(nq);Ep(sq)});var dq={};tt(dq,{registerCodeBlockProcessor:()=>vpe,registerGridCodeBlockProcessor:()=>Spe});async function fq(n,e,t,i){var h,d,u;let r=typeof e=="string"?{path:e}:e,s=Fd(n,r.path);if(!s)throw new Error(ur("workbench.fileNotFound",{path:r.path}));let a=(d=(h=s.split(".").pop())==null?void 0:h.toLowerCase())!=null?d:"";if(!_l(a))throw Ap(a)?new Error(J("codeBlock.splatDisabled")):new Error(ur("codeBlock.unsupportedFormat",{ext:`.${a}`,formats:gl().join(", ")}));let o=(u=eh(n,s))!=null?u:void 0,l=gd(t),c=await Ed({path:s,absolutePath:o,preferConversionExts:Sd(t),conversionManager:l,convertedAssetCache:i}),f=tv(c);return{sourcePath:s,effectivePath:f.path,effectiveExt:f.ext,warnings:f.warnings,model:{...r,path:f.path}}}async function gpe(n,e,t,i){let r=[];for(let s of e.models){let a=await fq(n,s,t,i);r.push(a.model)}return{...e,models:r}}function hq(n){mr()&&n.createDiv({cls:"ai3d-mobile-mode-hint ai3d-mobile-mode-hint--inline",text:J("codeBlock.mobileHint")})}function vpe(n,e,t,i){return{id:"3d",handler:(r,s,a)=>{var y,M;let o=r.trim();if(!o){s.createDiv({cls:"ai3d-inline-empty",text:J("codeBlock.noModelPathOrConfig")});return}let l;if(o.startsWith("{")||o.startsWith("["))try{let D=JSON.parse(o);l=Epe(D)}catch(D){let O=s.createDiv({cls:"ai3d-json-error"}),V=String(D).match(/position\s+(\d+)/),N=ur("codeBlock.jsonParseError",{error:String(D)});if(V){let F=parseInt(V[1],10),U=o.substring(0,F).split(` +`);N+=ur("codeBlock.jsonParseLine",{line:String(U.length)})}O.createEl("pre",{text:N});return}else l={models:[{path:o}]};if(!l.models||l.models.length===0){s.createDiv({cls:"ai3d-inline-empty",text:J("codeBlock.noModelsInConfig")});return}l.models.length>1&&console.warn(`[AI3D] \`\`\`3d only supports one model; ${l.models.length-1} additional models ignored. Use \`\`\`3dgrid for multi-model.`);let f=l.models[0],h=Fd(n,f.path);if(!h){s.createDiv({cls:"ai3d-inline-empty",text:ur("workbench.fileNotFound",{path:f.path})});return}let d=(M=(y=h.split(".").pop())==null?void 0:y.toLowerCase())!=null?M:"";if(!_l(d)){s.createDiv({cls:"ai3d-inline-empty",text:Ap(d)?J("codeBlock.splatDisabled"):ur("codeBlock.unsupportedFormat",{ext:`.${d}`,formats:gl().join(", ")})});return}let u=e(),m=s.createDiv({cls:"ai3d-preview-host"});l.height&&m.style.setProperty("--min-height",typeof l.height=="number"?`${l.height}px`:l.height),l.width&&m.style.setProperty("--max-width",typeof l.width=="number"?`${l.width}px`:l.width);let p=m.createEl("canvas",{cls:"ai3d-canvas-full"});p.tabIndex=0,p.addEventListener("keydown",D=>{var V,N,F,U,G;if(x||!_)return;let O=D.key.toLowerCase();O==="r"?((V=_.resetView)==null||V.call(_),D.preventDefault()):O==="w"?((N=_.toggleWireframe)==null||N.call(_),D.preventDefault()):O==="g"?((F=_.toggleOrientationGizmo)==null||F.call(_),D.preventDefault()):O==="b"?((U=_.toggleBoundingBox)==null||U.call(_),D.preventDefault()):O===" "?((G=_.toggleAnimation)==null||G.call(_),D.preventDefault()):O==="m"&&(Ao(_)&&_.toggleMeasurement(),D.preventDefault())}),m.appendChild(p);let _=null,g=null,v=!0,x=!1,A=!1,S=$g(s,m,n,()=>_,()=>h,()=>{x||(x=!0,E.disconnect(),I.disconnect(),g==null||g.destroy(),g=null,_==null||_.destroy(),_=null,m.remove())},e,()=>{if(v=!v,g){let D=m.querySelector(".ai3d-annotation-overlay");D&&D.classList.toggle("is-hidden",!v)}return v},void 0,{labelKey:"helper.toggleAnnotationsVisibilityLabel",activeTooltipKey:"helper.annotationsVisible",inactiveTooltipKey:"helper.annotationsHidden"});hq(s);let E=new MutationObserver(()=>{x||s.contains(m)||(x=!0,E.disconnect(),I.disconnect(),g==null||g.destroy(),g=null,_==null||_.destroy(),_=null)});E.observe(s,{childList:!0});async function R(){var O,V,N,F,U,G,ee;if(A||x||!h)return;A=!0;let D=Td(m);try{let j=(O=eh(n,h))!=null?O:void 0,Z=gd(u);D.setPhaseKey("loading.preparingModel");let X=await Ed({path:h,absolutePath:j,preferConversionExts:Sd(u),conversionManager:Z,convertedAssetCache:t}),Y=tv(X),ue=(V=i==null?void 0:i(h))!=null?V:[],Re={ext:Y.ext,annotationMode:ue.length>0?"readonly":"none",rendererRollout:u.previewRendererRollout,useThreeRenderer:u.useThreeRenderer},{preview:Be}=await _d(cq,{surface:"code-block",modelPath:h},p,Re);_=Be,S.syncCapabilities(),D.setPhaseKey("loading.loadingModel");let ae=await Ua(n,Y.path),me=async de=>Ua(n,de);if(x){D.hide();return}let re=await _.loadModel(ae,Y.ext,me,Y.path);if(D.setProgress(100),gp(m,re),x){D.hide();return}if(((N=l.scene)==null?void 0:N.autoRotate)===void 0&&u.autoRotateDefault&&(l.scene={...l.scene,autoRotate:!0,autoRotateSpeed:u.autoRotateSpeed}),_.applyConfig(l),(F=_.setRenderQuality)==null||F.call(_,u.renderQuality,u.renderScale),S.syncCapabilities(),ue.length>0&&eb(_)){let de=_.getAnnotationProvider();de.canvas&&(g=new wc(de,m,"readonly",ue,void 0,pp(n),void 0,{app:n,previewMode:u.annotationPreviewMode,displayMode:u.annotationDisplayMode}),S.showAnnotateButton(),S.updateAnnotationBadge(ue.length))}d==="stl"&&f.color&&((U=_.setSTLColor)==null||U.call(_,f.color)),d==="stl"&&f.wireframe!==void 0&&((G=_.setWireframe)==null||G.call(_,f.wireframe)),(ee=_.hasAnimations)!=null&&ee.call(_)&&S.showAnimButton(),D.hide()}catch(j){x=!0,E.disconnect(),I.disconnect(),D.hide(),_==null||_.destroy(),_=null,m.replaceChildren();let Z=up(j);dp(j)?console.warn("[AI3D] Inline preview blocked by converter settings:",Z.message):console.error("[AI3D] Inline preview failed:",j),_p(m,Z)}}let I=new IntersectionObserver(D=>{for(let O of D)O.isIntersecting&&(I.disconnect(),R())},{rootMargin:"200px"});I.observe(m)}}}function Epe(n){if(typeof n=="string")return{models:[{path:n}]};if(typeof n!="object"||n===null)return{models:[]};let e=n;return typeof e.path=="string"?{models:[{path:e.path,color:e.color,wireframe:e.wireframe}],camera:e.camera,lights:e.lights,scene:e.scene,stl:e.stl,width:e.width,height:e.height}:{models:Array.isArray(e.models)?e.models.filter(i=>{let r=typeof i=="string"?i:i&&typeof i=="object"&&"path"in i?i.path:void 0;return typeof r=="string"&&r.length>0}).map(i=>{if(typeof i=="string")return{path:i};let r=i;return{path:r.path,color:r.color,wireframe:r.wireframe}}):[],camera:e.camera,lights:e.lights,scene:e.scene,stl:e.stl,width:e.width,height:e.height}}function Spe(n,e,t){return{id:"3dgrid",handler:(i,r,s)=>{let a=i.trim();if(!a){r.createDiv({cls:"ai3d-inline-empty",text:J("codeBlock.noConfigSpecified")});return}let o;try{o=JSON.parse(a)}catch(f){r.createDiv({cls:"ai3d-json-error"}).createEl("pre",{text:`JSON parse error: ${String(f)}`});return}if(o.preset!=="compose"&&(!o.models||o.models.length===0)){r.createDiv({cls:"ai3d-inline-empty",text:J("codeBlock.noModelsSpecified")});return}let l=e(),c=Td(r);(async()=>{var E,R,I,y;let f=[];for(let M of(E=o.models)!=null?E:[])try{let D=await fq(n,M,l,t);f.push(D)}catch(D){c.hide(),r.createDiv({cls:"ai3d-inline-empty",text:D instanceof Error?D.message:String(D)});return}let h=f.map(M=>M.model),d=(I=(R=f[0])==null?void 0:R.sourcePath)!=null?I:"",u=r.createDiv({cls:"ai3d-grid-host"}),m=u.createEl("canvas");if(m.tabIndex=0,m.addEventListener("keydown",M=>{var O,V;if(_||!p)return;let D=M.key.toLowerCase();D==="r"?((O=p.resetView)==null||O.call(p),M.preventDefault()):D==="w"&&((V=p.toggleWireframe)==null||V.call(p),M.preventDefault())}),u.appendChild(m),typeof o.rowHeight=="number"){let M=o.preset==="compose"?1:Math.ceil(h.length/((y=o.columns)!=null?y:Math.min(h.length,3)));u.style.setProperty("--grid-height",`${o.rowHeight*M}px`)}let p=null,_=!1,g=!1,v=$g(r,u,n,()=>p,()=>d,()=>{_||(_=!0,x.disconnect(),S.disconnect(),p==null||p.destroy(),p=null,u.remove())},e);hq(r);let x=new MutationObserver(()=>{_||r.contains(u)||(_=!0,x.disconnect(),S.disconnect(),p==null||p.destroy(),p=null)});x.observe(r,{childList:!0});async function A(){var M,D,O,V,N,F,U;if(!(g||_)){g=!0,c.setPhaseKey("codeBlock.renderingGrid"),c.setProgress(-1);try{let{renderer:G}=await XK(cq,{surface:"3dgrid",preset:(M=o.preset)!=null?M:"compare",modelCount:(O=(D=o.models)==null?void 0:D.length)!=null?O:0},m);p=G,v.syncCapabilities();let ee=p,j=async Z=>Ua(n,Z);if(o.preset==="compose"){if(!o.sections||o.sections.length===0){c.hide(),u.createDiv({cls:"ai3d-inline-empty",text:J("codeBlock.composeRequiresSections")}),p.destroy(),p=null;return}let Z=[];for(let Y of o.sections)try{if(!d){let Re=Y.models[0];if(Re){let Be=typeof Re=="string"?Re:Re.path;d=(V=Fd(n,Be))!=null?V:Be}}let ue=await gpe(n,Y,l,t);Z.push(ue)}catch(ue){c.hide(),u.createDiv({cls:"ai3d-inline-empty",text:ue instanceof Error?ue.message:String(ue)}),ee.destroy(),p=null;return}let X=MN(Z,(N=o.direction)!=null?N:"horizontal",Number((F=o.params)==null?void 0:F.gap)||.02,Y=>typeof Y=="string"?null:Y,yN);if(!X){c.hide(),u.createDiv({cls:"ai3d-inline-empty",text:J("codeBlock.composeNoValidSections")}),ee.destroy(),p=null;return}await ee.loadWithPreset(X,j)}else if(o.preset){let Z=yN(o.preset);if(!Z){c.hide(),u.createDiv({cls:"ai3d-inline-empty",text:ur("codeBlock.unknownPreset",{preset:o.preset})}),ee.destroy(),p=null;return}let X=Z.compute(h,(U=o.params)!=null?U:{});if(!X){c.hide(),u.createDiv({cls:"ai3d-inline-empty",text:ur("codeBlock.presetRequiresModels",{preset:o.preset,min:String(Z.minModels),max:String(Z.maxModels),count:String(h.length)})}),ee.destroy(),p=null;return}await ee.loadWithPreset(X,j)}else await ee.loadModels(h,o,j);if(_){c.hide();return}c.hide()}catch(G){_=!0,x.disconnect(),S.disconnect(),c.hide(),p==null||p.destroy(),p=null,console.error("[AI3D Grid] Failed:",G),u.createDiv({cls:"ai3d-inline-empty",text:ur("codeBlock.gridFailed",{reason:String(G)})})}}}let S=new IntersectionObserver(M=>{for(let D of M)D.isIntersecting&&(S.disconnect(),A())},{rootMargin:"200px"});S.observe(u)})()}}}var cq,uq=C(()=>{"use strict";Io();Ev();ZR();rb();oa();lq();QO();mb();_b();lN();gb();vb();rv();mp();ia();Eb();Ys();Tn();cq=Wi("inline-code-block")});function ov(n){return createDiv().createDiv(n?{cls:n}:void 0)}function PN(n,e){return createDiv().createEl(n,e?{cls:e}:void 0)}var mq=C(()=>{"use strict"});var gq={};tt(gq,{registerLivePreviewExtension:()=>Ape});function pq(n,e,t,i,r,s,a,o,l,c,f,h,d,u,m,p){var v,x;let _="state"in n?n.state.doc:n.doc,g=[];for(let A=1;A<=_.lines;A++){let S=_.line(A),E=S.text;if(!E.includes("!["))continue;let R=0;for(;R0&&E[I-1]==="\\"){R=I+3;continue}let y=E.indexOf("]]",I+3);if(y===-1)break;let D=E.slice(I+3,y).split("|"),O=D[0].trim(),V=(x=(v=O.split(".").pop())==null?void 0:v.toLowerCase())!=null?x:"";if(!_l(V)){R=y+2;continue}let N=400,F=300;if(D.length>1){let j=D[1].trim().match(/^(\d+)\s*x\s*(\d+)$/);j&&(N=parseInt(j[1],10),F=parseInt(j[2],10))}let U=Fd(e,O);if(!U){R=y+2;continue}let G=S.from+I,ee=S.from+y+2;g.push(Sp.Decoration.replace({widget:new DN(e,U,N,F,t,i,r,s,a,o,l,c,f,h,d,u,m,p),block:!0}).range(G,ee)),R=y+2}}return g}function _q(n){return n.length===0?bd.RangeSet.empty:bd.RangeSet.of(n,!0)}function Ape(n,e,t,i){let r=bd.StateField.define({create(s){let a=e(),o=pq(s,n,a.autoRotateDefault,a.enabledConverterIds,a.freecadCommand,a.obj2gltfCommand,a.fbx2gltfCommand,a.freecadcmdCommand,a.preferObj2gltfForObj,a.preferFbx2gltfForFbx,a.annotationPreviewMode,a.annotationDisplayMode,a.previewRendererRollout,a.useThreeRenderer,t,i);return _q(o)},update(s,a){if(a.docChanged){let o=e(),l=pq(a.state,n,o.autoRotateDefault,o.enabledConverterIds,o.freecadCommand,o.obj2gltfCommand,o.fbx2gltfCommand,o.freecadcmdCommand,o.preferObj2gltfForObj,o.preferFbx2gltfForFbx,o.annotationPreviewMode,o.annotationDisplayMode,o.previewRendererRollout,o.useThreeRenderer,t,i);return _q(l)}return s.map(a.changes)},provide:s=>Sp.EditorView.decorations.from(s)});return[bd.Prec.highest(r)]}var Sp,bd,Tpe,DN,vq=C(()=>{"use strict";Sp=require("@codemirror/view"),bd=require("@codemirror/state");Io();Ev();ZR();rb();oa();mb();_b();gb();vb();rv();mq();mp();Ys();Eb();ia();Tn();Tpe=Wi("inline-live-preview"),DN=class extends Sp.WidgetType{constructor(t,i,r,s,a,o,l,c,f,h,d,u,m,p,_,g,v,x){super();this.app=t;this.modelPath=i;this.width=r;this.height=s;this.autoRotate=a;this.enabledConverterIds=o;this.freecadCommand=l;this.obj2gltfCommand=c;this.fbx2gltfCommand=f;this.freecadcmdCommand=h;this.preferObj2gltfForObj=d;this.preferFbx2gltfForFbx=u;this.annotationPreviewMode=m;this.annotationDisplayMode=p;this.previewRendererRollout=_;this.useThreeRenderer=g;this.convertedAssetCache=v;this.getAnnotations=x;this.preview=null;this.annotationMgr=null;this.readyObs=null;this.pollId=0;this.initStarted=!1;this.destroyed=!1;this.initGeneration=0}eq(t){return this.modelPath===t.modelPath&&this.width===t.width&&this.height===t.height&&this.autoRotate===t.autoRotate&&this.enabledConverterIds.join("|")===t.enabledConverterIds.join("|")&&this.freecadCommand===t.freecadCommand&&this.obj2gltfCommand===t.obj2gltfCommand&&this.fbx2gltfCommand===t.fbx2gltfCommand&&this.freecadcmdCommand===t.freecadcmdCommand&&this.preferObj2gltfForObj===t.preferObj2gltfForObj&&this.preferFbx2gltfForFbx===t.preferFbx2gltfForFbx&&this.annotationPreviewMode===t.annotationPreviewMode&&this.annotationDisplayMode===t.annotationDisplayMode&&this.previewRendererRollout===t.previewRendererRollout&&this.convertedAssetCache===t.convertedAssetCache}toDOM(){let t=mr(),i=ov("ai3d-embed-preview ai3d-cm-widget");i.setAttribute("contenteditable","false"),t&&i.classList.add("is-mobile","is-mobile-scroll-mode");let r=PN("canvas","ai3d-embed-canvas"),s=t?Math.min(this.height,220):this.height;r.style.setProperty("--ai3d-embed-height",`${s}px`),i.appendChild(r);let a=Td(i),o=ov("ai3d-embed-error is-hidden");if(i.appendChild(o),t){let h=!1,d=ov("ai3d-mobile-mode-bar"),u=ov("ai3d-mobile-mode-hint");u.textContent=J("livePreview.mobileHint");let m=PN("button","ai3d-mobile-mode-btn");m.type="button";let p=()=>{i.classList.toggle("is-mobile-interactive",h),i.classList.toggle("is-mobile-scroll-mode",!h),m.textContent=h?J("helper.scrollAction"):J("helper.interactAction"),m.classList.toggle("ai3d-btn-active",h),m.setAttribute("aria-label",h?J("helper.disableInteractionLabel"):J("helper.enableInteractionLabel"))};m.addEventListener("click",()=>{h=!h,p()}),p(),d.append(u,m),i.appendChild(d)}let l=()=>{this.destroyed||this.initStarted||!i.isConnected||r.clientWidth<=0||r.clientHeight<=0||(this.initStarted=!0,this.stopReadyWatch(),this.initPreview(i,r,a,o,++this.initGeneration))};this.readyObs=new ResizeObserver(()=>l()),this.readyObs.observe(i),this.readyObs.observe(r);let c=0,f=()=>{this.destroyed||this.initStarted||(l(),!this.initStarted&&(++c>240||(this.pollId=window.requestAnimationFrame(f))))};return this.pollId=window.requestAnimationFrame(f),i}async initPreview(t,i,r,s,a){var o,l,c,f,h,d;try{let u=(o=eh(this.app,this.modelPath))!=null?o:void 0,m=gd({enabledConverterIds:this.enabledConverterIds,freecadCommand:this.freecadCommand,obj2gltfCommand:this.obj2gltfCommand,fbx2gltfCommand:this.fbx2gltfCommand,freecadcmdCommand:this.freecadcmdCommand});r.setPhaseKey("loading.preparingModel");let p=await Ed({path:this.modelPath,absolutePath:u,preferConversionExts:Sd({preferObj2gltfForObj:this.preferObj2gltfForObj,preferFbx2gltfForFbx:this.preferFbx2gltfForFbx}),conversionManager:m,convertedAssetCache:this.convertedAssetCache}),_=(c=(l=this.getAnnotations)==null?void 0:l.call(this,this.modelPath))!=null?c:[],g={ext:p.effectiveExt,annotationMode:_.length>0?"readonly":"none",rendererRollout:this.previewRendererRollout,useThreeRenderer:this.useThreeRenderer},{preview:v}=await _d(Tpe,{surface:"live-preview",modelPath:this.modelPath},i,g);if(this.destroyed||a!==this.initGeneration){v.destroy();return}this.preview=v,r.setPhaseKey("loading.loadingModel");let x=await Ua(this.app,p.effectivePath);if(this.destroyed||a!==this.initGeneration){(f=this.preview)==null||f.destroy(),this.preview=null;return}let A=await this.preview.loadModel(x,p.effectiveExt,S=>Ua(this.app,S),p.effectivePath);if(this.destroyed||a!==this.initGeneration){(h=this.preview)==null||h.destroy(),this.preview=null;return}if(gp(t,A),this.autoRotate&&this.preview.applyConfig({models:[],scene:{autoRotate:!0,autoRotateSpeed:.5}}),_.length>0&&eb(this.preview)){let S=this.preview.getAnnotationProvider();S.canvas&&(this.annotationMgr=new wc(S,t,"readonly",_,void 0,pp(this.app),void 0,{app:this.app,previewMode:this.annotationPreviewMode,displayMode:this.annotationDisplayMode}))}r.setProgress(100),r.hide()}catch(u){if(this.destroyed||a!==this.initGeneration)return;(d=this.preview)==null||d.destroy(),this.preview=null,r.hide(),s.remove(),t.replaceChildren();let m=up(u);dp(u)?console.warn("[AI3D] Live Preview blocked by converter settings:",m.message):console.error("[AI3D] Live Preview failed:",u),_p(t,m)}}destroy(){var t;this.destroyed=!0,window.cancelAnimationFrame(this.pollId),this.pollId=0,this.stopReadyWatch(),(t=this.annotationMgr)==null||t.destroy(),this.annotationMgr=null,this.preview&&(this.preview.destroy(),this.preview=null),this.initStarted=!1}stopReadyWatch(){var t;(t=this.readyObs)==null||t.disconnect(),this.readyObs=null}ignoreEvent(){return!0}}});var Sq={};tt(Sq,{buildDiagnosticsReport:()=>bpe});function yb(n){return typeof n=="boolean"?n?"on":"off":typeof n=="number"?Number.isFinite(n)?String(n):"unknown":typeof n=="string"?n.length>0?n:"empty":"unknown"}function lv(n){return n?`set (${n})`:"not set"}function xpe(n){let e=n.settings;return e.analysisMode==="local"?"local only":[e.analysisMode,e.serviceBaseUrl.trim()?"service configured":"service missing",`geometry ${yb(e.sendGeometrySummaryToRemote)}`,`preview refs ${yb(e.sendPreviewImagesToRemote)}`,`raw model ${e.sendRawModelToRemote?"blocked if requested":"off"}`].join(", ")}function Rpe(n){let e=n.currentModelPath;return e?n.modelAssetProfiles[e]:void 0}function bpe(n){var o,l,c,f,h,d,u,m,p,_;let{manifest:e,state:t}=n,i=t.settings,r=Rpe(t),s=t.currentModelPath?kd({ext:(o=t.currentModelPath.split(".").pop())!=null?o:"",annotationMode:r!=null&&r.annotations.length?"readonly":"none",allowEditModeOnThree:!0,allowWorkbenchFeaturesOnThree:i.experimentalThreeWorkbench,rendererRollout:i.previewRendererRollout,useThreeRenderer:i.useThreeRenderer}):null,a=t.lastKnowledgeGeneration;return["# AI Model Workbench Diagnostics","",`Generated: ${(l=n.generatedAt)!=null?l:new Date().toISOString()}`,"","## Runtime","",`- Plugin version: ${e.version}`,`- Minimum Obsidian version: ${e.minAppVersion}`,`- Obsidian API version: ${Eq.apiVersion}`,`- Platform: ${mr()?"mobile":"desktop"}`,`- Locale: ${i.locale}`,"","## Renderer","",`- Use Three renderer: ${yb(i.useThreeRenderer)}`,`- Preview rollout: ${i.previewRendererRollout}`,`- Experimental Three workbench: ${yb(i.experimentalThreeWorkbench)}`,`- Current route: ${s?`${s.backend} (${s.reason})`:"no current model"}`,`- Render quality: ${i.renderQuality}`,`- Render scale: ${i.renderScale}`,"","## Current Model","",`- Path: ${(c=t.currentModelPath)!=null?c:"none"}`,`- Preview summary: ${t.modelPreview?`${t.modelPreview.meshCount} mesh(es), ${t.modelPreview.triangleCount.toLocaleString()} triangle(s), ${t.modelPreview.materialCount} material(s)`:"not captured"}`,`- Annotation count: ${(f=r==null?void 0:r.annotations.length)!=null?f:0}`,`- Registered part candidates: ${(d=(h=r==null?void 0:r.registeredParts)==null?void 0:h.length)!=null?d:0}`,`- Report note: ${lv(r==null?void 0:r.reportNotePath)}`,`- Analysis sidecar: ${lv(r==null?void 0:r.analysisSidecarPath)}`,`- Knowledge index: ${lv(r==null?void 0:r.knowledgeIndexPath)}`,"","## Knowledge Generation","",`- Mode: ${xpe(t)}`,`- Report folder: ${i.reportFolder}`,`- Part notes folder: ${i.partFolder}`,`- Snapshot folder: ${i.previewFolder}`,`- Last generation: ${a?`${a.status} at ${a.generatedAt}`:"none"}`,`- Last generated model: ${(u=a==null?void 0:a.modelPath)!=null?u:"none"}`,`- Last report: ${lv(a==null?void 0:a.reportNotePath)}`,`- Last index: ${lv(a==null?void 0:a.knowledgeIndexPath)}`,`- Last part notes: ${(m=a==null?void 0:a.partNoteCount)!=null?m:0}`,`- Last preview images: ${(p=a==null?void 0:a.previewImageCount)!=null?p:0}`,`- Last warning count: ${(_=a==null?void 0:a.warningCount)!=null?_:0}`,"","## Conversion","",`- Enabled converters: ${i.enabledConverterIds.length?i.enabledConverterIds.join(", "):"none"}`,`- Cached conversions: ${t.convertedAssetRecords.length}`,`- Supported direct/model extensions: ${gl().join(", ")}`,"","## Notes","","- Draft service URL and command paths are intentionally omitted from this report.","- Attach this report with the model format, console error, and reproduction steps when filing a bug.",""].join(` +`)}var Eq,Tq=C(()=>{"use strict";Eq=require("obsidian");Io();Sv();Ys()});var Ipe={};tt(Ipe,{default:()=>Pb});module.exports=Nq(Ipe);var Ls=require("obsidian");Nb();Io();Io();var Dpe=new Set(gl());var Lc={analysisMode:"local",serviceBaseUrl:"",copySourceModelToVault:!1,sourceModelFolder:"Assets/3D",reportFolder:"Analysis/3D Reports",partFolder:"Parts/3D Components",previewFolder:"Media/3D Previews",maxFileSizeMb:50,autoGenerateKnowledgeNotes:!0,annotationPreviewMode:"plain-text",annotationDisplayMode:"surface",previewRendererRollout:"three-direct-glb",useThreeRenderer:!0,experimentalThreeWorkbench:!1,sendRawModelToRemote:!1,sendPreviewImagesToRemote:!1,sendGeometrySummaryToRemote:!1,defaultKnowledgeTaxonomy:"default-v1",defaultCanvasHeight:400,autoRotateDefault:!1,autoRotateSpeed:.5,renderQuality:"high",renderScale:1,snapshotFolder:"Media/3D Previews",snapshotNaming:"model-name",enabledConverterIds:[],freecadCommand:"",obj2gltfCommand:"",fbx2gltfCommand:"",assimpCommand:"",freecadcmdCommand:"",preferObj2gltfForObj:!1,preferFbx2gltfForFbx:!1,logLevel:"warn",locale:"en"};function kN(n){let e={...n},t=new Set;return{getState:()=>e,setState(i){e={...e,...i};let r=[...t];for(let s of r)s()},subscribe(i){return t.add(i),()=>{t.delete(i)}}}}var Uq={settings:{...Lc},currentModelPath:null,convertedAssetRecords:[],modelAssetProfiles:{},agentDraft:"",agentPlan:null,modelPreview:null,selectedPart:null,lastKnowledgeGeneration:null};function HN(n){let e=kN(Uq),t=null;function i(){t&&window.clearTimeout(t),t=window.setTimeout(()=>{t=null,r().catch(a=>console.error("[AI3D] Auto-save failed:",a))},500)}async function r(){let a=e.getState(),o={settings:a.settings,convertedAssetRecords:a.convertedAssetRecords,modelAssetProfiles:a.modelAssetProfiles,agentDraft:a.agentDraft,agentPlan:a.agentPlan,lastKnowledgeGeneration:a.lastKnowledgeGeneration};await n.saveData(o)}e.subscribe(()=>i());let s=!1;return{store:e,get localeLoadedFromSaved(){return s},async load(){var o,l,c,f,h;let a=await n.loadData();a&&(s=!!((o=a.settings)!=null&&o.locale),e.setState({settings:{...Lc,...(l=a.settings)!=null?l:{}},convertedAssetRecords:(c=a.convertedAssetRecords)!=null?c:[],modelAssetProfiles:Vq(a.modelAssetProfiles),agentDraft:(f=a.agentDraft)!=null?f:"",agentPlan:(h=a.agentPlan)!=null?h:null,lastKnowledgeGeneration:kq(a.lastKnowledgeGeneration)}))},async save(){t&&(window.clearTimeout(t),t=null),await r()},dispose(){t&&(window.clearTimeout(t),t=null),r().catch(a=>console.error("[AI3D] Final save on dispose failed:",a))}}}function Vq(n){if(!n||typeof n!="object")return{};let e={};for(let[t,i]of Object.entries(n)){if(!i||typeof i!="object")continue;let r=new Date().toISOString();e[t]={tags:Array.isArray(i.tags)?i.tags:[],notes:typeof i.notes=="string"?i.notes:"",annotations:Array.isArray(i.annotations)?i.annotations:[],registeredParts:Gq(i.registeredParts,t),analysisVersion:typeof i.analysisVersion=="string"?i.analysisVersion:void 0,reportNotePath:typeof i.reportNotePath=="string"?i.reportNotePath:void 0,analysisSidecarPath:typeof i.analysisSidecarPath=="string"?i.analysisSidecarPath:void 0,previewImagePaths:Array.isArray(i.previewImagePaths)?i.previewImagePaths.filter(s=>typeof s=="string"):void 0,knowledgeIndexPath:typeof i.knowledgeIndexPath=="string"?i.knowledgeIndexPath:void 0,createdAt:typeof i.createdAt=="string"?i.createdAt:r,updatedAt:typeof i.updatedAt=="string"?i.updatedAt:r}}return e}function xp(n){return Array.isArray(n)?n.filter(e=>typeof e=="string"&&e.trim().length>0):[]}function WN(n){if(!Array.isArray(n)||n.length<3)return;let e=n.slice(0,3).map(t=>Number(t));return e.every(Number.isFinite)?[e[0],e[1],e[2]]:void 0}function Gq(n,e){if(!Array.isArray(n))return;let t=[],i=new Set;for(let r of n){if(!r||typeof r!="object")continue;let s=r,a=typeof s.partId=="string"?s.partId:"",o=typeof s.name=="string"?s.name:"";if(!a||!o)continue;let l=typeof s.assetId=="string"&&s.assetId?s.assetId:e,c=`${l}:${a}`;i.has(c)||(i.add(c),t.push({partId:a,assetId:l,parentPartId:typeof s.parentPartId=="string"?s.parentPartId:void 0,name:o,source:s.source==="group"||s.source==="mesh"||s.source==="component"?s.source:void 0,componentId:typeof s.componentId=="string"?s.componentId:void 0,occurrenceId:typeof s.occurrenceId=="string"?s.occurrenceId:void 0,partNumber:typeof s.partNumber=="string"?s.partNumber:void 0,componentPath:typeof s.componentPath=="string"?s.componentPath:void 0,category:typeof s.category=="string"?s.category:void 0,meshRefs:xp(s.meshRefs),childCount:Number.isFinite(s.childCount)?Math.max(0,Math.floor(Number(s.childCount))):void 0,materialRefs:xp(s.materialRefs),bbox:WN(s.bbox),center:WN(s.center),triangleCount:Number.isFinite(s.triangleCount)?Math.max(0,Math.floor(Number(s.triangleCount))):void 0,vertexCount:Number.isFinite(s.vertexCount)?Math.max(0,Math.floor(Number(s.vertexCount))):void 0,materialName:typeof s.materialName=="string"?s.materialName:null,confidence:Number.isFinite(s.confidence)?Math.max(0,Math.min(1,Number(s.confidence))):.5,observations:xp(s.observations),inferredFunctions:xp(s.inferredFunctions),knowledgeTags:xp(s.knowledgeTags),notePath:typeof s.notePath=="string"?s.notePath:void 0,registeredMatches:Array.isArray(s.registeredMatches)?s.registeredMatches:void 0,reviewed:s.reviewed===!0}))}return t.length>0?t:void 0}function kq(n){if(!n||typeof n!="object")return null;let e=typeof n.modelPath=="string"?n.modelPath:"";return e?{modelPath:e,reportNotePath:typeof n.reportNotePath=="string"?n.reportNotePath:void 0,analysisSidecarPath:typeof n.analysisSidecarPath=="string"?n.analysisSidecarPath:void 0,knowledgeIndexPath:typeof n.knowledgeIndexPath=="string"?n.knowledgeIndexPath:void 0,partNoteCount:Number.isFinite(n.partNoteCount)?Math.max(0,Math.floor(n.partNoteCount)):0,previewImageCount:Number.isFinite(n.previewImageCount)?Math.max(0,Math.floor(n.previewImageCount)):0,generatedAt:typeof n.generatedAt=="string"?n.generatedAt:new Date().toISOString(),status:n.status==="failed"?"failed":"success",warningCount:Number.isFinite(n.warningCount)?Math.max(0,Math.floor(n.warningCount)):0}:null}var Cc=require("obsidian");Ev();ZR();QO();mb();_b();lN();oa();gb();rv();vb();mp();ia();Eb();Ys();Tn();dN();ia();function yme(n){if(!n)return"";let e=n.split("/");return e[e.length-1]||n}function Sj(n,e,t){var o,l;let i=n.createDiv({cls:"ai3d-direct-workbench-match"}),r=i.createDiv({cls:"ai3d-direct-workbench-match-main"});r.createDiv({cls:"ai3d-direct-workbench-match-title",text:e}),r.createDiv({cls:"ai3d-direct-workbench-match-source",text:t.sourcePartName||t.sourcePartId}),t.sourceModelPath&&r.createDiv({cls:"ai3d-direct-workbench-match-model",text:ur("directWorkbench.registeredSourceModel",{model:yme(t.sourceModelPath)})}),r.createDiv({cls:"ai3d-direct-workbench-match-target",text:t.sourceNotePath?J("directWorkbench.registeredTargetPartNote"):t.sourceModelPath?J("directWorkbench.registeredTargetSourceModel"):J("directWorkbench.registeredTargetUnavailable")}),t.reasons.length>0&&r.createDiv({cls:"ai3d-direct-workbench-match-reasons",text:t.reasons.slice(0,2).join(" / ")});let s=i.createDiv({cls:"ai3d-direct-workbench-match-side"});s.createDiv({cls:"ai3d-direct-workbench-match-score",text:`${Math.round(t.matchScore*100)}%`});let a=s.createEl("button",{cls:"ai3d-direct-workbench-action ai3d-direct-workbench-match-open",text:t.sourceNotePath?J("directWorkbench.registeredOpenNote"):J("directWorkbench.registeredOpenModel"),attr:{type:"button","data-ai3d-action":"open-registered-part","data-ai3d-target-path":(l=(o=t.sourceNotePath)!=null?o:t.sourceModelPath)!=null?l:""}});return a.disabled=!t.sourceNotePath&&!t.sourceModelPath,i}var Ib="ai3d-direct-view",AN=Wi("direct-view"),Yj=new Set(["glb","gltf"]);function Kj(){return{tags:[],notes:"",annotations:[],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}}function fpe(n,e){return n.experimentalThreeWorkbench&&n.useThreeRenderer&&e.strategy==="direct"&&Yj.has(e.ext)&&Yj.has(e.sourceExt)}function Rb(n){return Math.round(n!=null?n:0).toLocaleString()}function hpe(n){return[n.boundingSize.x,n.boundingSize.y,n.boundingSize.z].map(e=>e.toFixed(2)).join(" x ")}function dpe(n){return n==="three"?"Three.js":"Babylon.js"}function upe(n){return n instanceof Error&&n.message.includes("Missing external model resource:")}function jj(n){var i,r,s;let e=(r=(i=n.occurrenceId)!=null?i:n.componentId)!=null?r:n.partNumber;if(e!=null&&e.trim())return`component:${e.trim().toLowerCase()}`;let t=n.meshRefs.map(a=>a.trim().toLowerCase()).filter(Boolean).sort().join("|");return`${(s=n.source)!=null?s:"mesh"}:${n.name.trim().toLowerCase()}:${t}`}function mpe(n,e){return n?{...e,notePath:n.notePath,reviewed:n.reviewed,inferredFunctions:n.inferredFunctions.length>0?n.inferredFunctions:e.inferredFunctions,knowledgeTags:n.knowledgeTags.length>0?n.knowledgeTags:e.knowledgeTags}:e}var bb=class extends Cc.FileView{constructor(t,i,r,s){super(t);this.preview=null;this.annotationMgr=null;this.annotationMode=!1;this.loadGeneration=0;this.escHandler=null;this.workbenchPanel=null;this.workbenchSummary=null;this.workbenchRoute=null;this.workbenchModelPath=null;this.sidebarContent=null;this.getSettings=i,this.convertedAssetCache=r,this.ps=s}getViewType(){return Ib}getDisplayText(){var t,i;return(i=(t=this.file)==null?void 0:t.name)!=null?i:J("workbench.modelTitle")}getIcon(){return"box"}async onOpen(){this.contentEl.empty(),this.contentEl.addClass("ai3d-direct-view"),this.file&&await this.loadModel(this.file)}async onLoadFile(t){this.contentEl.empty(),await this.loadModel(t)}onClose(){var t,i;return this.escHandler&&(activeDocument.removeEventListener("keydown",this.escHandler),this.escHandler=null),(t=this.annotationMgr)==null||t.destroy(),this.annotationMgr=null,(i=this.preview)==null||i.destroy(),this.preview=null,Promise.resolve()}async loadModel(t){var A,S,E,R,I,y,M,D,O;let i=++this.loadGeneration,r=mr();(A=this.annotationMgr)==null||A.destroy(),this.annotationMgr=null,this.workbenchPanel=null,this.workbenchSummary=null,this.workbenchRoute=null,this.workbenchModelPath=null,this.sidebarContent=null,(S=this.preview)==null||S.destroy(),this.preview=null,this.ps.store.setState({currentModelPath:t.path,modelPreview:null,selectedPart:null});let s=this.contentEl.createDiv({cls:"ai3d-workspace"}),a=s.createDiv({cls:"ai3d-workspace-track-top"}),o=a.createDiv({cls:"ai3d-workspace-main"}),l=a.createDiv({cls:"ai3d-resize-handle ai3d-resize-handle-h"}),c=a.createDiv({cls:"ai3d-workspace-sidebar"}),f=createDiv(),h=f.createDiv({cls:"ai3d-preview-host"}),d=f.createEl("canvas");d.className="ai3d-canvas-full",h.appendChild(d);let u=f.createDiv();u.className="ai3d-annot-mode-overlay is-hidden",h.appendChild(u),o.appendChild(h);let m=null,p=V=>{var N;this.annotationMode=V,r&&V&&(m==null||m.setMobileInteractionMode(!0)),(N=this.annotationMgr)==null||N.hideEditor(),u.classList.toggle("is-hidden",!V)};this.escHandler&&activeDocument.removeEventListener("keydown",this.escHandler),this.escHandler=V=>{V.key==="Escape"&&this.annotationMode&&p(!1)},activeDocument.addEventListener("keydown",this.escHandler),m=$g(o,h,this.app,()=>this.preview,()=>t.path,()=>{this.leaf.detach()},this.getSettings,()=>(p(!this.annotationMode),this.annotationMode),V=>{!V&&this.annotationMode&&p(!1)});let _=c.createDiv({cls:"ai3d-sidebar-content"});this.sidebarContent=_;let g=s.createDiv({cls:"ai3d-resize-handle ai3d-resize-handle-v"}),v=s.createDiv({cls:"ai3d-direct-workbench-panel is-hidden"});this.workbenchPanel=v,this.setupResizeHandles(l,g,a,s),r&&o.createDiv({cls:"ai3d-mobile-mode-hint ai3d-mobile-mode-hint--inline",text:J("directView.mobileHint")});let x=Td(h);try{let V=this.getSettings(),N=gd(V),F=(E=eh(this.app,t.path))!=null?E:void 0;x.setPhaseKey("loading.preparingModel");let U=await Ed({path:t.path,absolutePath:F,preferConversionExts:Sd(V),conversionManager:N,convertedAssetCache:this.convertedAssetCache});if(i!==this.loadGeneration){new Cc.Notice(J("directWorkbench.modelLoadInterrupted"));return}let G=tv(U),ee={ext:G.ext,annotationMode:"edit",allowEditModeOnThree:!0,allowWorkbenchFeaturesOnThree:fpe(V,G),requireWorkbenchFeatures:!0,rendererRollout:V.previewRendererRollout,useThreeRenderer:V.useThreeRenderer};m==null||m.syncCapabilities(),x.setPhaseKey("loading.loadingModel");let j=await Ua(this.app,G.path),Z=await this.createPreviewWithFallback(d,j,G,ee,t.path);if(i!==this.loadGeneration){Z.preview.destroy(),new Cc.Notice(J("directWorkbench.modelLoadInterrupted"));return}this.preview=Z.preview,h.dataset.ai3dBackend=Z.route.backend,h.dataset.ai3dRouteReason=Z.route.reason,m==null||m.syncCapabilities();let X=Z.summary,Y=(y=(I=(R=this.preview).getModelEvidence)==null?void 0:I.call(R))!=null?y:null;this.registerModelPartsFromEvidence(t.path,Y),gp(h,X),this.workbenchPanel=v,this.workbenchSummary=X,this.workbenchRoute=Z.route,this.workbenchModelPath=t.path,this.renderWorkbenchPanel(v,X,Z.route,t.path),this.renderSidebarContent(t.path,X),this.ps.store.setState({currentModelPath:t.path,modelPreview:X,selectedPart:null}),AN.info("direct view model loaded",{path:t.path,effectivePath:G.path,effectiveExt:G.ext,strategy:G.strategy,backend:Z.route.backend,routeReason:Z.route.reason,meshCount:X.meshCount,triangleCount:X.triangleCount}),x.setProgress(100);let ue=this.preview.getAnnotationProvider();if(ue.canvas){let Re=this.ps.store.getState().modelAssetProfiles[t.path],Be=(M=Re==null?void 0:Re.annotations)!=null?M:[],ae=pp(this.app),me=pj(this.app);this.annotationMgr=new wc(ue,h,"edit",Be,re=>{var he;let de=this.ps.store.getState().modelAssetProfiles,De=(he=de[t.path])!=null?he:Kj();this.ps.store.setState({modelAssetProfiles:{...de,[t.path]:{...De,annotations:re,updatedAt:new Date().toISOString()}}}),m.updateAnnotationBadge(re.length)},ae,me,{app:this.app,previewMode:this.getSettings().annotationPreviewMode,displayMode:this.getSettings().annotationDisplayMode}),m.showAnnotateButton(),m.updateAnnotationBadge(Be.length),this.preview.onPick(re=>{var Ie,ze;if(!this.annotationMode||!this.annotationMgr)return;let de=re.screenX,De=re.screenY,he=(ze=(Ie=this.preview)==null?void 0:Ie.getPickWorldPoint(re))!=null?ze:null;he&&this.annotationMgr.showEditor(de,De,he)})}x.hide()}catch(V){if(i!==this.loadGeneration)return;x.hide(),(D=this.preview)==null||D.destroy(),this.preview=null,h.replaceChildren(),(O=this.workbenchPanel)==null||O.addClass("is-hidden");let N=up(V);dp(V)?console.warn("[AI3D] Direct view blocked by converter settings:",N.message):console.error("[AI3D] Direct view failed:",V),this.ps.store.getState().currentModelPath===t.path&&this.ps.store.setState({modelPreview:null,selectedPart:null}),_p(h,N)}}registerModelPartsFromEvidence(t,i){var c,f;if(!(i!=null&&i.parts.length))return;let r=hN(t,i.parts);if(r.length===0)return;let s=this.ps.store.getState().modelAssetProfiles,a=(c=s[t])!=null?c:Kj(),o=new Map(((f=a.registeredParts)!=null?f:[]).map(h=>[jj(h),h])),l=r.map(h=>mpe(o.get(jj(h)),h));this.ps.store.setState({modelAssetProfiles:{...s,[t]:{...a,registeredParts:l,updatedAt:new Date().toISOString()}}})}renderWorkbenchPanel(t,i,r,s){var h,d,u,m;t.empty(),t.removeClass("is-hidden"),t.dataset.ai3dBackend=r.backend,t.dataset.ai3dRouteReason=r.reason;let a=t.createDiv({cls:"ai3d-direct-workbench-overview"}),o=a.createDiv({cls:"ai3d-direct-workbench-status"}),l=o.createDiv({cls:"ai3d-direct-workbench-line"});l.createSpan({cls:"ai3d-direct-workbench-label",text:J("directWorkbench.backendLabel")}),l.createSpan({cls:"ai3d-direct-workbench-value",text:dpe(r.backend)});let c=o.createDiv({cls:"ai3d-direct-workbench-line ai3d-direct-workbench-route"});c.createSpan({cls:"ai3d-direct-workbench-label",text:J("directWorkbench.routeLabel")}),c.createSpan({cls:"ai3d-direct-workbench-value",text:r.reason});let f=a.createDiv({cls:"ai3d-direct-workbench-metrics"});this.renderMetric(f,J("workbench.meshesLabel"),Rb(i.meshCount)),this.renderMetric(f,J("directWorkbench.partCandidatesLabel"),Rb((d=(h=this.ps.store.getState().modelAssetProfiles[s])==null?void 0:h.registeredParts)==null?void 0:d.length)),this.renderMetric(f,i.splatCount!==void 0?J("workbench.splatsLabel"):J("workbench.trianglesLabel"),Rb((u=i.splatCount)!=null?u:i.triangleCount)),this.renderMetric(f,J("workbench.materialsLabel"),Rb(i.materialCount)),this.renderMetric(f,J("workbench.boundingSizeLabel"),hpe(i)),this.renderMetric(f,J("directWorkbench.performanceLabel"),(m=i.performanceTier)!=null?m:"light")}renderSidebarContent(t,i){this.sidebarContent&&(this.sidebarContent.empty(),this.renderKnowledgeControls(this.sidebarContent,t),this.renderRegisteredPartMatches(this.sidebarContent,t,i))}refreshWorkbenchPanel(){!this.workbenchPanel||!this.workbenchSummary||!this.workbenchRoute||!this.workbenchModelPath||(this.renderWorkbenchPanel(this.workbenchPanel,this.workbenchSummary,this.workbenchRoute,this.workbenchModelPath),this.renderSidebarContent(this.workbenchModelPath,this.workbenchSummary))}setupResizeHandles(t,i,r,s){let a=(c,f,h)=>{let d=0,u=0,m=_=>{f(_.clientX-d,_.clientY-u),d=_.clientX,u=_.clientY},p=()=>{activeDocument.removeEventListener("mousemove",m),activeDocument.removeEventListener("mouseup",p),h()};c.addEventListener("mousedown",_=>{_.preventDefault(),d=_.clientX,u=_.clientY,activeDocument.addEventListener("mousemove",m),activeDocument.addEventListener("mouseup",p)})},o=200;a(t,c=>{o=Math.max(48,Math.min(400,o-c)),r.style.gridTemplateColumns=`1fr 4px ${o}px`},()=>{});let l=220;a(i,(c,f)=>{l=Math.max(120,Math.min(500,l-f)),s.style.gridTemplateRows=`1fr 4px ${l}px`},()=>{})}renderMetric(t,i,r){let s=t.createDiv({cls:"ai3d-direct-workbench-metric"});s.createSpan({cls:"ai3d-direct-workbench-label",text:i}),s.createSpan({cls:"ai3d-direct-workbench-value",text:r})}renderKnowledgeControls(t,i){let r=this.ps.store.getState().modelAssetProfiles[i],s=t.createDiv({cls:"ai3d-direct-workbench-control ai3d-direct-workbench-knowledge"});s.createDiv({cls:"ai3d-direct-workbench-label",text:J("directWorkbench.knowledgeTitle")}),s.createDiv({cls:"ai3d-direct-workbench-value",text:r!=null&&r.knowledgeIndexPath?J("workbench.indexReady"):r!=null&&r.reportNotePath?J("workbench.noteReady"):J("workbench.noReportYet")});let a=s.createDiv({cls:"ai3d-direct-workbench-actions"}),o=a.createEl("button",{cls:"ai3d-direct-workbench-action",text:J("workbench.generateNoteAction"),attr:{type:"button","data-ai3d-action":"generate-note"}});o.addEventListener("click",()=>{o.disabled=!0,Promise.resolve().then(()=>(xb(),Ab)).then(({generateKnowledgeNote:f})=>f(this.app,this.ps,{preview:this.preview})).catch(f=>{console.error("[AI3D] Generate knowledge note failed:",f)}).finally(()=>{o.disabled=!1,this.refreshWorkbenchPanel()})});let l=a.createEl("button",{cls:"ai3d-direct-workbench-action",text:J("workbench.openNoteAction"),attr:{type:"button","data-ai3d-action":"open-note"}});l.disabled=!(r!=null&&r.reportNotePath),l.addEventListener("click",()=>{var d;let f=(d=this.ps.store.getState().modelAssetProfiles[i])==null?void 0:d.reportNotePath;if(!f)return;let h=this.app.vault.getAbstractFileByPath(f);h instanceof Cc.TFile&&this.app.workspace.getLeaf(!0).openFile(h,{active:!0})});let c=a.createEl("button",{cls:"ai3d-direct-workbench-action",text:J("workbench.openIndexAction"),attr:{type:"button","data-ai3d-action":"open-index"}});c.disabled=!(r!=null&&r.knowledgeIndexPath),c.addEventListener("click",()=>{var d;let f=(d=this.ps.store.getState().modelAssetProfiles[i])==null?void 0:d.knowledgeIndexPath;if(!f)return;let h=this.app.vault.getAbstractFileByPath(f);h instanceof Cc.TFile&&this.app.workspace.getLeaf(!0).openFile(h,{active:!0})})}renderRegisteredPartMatches(t,i,r){var d,u,m;let s=this.loadGeneration,a=t.createDiv({cls:"ai3d-direct-workbench-control ai3d-direct-workbench-registered"}),o=a.createDiv({cls:"ai3d-direct-workbench-control-head"});o.createSpan({cls:"ai3d-direct-workbench-label",text:J("directWorkbench.registeredTitle")});let l=o.createSpan({cls:"ai3d-direct-workbench-value",text:J("directWorkbench.registeredLoading")}),c=a.createDiv({cls:"ai3d-direct-workbench-registered-body"}),f=p=>{l.setText(""),c.empty(),c.createDiv({cls:"ai3d-direct-workbench-empty",text:J(p)})},h=(m=(u=(d=this.preview)==null?void 0:d.getModelEvidence)==null?void 0:u.call(d))!=null?m:null;if(!(h!=null&&h.parts.length)){f("directWorkbench.registeredUnavailable");return}Promise.resolve().then(()=>(xb(),Ab)).then(async({collectRegisteredPartsFromProfiles:p})=>{var E;let _=this.ps.store.getState(),g=await p(this.app,_.modelAssetProfiles,i);if(s!==this.loadGeneration||this.workbenchModelPath!==i||!a.isConnected)return;if(g.length===0){f("directWorkbench.registeredEmpty");return}let v=this.ps.store.getState().modelAssetProfiles[i],A=Tb({modelPath:i,profile:v,preview:r,evidence:h,registeredParts:g}).parts.filter(R=>{var I;return(I=R.registeredMatches)==null?void 0:I.length}).sort((R,I)=>{var y,M,D,O,V,N;return((D=(M=(y=I.registeredMatches)==null?void 0:y[0])==null?void 0:M.matchScore)!=null?D:0)-((N=(V=(O=R.registeredMatches)==null?void 0:O[0])==null?void 0:V.matchScore)!=null?N:0)}).slice(0,5);if(A.length===0){f("directWorkbench.registeredEmpty");return}l.setText(ur("directWorkbench.registeredCount",{count:String(A.length)})),c.empty();let S=c.createDiv({cls:"ai3d-direct-workbench-match-list"});for(let R of A){let I=(E=R.registeredMatches)==null?void 0:E[0];if(!I)continue;let M=Sj(S,R.name,I).querySelector("[data-ai3d-action='open-registered-part']");M instanceof HTMLButtonElement&&M.addEventListener("click",()=>{let D=M.getAttribute("data-ai3d-target-path")||void 0;if(!D)return;let O=this.app.vault.getAbstractFileByPath(D);O instanceof Cc.TFile&&this.app.workspace.getLeaf(!0).openFile(O,{active:!0})})}}).catch(p=>{console.warn("[AI3D] Registered part match preview failed:",p),s===this.loadGeneration&&this.workbenchModelPath===i&&a.isConnected&&f("directWorkbench.registeredUnavailable")})}async createPreviewWithFallback(t,i,r,s,a){let o=await _d(AN,{surface:"direct-view",modelPath:a},t,s);try{let l=await o.preview.loadModel(i.slice(0),r.ext,c=>Ua(this.app,c),r.path);return{preview:o.preview,summary:l,route:o.route}}catch(l){if(o.preview.destroy(),o.route.backend!=="three"||!s.allowWorkbenchFeaturesOnThree)throw l;console.warn("[AI3D] Experimental Three workbench failed; falling back to Babylon:",l);let c={...s,allowWorkbenchFeaturesOnThree:!1},f=await _d(AN,{surface:"direct-view-fallback",modelPath:a},t,c);try{let h=await f.preview.loadModel(i.slice(0),r.ext,d=>Ua(this.app,d),r.path);return{preview:f.preview,summary:h,route:f.route}}catch(h){throw f.preview.destroy(),upe(l)?l:h}}}};var qj=require("obsidian");Io();ia();var Mb=class extends qj.FuzzySuggestModal{constructor(e,t){super(e),this.onChoose=t,this.setPlaceholder(J("modal.selectModel"))}getItems(){return this.app.vault.getFiles().filter(e=>{let t=e.extension.toLowerCase();return _l(t)})}getItemText(e){return e.path}onChooseItem(e){this.onChoose(e)}};var Qt=require("obsidian");$f();ia();Ys();or();var xN=uv();function ppe(){switch(xN==null?void 0:xN.platform){case"win32":return{python:"Path to python executable",freecad:"Path to FreeCADCmd.exe",obj2gltf:"Path to obj2gltf.cmd",fbx2gltf:"Path to FBX2glTF.exe"};case"darwin":return{python:"Path to python3",freecad:"Path to FreeCADCmd",obj2gltf:"Path to obj2gltf",fbx2gltf:"Path to FBX2glTF"};case"linux":return{python:"Path to python3",freecad:"Path to freecadcmd",obj2gltf:"Path to obj2gltf",fbx2gltf:"Path to FBX2glTF"};default:return{python:"Path to python executable",freecad:"Path to FreeCAD command",obj2gltf:"Path to obj2gltf",fbx2gltf:"Path to FBX2glTF"}}}var Cb=class extends Qt.PluginSettingTab{constructor(t,i){super(t,i);this.diagnosticsRunId=0;this.plugin=i}display(){let{containerEl:t}=this;t.empty(),Rp(this.plugin.getSettings().locale);let i=ppe(),r=mr(),s=null,a=(l,c,f)=>{let h=l.createEl("details",{cls:"ai3d-settings-secondary-menu"});h.createEl("summary",{cls:"ai3d-settings-secondary-menu-summary",text:c});let d=h.createDiv({cls:"ai3d-settings-secondary-menu-body"});return d.createEl("p",{cls:"setting-item-description",text:f}),d},o=()=>{s&&(this.diagnosticsRunId++,s.empty(),s.createEl("p",{text:J("settings.diagnostics.idle")}))};if(new Qt.Setting(t).setName(J("settings.title")).setHeading(),new Qt.Setting(t).setName(J("settings.language")).setDesc(J("settings.language.desc")).addDropdown(l=>l.addOption("en","English").addOption("zh-CN","\u7B80\u4F53\u4E2D\u6587").setValue(this.plugin.getSettings().locale).onChange(c=>{this.plugin.updateSettings({locale:c}),this.display()})),new Qt.Setting(t).setName(J("settings.folders")).setHeading(),new Qt.Setting(t).setName(J("settings.sourceModelFolder")).setDesc(J("settings.sourceModelFolder.desc")).addText(l=>l.setPlaceholder(Lc.sourceModelFolder).setValue(this.plugin.getSettings().sourceModelFolder).onChange(c=>{this.plugin.updateSettings({sourceModelFolder:c})})),new Qt.Setting(t).setName(J("settings.reportFolder")).setDesc(J("settings.reportFolder.desc")).addText(l=>l.setPlaceholder(Lc.reportFolder).setValue(this.plugin.getSettings().reportFolder).onChange(c=>{this.plugin.updateSettings({reportFolder:c})})),new Qt.Setting(t).setName(J("settings.partFolder")).setDesc(J("settings.partFolder.desc")).addText(l=>l.setPlaceholder(Lc.partFolder).setValue(this.plugin.getSettings().partFolder).onChange(c=>{this.plugin.updateSettings({partFolder:c})})),new Qt.Setting(t).setName(J("settings.snapshotFolder")).setDesc(J("settings.snapshotFolder.desc")).addText(l=>l.setPlaceholder(Lc.snapshotFolder).setValue(this.plugin.getSettings().snapshotFolder).onChange(c=>{this.plugin.updateSettings({snapshotFolder:c})})),new Qt.Setting(t).setName(J("settings.behavior")).setHeading(),new Qt.Setting(t).setName(J("settings.autoGenerateKnowledgeNotes")).setDesc(J("settings.autoGenerateKnowledgeNotes.desc")).addToggle(l=>l.setValue(this.plugin.getSettings().autoGenerateKnowledgeNotes).onChange(c=>{this.plugin.updateSettings({autoGenerateKnowledgeNotes:c})})),new Qt.Setting(t).setName(J("settings.annotationPreviewMode")).setDesc(J("settings.annotationPreviewMode.desc")).addDropdown(l=>l.addOption("plain-text",J("settings.annotationPreviewMode.plainText")).addOption("markdown",J("settings.annotationPreviewMode.markdown")).setValue(this.plugin.getSettings().annotationPreviewMode).onChange(c=>{this.plugin.updateSettings({annotationPreviewMode:c})})),new Qt.Setting(t).setName(J("settings.annotationDisplayMode")).setDesc(J("settings.annotationDisplayMode.desc")).addDropdown(l=>l.addOption("snippet",J("settings.annotationDisplayMode.snippet")).addOption("surface",J("settings.annotationDisplayMode.surface")).addOption("dot",J("settings.annotationDisplayMode.dot")).setValue(this.plugin.getSettings().annotationDisplayMode).onChange(c=>{this.plugin.updateSettings({annotationDisplayMode:c})})),new Qt.Setting(t).setName(J("settings.previewRendererRollout")).setDesc(J("settings.previewRendererRollout.desc")).addDropdown(l=>l.addOption("babylon-safe",J("settings.previewRendererRollout.babylonSafe")).addOption("three-readonly-glb",J("settings.previewRendererRollout.readonly")).addOption("three-direct-glb",J("settings.previewRendererRollout.direct")).setValue(this.plugin.getSettings().previewRendererRollout).onChange(c=>{this.plugin.updateSettings({previewRendererRollout:c})})),new Qt.Setting(t).setName(J("settings.useThreeRenderer")).setDesc(J("settings.useThreeRenderer.desc")).addToggle(l=>l.setValue(this.plugin.getSettings().useThreeRenderer).onChange(c=>{this.plugin.updateSettings({useThreeRenderer:c})})),new Qt.Setting(t).setName(J("settings.experimentalThreeWorkbench")).setDesc(J("settings.experimentalThreeWorkbench.desc")).addToggle(l=>l.setValue(this.plugin.getSettings().experimentalThreeWorkbench).onChange(c=>{this.plugin.updateSettings({experimentalThreeWorkbench:c})})),new Qt.Setting(t).setName(J("settings.autoRotateDefault")).setDesc(J("settings.autoRotateDefault.desc")).addToggle(l=>l.setValue(this.plugin.getSettings().autoRotateDefault).onChange(c=>{this.plugin.updateSettings({autoRotateDefault:c})})),new Qt.Setting(t).setName(J("settings.snapshotNaming")).setDesc(J("settings.snapshotNaming.desc")).addDropdown(l=>l.addOption("model-name",J("settings.snapshotNaming.modelName")).addOption("timestamp",J("settings.snapshotNaming.timestamp")).setValue(this.plugin.getSettings().snapshotNaming).onChange(c=>{this.plugin.updateSettings({snapshotNaming:c})})),new Qt.Setting(t).setName(J("settings.logLevel")).setDesc(J("settings.logLevel.desc")).addDropdown(l=>l.addOption("debug","Debug").addOption("info","Info").addOption("warn","Warn").addOption("error","Error").setValue(this.plugin.getSettings().logLevel).onChange(c=>{this.plugin.updateSettings({logLevel:c})})),new Qt.Setting(t).setName(J("settings.knowledgeGeneration")).setHeading(),new Qt.Setting(t).setName(J("settings.analysisMode")).setDesc(J("settings.analysisMode.desc")).addDropdown(l=>l.addOption("local",J("settings.analysisMode.local")).addOption("hybrid",J("settings.analysisMode.hybrid")).addOption("remote",J("settings.analysisMode.remote")).setValue(this.plugin.getSettings().analysisMode).onChange(c=>{this.plugin.updateSettings({analysisMode:c})})),new Qt.Setting(t).setName(J("settings.serviceBaseUrl")).setDesc(J("settings.serviceBaseUrl.desc")).addText(l=>l.setPlaceholder("Local draft service URL").setValue(this.plugin.getSettings().serviceBaseUrl).onChange(c=>{this.plugin.updateSettings({serviceBaseUrl:c.trim()})})),new Qt.Setting(t).setName(J("settings.sendGeometrySummaryToRemote")).setDesc(J("settings.sendGeometrySummaryToRemote.desc")).addToggle(l=>l.setValue(this.plugin.getSettings().sendGeometrySummaryToRemote).onChange(c=>{this.plugin.updateSettings({sendGeometrySummaryToRemote:c})})),new Qt.Setting(t).setName(J("settings.sendPreviewImagesToRemote")).setDesc(J("settings.sendPreviewImagesToRemote.desc")).addToggle(l=>l.setValue(this.plugin.getSettings().sendPreviewImagesToRemote).onChange(c=>{this.plugin.updateSettings({sendPreviewImagesToRemote:c})})),new Qt.Setting(t).setName(J("settings.sendRawModelToRemote")).setDesc(J("settings.sendRawModelToRemote.desc")).addToggle(l=>l.setValue(this.plugin.getSettings().sendRawModelToRemote).onChange(c=>{this.plugin.updateSettings({sendRawModelToRemote:c})})),new Qt.Setting(t).setName(J("settings.converters")).setHeading(),r)t.createEl("p",{cls:"setting-item-description",text:J("settings.mobileSupport.desc")});else{let l=a(t,J("settings.converterMenu"),J("settings.converterMenu.desc"));new Qt.Setting(l).setName(J("settings.enableCad")).setDesc(J("settings.enableCad.desc")).addToggle(h=>{let d=this.plugin.getSettings().enabledConverterIds.includes("freecad");return h.setValue(d).onChange(u=>{let m=this.plugin.getSettings().enabledConverterIds,p=u?Array.from(new Set([...m,"freecad"])):m.filter(_=>_!=="freecad");this.plugin.updateSettings({enabledConverterIds:p})})}),new Qt.Setting(l).setName(J("settings.enableObj2gltf")).setDesc(J("settings.enableObj2gltf.desc")).addToggle(h=>{let d=this.plugin.getSettings().enabledConverterIds.includes("obj2gltf");return h.setValue(d).onChange(u=>{let m=this.plugin.getSettings().enabledConverterIds,p=u?Array.from(new Set([...m,"obj2gltf"])):m.filter(_=>_!=="obj2gltf");this.plugin.updateSettings({enabledConverterIds:p})})}),new Qt.Setting(l).setName(J("settings.preferObj2gltf")).setDesc(J("settings.preferObj2gltf.desc")).addToggle(h=>h.setValue(this.plugin.getSettings().preferObj2gltfForObj).onChange(d=>{this.plugin.updateSettings({preferObj2gltfForObj:d})})),new Qt.Setting(l).setName(J("settings.enableFbx2gltf")).setDesc(J("settings.enableFbx2gltf.desc")).addToggle(h=>{let d=this.plugin.getSettings().enabledConverterIds.includes("fbx2gltf");return h.setValue(d).onChange(u=>{let m=this.plugin.getSettings().enabledConverterIds,p=u?Array.from(new Set([...m,"fbx2gltf"])):m.filter(_=>_!=="fbx2gltf");this.plugin.updateSettings({enabledConverterIds:p})})}),new Qt.Setting(l).setName(J("settings.enableMesh")).setDesc(J("settings.enableMesh.desc")).addToggle(h=>{let d=this.plugin.getSettings().enabledConverterIds.includes("assimp");return h.setValue(d).onChange(u=>{let m=this.plugin.getSettings().enabledConverterIds,p=u?Array.from(new Set([...m,"assimp"])):m.filter(_=>_!=="assimp");this.plugin.updateSettings({enabledConverterIds:p})})}),new Qt.Setting(l).setName(J("settings.enableSldprt")).setDesc(J("settings.enableSldprt.desc")).addToggle(h=>{let d=this.plugin.getSettings().enabledConverterIds.includes("sldprt");return h.setValue(d).onChange(u=>{let m=this.plugin.getSettings().enabledConverterIds,p=u?Array.from(new Set([...m,"sldprt"])):m.filter(_=>_!=="sldprt");this.plugin.updateSettings({enabledConverterIds:p})})});let c=a(t,J("settings.environmentInspector"),J("settings.environmentInspector.desc"));new Qt.Setting(c).setName(J("settings.paths")).setHeading(),new Qt.Setting(c).setName(J("settings.pythonCmd")).setDesc(J("settings.pythonCmd.desc")).addText(h=>h.setPlaceholder(i.python).setValue(this.plugin.getSettings().freecadCommand).onChange(d=>{this.plugin.updateSettings({freecadCommand:d.trim()}),o()})),new Qt.Setting(c).setName(J("settings.freecadCmd")).setDesc(J("settings.freecadCmd.desc")).addText(h=>h.setPlaceholder(i.freecad).setValue(this.plugin.getSettings().freecadcmdCommand).onChange(d=>{this.plugin.updateSettings({freecadcmdCommand:d.trim()}),o()})),new Qt.Setting(c).setName(J("settings.obj2gltfCmd")).setDesc(J("settings.obj2gltfCmd.desc")).addText(h=>h.setPlaceholder(i.obj2gltf).setValue(this.plugin.getSettings().obj2gltfCommand).onChange(d=>{this.plugin.updateSettings({obj2gltfCommand:d.trim()}),o()})),new Qt.Setting(c).setName(J("settings.fbx2gltfCmd")).setDesc(J("settings.fbx2gltfCmd.desc")).addText(h=>h.setPlaceholder(i.fbx2gltf).setValue(this.plugin.getSettings().fbx2gltfCommand).onChange(d=>{this.plugin.updateSettings({fbx2gltfCommand:d.trim()}),o()})),new Qt.Setting(c).setName(J("settings.assimpCmd")).setDesc(J("settings.assimpCmd.desc")).addText(h=>h.setPlaceholder(i.python).setValue(this.plugin.getSettings().assimpCommand).onChange(d=>{this.plugin.updateSettings({assimpCommand:d.trim()}),o()})),new Qt.Setting(c).setName(J("settings.diagnostics")).setDesc(J("settings.diagnostics.desc")).addButton(h=>h.setButtonText(J("settings.diagnostics.checkNow")).onClick(async()=>{h.setDisabled(!0),h.setButtonText(J("settings.diagnostics.checking")),s&&await this.renderCommandDiagnostics(s),h.setButtonText(J("settings.diagnostics.checkNow")),h.setDisabled(!1),new Qt.Notice(J("settings.diagnostics.refreshed"))})),s=c.createDiv({cls:"ai3d-settings-diagnostics"}),o()}new Qt.Setting(t).setName(J("settings.performance")).setHeading(),new Qt.Setting(t).setName(J("settings.canvasHeight")).setDesc(J("settings.canvasHeight.desc")).addSlider(l=>l.setLimits(200,800,25).setValue(this.plugin.getSettings().defaultCanvasHeight).setDynamicTooltip().onChange(c=>{this.plugin.updateSettings({defaultCanvasHeight:c})})),new Qt.Setting(t).setName(J("settings.autoRotateSpeed")).setDesc(J("settings.autoRotateSpeed.desc")).addSlider(l=>l.setLimits(.1,2,.1).setValue(this.plugin.getSettings().autoRotateSpeed).setDynamicTooltip().onChange(c=>{this.plugin.updateSettings({autoRotateSpeed:c})})),new Qt.Setting(t).setName(J("settings.renderQuality")).setDesc(J("settings.renderQuality.desc")).addDropdown(l=>l.addOption("low","Low").addOption("medium","Medium").addOption("high","High").setValue(this.plugin.getSettings().renderQuality).onChange(c=>{this.plugin.updateSettings({renderQuality:c})})),new Qt.Setting(t).setName(J("settings.renderScale")).setDesc(J("settings.renderScale.desc")).addSlider(l=>l.setLimits(.25,2,.25).setValue(this.plugin.getSettings().renderScale).setDynamicTooltip().onChange(c=>{this.plugin.updateSettings({renderScale:c})}))}async renderCommandDiagnostics(t){let i=++this.diagnosticsRunId;t.empty(),t.createEl("p",{text:J("settings.diagnostics.checkingAvailability")});let r=await ob(this.plugin.getSettings());if(i===this.diagnosticsRunId){t.empty();for(let s of r)this.renderCommandStatus(t,s)}}renderCommandStatus(t,i){var a;let r=t.createDiv({cls:"ai3d-settings-status-block"});r.createEl("strong",{text:`${i.label}: ${i.available?J("settings.diagnostics.available"):J("settings.diagnostics.notFound")}`});let s=[`${J("settings.diagnostics.sourceLabel")}: ${ab(i.source)}`,`${J("settings.diagnostics.commandLabel")}: ${i.command}`,i.resolvedPath&&i.resolvedPath!==i.command?`${J("settings.diagnostics.resolvedPathLabel")}: ${i.resolvedPath}`:"",i.detail].filter(Boolean);for(let o of s)r.createDiv({text:o});for(let o of(a=i.dependencyChecks)!=null?a:[])this.renderDependencyCheck(r,o)}renderDependencyCheck(t,i){let r=(()=>{switch(i.kind){case"cad-python":return J("settings.diagnostics.cadPythonCheck");case"mesh-python":return J("settings.diagnostics.meshPythonCheck");case"freecadcmd-cli":return J("settings.diagnostics.freecadCmdCheck");case"obj2gltf-cli":return J("settings.diagnostics.obj2gltfCheck");case"fbx2gltf-cli":return J("settings.diagnostics.fbx2gltfCheck")}})(),s=i.ok?J("settings.diagnostics.selfCheckOk"):J("settings.diagnostics.selfCheckFailed");t.createDiv({text:`${J("settings.diagnostics.selfCheckLabel")}: ${r} - ${s}`}),i.detail&&t.createDiv({text:i.detail})}};$f();Tn();ia();rv();Ys();oa();var Aq=Wi("main");function cv(n,e){return()=>{n().catch(t=>{Aq.error(`Command ${e} failed`,{error:String(t)}),new Ls.Notice(`AI3D: ${e} failed \u2014 ${String(t)}`,5e3)})}}var Pb=class extends Ls.Plugin{getSettings(){return this.ps.store.getState().settings}updateSettings(e){let i={...this.ps.store.getState().settings,...e};this.ps.store.setState({settings:i}),jO(i.logLevel),Rp(i.locale)}async onload(){var l;if(this.ps=HN(this),await this.ps.load(),this.convertedAssetCache=VN(this.ps.store.getState().convertedAssetRecords,c=>this.ps.store.setState({convertedAssetRecords:c})),jO(this.getSettings().logLevel),!this.ps.localeLoadedFromSaved){let f=((l=navigator.language)!=null?l:"en").startsWith("zh")?"zh-CN":"en";this.updateSettings({locale:f})}Rp(this.getSettings().locale),this.addRibbonIcon("box",J("main.commandImportModel"),()=>this.importModel()),this.addCommand({id:"import-model",name:J("main.commandImportModel"),callback:()=>this.importModel()}),this.addCommand({id:"generate-note",name:J("main.commandGenerateNote"),callback:cv(()=>this.generateNote(),"generate note")}),this.addCommand({id:"open-knowledge-index",name:J("main.commandOpenKnowledgeIndex"),callback:cv(()=>this.openKnowledgeIndex(),"open knowledge index")}),this.addCommand({id:"clear-conversion-cache",name:J("main.commandClearConversionCache"),callback:cv(()=>Promise.resolve(this.clearConversionCache()),"clear conversion cache")}),this.addCommand({id:"check-converters",name:J("main.commandCheckConverters"),callback:cv(()=>this.checkConverterCommands(),"check converters")}),this.addCommand({id:"copy-diagnostics-report",name:J("main.commandCopyDiagnostics"),callback:cv(()=>this.copyDiagnosticsReport(),"copy diagnostics")}),this.addSettingTab(new Cb(this.app,this)),this.registerView(Ib,c=>new bb(c,()=>this.getSettings(),this.convertedAssetCache,this.ps)),this.registerExtensions(gl(),Ib);let{registerCodeBlockProcessor:e,registerGridCodeBlockProcessor:t}=await Promise.resolve().then(()=>(uq(),dq)),i=c=>{var f,h;return(h=(f=this.ps.store.getState().modelAssetProfiles[c])==null?void 0:f.annotations)!=null?h:[]},r=e(this.app,()=>this.getSettings(),this.convertedAssetCache,i);this.registerMarkdownCodeBlockProcessor(r.id,r.handler);let s=t(this.app,()=>this.getSettings(),this.convertedAssetCache);this.registerMarkdownCodeBlockProcessor(s.id,s.handler);let{registerLivePreviewExtension:a}=await Promise.resolve().then(()=>(vq(),gq)),o=a(this.app,()=>this.getSettings(),this.convertedAssetCache,i);for(let c of o)this.registerEditorExtension(c);this.setupHeadingPinObserver()}onunload(){this.ps.save().catch(e=>console.error("[AI3D] unload save failed:",e))}setupHeadingPinObserver(){let e=".markdown-preview-view, .markdown-source-view",t=[".markdown-preview-view h1",".markdown-preview-view h2",".markdown-preview-view h3",".markdown-preview-view h4",".markdown-preview-view h5",".markdown-preview-view h6",".cm-heading-1",".cm-heading-2",".cm-heading-3",".cm-heading-4",".cm-heading-5",".cm-heading-6",".cm-header-1",".cm-header-2",".cm-header-3",".cm-header-4",".cm-header-5",".cm-header-6"].join(", "),i=new Map,r=M=>{if(M.length===0)return"var(--interactive-accent)";if(M.length===1)return M[0];let D=100/M.length;return`linear-gradient(135deg, ${M.map((O,V)=>{let N=Math.round(V*D),F=Math.round((V+1)*D);return`${O} ${N}% ${F}%`}).join(", ")})`},s=()=>{let M=new Map,D=this.ps.store.getState().modelAssetProfiles;for(let[O,V]of Object.entries(D))for(let N of V.annotations)if(N.headingRef&&N.id){let F=iv(N.headingRef);if(!F)continue;let U=M.get(F);U||(U=[],M.set(F,U)),U.push({pinId:N.id,modelPath:O,color:N.color})}return M},a=M=>M.map(D=>`${D.pinId}:${D.modelPath}:${D.color}`).sort().join("|"),o=M=>Array.from(M.entries()).map(([D,O])=>`${D}=>${a(O)}`).sort().join("||"),l=M=>iv(Array.from(M.childNodes).map(D=>{var O;return D.instanceOf(Element)&&D.classList.contains("ai3d-heading-pin-badge")?"":(O=D.textContent)!=null?O:""}).join(" ")),c=M=>{let D=i.get(M);D&&(M.removeEventListener("mouseover",D.handler),D.badge.remove(),delete M.dataset.pinBound,i.delete(M))},f=(M,D)=>{if(D.length===0){c(M);return}let O=a(D),V=i.get(M);if((V==null?void 0:V.signature)===O)return;V&&c(M),M.dataset.pinBound=O;let N=M.createSpan({cls:"ai3d-heading-pin-badge"}),F=[...new Set(D.map(Z=>Z.color).filter(Boolean))],U=N.createSpan({cls:"ai3d-heading-pin-badge-swatch"});if(U.style.background=r(F),U.title=D.length>1?J("headingPin.showMultiple"):J("headingPin.showSingle"),U.setAttribute("role","button"),U.setAttribute("tabindex","0"),D.length>1){let Z=N.createSpan({cls:"ai3d-heading-pin-badge-count"});Z.textContent=`\xD7${D.length}`}let G=[...new Set(D.map(Z=>jr(Z.modelPath)))];N.title=ur("headingPin.linkedTo",{models:G.join(", ")});let ee=Z=>{Z==null||Z.stopPropagation(),Z==null||Z.preventDefault();for(let X of D)activeDocument.dispatchEvent(new CustomEvent("ai3d-pin-highlight",{detail:{pinId:X.pinId}}))};U.addEventListener("click",Z=>{ee(Z)}),U.addEventListener("keydown",Z=>{Z.instanceOf(KeyboardEvent)&&(Z.key!=="Enter"&&Z.key!==" "||ee(Z))}),N.addEventListener("click",Z=>{Z.stopPropagation()}),M.appendChild(N);let j=()=>{for(let Z of D)activeDocument.dispatchEvent(new CustomEvent("ai3d-pin-highlight",{detail:{pinId:Z.pinId}}))};M.addEventListener("mouseover",j),i.set(M,{badge:N,handler:j,signature:O})},h=(M,D)=>{var V;let O=l(M);f(M,(V=D.get(O))!=null?V:[])},d=M=>{var D;for(let[O,V]of Array.from(i.entries())){if(!O.isConnected){c(O);continue}let N=(D=M.get(l(O)))!=null?D:[],F=a(N);(N.length===0||V.signature!==F)&&f(O,N)}},u=(M,D)=>{M.querySelectorAll(t).forEach(O=>h(O,D))},m=()=>{let M=s();d(M),activeDocument.querySelectorAll(e).forEach(O=>u(O,M))},p=o(s()),_=0,g=(M=0)=>{_&&window.clearTimeout(_),_=window.setTimeout(()=>{_=0,m()},M)},v=this.ps.store.subscribe(()=>{let M=s(),D=o(M);D!==p&&(p=D,g())});this.registerEvent(this.app.workspace.on("layout-change",()=>{g(200)}));let x=M=>M.matches(e)||M.matches(t)?!0:!!M.querySelector(e)||!!M.querySelector(t),A=M=>M.isConnected&&x(M),S=M=>x(M),E=new Set,R=0,I=()=>{var O,V,N,F,U,G;let M=Array.from(E);E.clear(),R=0;let D=s();d(D);for(let ee of M)ee.isConnected&&((O=ee.matches)!=null&&O.call(ee,t)&&h(ee,D),(N=(V=ee.querySelectorAll)==null?void 0:V.call(ee,t))==null||N.forEach(j=>h(j,D)),(F=ee.matches)!=null&&F.call(ee,e)&&u(ee,D),(G=(U=ee.querySelectorAll)==null?void 0:U.call(ee,e))==null||G.forEach(j=>u(j,D)));p=o(D)},y=new MutationObserver(M=>{let D=!1;for(let O of M){for(let V of Array.from(O.addedNodes))V.instanceOf(HTMLElement)&&A(V)&&(E.add(V),D=!0);for(let V of Array.from(O.removedNodes))V.instanceOf(HTMLElement)&&S(V)&&(D=!0)}D&&!R&&(R=window.setTimeout(I,100))});y.observe(activeDocument.body,{childList:!0,subtree:!0}),this.register(()=>{v(),y.disconnect(),R&&(window.clearTimeout(R),R=0),_&&(window.clearTimeout(_),_=0);for(let M of Array.from(i.keys()))c(M)}),g(500)}importModel(){new Mb(this.app,e=>{let t=e.extension.toLowerCase();_l(t)&&this.openModelFile(e)}).open()}async openModelFile(e){this.ps.store.setState({currentModelPath:e.path,modelPreview:null,selectedPart:null}),await this.app.workspace.getLeaf(!0).openFile(e,{active:!0})}async generateNote(){let{generateKnowledgeNote:e}=await Promise.resolve().then(()=>(xb(),Ab));await e(this.app,this.ps)}async openKnowledgeIndex(){let e=this.resolveKnowledgeIndexPath();if(!e){new Ls.Notice(J("workbench.noIndexYet"));return}let t=this.app.vault.getAbstractFileByPath(e);t instanceof Ls.TFile?await this.app.workspace.getLeaf(!0).openFile(t,{active:!0}):new Ls.Notice(ur("workbench.fileNotFound",{path:e}))}resolveKnowledgeIndexPath(){var s,a,o;let e=this.ps.store.getState(),t=e.currentModelPath,i=t?(s=e.modelAssetProfiles[t])==null?void 0:s.knowledgeIndexPath:void 0;return i||((a=e.lastKnowledgeGeneration)!=null&&a.knowledgeIndexPath?e.lastKnowledgeGeneration.knowledgeIndexPath:(o=Object.values(e.modelAssetProfiles).filter(l=>!!l.knowledgeIndexPath).sort((l,c)=>Date.parse(c.updatedAt)-Date.parse(l.updatedAt))[0])==null?void 0:o.knowledgeIndexPath)}clearConversionCache(){this.convertedAssetCache.clear(),new Ls.Notice("AI 3d conversion cache cleared.")}async checkConverterCommands(){if(mr()){new Ls.Notice(J("main.converterDiagnosticsMobileUnavailable"),8e3);return}let e=await ob(this.getSettings()),t=e.filter(r=>r.available).map(r=>r.label),i=e.filter(r=>!r.available).map(r=>r.label);if(i.length===0){new Ls.Notice(`AI 3D converter diagnostics: all commands available (${t.join(", ")}).`,8e3);return}new Ls.Notice(`AI 3D converter diagnostics: available ${t.join(", ")||"none"}; missing ${i.join(", ")}.`,1e4)}async copyDiagnosticsReport(){let{buildDiagnosticsReport:e}=await Promise.resolve().then(()=>(Tq(),Sq)),t=e({manifest:this.manifest,state:this.ps.store.getState()});try{await navigator.clipboard.writeText(t),new Ls.Notice(J("main.diagnosticsCopied"),8e3)}catch(i){let r=this.getSettings().reportFolder.replace(/\\/g,"/").replace(/^\/+|\/+$/g,"").trim()||"Analysis/3D Reports";await this.ensureVaultFolder(r);let s=`AI Model Workbench Diagnostics ${new Date().toISOString().replace(/[:.]/g,"-")}.md`,a=await this.app.vault.create(`${r}/${s}`,t);await this.app.workspace.getLeaf(!0).openFile(a,{active:!0}),new Ls.Notice(J("main.diagnosticsCopyFailed"),1e4)}}async ensureVaultFolder(e){let t="";for(let i of e.split("/").filter(Boolean))t=t?`${t}/${i}`:i,this.app.vault.getAbstractFileByPath(t)||await this.app.vault.createFolder(t).catch(r=>{Aq.warn("Failed to create vault folder",{path:t,error:String(r)})})}}; diff --git a/manifest.json b/manifest.json index e3aca5a..fb59931 100644 --- a/manifest.json +++ b/manifest.json @@ -1,10 +1,10 @@ -{ - "id": "ai-model-workbench", - "name": "AI Model Workbench", - "version": "0.5.5", - "minAppVersion": "1.5.0", - "description": "Turn 3D models into linked knowledge assets.", - "author": "flash", - "authorUrl": "https://github.com/flash555588", - "isDesktopOnly": false -} +{ + "id": "ai-model-workbench", + "name": "AI Model Workbench", + "version": "0.5.5", + "minAppVersion": "1.5.0", + "description": "Turn 3D models into linked knowledge assets.", + "author": "flash", + "authorUrl": "https://github.com/flash555588", + "isDesktopOnly": false +} diff --git a/package.json b/package.json index 08e4a47..336fac4 100644 --- a/package.json +++ b/package.json @@ -1,47 +1,49 @@ -{ - "name": "obsidian-ai-model-workbench", - "version": "0.5.5", - "private": true, - "description": "Obsidian plugin for turning 3D models into linked knowledge assets.", - "scripts": { - "dev": "node esbuild.config.mjs", - "build": "node esbuild.config.mjs production", - "typecheck": "tsc --noEmit --skipLibCheck", - "test": "vitest run", - "test:coverage": "vitest run --coverage", - "verify:preview": "node scripts/verify-preview.mjs", - "verify:preview:rollback": "node scripts/verify-preview.mjs --rollout babylon-safe", - "verify:preview:success": "node scripts/verify-preview-success.mjs", - "verify:obsidian": "node scripts/verify-obsidian.mjs", - "verify:release": "node scripts/verify-release-assets.mjs", - "install:vault": "node scripts/install-to-vault.mjs", - "verify:settings": "node scripts/verify-settings-migration.mjs", - "verify:remote-draft": "node scripts/verify-remote-draft.mjs", - "verify:knowledge-index": "node scripts/verify-knowledge-index.mjs", - "verify:diagnostics": "node scripts/verify-diagnostics.mjs" - }, - "devDependencies": { - "@codemirror/language": "^6.12.3", - "@codemirror/state": "^6.5.0", - "@codemirror/view": "^6.38.6", - "@lezer/common": "^1.5.2", - "@lezer/highlight": "^1.2.3", - "@lezer/lr": "^1.4.10", - "@types/node": "^22.15.17", - "@types/three": "^0.184.1", - "@typescript-eslint/parser": "^8.59.2", - "@vitest/coverage-v8": "^4.1.9", - "esbuild": "^0.28.1", - "eslint": "^9.39.4", - "eslint-plugin-obsidianmd": "^0.2.9", - "obsidian": "^1.8.7", - "playwright-core": "^1.59.1", - "typescript": "^5.8.3", - "vitest": "^4.1.9" - }, - "dependencies": { - "@babylonjs/core": "^9.6.0", - "@babylonjs/loaders": "^9.6.0", - "three": "^0.184.0" - } -} +{ + "name": "obsidian-ai-model-workbench", + "version": "0.5.5", + "private": true, + "description": "Obsidian plugin for turning 3D models into linked knowledge assets.", + "scripts": { + "dev": "node esbuild.config.mjs", + "build": "node esbuild.config.mjs production", + "typecheck": "tsc --noEmit --skipLibCheck", + "lint": "eslint src scripts --max-warnings=0", + "lint:fix": "eslint src scripts --fix", + "test": "vitest run", + "test:coverage": "vitest run --coverage", + "verify:preview": "node scripts/verify-preview.mjs", + "verify:preview:rollback": "node scripts/verify-preview.mjs --rollout babylon-safe", + "verify:preview:success": "node scripts/verify-preview-success.mjs", + "verify:obsidian": "node scripts/verify-obsidian.mjs", + "verify:release": "node scripts/verify-release-assets.mjs", + "install:vault": "node scripts/install-to-vault.mjs", + "verify:settings": "node scripts/verify-settings-migration.mjs", + "verify:remote-draft": "node scripts/verify-remote-draft.mjs", + "verify:knowledge-index": "node scripts/verify-knowledge-index.mjs", + "verify:diagnostics": "node scripts/verify-diagnostics.mjs" + }, + "devDependencies": { + "@codemirror/language": "^6.12.3", + "@codemirror/state": "^6.5.0", + "@codemirror/view": "^6.38.6", + "@lezer/common": "^1.5.2", + "@lezer/highlight": "^1.2.3", + "@lezer/lr": "^1.4.10", + "@types/node": "^22.15.17", + "@types/three": "^0.184.1", + "@typescript-eslint/parser": "^8.59.2", + "@vitest/coverage-v8": "^4.1.9", + "esbuild": "^0.28.1", + "eslint": "^9.39.4", + "eslint-plugin-obsidianmd": "^0.2.9", + "obsidian": "^1.8.7", + "playwright-core": "^1.59.1", + "typescript": "^5.8.3", + "vitest": "^4.1.9" + }, + "dependencies": { + "@babylonjs/core": "^9.6.0", + "@babylonjs/loaders": "^9.6.0", + "three": "^0.184.0" + } +} diff --git a/src/i18n/en.ts b/src/i18n/en.ts index 5f88b14..bfa961d 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -1,345 +1,345 @@ -export const en = { - // Section headers - "settings.title": "AI 3d model workbench", - "settings.folders": "Folders", - "settings.behavior": "Behavior", - "settings.converters": "Converters", - "settings.converterMenu": "Model converters", - "settings.converterMenu.desc": "Closed by default. Open this section only when you want to manually enable an optional local conversion route.", - "settings.environmentInspector": "Environment inspector", - "settings.environmentInspector.desc": "Closed by default. Open this section when you need to configure command paths or run environment checks.", - "settings.paths": "Converter paths", - "settings.diagnostics": "Converter command diagnostics", - "settings.performance": "Performance & display", - "settings.mobileSupport": "Mobile support", - "settings.knowledgeGeneration": "Knowledge generation", - - // Folders - "settings.sourceModelFolder": "Source model folder", - "settings.sourceModelFolder.desc": "Vault folder where source model files are stored.", - "settings.reportFolder": "Report folder", - "settings.reportFolder.desc": "Vault folder where generated knowledge notes are saved.", - "settings.partFolder": "Part notes folder", - "settings.partFolder.desc": "Vault folder where generated part note drafts are saved.", - "settings.snapshotFolder": "Snapshot folder", - "settings.snapshotFolder.desc": "Vault folder where exported snapshots are saved.", - - // Behavior - "settings.autoGenerateKnowledgeNotes": "Auto-generate knowledge notes", - "settings.autoGenerateKnowledgeNotes.desc": "Reserved for a future automation flow. For now, generate notes manually from the command palette.", - "settings.annotationPreviewMode": "Annotation preview mode", - "settings.annotationPreviewMode.desc": "Choose how bound note previews render in annotation popovers and the editor.", - "settings.annotationPreviewMode.plainText": "Plain text", - "settings.annotationPreviewMode.markdown": "Markdown", - "settings.annotationDisplayMode": "Annotation display mode", - "settings.annotationDisplayMode.desc": "Choose how bookmark pins appear over the model.", - "settings.annotationDisplayMode.snippet": "Full snippet", - "settings.annotationDisplayMode.surface": "Single surface", - "settings.annotationDisplayMode.dot": "Single dot", - "settings.previewRendererRollout": "Preview compatibility mode", - "settings.previewRendererRollout.desc": "Controls how widely the Three.js preview path is used for single-model previews (GLB, GLTF, STL, PLY, OBJ). Switch back to Compatibility mode if pin projection, occlusion, edit pins, snapshots, or toolbar behavior regress. 3dgrid is not affected by this setting.", - "settings.previewRendererRollout.babylonSafe": "Compatibility mode", - "settings.previewRendererRollout.readonly": "Reading surfaces only", - "settings.previewRendererRollout.direct": "Reading + file view (Recommended)", - "settings.useThreeRenderer": "Use Three.js renderer", - "settings.useThreeRenderer.desc": "Toggle between Three.js (faster, lighter) and Babylon.js (full compatibility) for single-model previews. Three.js supports GLB/GLTF/STL/PLY/OBJ. 3dgrid always uses Babylon.js.", - "settings.experimentalThreeWorkbench": "Experimental Three workbench", - "settings.experimentalThreeWorkbench.desc": "Try the Three.js workbench path for direct GLB/GLTF files only. If loading fails, the file view falls back to Babylon.js automatically.", - "settings.autoRotateDefault": "Auto-rotate by default", - "settings.autoRotateDefault.desc": "Start model previews with auto-rotation enabled.", - "settings.snapshotNaming": "Snapshot naming", - "settings.snapshotNaming.desc": "How exported snapshot files are named.", - "settings.snapshotNaming.modelName": "Model name + timestamp", - "settings.snapshotNaming.timestamp": "Timestamp only", - "settings.logLevel": "Log level", - "settings.logLevel.desc": "Controls plugin runtime log verbosity in the developer console.", - "settings.language": "Language", - "settings.language.desc": "Display language for plugin settings. Takes effect immediately.", - "settings.analysisMode": "AI drafting mode", - "settings.analysisMode.desc": "Controls whether knowledge-note generation stays local or also requests a sanitized remote draft. Raw model upload is blocked by the current client.", - "settings.analysisMode.local": "Local evidence only", - "settings.analysisMode.hybrid": "Local evidence + remote draft", - "settings.analysisMode.remote": "Remote draft from evidence", - "settings.serviceBaseUrl": "Draft service URL", - "settings.serviceBaseUrl.desc": "Optional base URL for a service that accepts POST /draft-note. Leave empty to keep all drafting local.", - "settings.sendGeometrySummaryToRemote": "Send geometry summary", - "settings.sendGeometrySummaryToRemote.desc": "Allow sanitized mesh counts, bounds, part candidates, annotation coordinates, and nearest-part links to be included in remote draft input.", - "settings.sendPreviewImagesToRemote": "Send preview image references", - "settings.sendPreviewImagesToRemote.desc": "Allow generated preview image paths to be listed in the remote draft input. Image bytes are not uploaded by this client.", - "settings.sendRawModelToRemote": "Send raw model file", - "settings.sendRawModelToRemote.desc": "Reserved for future explicit upload support. If enabled manually, remote draft requests are blocked instead of uploading the model.", - - // Converters - "settings.enableCad": "Enable cad conversion for step, iges, and brep files", - "settings.enableCad.desc": "Enable cad conversion for step, iges, and brep formats. Requires cadquery and trimesh in your python environment.", - "settings.enableObj2gltf": "Enable obj2gltf converter (experimental)", - "settings.enableObj2gltf.desc": "Keep obj direct loading as the default. Enable this only if you want an optional local normalization route through obj2gltf.", - "settings.preferObj2gltf": "Prefer obj2gltf for obj", - "settings.preferObj2gltf.desc": "Recommended default is off. Turn this on only when you want normalized output files or direct obj loading is not good enough.", - "settings.enableFbx2gltf": "Enable FBX2glTF converter", - "settings.enableFbx2gltf.desc": "Enable conversion for fbx files via FBX2glTF. Requires the FBX2glTF binary installed locally.", - "settings.enableMesh": "Enable mesh conversion for 3mf and dae files", - "settings.enableMesh.desc": "Enable conversion for 3mf and dae formats via python trimesh. Requires trimesh, numpy, networkx, and pycollada in your python environment.", - "settings.enableSldprt": "Enable sldprt conversion for SolidWorks files", - "settings.enableSldprt.desc": "Enable conversion for SolidWorks sldprt files via FreeCAD. Requires FreeCAD installed locally.", - "settings.mobileSupport.desc": "On iOS, iPadOS, and Android, direct formats like GLB, GLTF, STL, OBJ, and PLY are supported. Local converter settings and diagnostics remain desktop-only.", - - // Converter paths - "settings.pythonCmd": "Path to the python command for cad conversion", - "settings.pythonCmd.desc": "Optional path to the python command used for cad conversion. Windows usually uses py. macOS and Linux usually use python3. Overrides auto-discovery when set.", - "settings.freecadCmd": "Path to the FreeCAD command for sldprt conversion", - "settings.freecadCmd.desc": "Optional path to the FreeCAD command used for SolidWorks file conversion. Windows usually uses FreeCADCmd.exe, macOS usually uses FreeCADCmd, and Linux usually uses freecadcmd. Overrides auto-discovery when set.", - "settings.obj2gltfCmd": "Path to the obj2gltf command", - "settings.obj2gltfCmd.desc": "Optional path to the obj2gltf command. Windows usually uses obj2gltf.cmd, and macOS and Linux usually use obj2gltf. Overrides auto-discovery when set.", - "settings.fbx2gltfCmd": "FBX2glTF command path", - "settings.fbx2gltfCmd.desc": "Optional path to the FBX2glTF command. Windows usually uses FBX2glTF.exe, and macOS and Linux usually use FBX2glTF. Overrides auto-discovery when set.", - "settings.assimpCmd": "Path to the python command for 3mf and dae conversion", - "settings.assimpCmd.desc": "Optional path to the python command used for 3mf and dae conversion. Windows usually uses py. macOS and Linux usually use python3. Overrides auto-discovery when set.", - - // Diagnostics - "settings.diagnostics.desc": "Shows the exact executable path the plugin would use right now and runs lightweight self-checks for Python environments and converter CLIs.", - "settings.diagnostics.idle": "Diagnostics are off by default. Click Check now to run them manually.", - "settings.diagnostics.checkNow": "Check now", - "settings.diagnostics.checking": "Checking...", - "settings.diagnostics.refreshed": "Converter command diagnostics refreshed.", - "settings.diagnostics.checkingAvailability": "Checking converter command availability...", - "settings.diagnostics.available": "available", - "settings.diagnostics.notFound": "not found", - "settings.diagnostics.sourceLabel": "Source", - "settings.diagnostics.commandLabel": "Command", - "settings.diagnostics.resolvedPathLabel": "Resolved path", - "settings.diagnostics.selfCheckLabel": "Self-check", - "settings.diagnostics.selfCheckOk": "passed", - "settings.diagnostics.selfCheckFailed": "failed", - "settings.diagnostics.cadPythonCheck": "Python packages (cadquery, trimesh)", - "settings.diagnostics.meshPythonCheck": "Python packages (trimesh, numpy, networkx, collada)", - "settings.diagnostics.freecadCmdCheck": "FreeCADCmd launch probe", - "settings.diagnostics.obj2gltfCheck": "obj2gltf launch probe", - "settings.diagnostics.fbx2gltfCheck": "FBX2glTF launch probe", - - // Performance - "settings.canvasHeight": "Default canvas height", - "settings.canvasHeight.desc": "Default height (px) for inline model previews. Range: 200–800.", - "settings.autoRotateSpeed": "Auto-rotate speed", - "settings.autoRotateSpeed.desc": "Rotation speed when auto-rotate is enabled. Range: 0.1–2.0.", - "settings.renderQuality": "Render quality", - "settings.renderQuality.desc": "Higher quality uses more GPU resources. Affects anti-aliasing and resolution.", - "settings.renderScale": "Resolution scale", - "settings.renderScale.desc": "Render resolution multiplier. 1.0 = native, 0.5 = half, 2.0 = double (supersampling). Range: 0.25–2.0.", - - // Model load feedback - "modelLoad.warningTitle": "Model preview unavailable", - "modelLoad.warningMessage": "{ext} files need the {converterName} converter enabled in plugin settings before they can load.", - "modelLoad.warningHint": "Enable the matching converter in plugin settings, then reload this file.", - "modelLoad.mobileWarningMessage": "{ext} files need local conversion tools that are unavailable on iOS, iPadOS, and Android.", - "modelLoad.mobileWarningHint": "Open this file on desktop, or convert it to GLB, GLTF, OBJ, STL, or PLY first.", - "modelLoad.errorTitle": "Couldn't display this model", - "modelLoad.errorMessage": "Failed to load: {reason}", - "modelLoad.errorHint": "Check the file format or open the developer console for details.", - - // Heading pin badge - "headingPin.showSingle": "Show linked pin", - "headingPin.showMultiple": "Show linked pins", - "headingPin.linkedTo": "Pin linked to: {models}", - - // Helper toolbar - "helper.resetViewLabel": "Reset view", - "helper.resetViewDone": "Reset", - "helper.copyModelInfoLabel": "Copy model info as Markdown", - "helper.copySelectedPartInfoLabel": "Copy selected part info", - "helper.noSelectedPart": "Select a part first", - "helper.copied": "Copied!", - "helper.failed": "Failed", - "helper.toggleWireframeLabel": "Toggle wireframe", - "helper.wireframeOn": "Wireframe", - "helper.wireframeOff": "Solid", - "helper.toggleAxesLabel": "Toggle orientation axes", - "helper.axesOn": "Axes on", - "helper.axesOff": "Axes off", - "helper.toggleBoundingBoxLabel": "Toggle bounding box", - "helper.boundingBoxOn": "Bounding box on", - "helper.boundingBoxOff": "Bounding box off", - "helper.toggleFocusSelectionLabel": "Focus selected part", - "helper.focusSelectionOn": "Focus mode on", - "helper.focusSelectionOff": "Focus mode off", - "helper.toggleDisassemblyLabel": "Toggle disassembly mode", - "helper.disassemblyOn": "Disassembly on", - "helper.disassemblyOff": "Disassembly off", - "helper.resetPartsLabel": "Reset disassembled parts", - "helper.partsReset": "Parts reset", - "helper.changeResolutionLabel": "Change resolution", - "helper.resolutionValue": "Resolution: {value}", - "helper.toggleAnimationLabel": "Play or pause animation", - "helper.playing": "Playing", - "helper.paused": "Paused", - "helper.toggleMeasurementLabel": "Toggle distance measurement", - "helper.measurementOn": "Measurement on", - "helper.measurementOff": "Measurement off", - "helper.clearMeasurementsLabel": "Clear measurements", - "helper.measurementsCleared": "Cleared", - "helper.calibrateLabel": "Calibrate measurement scale", - "helper.calibrateTitle": "Measurement Calibration", - "helper.calibrateCurrent": "Current size:", - "helper.calibrateReal": "Real size:", - "helper.calibrateLock": "Lock ratio", - "helper.calibrateApply": "Apply", - "helper.calibrateReset": "Reset", - "helper.calibrated": "Scale applied", - "helper.calibrateResetDone": "Scale reset", - "helper.calibrateOpen": "Calibration panel opened", - "helper.calibrateClose": "Calibration panel closed", - "helper.removePreviewLabel": "Remove preview", - "helper.copySnapshotLabel": "Copy snapshot", - "helper.saveSnapshotLabel": "Save snapshot to vault", - "helper.saved": "Saved!", - "helper.downloadSnapshotLabel": "Download snapshot", - "helper.downloaded": "Downloaded!", - "helper.toggleAnnotationLabel": "Toggle annotation mode", - "helper.toggleAnnotationsVisibilityLabel": "Show or hide annotations", - "helper.annotateOn": "Annotation mode on", - "helper.annotateOff": "Annotation mode off", - "helper.annotationsVisible": "Annotations shown", - "helper.annotationsHidden": "Annotations hidden", - "helper.enableInteractionLabel": "Enable touch interaction", - "helper.disableInteractionLabel": "Return to scroll mode", - "helper.interactionOn": "Model interaction on", - "helper.interactionOff": "Scroll mode on", - "helper.showMoreActionsLabel": "Show more actions", - "helper.hideMoreActionsLabel": "Hide extra actions", - "helper.moreActionsShown": "More actions shown", - "helper.moreActionsHidden": "Extra actions hidden", - "helper.interactAction": "Interact", - "helper.scrollAction": "Scroll", - - // Workbench and views - "workbench.emptyTitle": "No model", - "workbench.emptyText": "Use the \"import 3D model\" command to load a GLB, GLTF, STL, OBJ, or PLY file.", - "workbench.modelTitle": "Model", - "workbench.studioTitle": "AI Model Workbench", - "workbench.studioTagline": "Inspect, annotate, and turn 3D assets into linked notes.", - "workbench.navLabel": "Workbench sections", - "workbench.navGallery": "Gallery", - "workbench.navLibrary": "Library", - "workbench.navNotebooks": "Notebooks", - "workbench.navSettings": "Settings", - "workbench.sourcesTitle": "Model sources", - "workbench.layersTitle": "Review layers", - "workbench.viewModeTitle": "View mode", - "workbench.modeMesh": "Mesh view", - "workbench.modeFocus": "Focus selection", - "workbench.modeMeshShort": "Mesh", - "workbench.modeFocusShort": "Focus", - "workbench.previewViewsTitle": "Preview views", - "workbench.connectionsTitle": "Knowledge connections", - "workbench.currentModelLabel": "Current model", - "workbench.noReportYet": "No report note yet", - "workbench.noIndexYet": "No knowledge index yet. Generate a knowledge note first.", - "workbench.noModelLoaded": "No model loaded", - "workbench.disassemblyTitle": "Disassembly", - "workbench.explodeLabel": "Explode", - "workbench.summaryTitle": "Summary", - "workbench.meshesLabel": "Meshes", - "workbench.splatsLabel": "Splats", - "workbench.trianglesLabel": "Triangles", - "workbench.verticesLabel": "Vertices", - "workbench.materialsLabel": "Materials", - "workbench.boundingSizeLabel": "Bounds", - "workbench.centerLabel": "Center", - "workbench.selectedPartTitle": "Selected Part", - "workbench.partMeshLabel": "Mesh", - "workbench.noSelectedPart": "Click a model part to inspect it here.", - "workbench.tagsTitle": "Tags", - "workbench.noTagsYet": "No tags yet", - "workbench.addTagPlaceholder": "Add tag...", - "workbench.addTagAction": "Add", - "workbench.annotationsTitle": "Annotations", - "workbench.exitAnnotate": "Exit annotate", - "workbench.annotate": "Annotate", - "workbench.annotateHintActive": "Click the model to add a label · press Esc to exit", - "workbench.annotateHintActiveMobile": "Tap the model to add a label. Switch back to Scroll when you want to move through the note again.", - "workbench.pinCount": "{count} pin(s)", - "workbench.editAction": "Edit", - "workbench.deleteAction": "Delete", - "workbench.resetViewAction": "Reset view", - "workbench.insertInfoAction": "Insert info", - "workbench.insertGalleryAction": "Insert Gallery", - "workbench.insertCompareAction": "Insert Compare", - "workbench.playAction": "Play", - "workbench.pauseAction": "Pause", - "workbench.saveProfileAction": "Save profile", - "workbench.generateNoteAction": "Generate note", - "workbench.openNoteAction": "Open note", - "workbench.openIndexAction": "Open index", - "workbench.recordTitle": "Specimen card", - "workbench.recordSubtitle": "Current asset profile", - "workbench.notesTitle": "Analysis notes", - "workbench.whereTitle": "Where it connects", - "workbench.noteReady": "Linked note ready", - "workbench.indexReady": "Knowledge index ready", - "workbench.notePending": "Linked note pending", - "workbench.analysisLabel": "Analysis", - "workbench.settingsUnavailable": "Open this plugin from Obsidian settings to change workbench options.", - "workbench.profileSaved": "Profile saved", - "workbench.viewReset": "View reset", - "workbench.infoInserted": "Model info inserted", - "workbench.infoCopied": "Model info copied", - "workbench.templateInserted": "Template inserted", - "workbench.templateCopied": "Template copied", - "workbench.mobileHint": "Mobile tip: tap Interact to move the model, then switch back to Scroll to keep reading the note.", - "workbench.mobileHintInteractive": "Interaction mode is on. Switch back to Scroll when you want to move through the note again.", - "directView.mobileHint": "Mobile tip: use the toolbar Interact button to switch between model interaction and note scrolling.", - "directWorkbench.modelLoadInterrupted": "Model load was interrupted by a newer request.", - "directWorkbench.backendLabel": "Backend", - "directWorkbench.routeLabel": "Route", - "directWorkbench.performanceLabel": "Performance", - "directWorkbench.partCandidatesLabel": "Part candidates", - "directWorkbench.knowledgeTitle": "Knowledge", - "directWorkbench.registeredTitle": "Registered part matches", - "directWorkbench.registeredLoading": "Checking...", - "directWorkbench.registeredCount": "{count} match(es)", - "directWorkbench.registeredEmpty": "No cross-model part match yet", - "directWorkbench.registeredUnavailable": "Part evidence unavailable", - "directWorkbench.registeredOpen": "Open", - "directWorkbench.registeredOpenNote": "Note", - "directWorkbench.registeredOpenModel": "Model", - "directWorkbench.registeredSourceModel": "From {model}", - "directWorkbench.registeredTargetPartNote": "Opens matched part note", - "directWorkbench.registeredTargetSourceModel": "Opens source model", - "directWorkbench.registeredTargetUnavailable": "No linked target", - "workbench.fileNotFound": "File not found: {path}", - "annotation.selectColor": "Select color {color}", - "annotation.sectionEmpty": "Section is empty.", - "modal.selectModel": "Select a 3D model...", - "main.commandImportModel": "Import a 3D model", - "main.commandGenerateNote": "Generate knowledge note", - "main.commandOpenKnowledgeIndex": "Open knowledge index", - "main.commandClearConversionCache": "Clear conversion cache", - "main.commandCheckConverters": "Check converters", - "main.commandCopyDiagnostics": "Copy diagnostics report", - "main.converterDiagnosticsMobileUnavailable": "Converter diagnostics are only available on desktop. On iOS, iPadOS, and Android, direct formats can still load.", - "main.diagnosticsCopied": "AI Model Workbench diagnostics copied to clipboard.", - "main.diagnosticsCopyFailed": "Couldn't copy diagnostics. A sanitized diagnostics note was created instead.", - - // Inline code block and loading - "codeBlock.noModelPathOrConfig": "No model path or config specified.", - "codeBlock.jsonParseError": "JSON parse error: {error}", - "codeBlock.jsonParseLine": " (line {line})", - "codeBlock.noModelsInConfig": "No models specified in config.", - "codeBlock.unsupportedFormat": "Unsupported format: {ext}. Supported: {formats}", - "codeBlock.splatDisabled": "SPLAT preview is disabled in packaged builds. Local-only .splat support is planned first; .spz/.sog need locally bundled decoders before reevaluation.", - "codeBlock.noConfigSpecified": "No config specified.", - "codeBlock.noModelsSpecified": "No models specified.", - "codeBlock.mobileHint": "Mobile tip: use Interact to manipulate the model, then switch back to Scroll to keep moving through the note.", - "codeBlock.renderingGrid": "Rendering grid...", - "codeBlock.composeRequiresSections": "\"compose\" preset requires a \"sections\" array.", - "codeBlock.composeNoValidSections": "Compose: no valid sections.", - "codeBlock.unknownPreset": "Unknown preset: \"{preset}\". Available: compare, showcase, explode, timeline, compose", - "codeBlock.presetRequiresModels": "Preset \"{preset}\" requires {min}-{max} models, got {count}.", - "codeBlock.gridFailed": "Grid failed: {reason}", - "livePreview.mobileHint": "Mobile tip: switch between Interact and Scroll depending on whether you want to move the model or keep reading.", - "loading.default": "Loading...", - "loading.preparingModel": "Preparing model...", - "loading.loadingModel": "Loading model...", -} as const; - -export type TranslationKey = keyof typeof en; +export const en = { + // Section headers + "settings.title": "AI 3d model workbench", + "settings.folders": "Folders", + "settings.behavior": "Behavior", + "settings.converters": "Converters", + "settings.converterMenu": "Model converters", + "settings.converterMenu.desc": "Closed by default. Open this section only when you want to manually enable an optional local conversion route.", + "settings.environmentInspector": "Environment inspector", + "settings.environmentInspector.desc": "Closed by default. Open this section when you need to configure command paths or run environment checks.", + "settings.paths": "Converter paths", + "settings.diagnostics": "Converter command diagnostics", + "settings.performance": "Performance & display", + "settings.mobileSupport": "Mobile support", + "settings.knowledgeGeneration": "Knowledge generation", + + // Folders + "settings.sourceModelFolder": "Source model folder", + "settings.sourceModelFolder.desc": "Vault folder where source model files are stored.", + "settings.reportFolder": "Report folder", + "settings.reportFolder.desc": "Vault folder where generated knowledge notes are saved.", + "settings.partFolder": "Part notes folder", + "settings.partFolder.desc": "Vault folder where generated part note drafts are saved.", + "settings.snapshotFolder": "Snapshot folder", + "settings.snapshotFolder.desc": "Vault folder where exported snapshots are saved.", + + // Behavior + "settings.autoGenerateKnowledgeNotes": "Auto-generate knowledge notes", + "settings.autoGenerateKnowledgeNotes.desc": "Reserved for a future automation flow. For now, generate notes manually from the command palette.", + "settings.annotationPreviewMode": "Annotation preview mode", + "settings.annotationPreviewMode.desc": "Choose how bound note previews render in annotation popovers and the editor.", + "settings.annotationPreviewMode.plainText": "Plain text", + "settings.annotationPreviewMode.markdown": "Markdown", + "settings.annotationDisplayMode": "Annotation display mode", + "settings.annotationDisplayMode.desc": "Choose how bookmark pins appear over the model.", + "settings.annotationDisplayMode.snippet": "Full snippet", + "settings.annotationDisplayMode.surface": "Single surface", + "settings.annotationDisplayMode.dot": "Single dot", + "settings.previewRendererRollout": "Preview compatibility mode", + "settings.previewRendererRollout.desc": "Controls how widely the Three.js preview path is used for single-model previews (GLB, GLTF, STL, PLY, OBJ). Switch back to Compatibility mode if pin projection, occlusion, edit pins, snapshots, or toolbar behavior regress. 3dgrid is not affected by this setting.", + "settings.previewRendererRollout.babylonSafe": "Compatibility mode", + "settings.previewRendererRollout.readonly": "Reading surfaces only", + "settings.previewRendererRollout.direct": "Reading + file view (Recommended)", + "settings.useThreeRenderer": "Use Three.js renderer", + "settings.useThreeRenderer.desc": "Toggle between Three.js (faster, lighter) and Babylon.js (full compatibility) for single-model previews. Three.js supports GLB/GLTF/STL/PLY/OBJ. 3dgrid always uses Babylon.js.", + "settings.experimentalThreeWorkbench": "Experimental Three workbench", + "settings.experimentalThreeWorkbench.desc": "Try the Three.js workbench path for direct GLB/GLTF files only. If loading fails, the file view falls back to Babylon.js automatically.", + "settings.autoRotateDefault": "Auto-rotate by default", + "settings.autoRotateDefault.desc": "Start model previews with auto-rotation enabled.", + "settings.snapshotNaming": "Snapshot naming", + "settings.snapshotNaming.desc": "How exported snapshot files are named.", + "settings.snapshotNaming.modelName": "Model name + timestamp", + "settings.snapshotNaming.timestamp": "Timestamp only", + "settings.logLevel": "Log level", + "settings.logLevel.desc": "Controls plugin runtime log verbosity in the developer console.", + "settings.language": "Language", + "settings.language.desc": "Display language for plugin settings. Takes effect immediately.", + "settings.analysisMode": "AI drafting mode", + "settings.analysisMode.desc": "Controls whether knowledge-note generation stays local or also requests a sanitized remote draft. Raw model upload is blocked by the current client.", + "settings.analysisMode.local": "Local evidence only", + "settings.analysisMode.hybrid": "Local evidence + remote draft", + "settings.analysisMode.remote": "Remote draft from evidence", + "settings.serviceBaseUrl": "Draft service URL", + "settings.serviceBaseUrl.desc": "Optional base URL for a service that accepts POST /draft-note. Leave empty to keep all drafting local.", + "settings.sendGeometrySummaryToRemote": "Send geometry summary", + "settings.sendGeometrySummaryToRemote.desc": "Allow sanitized mesh counts, bounds, part candidates, annotation coordinates, and nearest-part links to be included in remote draft input.", + "settings.sendPreviewImagesToRemote": "Send preview image references", + "settings.sendPreviewImagesToRemote.desc": "Allow generated preview image paths to be listed in the remote draft input. Image bytes are not uploaded by this client.", + "settings.sendRawModelToRemote": "Send raw model file", + "settings.sendRawModelToRemote.desc": "Reserved for future explicit upload support. If enabled manually, remote draft requests are blocked instead of uploading the model.", + + // Converters + "settings.enableCad": "Enable cad conversion for step, iges, and brep files", + "settings.enableCad.desc": "Enable cad conversion for step, iges, and brep formats. Requires cadquery and trimesh in your python environment.", + "settings.enableObj2gltf": "Enable obj2gltf converter (experimental)", + "settings.enableObj2gltf.desc": "Keep obj direct loading as the default. Enable this only if you want an optional local normalization route through obj2gltf.", + "settings.preferObj2gltf": "Prefer obj2gltf for obj", + "settings.preferObj2gltf.desc": "Recommended default is off. Turn this on only when you want normalized output files or direct obj loading is not good enough.", + "settings.enableFbx2gltf": "Enable FBX2glTF converter", + "settings.enableFbx2gltf.desc": "Enable conversion for fbx files via FBX2glTF. Requires the FBX2glTF binary installed locally.", + "settings.enableMesh": "Enable mesh conversion for 3mf and dae files", + "settings.enableMesh.desc": "Enable conversion for 3mf and dae formats via python trimesh. Requires trimesh, numpy, networkx, and pycollada in your python environment.", + "settings.enableSldprt": "Enable sldprt conversion for SolidWorks files", + "settings.enableSldprt.desc": "Enable conversion for SolidWorks sldprt files via FreeCAD. Requires FreeCAD installed locally.", + "settings.mobileSupport.desc": "On iOS, iPadOS, and Android, direct formats like GLB, GLTF, STL, OBJ, and PLY are supported. Local converter settings and diagnostics remain desktop-only.", + + // Converter paths + "settings.pythonCmd": "Path to the python command for cad conversion", + "settings.pythonCmd.desc": "Optional path to the python command used for cad conversion. Windows usually uses py. macOS and Linux usually use python3. Overrides auto-discovery when set.", + "settings.freecadCmd": "Path to the FreeCAD command for sldprt conversion", + "settings.freecadCmd.desc": "Optional path to the FreeCAD command used for SolidWorks file conversion. Windows usually uses FreeCADCmd.exe, macOS usually uses FreeCADCmd, and Linux usually uses freecadcmd. Overrides auto-discovery when set.", + "settings.obj2gltfCmd": "Path to the obj2gltf command", + "settings.obj2gltfCmd.desc": "Optional path to the obj2gltf command. Windows usually uses obj2gltf.cmd, and macOS and Linux usually use obj2gltf. Overrides auto-discovery when set.", + "settings.fbx2gltfCmd": "FBX2glTF command path", + "settings.fbx2gltfCmd.desc": "Optional path to the FBX2glTF command. Windows usually uses FBX2glTF.exe, and macOS and Linux usually use FBX2glTF. Overrides auto-discovery when set.", + "settings.assimpCmd": "Path to the python command for 3mf and dae conversion", + "settings.assimpCmd.desc": "Optional path to the python command used for 3mf and dae conversion. Windows usually uses py. macOS and Linux usually use python3. Overrides auto-discovery when set.", + + // Diagnostics + "settings.diagnostics.desc": "Shows the exact executable path the plugin would use right now and runs lightweight self-checks for Python environments and converter CLIs.", + "settings.diagnostics.idle": "Diagnostics are off by default. Click Check now to run them manually.", + "settings.diagnostics.checkNow": "Check now", + "settings.diagnostics.checking": "Checking...", + "settings.diagnostics.refreshed": "Converter command diagnostics refreshed.", + "settings.diagnostics.checkingAvailability": "Checking converter command availability...", + "settings.diagnostics.available": "available", + "settings.diagnostics.notFound": "not found", + "settings.diagnostics.sourceLabel": "Source", + "settings.diagnostics.commandLabel": "Command", + "settings.diagnostics.resolvedPathLabel": "Resolved path", + "settings.diagnostics.selfCheckLabel": "Self-check", + "settings.diagnostics.selfCheckOk": "passed", + "settings.diagnostics.selfCheckFailed": "failed", + "settings.diagnostics.cadPythonCheck": "Python packages (cadquery, trimesh)", + "settings.diagnostics.meshPythonCheck": "Python packages (trimesh, numpy, networkx, collada)", + "settings.diagnostics.freecadCmdCheck": "FreeCADCmd launch probe", + "settings.diagnostics.obj2gltfCheck": "obj2gltf launch probe", + "settings.diagnostics.fbx2gltfCheck": "FBX2glTF launch probe", + + // Performance + "settings.canvasHeight": "Default canvas height", + "settings.canvasHeight.desc": "Default height (px) for inline model previews. Range: 200–800.", + "settings.autoRotateSpeed": "Auto-rotate speed", + "settings.autoRotateSpeed.desc": "Rotation speed when auto-rotate is enabled. Range: 0.1–2.0.", + "settings.renderQuality": "Render quality", + "settings.renderQuality.desc": "Higher quality uses more GPU resources. Affects anti-aliasing and resolution.", + "settings.renderScale": "Resolution scale", + "settings.renderScale.desc": "Render resolution multiplier. 1.0 = native, 0.5 = half, 2.0 = double (supersampling). Range: 0.25–2.0.", + + // Model load feedback + "modelLoad.warningTitle": "Model preview unavailable", + "modelLoad.warningMessage": "{ext} files need the {converterName} converter enabled in plugin settings before they can load.", + "modelLoad.warningHint": "Enable the matching converter in plugin settings, then reload this file.", + "modelLoad.mobileWarningMessage": "{ext} files need local conversion tools that are unavailable on iOS, iPadOS, and Android.", + "modelLoad.mobileWarningHint": "Open this file on desktop, or convert it to GLB, GLTF, OBJ, STL, or PLY first.", + "modelLoad.errorTitle": "Couldn't display this model", + "modelLoad.errorMessage": "Failed to load: {reason}", + "modelLoad.errorHint": "Check the file format or open the developer console for details.", + + // Heading pin badge + "headingPin.showSingle": "Show linked pin", + "headingPin.showMultiple": "Show linked pins", + "headingPin.linkedTo": "Pin linked to: {models}", + + // Helper toolbar + "helper.resetViewLabel": "Reset view", + "helper.resetViewDone": "Reset", + "helper.copyModelInfoLabel": "Copy model info as Markdown", + "helper.copySelectedPartInfoLabel": "Copy selected part info", + "helper.noSelectedPart": "Select a part first", + "helper.copied": "Copied!", + "helper.failed": "Failed", + "helper.toggleWireframeLabel": "Toggle wireframe", + "helper.wireframeOn": "Wireframe", + "helper.wireframeOff": "Solid", + "helper.toggleAxesLabel": "Toggle orientation axes", + "helper.axesOn": "Axes on", + "helper.axesOff": "Axes off", + "helper.toggleBoundingBoxLabel": "Toggle bounding box", + "helper.boundingBoxOn": "Bounding box on", + "helper.boundingBoxOff": "Bounding box off", + "helper.toggleFocusSelectionLabel": "Focus selected part", + "helper.focusSelectionOn": "Focus mode on", + "helper.focusSelectionOff": "Focus mode off", + "helper.toggleDisassemblyLabel": "Toggle disassembly mode", + "helper.disassemblyOn": "Disassembly on", + "helper.disassemblyOff": "Disassembly off", + "helper.resetPartsLabel": "Reset disassembled parts", + "helper.partsReset": "Parts reset", + "helper.changeResolutionLabel": "Change resolution", + "helper.resolutionValue": "Resolution: {value}", + "helper.toggleAnimationLabel": "Play or pause animation", + "helper.playing": "Playing", + "helper.paused": "Paused", + "helper.toggleMeasurementLabel": "Toggle distance measurement", + "helper.measurementOn": "Measurement on", + "helper.measurementOff": "Measurement off", + "helper.clearMeasurementsLabel": "Clear measurements", + "helper.measurementsCleared": "Cleared", + "helper.calibrateLabel": "Calibrate measurement scale", + "helper.calibrateTitle": "Measurement Calibration", + "helper.calibrateCurrent": "Current size:", + "helper.calibrateReal": "Real size:", + "helper.calibrateLock": "Lock ratio", + "helper.calibrateApply": "Apply", + "helper.calibrateReset": "Reset", + "helper.calibrated": "Scale applied", + "helper.calibrateResetDone": "Scale reset", + "helper.calibrateOpen": "Calibration panel opened", + "helper.calibrateClose": "Calibration panel closed", + "helper.removePreviewLabel": "Remove preview", + "helper.copySnapshotLabel": "Copy snapshot", + "helper.saveSnapshotLabel": "Save snapshot to vault", + "helper.saved": "Saved!", + "helper.downloadSnapshotLabel": "Download snapshot", + "helper.downloaded": "Downloaded!", + "helper.toggleAnnotationLabel": "Toggle annotation mode", + "helper.toggleAnnotationsVisibilityLabel": "Show or hide annotations", + "helper.annotateOn": "Annotation mode on", + "helper.annotateOff": "Annotation mode off", + "helper.annotationsVisible": "Annotations shown", + "helper.annotationsHidden": "Annotations hidden", + "helper.enableInteractionLabel": "Enable touch interaction", + "helper.disableInteractionLabel": "Return to scroll mode", + "helper.interactionOn": "Model interaction on", + "helper.interactionOff": "Scroll mode on", + "helper.showMoreActionsLabel": "Show more actions", + "helper.hideMoreActionsLabel": "Hide extra actions", + "helper.moreActionsShown": "More actions shown", + "helper.moreActionsHidden": "Extra actions hidden", + "helper.interactAction": "Interact", + "helper.scrollAction": "Scroll", + + // Workbench and views + "workbench.emptyTitle": "No model", + "workbench.emptyText": "Use the \"import 3D model\" command to load a GLB, GLTF, STL, OBJ, or PLY file.", + "workbench.modelTitle": "Model", + "workbench.studioTitle": "AI Model Workbench", + "workbench.studioTagline": "Inspect, annotate, and turn 3D assets into linked notes.", + "workbench.navLabel": "Workbench sections", + "workbench.navGallery": "Gallery", + "workbench.navLibrary": "Library", + "workbench.navNotebooks": "Notebooks", + "workbench.navSettings": "Settings", + "workbench.sourcesTitle": "Model sources", + "workbench.layersTitle": "Review layers", + "workbench.viewModeTitle": "View mode", + "workbench.modeMesh": "Mesh view", + "workbench.modeFocus": "Focus selection", + "workbench.modeMeshShort": "Mesh", + "workbench.modeFocusShort": "Focus", + "workbench.previewViewsTitle": "Preview views", + "workbench.connectionsTitle": "Knowledge connections", + "workbench.currentModelLabel": "Current model", + "workbench.noReportYet": "No report note yet", + "workbench.noIndexYet": "No knowledge index yet. Generate a knowledge note first.", + "workbench.noModelLoaded": "No model loaded", + "workbench.disassemblyTitle": "Disassembly", + "workbench.explodeLabel": "Explode", + "workbench.summaryTitle": "Summary", + "workbench.meshesLabel": "Meshes", + "workbench.splatsLabel": "Splats", + "workbench.trianglesLabel": "Triangles", + "workbench.verticesLabel": "Vertices", + "workbench.materialsLabel": "Materials", + "workbench.boundingSizeLabel": "Bounds", + "workbench.centerLabel": "Center", + "workbench.selectedPartTitle": "Selected Part", + "workbench.partMeshLabel": "Mesh", + "workbench.noSelectedPart": "Click a model part to inspect it here.", + "workbench.tagsTitle": "Tags", + "workbench.noTagsYet": "No tags yet", + "workbench.addTagPlaceholder": "Add tag...", + "workbench.addTagAction": "Add", + "workbench.annotationsTitle": "Annotations", + "workbench.exitAnnotate": "Exit annotate", + "workbench.annotate": "Annotate", + "workbench.annotateHintActive": "Click the model to add a label · press Esc to exit", + "workbench.annotateHintActiveMobile": "Tap the model to add a label. Switch back to Scroll when you want to move through the note again.", + "workbench.pinCount": "{count} pin(s)", + "workbench.editAction": "Edit", + "workbench.deleteAction": "Delete", + "workbench.resetViewAction": "Reset view", + "workbench.insertInfoAction": "Insert info", + "workbench.insertGalleryAction": "Insert Gallery", + "workbench.insertCompareAction": "Insert Compare", + "workbench.playAction": "Play", + "workbench.pauseAction": "Pause", + "workbench.saveProfileAction": "Save profile", + "workbench.generateNoteAction": "Generate note", + "workbench.openNoteAction": "Open note", + "workbench.openIndexAction": "Open index", + "workbench.recordTitle": "Specimen card", + "workbench.recordSubtitle": "Current asset profile", + "workbench.notesTitle": "Analysis notes", + "workbench.whereTitle": "Where it connects", + "workbench.noteReady": "Linked note ready", + "workbench.indexReady": "Knowledge index ready", + "workbench.notePending": "Linked note pending", + "workbench.analysisLabel": "Analysis", + "workbench.settingsUnavailable": "Open this plugin from Obsidian settings to change workbench options.", + "workbench.profileSaved": "Profile saved", + "workbench.viewReset": "View reset", + "workbench.infoInserted": "Model info inserted", + "workbench.infoCopied": "Model info copied", + "workbench.templateInserted": "Template inserted", + "workbench.templateCopied": "Template copied", + "workbench.mobileHint": "Mobile tip: tap Interact to move the model, then switch back to Scroll to keep reading the note.", + "workbench.mobileHintInteractive": "Interaction mode is on. Switch back to Scroll when you want to move through the note again.", + "directView.mobileHint": "Mobile tip: use the toolbar Interact button to switch between model interaction and note scrolling.", + "directWorkbench.modelLoadInterrupted": "Model load was interrupted by a newer request.", + "directWorkbench.backendLabel": "Backend", + "directWorkbench.routeLabel": "Route", + "directWorkbench.performanceLabel": "Performance", + "directWorkbench.partCandidatesLabel": "Part candidates", + "directWorkbench.knowledgeTitle": "Knowledge", + "directWorkbench.registeredTitle": "Registered part matches", + "directWorkbench.registeredLoading": "Checking...", + "directWorkbench.registeredCount": "{count} match(es)", + "directWorkbench.registeredEmpty": "No cross-model part match yet", + "directWorkbench.registeredUnavailable": "Part evidence unavailable", + "directWorkbench.registeredOpen": "Open", + "directWorkbench.registeredOpenNote": "Note", + "directWorkbench.registeredOpenModel": "Model", + "directWorkbench.registeredSourceModel": "From {model}", + "directWorkbench.registeredTargetPartNote": "Opens matched part note", + "directWorkbench.registeredTargetSourceModel": "Opens source model", + "directWorkbench.registeredTargetUnavailable": "No linked target", + "workbench.fileNotFound": "File not found: {path}", + "annotation.selectColor": "Select color {color}", + "annotation.sectionEmpty": "Section is empty.", + "modal.selectModel": "Select a 3D model...", + "main.commandImportModel": "Import a 3D model", + "main.commandGenerateNote": "Generate knowledge note", + "main.commandOpenKnowledgeIndex": "Open knowledge index", + "main.commandClearConversionCache": "Clear conversion cache", + "main.commandCheckConverters": "Check converters", + "main.commandCopyDiagnostics": "Copy diagnostics report", + "main.converterDiagnosticsMobileUnavailable": "Converter diagnostics are only available on desktop. On iOS, iPadOS, and Android, direct formats can still load.", + "main.diagnosticsCopied": "AI Model Workbench diagnostics copied to clipboard.", + "main.diagnosticsCopyFailed": "Couldn't copy diagnostics. A sanitized diagnostics note was created instead.", + + // Inline code block and loading + "codeBlock.noModelPathOrConfig": "No model path or config specified.", + "codeBlock.jsonParseError": "JSON parse error: {error}", + "codeBlock.jsonParseLine": " (line {line})", + "codeBlock.noModelsInConfig": "No models specified in config.", + "codeBlock.unsupportedFormat": "Unsupported format: {ext}. Supported: {formats}", + "codeBlock.splatDisabled": "SPLAT preview is disabled in packaged builds. Local-only .splat support is planned first; .spz/.sog need locally bundled decoders before reevaluation.", + "codeBlock.noConfigSpecified": "No config specified.", + "codeBlock.noModelsSpecified": "No models specified.", + "codeBlock.mobileHint": "Mobile tip: use Interact to manipulate the model, then switch back to Scroll to keep moving through the note.", + "codeBlock.renderingGrid": "Rendering grid...", + "codeBlock.composeRequiresSections": "\"compose\" preset requires a \"sections\" array.", + "codeBlock.composeNoValidSections": "Compose: no valid sections.", + "codeBlock.unknownPreset": "Unknown preset: \"{preset}\". Available: compare, showcase, explode, timeline, compose", + "codeBlock.presetRequiresModels": "Preset \"{preset}\" requires {min}-{max} models, got {count}.", + "codeBlock.gridFailed": "Grid failed: {reason}", + "livePreview.mobileHint": "Mobile tip: switch between Interact and Scroll depending on whether you want to move the model or keep reading.", + "loading.default": "Loading...", + "loading.preparingModel": "Preparing model...", + "loading.loadingModel": "Loading model...", +} as const; + +export type TranslationKey = keyof typeof en; diff --git a/src/i18n/zh-CN.ts b/src/i18n/zh-CN.ts index 4a73e67..c2e9e0f 100644 --- a/src/i18n/zh-CN.ts +++ b/src/i18n/zh-CN.ts @@ -1,345 +1,345 @@ -import type { TranslationKey } from "./en"; - -export const zhCN: Record = { - // 区块标题 - "settings.title": "AI 3D 模型工作台", - "settings.folders": "文件夹", - "settings.behavior": "行为", - "settings.converters": "转换器", - "settings.converterMenu": "模型转换器", - "settings.converterMenu.desc": "默认收起。仅在你需要手动启用某条本地转换路线时再展开。", - "settings.environmentInspector": "环境检查器", - "settings.environmentInspector.desc": "默认收起。仅在需要配置命令路径或手动执行环境检查时再展开。", - "settings.paths": "转换器路径", - "settings.diagnostics": "转换器命令诊断", - "settings.performance": "性能与显示", - "settings.mobileSupport": "移动端支持", - "settings.knowledgeGeneration": "知识生成", - - // 文件夹 - "settings.sourceModelFolder": "源模型文件夹", - "settings.sourceModelFolder.desc": "存放源 3D 模型的库文件夹。", - "settings.reportFolder": "报告文件夹", - "settings.reportFolder.desc": "保存生成的知识笔记的库文件夹。", - "settings.partFolder": "部件笔记文件夹", - "settings.partFolder.desc": "保存生成的部件笔记草稿的库文件夹。", - "settings.snapshotFolder": "快照文件夹", - "settings.snapshotFolder.desc": "保存导出快照的库文件夹。", - - // 行为 - "settings.autoGenerateKnowledgeNotes": "自动生成知识笔记", - "settings.autoGenerateKnowledgeNotes.desc": "预留给后续自动化流程。当前请通过命令或工作台按钮手动生成知识笔记。", - "settings.annotationPreviewMode": "标注预览模式", - "settings.annotationPreviewMode.desc": "选择标注绑定笔记在悬浮预览和编辑器中的显示方式。", - "settings.annotationPreviewMode.plainText": "纯文本", - "settings.annotationPreviewMode.markdown": "Markdown", - "settings.annotationDisplayMode": "标注显示模式", - "settings.annotationDisplayMode.desc": "选择模型上书签标注的显示方式。", - "settings.annotationDisplayMode.snippet": "完整片段", - "settings.annotationDisplayMode.surface": "单个标签面", - "settings.annotationDisplayMode.dot": "单个圆点", - "settings.previewRendererRollout": "预览兼容模式", - "settings.previewRendererRollout.desc": "控制单模型预览(GLB、GLTF、STL、PLY、OBJ)中 Three.js 渲染路径的启用范围。只要出现 pin 投影、遮挡、编辑态 pin、快照或工具栏行为回退,就切回“兼容优先”。workbench 和 3dgrid 不受这个设置影响。", - "settings.previewRendererRollout.babylonSafe": "兼容优先", - "settings.previewRendererRollout.readonly": "仅阅读场景", - "settings.previewRendererRollout.direct": "阅读 + 文件视图(推荐)", - "settings.useThreeRenderer": "使用 Three.js 渲染器", - "settings.useThreeRenderer.desc": "在 Three.js(更快、更轻量)和 Babylon.js(完全兼容)之间切换单模型预览渲染器。Three.js 支持 GLB/GLTF/STL/PLY/OBJ。工作台和 3dgrid 始终使用 Babylon.js。", - "settings.experimentalThreeWorkbench": "实验性 Three 工作台", - "settings.experimentalThreeWorkbench.desc": "仅对直读 GLB/GLTF 文件尝试使用 Three.js 工作台路径。加载失败时,文件视图会自动回退到 Babylon.js。", - "settings.autoRotateDefault": "默认自动旋转", - "settings.autoRotateDefault.desc": "启动 3D 预览时默认开启自动旋转。", - "settings.snapshotNaming": "快照命名", - "settings.snapshotNaming.desc": "导出快照文件的命名方式。", - "settings.snapshotNaming.modelName": "模型名 + 时间戳", - "settings.snapshotNaming.timestamp": "仅时间戳", - "settings.logLevel": "日志级别", - "settings.logLevel.desc": "控制插件在开发者控制台中的日志详细程度。", - "settings.language": "语言", - "settings.language.desc": "插件设置界面的显示语言。立即生效。", - "settings.analysisMode": "AI 草稿模式", - "settings.analysisMode.desc": "控制知识笔记生成保持本地,还是额外请求经过裁剪的远程草稿。当前客户端会阻止原始模型上传。", - "settings.analysisMode.local": "仅本地证据", - "settings.analysisMode.hybrid": "本地证据 + 远程草稿", - "settings.analysisMode.remote": "基于证据的远程草稿", - "settings.serviceBaseUrl": "草稿服务 URL", - "settings.serviceBaseUrl.desc": "可选的草稿服务基础地址,服务需接收 POST /draft-note。留空时所有草稿输入都保留在本地。", - "settings.sendGeometrySummaryToRemote": "发送几何摘要", - "settings.sendGeometrySummaryToRemote.desc": "允许把经过裁剪的网格数量、包围盒、部件候选、标注坐标和最近部件关联加入远程草稿输入。", - "settings.sendPreviewImagesToRemote": "发送预览图引用", - "settings.sendPreviewImagesToRemote.desc": "允许在远程草稿输入中列出生成的预览图路径。当前客户端不会上传图片字节。", - "settings.sendRawModelToRemote": "发送原始模型文件", - "settings.sendRawModelToRemote.desc": "预留给未来显式上传支持。若手动开启,远程草稿请求会被阻止,不会上传模型。", - - // 转换器 - "settings.enableCad": "启用 CAD 转换器 (STEP/IGES/BREP)", - "settings.enableCad.desc": "启用 STEP/IGES/BREP 格式的 CAD 转换路线,通过 Python CadQuery (OpenCASCADE)。需要:pip install cadquery trimesh", - "settings.enableObj2gltf": "启用 obj2gltf 转换器(实验性)", - "settings.enableObj2gltf.desc": "默认使用 OBJ 直接加载。仅在需要本地标准化 GLB 输出时启用。", - "settings.preferObj2gltf": "OBJ 优先使用 obj2gltf", - "settings.preferObj2gltf.desc": "默认关闭。仅在需要标准化 GLB 输出或直接 OBJ 加载效果不佳时开启。", - "settings.enableFbx2gltf": "启用 FBX2glTF 转换器", - "settings.enableFbx2gltf.desc": "启用 FBX 文件通过 FBX2glTF 转换。需要本地安装 FBX2glTF 二进制文件。", - "settings.enableMesh": "启用网格转换器 (3MF/DAE)", - "settings.enableMesh.desc": "启用 3MF 和 DAE (Collada) 格式的转换路线,通过 Python trimesh。需要安装 Python 和 trimesh (pip install trimesh numpy networkx pycollada)。", - "settings.enableSldprt": "启用 SLDPRT 转换器 (SolidWorks)", - "settings.enableSldprt.desc": "启用 SolidWorks .sldprt 文件通过 FreeCAD 转换。需要安装 FreeCAD (https://www.freecad.org/downloads.php)。", - "settings.mobileSupport.desc": "在 iOS、iPadOS 和 Android 上,GLB、GLTF、STL、OBJ、PLY 这类直读格式可用。本地转换器设置和命令诊断仍仅支持桌面端。", - - // 转换器路径 - "settings.pythonCmd": "Python 命令路径(CAD 用)", - "settings.pythonCmd.desc": "可选的 Python 命令路径,用于 CAD 转换。Windows 通常用 py,macOS 和 Linux 通常用 python3。设置后覆盖自动发现和 AI3D_FREECAD_CMD。", - "settings.freecadCmd": "FreeCAD 命令路径(SLDPRT 用)", - "settings.freecadCmd.desc": "可选的 FreeCAD 命令路径,用于 SolidWorks 文件转换。Windows 通常用 FreeCADCmd.exe,macOS 通常用 FreeCADCmd,Linux 通常用 freecadcmd。设置后覆盖自动发现和 AI3D_FREECADCMD。", - "settings.obj2gltfCmd": "obj2gltf 命令路径", - "settings.obj2gltfCmd.desc": "可选的 obj2gltf 命令路径。Windows 通常用 obj2gltf.cmd,macOS 和 Linux 通常用 obj2gltf。设置后覆盖自动发现和 AI3D_OBJ2GLTF_CMD。", - "settings.fbx2gltfCmd": "FBX2glTF 命令路径", - "settings.fbx2gltfCmd.desc": "可选的 FBX2glTF 命令路径。Windows 通常用 FBX2glTF.exe,macOS 和 Linux 通常用 FBX2glTF。设置后覆盖自动发现和 AI3D_FBX2GLTF_CMD。", - "settings.assimpCmd": "Python 命令路径(3MF/DAE 用)", - "settings.assimpCmd.desc": "可选的 Python 命令路径,用于 3MF 和 DAE 转换。Windows 通常用 py,macOS 和 Linux 通常用 python3。设置后覆盖自动发现和 AI3D_ASSIMP_CMD。", - - // 诊断 - "settings.diagnostics.desc": "显示插件当前实际使用的可执行文件路径,并为 Python 环境和转换器命令执行轻量自检。", - "settings.diagnostics.idle": "环境检查默认关闭。点击“立即检查”后才会执行。", - "settings.diagnostics.checkNow": "立即检查", - "settings.diagnostics.checking": "检查中...", - "settings.diagnostics.refreshed": "AI 3D 转换器命令诊断已刷新。", - "settings.diagnostics.checkingAvailability": "正在检查转换器命令可用性...", - "settings.diagnostics.available": "可用", - "settings.diagnostics.notFound": "未找到", - "settings.diagnostics.sourceLabel": "来源", - "settings.diagnostics.commandLabel": "命令", - "settings.diagnostics.resolvedPathLabel": "解析路径", - "settings.diagnostics.selfCheckLabel": "自检", - "settings.diagnostics.selfCheckOk": "通过", - "settings.diagnostics.selfCheckFailed": "失败", - "settings.diagnostics.cadPythonCheck": "Python 包(cadquery、trimesh)", - "settings.diagnostics.meshPythonCheck": "Python 包(trimesh、numpy、networkx、collada)", - "settings.diagnostics.freecadCmdCheck": "FreeCADCmd 启动探测", - "settings.diagnostics.obj2gltfCheck": "obj2gltf 启动探测", - "settings.diagnostics.fbx2gltfCheck": "FBX2glTF 启动探测", - - // 性能 - "settings.canvasHeight": "默认画布高度", - "settings.canvasHeight.desc": "内联 3D 预览的默认高度(像素)。范围:200–800。", - "settings.autoRotateSpeed": "自动旋转速度", - "settings.autoRotateSpeed.desc": "启用自动旋转时的旋转速度。范围:0.1–2.0。", - "settings.renderQuality": "渲染质量", - "settings.renderQuality.desc": "更高质量使用更多 GPU 资源。影响抗锯齿和分辨率。", - "settings.renderScale": "渲染缩放", - "settings.renderScale.desc": "渲染分辨率倍数。1.0 = 原始,0.5 = 一半,2.0 = 双倍(超采样)。范围:0.25–2.0。", - - // 模型加载提示 - "modelLoad.warningTitle": "暂时无法预览模型", - "modelLoad.warningMessage": "{ext} 文件需要先在插件设置中启用 {converterName} 转换器,才能加载。", - "modelLoad.warningHint": "请先在插件设置中启用对应转换器,然后重新加载当前文件。", - "modelLoad.mobileWarningMessage": "{ext} 文件需要本地转换工具,但这些工具在 iOS、iPadOS 和 Android 上不可用。", - "modelLoad.mobileWarningHint": "请在桌面端打开此文件,或先将它转换为 GLB、GLTF、OBJ、STL 或 PLY。", - "modelLoad.errorTitle": "无法显示这个模型", - "modelLoad.errorMessage": "加载失败:{reason}", - "modelLoad.errorHint": "请检查文件格式,或打开开发者控制台查看详细信息。", - - // 标题 pin 徽标 - "headingPin.showSingle": "显示关联标注", - "headingPin.showMultiple": "显示关联标注", - "headingPin.linkedTo": "关联到:{models}", - - // 工具栏 - "helper.resetViewLabel": "重置视图", - "helper.resetViewDone": "已重置", - "helper.copyModelInfoLabel": "复制模型信息为 Markdown", - "helper.copySelectedPartInfoLabel": "复制选中部件信息", - "helper.noSelectedPart": "请先点击一个部件", - "helper.copied": "已复制", - "helper.failed": "失败", - "helper.toggleWireframeLabel": "切换线框显示", - "helper.wireframeOn": "线框", - "helper.wireframeOff": "实体", - "helper.toggleAxesLabel": "切换方向坐标轴", - "helper.axesOn": "坐标轴已开启", - "helper.axesOff": "坐标轴已关闭", - "helper.toggleBoundingBoxLabel": "切换包围盒", - "helper.boundingBoxOn": "包围盒已开启", - "helper.boundingBoxOff": "包围盒已关闭", - "helper.toggleFocusSelectionLabel": "聚焦选中部件", - "helper.focusSelectionOn": "聚焦模式已开启", - "helper.focusSelectionOff": "聚焦模式已关闭", - "helper.toggleDisassemblyLabel": "切换分解模式", - "helper.disassemblyOn": "分解模式已开启", - "helper.disassemblyOff": "分解模式已关闭", - "helper.resetPartsLabel": "重置分解部件", - "helper.partsReset": "部件已重置", - "helper.changeResolutionLabel": "切换分辨率", - "helper.resolutionValue": "分辨率:{value}", - "helper.toggleAnimationLabel": "播放或暂停动画", - "helper.playing": "播放中", - "helper.paused": "已暂停", - "helper.toggleMeasurementLabel": "切换距离测量", - "helper.measurementOn": "测量已开启", - "helper.measurementOff": "测量已关闭", - "helper.clearMeasurementsLabel": "清除测量", - "helper.measurementsCleared": "已清除", - "helper.calibrateLabel": "校准测量比例", - "helper.calibrateTitle": "测量校准", - "helper.calibrateCurrent": "当前尺寸:", - "helper.calibrateReal": "真实尺寸:", - "helper.calibrateLock": "锁定比例", - "helper.calibrateApply": "应用", - "helper.calibrateReset": "重置", - "helper.calibrated": "比例已应用", - "helper.calibrateResetDone": "比例已重置", - "helper.calibrateOpen": "校准面板已打开", - "helper.calibrateClose": "校准面板已关闭", - "helper.removePreviewLabel": "移除预览", - "helper.copySnapshotLabel": "复制快照", - "helper.saveSnapshotLabel": "保存快照到仓库", - "helper.saved": "已保存", - "helper.downloadSnapshotLabel": "下载快照", - "helper.downloaded": "已下载", - "helper.toggleAnnotationLabel": "切换标注模式", - "helper.toggleAnnotationsVisibilityLabel": "显示或隐藏标注", - "helper.annotateOn": "标注模式已开启", - "helper.annotateOff": "标注模式已关闭", - "helper.annotationsVisible": "标注已显示", - "helper.annotationsHidden": "标注已隐藏", - "helper.enableInteractionLabel": "启用触控交互", - "helper.disableInteractionLabel": "切回滚动模式", - "helper.interactionOn": "模型交互已开启", - "helper.interactionOff": "滚动模式已开启", - "helper.showMoreActionsLabel": "显示更多操作", - "helper.hideMoreActionsLabel": "收起额外操作", - "helper.moreActionsShown": "已展开更多操作", - "helper.moreActionsHidden": "已收起额外操作", - "helper.interactAction": "交互", - "helper.scrollAction": "滚动", - - // 工作台与视图 - "workbench.emptyTitle": "暂无模型", - "workbench.emptyText": "使用“导入 3D 模型”命令加载 GLB、GLTF、STL、OBJ 或 PLY 文件。", - "workbench.modelTitle": "3D 模型", - "workbench.studioTitle": "AI 模型工作台", - "workbench.studioTagline": "检查、标注,并把 3D 资产整理成双链笔记。", - "workbench.navLabel": "工作台分区", - "workbench.navGallery": "画廊", - "workbench.navLibrary": "资料库", - "workbench.navNotebooks": "笔记本", - "workbench.navSettings": "设置", - "workbench.sourcesTitle": "模型来源", - "workbench.layersTitle": "审阅层", - "workbench.viewModeTitle": "视图模式", - "workbench.modeMesh": "网格视图", - "workbench.modeFocus": "聚焦选区", - "workbench.modeMeshShort": "网格", - "workbench.modeFocusShort": "聚焦", - "workbench.previewViewsTitle": "预览视图", - "workbench.connectionsTitle": "知识连接", - "workbench.currentModelLabel": "当前模型", - "workbench.noReportYet": "还没有报告笔记", - "workbench.noIndexYet": "还没有知识索引。请先生成知识笔记。", - "workbench.noModelLoaded": "尚未加载模型", - "workbench.disassemblyTitle": "分解", - "workbench.explodeLabel": "爆炸", - "workbench.summaryTitle": "摘要", - "workbench.meshesLabel": "网格", - "workbench.splatsLabel": "点云", - "workbench.trianglesLabel": "三角形", - "workbench.verticesLabel": "顶点", - "workbench.materialsLabel": "材质", - "workbench.boundingSizeLabel": "包围盒", - "workbench.centerLabel": "中心", - "workbench.selectedPartTitle": "当前选中部件", - "workbench.partMeshLabel": "网格", - "workbench.noSelectedPart": "点击模型中的部件后会显示详细信息。", - "workbench.tagsTitle": "标签", - "workbench.noTagsYet": "还没有标签", - "workbench.addTagPlaceholder": "添加标签...", - "workbench.addTagAction": "添加", - "workbench.annotationsTitle": "标注", - "workbench.exitAnnotate": "退出标注", - "workbench.annotate": "标注", - "workbench.annotateHintActive": "点击模型添加标签 · 按 Esc 退出", - "workbench.annotateHintActiveMobile": "点按模型添加标签。需要继续阅读时切回“滚动”。", - "workbench.pinCount": "{count} 个标注", - "workbench.editAction": "编辑", - "workbench.deleteAction": "删除", - "workbench.resetViewAction": "重置视图", - "workbench.insertInfoAction": "插入信息", - "workbench.insertGalleryAction": "插入 Gallery", - "workbench.insertCompareAction": "插入对比", - "workbench.playAction": "播放", - "workbench.pauseAction": "暂停", - "workbench.saveProfileAction": "保存配置", - "workbench.generateNoteAction": "生成笔记", - "workbench.openNoteAction": "打开笔记", - "workbench.openIndexAction": "打开索引", - "workbench.recordTitle": "标本卡", - "workbench.recordSubtitle": "当前资产档案", - "workbench.notesTitle": "分析札记", - "workbench.whereTitle": "关联位置", - "workbench.noteReady": "关联笔记已就绪", - "workbench.indexReady": "知识索引已就绪", - "workbench.notePending": "关联笔记待生成", - "workbench.analysisLabel": "分析", - "workbench.settingsUnavailable": "请从 Obsidian 设置中打开本插件来调整工作台选项。", - "workbench.profileSaved": "配置已保存", - "workbench.viewReset": "视图已重置", - "workbench.infoInserted": "模型信息已插入", - "workbench.infoCopied": "模型信息已复制", - "workbench.templateInserted": "模板已插入", - "workbench.templateCopied": "模板已复制", - "workbench.mobileHint": "移动端提示:需要操作模型时点“交互”,继续阅读笔记时切回“滚动”。", - "workbench.mobileHintInteractive": "当前为交互模式。需要继续滚动笔记时,请切回“滚动”。", - "directView.mobileHint": "移动端提示:使用下方工具栏里的“交互”按钮,在模型操作和笔记滚动之间切换。", - "directWorkbench.modelLoadInterrupted": "模型加载被新请求中断。", - "directWorkbench.backendLabel": "后端", - "directWorkbench.routeLabel": "路由", - "directWorkbench.performanceLabel": "性能", - "directWorkbench.partCandidatesLabel": "候选零件", - "directWorkbench.knowledgeTitle": "知识", - "directWorkbench.registeredTitle": "已注册零件匹配", - "directWorkbench.registeredLoading": "检查中...", - "directWorkbench.registeredCount": "{count} 个匹配", - "directWorkbench.registeredEmpty": "暂无跨模型零件匹配", - "directWorkbench.registeredUnavailable": "暂无零件证据", - "directWorkbench.registeredOpen": "打开", - "directWorkbench.registeredOpenNote": "笔记", - "directWorkbench.registeredOpenModel": "模型", - "directWorkbench.registeredSourceModel": "来自 {model}", - "directWorkbench.registeredTargetPartNote": "打开匹配零件笔记", - "directWorkbench.registeredTargetSourceModel": "打开来源模型", - "directWorkbench.registeredTargetUnavailable": "暂无可打开目标", - "workbench.fileNotFound": "未找到文件:{path}", - "annotation.selectColor": "选择颜色 {color}", - "annotation.sectionEmpty": "该段内容为空。", - "modal.selectModel": "选择一个 3D 模型...", - "main.commandImportModel": "导入 3D 模型", - "main.commandGenerateNote": "生成知识笔记", - "main.commandOpenKnowledgeIndex": "打开知识索引", - "main.commandClearConversionCache": "清除转换缓存", - "main.commandCheckConverters": "检查转换器", - "main.commandCopyDiagnostics": "复制诊断报告", - "main.converterDiagnosticsMobileUnavailable": "转换器诊断仅支持桌面端。在 iOS、iPadOS 和 Android 上,直读格式仍可加载。", - "main.diagnosticsCopied": "AI Model Workbench 诊断报告已复制到剪贴板。", - "main.diagnosticsCopyFailed": "无法复制诊断报告,已改为创建一份脱敏诊断笔记。", - - // 内联代码块与加载 - "codeBlock.noModelPathOrConfig": "未指定模型路径或配置。", - "codeBlock.jsonParseError": "JSON 解析错误:{error}", - "codeBlock.jsonParseLine": "(第 {line} 行)", - "codeBlock.noModelsInConfig": "配置中未指定模型。", - "codeBlock.unsupportedFormat": "不支持的格式:{ext}。支持:{formats}", - "codeBlock.splatDisabled": "当前打包版本暂未启用 SPLAT 预览。后续会优先恢复本地-only .splat;.spz/.sog 需要本地打包解码器后再评估。", - "codeBlock.noConfigSpecified": "未指定配置。", - "codeBlock.noModelsSpecified": "未指定模型。", - "codeBlock.mobileHint": "移动端提示:需要操作模型时点“交互”,继续阅读笔记时切回“滚动”。", - "codeBlock.renderingGrid": "正在渲染网格...", - "codeBlock.composeRequiresSections": "“compose” 预设需要提供 “sections” 数组。", - "codeBlock.composeNoValidSections": "Compose:没有有效的分段。", - "codeBlock.unknownPreset": "未知预设:“{preset}”。可用:compare、showcase、explode、timeline、compose", - "codeBlock.presetRequiresModels": "预设 “{preset}” 需要 {min}-{max} 个模型,当前为 {count} 个。", - "codeBlock.gridFailed": "网格渲染失败:{reason}", - "livePreview.mobileHint": "移动端提示:需要拖动模型时切到“交互”,继续阅读时切回“滚动”。", - "loading.default": "加载中...", - "loading.preparingModel": "正在准备模型...", - "loading.loadingModel": "正在加载模型...", -}; +import type { TranslationKey } from "./en"; + +export const zhCN: Record = { + // 区块标题 + "settings.title": "AI 3D 模型工作台", + "settings.folders": "文件夹", + "settings.behavior": "行为", + "settings.converters": "转换器", + "settings.converterMenu": "模型转换器", + "settings.converterMenu.desc": "默认收起。仅在你需要手动启用某条本地转换路线时再展开。", + "settings.environmentInspector": "环境检查器", + "settings.environmentInspector.desc": "默认收起。仅在需要配置命令路径或手动执行环境检查时再展开。", + "settings.paths": "转换器路径", + "settings.diagnostics": "转换器命令诊断", + "settings.performance": "性能与显示", + "settings.mobileSupport": "移动端支持", + "settings.knowledgeGeneration": "知识生成", + + // 文件夹 + "settings.sourceModelFolder": "源模型文件夹", + "settings.sourceModelFolder.desc": "存放源 3D 模型的库文件夹。", + "settings.reportFolder": "报告文件夹", + "settings.reportFolder.desc": "保存生成的知识笔记的库文件夹。", + "settings.partFolder": "部件笔记文件夹", + "settings.partFolder.desc": "保存生成的部件笔记草稿的库文件夹。", + "settings.snapshotFolder": "快照文件夹", + "settings.snapshotFolder.desc": "保存导出快照的库文件夹。", + + // 行为 + "settings.autoGenerateKnowledgeNotes": "自动生成知识笔记", + "settings.autoGenerateKnowledgeNotes.desc": "预留给后续自动化流程。当前请通过命令或工作台按钮手动生成知识笔记。", + "settings.annotationPreviewMode": "标注预览模式", + "settings.annotationPreviewMode.desc": "选择标注绑定笔记在悬浮预览和编辑器中的显示方式。", + "settings.annotationPreviewMode.plainText": "纯文本", + "settings.annotationPreviewMode.markdown": "Markdown", + "settings.annotationDisplayMode": "标注显示模式", + "settings.annotationDisplayMode.desc": "选择模型上书签标注的显示方式。", + "settings.annotationDisplayMode.snippet": "完整片段", + "settings.annotationDisplayMode.surface": "单个标签面", + "settings.annotationDisplayMode.dot": "单个圆点", + "settings.previewRendererRollout": "预览兼容模式", + "settings.previewRendererRollout.desc": "控制单模型预览(GLB、GLTF、STL、PLY、OBJ)中 Three.js 渲染路径的启用范围。只要出现 pin 投影、遮挡、编辑态 pin、快照或工具栏行为回退,就切回“兼容优先”。workbench 和 3dgrid 不受这个设置影响。", + "settings.previewRendererRollout.babylonSafe": "兼容优先", + "settings.previewRendererRollout.readonly": "仅阅读场景", + "settings.previewRendererRollout.direct": "阅读 + 文件视图(推荐)", + "settings.useThreeRenderer": "使用 Three.js 渲染器", + "settings.useThreeRenderer.desc": "在 Three.js(更快、更轻量)和 Babylon.js(完全兼容)之间切换单模型预览渲染器。Three.js 支持 GLB/GLTF/STL/PLY/OBJ。工作台和 3dgrid 始终使用 Babylon.js。", + "settings.experimentalThreeWorkbench": "实验性 Three 工作台", + "settings.experimentalThreeWorkbench.desc": "仅对直读 GLB/GLTF 文件尝试使用 Three.js 工作台路径。加载失败时,文件视图会自动回退到 Babylon.js。", + "settings.autoRotateDefault": "默认自动旋转", + "settings.autoRotateDefault.desc": "启动 3D 预览时默认开启自动旋转。", + "settings.snapshotNaming": "快照命名", + "settings.snapshotNaming.desc": "导出快照文件的命名方式。", + "settings.snapshotNaming.modelName": "模型名 + 时间戳", + "settings.snapshotNaming.timestamp": "仅时间戳", + "settings.logLevel": "日志级别", + "settings.logLevel.desc": "控制插件在开发者控制台中的日志详细程度。", + "settings.language": "语言", + "settings.language.desc": "插件设置界面的显示语言。立即生效。", + "settings.analysisMode": "AI 草稿模式", + "settings.analysisMode.desc": "控制知识笔记生成保持本地,还是额外请求经过裁剪的远程草稿。当前客户端会阻止原始模型上传。", + "settings.analysisMode.local": "仅本地证据", + "settings.analysisMode.hybrid": "本地证据 + 远程草稿", + "settings.analysisMode.remote": "基于证据的远程草稿", + "settings.serviceBaseUrl": "草稿服务 URL", + "settings.serviceBaseUrl.desc": "可选的草稿服务基础地址,服务需接收 POST /draft-note。留空时所有草稿输入都保留在本地。", + "settings.sendGeometrySummaryToRemote": "发送几何摘要", + "settings.sendGeometrySummaryToRemote.desc": "允许把经过裁剪的网格数量、包围盒、部件候选、标注坐标和最近部件关联加入远程草稿输入。", + "settings.sendPreviewImagesToRemote": "发送预览图引用", + "settings.sendPreviewImagesToRemote.desc": "允许在远程草稿输入中列出生成的预览图路径。当前客户端不会上传图片字节。", + "settings.sendRawModelToRemote": "发送原始模型文件", + "settings.sendRawModelToRemote.desc": "预留给未来显式上传支持。若手动开启,远程草稿请求会被阻止,不会上传模型。", + + // 转换器 + "settings.enableCad": "启用 CAD 转换器 (STEP/IGES/BREP)", + "settings.enableCad.desc": "启用 STEP/IGES/BREP 格式的 CAD 转换路线,通过 Python CadQuery (OpenCASCADE)。需要:pip install cadquery trimesh", + "settings.enableObj2gltf": "启用 obj2gltf 转换器(实验性)", + "settings.enableObj2gltf.desc": "默认使用 OBJ 直接加载。仅在需要本地标准化 GLB 输出时启用。", + "settings.preferObj2gltf": "OBJ 优先使用 obj2gltf", + "settings.preferObj2gltf.desc": "默认关闭。仅在需要标准化 GLB 输出或直接 OBJ 加载效果不佳时开启。", + "settings.enableFbx2gltf": "启用 FBX2glTF 转换器", + "settings.enableFbx2gltf.desc": "启用 FBX 文件通过 FBX2glTF 转换。需要本地安装 FBX2glTF 二进制文件。", + "settings.enableMesh": "启用网格转换器 (3MF/DAE)", + "settings.enableMesh.desc": "启用 3MF 和 DAE (Collada) 格式的转换路线,通过 Python trimesh。需要安装 Python 和 trimesh (pip install trimesh numpy networkx pycollada)。", + "settings.enableSldprt": "启用 SLDPRT 转换器 (SolidWorks)", + "settings.enableSldprt.desc": "启用 SolidWorks .sldprt 文件通过 FreeCAD 转换。需要安装 FreeCAD (https://www.freecad.org/downloads.php)。", + "settings.mobileSupport.desc": "在 iOS、iPadOS 和 Android 上,GLB、GLTF、STL、OBJ、PLY 这类直读格式可用。本地转换器设置和命令诊断仍仅支持桌面端。", + + // 转换器路径 + "settings.pythonCmd": "Python 命令路径(CAD 用)", + "settings.pythonCmd.desc": "可选的 Python 命令路径,用于 CAD 转换。Windows 通常用 py,macOS 和 Linux 通常用 python3。设置后覆盖自动发现和 AI3D_FREECAD_CMD。", + "settings.freecadCmd": "FreeCAD 命令路径(SLDPRT 用)", + "settings.freecadCmd.desc": "可选的 FreeCAD 命令路径,用于 SolidWorks 文件转换。Windows 通常用 FreeCADCmd.exe,macOS 通常用 FreeCADCmd,Linux 通常用 freecadcmd。设置后覆盖自动发现和 AI3D_FREECADCMD。", + "settings.obj2gltfCmd": "obj2gltf 命令路径", + "settings.obj2gltfCmd.desc": "可选的 obj2gltf 命令路径。Windows 通常用 obj2gltf.cmd,macOS 和 Linux 通常用 obj2gltf。设置后覆盖自动发现和 AI3D_OBJ2GLTF_CMD。", + "settings.fbx2gltfCmd": "FBX2glTF 命令路径", + "settings.fbx2gltfCmd.desc": "可选的 FBX2glTF 命令路径。Windows 通常用 FBX2glTF.exe,macOS 和 Linux 通常用 FBX2glTF。设置后覆盖自动发现和 AI3D_FBX2GLTF_CMD。", + "settings.assimpCmd": "Python 命令路径(3MF/DAE 用)", + "settings.assimpCmd.desc": "可选的 Python 命令路径,用于 3MF 和 DAE 转换。Windows 通常用 py,macOS 和 Linux 通常用 python3。设置后覆盖自动发现和 AI3D_ASSIMP_CMD。", + + // 诊断 + "settings.diagnostics.desc": "显示插件当前实际使用的可执行文件路径,并为 Python 环境和转换器命令执行轻量自检。", + "settings.diagnostics.idle": "环境检查默认关闭。点击“立即检查”后才会执行。", + "settings.diagnostics.checkNow": "立即检查", + "settings.diagnostics.checking": "检查中...", + "settings.diagnostics.refreshed": "AI 3D 转换器命令诊断已刷新。", + "settings.diagnostics.checkingAvailability": "正在检查转换器命令可用性...", + "settings.diagnostics.available": "可用", + "settings.diagnostics.notFound": "未找到", + "settings.diagnostics.sourceLabel": "来源", + "settings.diagnostics.commandLabel": "命令", + "settings.diagnostics.resolvedPathLabel": "解析路径", + "settings.diagnostics.selfCheckLabel": "自检", + "settings.diagnostics.selfCheckOk": "通过", + "settings.diagnostics.selfCheckFailed": "失败", + "settings.diagnostics.cadPythonCheck": "Python 包(cadquery、trimesh)", + "settings.diagnostics.meshPythonCheck": "Python 包(trimesh、numpy、networkx、collada)", + "settings.diagnostics.freecadCmdCheck": "FreeCADCmd 启动探测", + "settings.diagnostics.obj2gltfCheck": "obj2gltf 启动探测", + "settings.diagnostics.fbx2gltfCheck": "FBX2glTF 启动探测", + + // 性能 + "settings.canvasHeight": "默认画布高度", + "settings.canvasHeight.desc": "内联 3D 预览的默认高度(像素)。范围:200–800。", + "settings.autoRotateSpeed": "自动旋转速度", + "settings.autoRotateSpeed.desc": "启用自动旋转时的旋转速度。范围:0.1–2.0。", + "settings.renderQuality": "渲染质量", + "settings.renderQuality.desc": "更高质量使用更多 GPU 资源。影响抗锯齿和分辨率。", + "settings.renderScale": "渲染缩放", + "settings.renderScale.desc": "渲染分辨率倍数。1.0 = 原始,0.5 = 一半,2.0 = 双倍(超采样)。范围:0.25–2.0。", + + // 模型加载提示 + "modelLoad.warningTitle": "暂时无法预览模型", + "modelLoad.warningMessage": "{ext} 文件需要先在插件设置中启用 {converterName} 转换器,才能加载。", + "modelLoad.warningHint": "请先在插件设置中启用对应转换器,然后重新加载当前文件。", + "modelLoad.mobileWarningMessage": "{ext} 文件需要本地转换工具,但这些工具在 iOS、iPadOS 和 Android 上不可用。", + "modelLoad.mobileWarningHint": "请在桌面端打开此文件,或先将它转换为 GLB、GLTF、OBJ、STL 或 PLY。", + "modelLoad.errorTitle": "无法显示这个模型", + "modelLoad.errorMessage": "加载失败:{reason}", + "modelLoad.errorHint": "请检查文件格式,或打开开发者控制台查看详细信息。", + + // 标题 pin 徽标 + "headingPin.showSingle": "显示关联标注", + "headingPin.showMultiple": "显示关联标注", + "headingPin.linkedTo": "关联到:{models}", + + // 工具栏 + "helper.resetViewLabel": "重置视图", + "helper.resetViewDone": "已重置", + "helper.copyModelInfoLabel": "复制模型信息为 Markdown", + "helper.copySelectedPartInfoLabel": "复制选中部件信息", + "helper.noSelectedPart": "请先点击一个部件", + "helper.copied": "已复制", + "helper.failed": "失败", + "helper.toggleWireframeLabel": "切换线框显示", + "helper.wireframeOn": "线框", + "helper.wireframeOff": "实体", + "helper.toggleAxesLabel": "切换方向坐标轴", + "helper.axesOn": "坐标轴已开启", + "helper.axesOff": "坐标轴已关闭", + "helper.toggleBoundingBoxLabel": "切换包围盒", + "helper.boundingBoxOn": "包围盒已开启", + "helper.boundingBoxOff": "包围盒已关闭", + "helper.toggleFocusSelectionLabel": "聚焦选中部件", + "helper.focusSelectionOn": "聚焦模式已开启", + "helper.focusSelectionOff": "聚焦模式已关闭", + "helper.toggleDisassemblyLabel": "切换分解模式", + "helper.disassemblyOn": "分解模式已开启", + "helper.disassemblyOff": "分解模式已关闭", + "helper.resetPartsLabel": "重置分解部件", + "helper.partsReset": "部件已重置", + "helper.changeResolutionLabel": "切换分辨率", + "helper.resolutionValue": "分辨率:{value}", + "helper.toggleAnimationLabel": "播放或暂停动画", + "helper.playing": "播放中", + "helper.paused": "已暂停", + "helper.toggleMeasurementLabel": "切换距离测量", + "helper.measurementOn": "测量已开启", + "helper.measurementOff": "测量已关闭", + "helper.clearMeasurementsLabel": "清除测量", + "helper.measurementsCleared": "已清除", + "helper.calibrateLabel": "校准测量比例", + "helper.calibrateTitle": "测量校准", + "helper.calibrateCurrent": "当前尺寸:", + "helper.calibrateReal": "真实尺寸:", + "helper.calibrateLock": "锁定比例", + "helper.calibrateApply": "应用", + "helper.calibrateReset": "重置", + "helper.calibrated": "比例已应用", + "helper.calibrateResetDone": "比例已重置", + "helper.calibrateOpen": "校准面板已打开", + "helper.calibrateClose": "校准面板已关闭", + "helper.removePreviewLabel": "移除预览", + "helper.copySnapshotLabel": "复制快照", + "helper.saveSnapshotLabel": "保存快照到仓库", + "helper.saved": "已保存", + "helper.downloadSnapshotLabel": "下载快照", + "helper.downloaded": "已下载", + "helper.toggleAnnotationLabel": "切换标注模式", + "helper.toggleAnnotationsVisibilityLabel": "显示或隐藏标注", + "helper.annotateOn": "标注模式已开启", + "helper.annotateOff": "标注模式已关闭", + "helper.annotationsVisible": "标注已显示", + "helper.annotationsHidden": "标注已隐藏", + "helper.enableInteractionLabel": "启用触控交互", + "helper.disableInteractionLabel": "切回滚动模式", + "helper.interactionOn": "模型交互已开启", + "helper.interactionOff": "滚动模式已开启", + "helper.showMoreActionsLabel": "显示更多操作", + "helper.hideMoreActionsLabel": "收起额外操作", + "helper.moreActionsShown": "已展开更多操作", + "helper.moreActionsHidden": "已收起额外操作", + "helper.interactAction": "交互", + "helper.scrollAction": "滚动", + + // 工作台与视图 + "workbench.emptyTitle": "暂无模型", + "workbench.emptyText": "使用“导入 3D 模型”命令加载 GLB、GLTF、STL、OBJ 或 PLY 文件。", + "workbench.modelTitle": "3D 模型", + "workbench.studioTitle": "AI 模型工作台", + "workbench.studioTagline": "检查、标注,并把 3D 资产整理成双链笔记。", + "workbench.navLabel": "工作台分区", + "workbench.navGallery": "画廊", + "workbench.navLibrary": "资料库", + "workbench.navNotebooks": "笔记本", + "workbench.navSettings": "设置", + "workbench.sourcesTitle": "模型来源", + "workbench.layersTitle": "审阅层", + "workbench.viewModeTitle": "视图模式", + "workbench.modeMesh": "网格视图", + "workbench.modeFocus": "聚焦选区", + "workbench.modeMeshShort": "网格", + "workbench.modeFocusShort": "聚焦", + "workbench.previewViewsTitle": "预览视图", + "workbench.connectionsTitle": "知识连接", + "workbench.currentModelLabel": "当前模型", + "workbench.noReportYet": "还没有报告笔记", + "workbench.noIndexYet": "还没有知识索引。请先生成知识笔记。", + "workbench.noModelLoaded": "尚未加载模型", + "workbench.disassemblyTitle": "分解", + "workbench.explodeLabel": "爆炸", + "workbench.summaryTitle": "摘要", + "workbench.meshesLabel": "网格", + "workbench.splatsLabel": "点云", + "workbench.trianglesLabel": "三角形", + "workbench.verticesLabel": "顶点", + "workbench.materialsLabel": "材质", + "workbench.boundingSizeLabel": "包围盒", + "workbench.centerLabel": "中心", + "workbench.selectedPartTitle": "当前选中部件", + "workbench.partMeshLabel": "网格", + "workbench.noSelectedPart": "点击模型中的部件后会显示详细信息。", + "workbench.tagsTitle": "标签", + "workbench.noTagsYet": "还没有标签", + "workbench.addTagPlaceholder": "添加标签...", + "workbench.addTagAction": "添加", + "workbench.annotationsTitle": "标注", + "workbench.exitAnnotate": "退出标注", + "workbench.annotate": "标注", + "workbench.annotateHintActive": "点击模型添加标签 · 按 Esc 退出", + "workbench.annotateHintActiveMobile": "点按模型添加标签。需要继续阅读时切回“滚动”。", + "workbench.pinCount": "{count} 个标注", + "workbench.editAction": "编辑", + "workbench.deleteAction": "删除", + "workbench.resetViewAction": "重置视图", + "workbench.insertInfoAction": "插入信息", + "workbench.insertGalleryAction": "插入 Gallery", + "workbench.insertCompareAction": "插入对比", + "workbench.playAction": "播放", + "workbench.pauseAction": "暂停", + "workbench.saveProfileAction": "保存配置", + "workbench.generateNoteAction": "生成笔记", + "workbench.openNoteAction": "打开笔记", + "workbench.openIndexAction": "打开索引", + "workbench.recordTitle": "标本卡", + "workbench.recordSubtitle": "当前资产档案", + "workbench.notesTitle": "分析札记", + "workbench.whereTitle": "关联位置", + "workbench.noteReady": "关联笔记已就绪", + "workbench.indexReady": "知识索引已就绪", + "workbench.notePending": "关联笔记待生成", + "workbench.analysisLabel": "分析", + "workbench.settingsUnavailable": "请从 Obsidian 设置中打开本插件来调整工作台选项。", + "workbench.profileSaved": "配置已保存", + "workbench.viewReset": "视图已重置", + "workbench.infoInserted": "模型信息已插入", + "workbench.infoCopied": "模型信息已复制", + "workbench.templateInserted": "模板已插入", + "workbench.templateCopied": "模板已复制", + "workbench.mobileHint": "移动端提示:需要操作模型时点“交互”,继续阅读笔记时切回“滚动”。", + "workbench.mobileHintInteractive": "当前为交互模式。需要继续滚动笔记时,请切回“滚动”。", + "directView.mobileHint": "移动端提示:使用下方工具栏里的“交互”按钮,在模型操作和笔记滚动之间切换。", + "directWorkbench.modelLoadInterrupted": "模型加载被新请求中断。", + "directWorkbench.backendLabel": "后端", + "directWorkbench.routeLabel": "路由", + "directWorkbench.performanceLabel": "性能", + "directWorkbench.partCandidatesLabel": "候选零件", + "directWorkbench.knowledgeTitle": "知识", + "directWorkbench.registeredTitle": "已注册零件匹配", + "directWorkbench.registeredLoading": "检查中...", + "directWorkbench.registeredCount": "{count} 个匹配", + "directWorkbench.registeredEmpty": "暂无跨模型零件匹配", + "directWorkbench.registeredUnavailable": "暂无零件证据", + "directWorkbench.registeredOpen": "打开", + "directWorkbench.registeredOpenNote": "笔记", + "directWorkbench.registeredOpenModel": "模型", + "directWorkbench.registeredSourceModel": "来自 {model}", + "directWorkbench.registeredTargetPartNote": "打开匹配零件笔记", + "directWorkbench.registeredTargetSourceModel": "打开来源模型", + "directWorkbench.registeredTargetUnavailable": "暂无可打开目标", + "workbench.fileNotFound": "未找到文件:{path}", + "annotation.selectColor": "选择颜色 {color}", + "annotation.sectionEmpty": "该段内容为空。", + "modal.selectModel": "选择一个 3D 模型...", + "main.commandImportModel": "导入 3D 模型", + "main.commandGenerateNote": "生成知识笔记", + "main.commandOpenKnowledgeIndex": "打开知识索引", + "main.commandClearConversionCache": "清除转换缓存", + "main.commandCheckConverters": "检查转换器", + "main.commandCopyDiagnostics": "复制诊断报告", + "main.converterDiagnosticsMobileUnavailable": "转换器诊断仅支持桌面端。在 iOS、iPadOS 和 Android 上,直读格式仍可加载。", + "main.diagnosticsCopied": "AI Model Workbench 诊断报告已复制到剪贴板。", + "main.diagnosticsCopyFailed": "无法复制诊断报告,已改为创建一份脱敏诊断笔记。", + + // 内联代码块与加载 + "codeBlock.noModelPathOrConfig": "未指定模型路径或配置。", + "codeBlock.jsonParseError": "JSON 解析错误:{error}", + "codeBlock.jsonParseLine": "(第 {line} 行)", + "codeBlock.noModelsInConfig": "配置中未指定模型。", + "codeBlock.unsupportedFormat": "不支持的格式:{ext}。支持:{formats}", + "codeBlock.splatDisabled": "当前打包版本暂未启用 SPLAT 预览。后续会优先恢复本地-only .splat;.spz/.sog 需要本地打包解码器后再评估。", + "codeBlock.noConfigSpecified": "未指定配置。", + "codeBlock.noModelsSpecified": "未指定模型。", + "codeBlock.mobileHint": "移动端提示:需要操作模型时点“交互”,继续阅读笔记时切回“滚动”。", + "codeBlock.renderingGrid": "正在渲染网格...", + "codeBlock.composeRequiresSections": "“compose” 预设需要提供 “sections” 数组。", + "codeBlock.composeNoValidSections": "Compose:没有有效的分段。", + "codeBlock.unknownPreset": "未知预设:“{preset}”。可用:compare、showcase、explode、timeline、compose", + "codeBlock.presetRequiresModels": "预设 “{preset}” 需要 {min}-{max} 个模型,当前为 {count} 个。", + "codeBlock.gridFailed": "网格渲染失败:{reason}", + "livePreview.mobileHint": "移动端提示:需要拖动模型时切到“交互”,继续阅读时切回“滚动”。", + "loading.default": "加载中...", + "loading.preparingModel": "正在准备模型...", + "loading.loadingModel": "正在加载模型...", +}; diff --git a/src/io/conversion/manager.ts b/src/io/conversion/manager.ts index 184dd3d..987b6aa 100644 --- a/src/io/conversion/manager.ts +++ b/src/io/conversion/manager.ts @@ -13,12 +13,14 @@ export class ConversionTimeoutError extends Error { } } -function withTimeout(promise: Promise, ms: number, context: Record): Promise { +function withTimeout(promise: Promise, ms: number, _context: Record): Promise { + const setTimer = typeof activeWindow !== "undefined" ? activeWindow.setTimeout.bind(activeWindow) : setTimeout; + const clearTimer = typeof activeWindow !== "undefined" ? activeWindow.clearTimeout.bind(activeWindow) : clearTimeout; const timeout = new Promise((_, reject) => { - const id = setTimeout(() => { + const id = setTimer(() => { reject(new ConversionTimeoutError(`Conversion did not complete within ${ms}ms`)); }, ms); - promise.then(() => clearTimeout(id)).catch(() => clearTimeout(id)); + promise.then(() => clearTimer(id)).catch(() => clearTimer(id)); }); return Promise.race([promise, timeout]); } diff --git a/src/render/babylon/grid.ts b/src/render/babylon/grid.ts index 6b7fd59..3128550 100644 --- a/src/render/babylon/grid.ts +++ b/src/render/babylon/grid.ts @@ -1,543 +1,543 @@ -import { Engine } from "@babylonjs/core/Engines/engine.js"; -import { Scene } from "@babylonjs/core/scene.js"; -import { ArcRotateCamera } from "@babylonjs/core/Cameras/arcRotateCamera.js"; -import { HemisphericLight } from "@babylonjs/core/Lights/hemisphericLight.js"; -import { Vector3 } from "@babylonjs/core/Maths/math.vector.js"; -import { Color3, Color4 } from "@babylonjs/core/Maths/math.color.js"; -import { Viewport } from "@babylonjs/core/Maths/math.viewport.js"; -import { ImportMeshAsync } from "@babylonjs/core/Loading/sceneLoader.js"; -import type { AbstractMesh } from "@babylonjs/core/Meshes/abstractMesh.js"; -import { TransformNode } from "@babylonjs/core/Meshes/transformNode.js"; -import { StandardMaterial } from "@babylonjs/core/Materials/standardMaterial.js"; -import type { ModelConfig, GridBlockConfig, ModelPlacement, CellLayout, PresetResult } from "../../domain/models"; -import "./loaders/register"; -import { ensureLoadersRegistered } from "./loaders/register"; -import { - createBabylonModelPreviewSummary, - getBabylonMeshesPreviewBounds, - getBabylonRenderableMeshes, - getBabylonTopLevelImportedMeshes, -} from "./mesh-preview"; -import { arrayBufferToBase64 } from "../../utils/base64"; -import { isMobile } from "../../utils/device"; -import { - getPreviewBoundsCenter, - getPreviewBoundsRadius, -} from "../preview/bounds"; -import { - createPreviewOrbitCameraFit, - createPreviewOrbitCameraFitFromRadius, -} from "../preview/camera-fit"; -import type { PreviewGridRenderer } from "../preview/grid"; - -/** Babylon.js uses 32-bit layerMask — one bit per cell, so max 32 cells. */ -const MAX_CELLS = 32; - -function escapeTableCell(value: string): string { - return value.replace(/\|/g, "\\|").replace(/\r?\n/g, " "); -} - -function toBabylonVector3(value: { x: number; y: number; z: number }): Vector3 { - return new Vector3(value.x, value.y, value.z); -} - -interface GridCell { - meshes: AbstractMesh[]; - camera: ArcRotateCamera; -} - -/** - * Renders multiple models in a single Babylon Scene using per-cell viewports. - * One Engine / one WebGL context regardless of grid size. - */ -class BabylonGridRenderer implements PreviewGridRenderer { - private engine: Engine; - private scene: Scene; - private cells: GridCell[] = []; - private initialCameras: { alpha: number; beta: number; radius: number; target: Vector3 }[] = []; - private wireframeEnabled = false; - private rendering = false; - private dirty = true; - private contextLost = false; - private resizeObs: ResizeObserver; - private readonly preventCanvasWheelScroll = (event: WheelEvent) => { - event.preventDefault(); - event.stopPropagation(); - }; - - private canRender(): boolean { - const canvas = this.engine.getRenderingCanvas(); - return !!canvas?.isConnected && canvas.clientWidth > 0 && canvas.clientHeight > 0; - } - - private markDirty(): void { - this.dirty = true; - } - - private getCellBounds(meshes: readonly AbstractMesh[]) { - const bounds = getBabylonMeshesPreviewBounds(meshes); - if (!bounds) { - throw new Error("Grid cell has no renderable meshes"); - } - return bounds; - } - - constructor(canvas: HTMLCanvasElement) { - canvas.className = "ai3d-canvas-full"; - canvas.addEventListener("wheel", this.preventCanvasWheelScroll, { passive: false }); - this.engine = new Engine(canvas, true, { preserveDrawingBuffer: true }); - canvas.addEventListener("webglcontextlost", this.handleContextLost); - canvas.addEventListener("webglcontextrestored", this.handleContextRestored); - this.scene = new Scene(this.engine); - this.scene.clearColor = new Color4(0.12, 0.12, 0.14, 1); - this.scene.autoClear = false; - new HemisphericLight("default-light", new Vector3(0, 1, 0.5), this.scene); - - this.resizeObs = new ResizeObserver(() => { this.engine.resize(); this.markDirty(); }); - this.resizeObs.observe(canvas); - window.requestAnimationFrame(() => this.engine.resize()); - } - - async loadModels( - models: ModelConfig[], - config: GridBlockConfig, - readFile: (path: string) => Promise, - ): Promise { - await ensureLoadersRegistered(); - - const effectiveModels = models.length > MAX_CELLS - ? (console.warn(`[AI3D Grid] Capping ${models.length} models to ${MAX_CELLS} (layerMask limit)`), models.slice(0, MAX_CELLS)) - : models; - - const cols = config.columns ?? Math.min(effectiveModels.length, 3); - const gapX = config.gapX ?? 0.02; - const gapY = config.gapY ?? 0.02; - const rows = Math.ceil(effectiveModels.length / cols); - const cellW = (1 - gapX * (cols + 1)) / cols; - const cellH = (1 - gapY * (rows + 1)) / rows; - - for (let i = 0; i < effectiveModels.length; i++) { - const model = effectiveModels[i]; - const col = i % cols; - const row = Math.floor(i / cols); - const x = gapX + col * (cellW + gapX); - const y = gapY + (rows - 1 - row) * (cellH + gapY); - - try { - await this.loadOne(model, readFile, x, y, cellW, cellH, i); - } catch (err) { - console.error(`[AI3D Grid] Failed to load ${model.path}:`, err); - } - } - - this.startRenderLoop(); - this.markDirty(); - this.engine.resize(); - } - - /** - * Load models using a preset layout (placements + cells). - * Models with the same path share geometry (loaded once, placed at different positions). - */ - async loadWithPreset( - result: PresetResult, - readFile: (path: string) => Promise, - ): Promise { - await ensureLoadersRegistered(); - - // Load each unique model placement (deduplicated by path+position) - const effectivePlacements = result.placements.length > MAX_CELLS - ? (console.warn(`[AI3D Preset] Capping ${result.placements.length} placements to ${MAX_CELLS} (layerMask limit)`), result.placements.slice(0, MAX_CELLS)) - : result.placements; - - const loadedMeshes: AbstractMesh[][] = []; - for (let i = 0; i < effectivePlacements.length; i++) { - const placement = effectivePlacements[i]; - try { - const meshes = await this.loadPlacementMesh(placement, readFile, i); - loadedMeshes.push(meshes); - } catch (err) { - console.error(`[AI3D Preset] Failed to load ${placement.path}:`, err); - loadedMeshes.push([]); - } - } - - // Compute overall scene bounding box (for "gallery" mode cameras) - const allSceneMeshes = loadedMeshes.flat(); - let sceneCenter = Vector3.Zero(); - let sceneRadius = 1; - const sceneBounds = getBabylonMeshesPreviewBounds(allSceneMeshes); - if (sceneBounds) { - sceneCenter = toBabylonVector3(getPreviewBoundsCenter(sceneBounds)); - sceneRadius = getPreviewBoundsRadius(sceneBounds); - } - - // Create cells from layout definitions. - // Single-cell presets (gallery) get ALL placements merged into one cell. - const isSingleCell = result.cells.length === 1; - - for (const cellDef of result.cells) { - const primaryMeshes = loadedMeshes[cellDef.modelIndex]; - if (!primaryMeshes || primaryMeshes.length === 0) continue; - - let cellMeshes: AbstractMesh[]; - let combinedMask: number; - - if (isSingleCell) { - // Single cell: include ALL loaded placements - cellMeshes = []; - combinedMask = 0; - for (let i = 0; i < loadedMeshes.length; i++) { - if (loadedMeshes[i].length > 0) { - cellMeshes.push(...loadedMeshes[i]); - combinedMask |= 1 << i; - } - } - } else { - // Multi-cell: each cell gets its own placement only. - // Camera and meshes share the same single-bit mask. - cellMeshes = primaryMeshes ? [...primaryMeshes] : []; - combinedMask = 1 << cellDef.modelIndex; - } - - // Override mesh layerMasks - for (const mesh of cellMeshes) mesh.layerMask = combinedMask; - - const camera = this.createCameraFromDef( - cellDef, - primaryMeshes, - this.cells.length, - isSingleCell ? sceneCenter : undefined, - isSingleCell ? sceneRadius : undefined, - ); - camera.layerMask = combinedMask; - - this.cells.push({ meshes: cellMeshes, camera }); - } - - this.startRenderLoop(); - this.engine.resize(); - } - - /** - * Import a mesh from raw data using Babylon's SceneLoader. - * Shared by loadPlacementMesh() and loadOne(). - */ - private async importMesh( - path: string, - data: ArrayBuffer, - index: number, - ): Promise<{ root: AbstractMesh; renderableMeshes: AbstractMesh[]; topLevelMeshes: AbstractMesh[] }> { - const ext = path.split(".").pop()?.replace(".", "").toLowerCase() ?? "glb"; - const dataUrl = `data:application/octet-stream;base64,${arrayBufferToBase64(data)}`; - const extToLoader: Record = { - glb: ".glb", gltf: ".gltf", stl: ".stl", obj: ".obj", splat: ".splat", ply: ".ply", - }; - const fileExt = extToLoader[ext] ?? `.${ext}`; - - const result = await ImportMeshAsync(dataUrl, this.scene, { meshNames: "", pluginExtension: fileExt }); - if (result.meshes.length === 0) throw new Error(`No mesh in ${path}`); - - const root = result.meshes[0]; - const renderableMeshes = getBabylonRenderableMeshes(root, result.meshes); - const topLevelMeshes = getBabylonTopLevelImportedMeshes(result.meshes); - const cellMask = 1 << index; - for (const m of renderableMeshes) m.layerMask = cellMask; - if ("layerMask" in root) (root as unknown as { layerMask: number }).layerMask = cellMask; - - return { root, renderableMeshes, topLevelMeshes }; - } - - private async loadPlacementMesh( - placement: ModelPlacement, - readFile: (path: string) => Promise, - index: number, - ): Promise { - const data = await readFile(placement.path); - const { renderableMeshes, topLevelMeshes } = await this.importMesh(placement.path, data, index); - const placementRoot = new TransformNode(`placement-root-${index}`, this.scene); - for (const mesh of topLevelMeshes) { - mesh.parent = placementRoot; - } - - // Position in world space - if (placement.position) { - placementRoot.position = new Vector3(...placement.position); - } - if (placement.rotation) { - placementRoot.rotation = new Vector3(...placement.rotation); - } - if (placement.scale !== undefined) { - placementRoot.scaling = new Vector3(placement.scale, placement.scale, placement.scale); - } - - return renderableMeshes; - } - - private createCameraFromDef( - cellDef: CellLayout, - meshes: readonly AbstractMesh[], - globalIndex: number, - sceneCenter?: Vector3, - sceneRadius?: number, - ): ArcRotateCamera { - const bounds = this.getCellBounds(meshes); - const def = cellDef.camera; - const target = def.target - ? { x: def.target[0], y: def.target[1], z: def.target[2] } - : sceneCenter - ? { x: sceneCenter.x, y: sceneCenter.y, z: sceneCenter.z } - : getPreviewBoundsCenter(bounds); - const fit = createPreviewOrbitCameraFitFromRadius( - target, - sceneRadius ?? getPreviewBoundsRadius(bounds), - { radiusMultiplier: def.radiusMultiplier ?? 2.5 }, - ); - - const camera = new ArcRotateCamera( - `cell-cam-${globalIndex}`, - def.alpha, - def.beta, - fit.radius, - toBabylonVector3(fit.target), - this.scene, - ); - camera.fov = ((def.fov ?? 45) * Math.PI) / 180; - camera.minZ = fit.near; - camera.maxZ = fit.far; - camera.lowerRadiusLimit = fit.lowerRadiusLimit; - camera.upperRadiusLimit = fit.upperRadiusLimit; - camera.wheelPrecision = 30; - camera.viewport = new Viewport( - cellDef.viewport.x, - cellDef.viewport.y, - cellDef.viewport.w, - cellDef.viewport.h, - ); - camera.layerMask = 1 << globalIndex; - const canvas = this.engine.getRenderingCanvas(); - if (canvas) { camera.attachControl(canvas, true); camera.onViewMatrixChangedObservable.add(() => this.markDirty()); } - this.initialCameras.push({ - alpha: camera.alpha, beta: camera.beta, - radius: camera.radius, target: camera.target.clone(), - }); - return camera; - } - - private async loadOne( - model: ModelConfig, - readFile: (path: string) => Promise, - vx: number, - vy: number, - vw: number, - vh: number, - index: number, - ): Promise { - const data = await readFile(model.path); - const ext = model.path.split(".").pop()?.replace(".", "").toLowerCase() ?? "glb"; - const { renderableMeshes } = await this.importMesh(model.path, data, index); - - // Apply STL color if specified - if (ext === "stl" && model.color) { - const color = Color3.FromHexString(model.color); - for (const m of renderableMeshes) { - if (m.material instanceof StandardMaterial && m.material.name === "stl-mat") { - m.material.diffuseColor = color; - } - } - } - - // Apply wireframe if specified - if (ext === "stl" && model.wireframe !== undefined) { - for (const m of renderableMeshes) { - if (m.material instanceof StandardMaterial) m.material.wireframe = model.wireframe; - } - } - - // Create camera for this cell - const camera = this.createCellCamera(renderableMeshes, index, vx, vy, vw, vh); - - this.cells.push({ meshes: renderableMeshes, camera }); - } - - private createCellCamera( - meshes: readonly AbstractMesh[], - index: number, - vx: number, - vy: number, - vw: number, - vh: number, - ): ArcRotateCamera { - const fit = createPreviewOrbitCameraFit(this.getCellBounds(meshes)); - - const camera = new ArcRotateCamera( - `cell-cam-${index}`, - Math.PI / 4, - Math.PI / 3, - fit.radius, - toBabylonVector3(fit.target), - this.scene, - ); - camera.fov = (45 * Math.PI) / 180; - camera.minZ = fit.near; - camera.maxZ = fit.far; - camera.lowerRadiusLimit = fit.lowerRadiusLimit; - camera.upperRadiusLimit = fit.upperRadiusLimit; - camera.wheelPrecision = 30; - camera.viewport = new Viewport(vx, vy, vw, vh); - camera.layerMask = 1 << index; - const canvas = this.engine.getRenderingCanvas(); - if (canvas) { camera.attachControl(canvas, true); camera.onViewMatrixChangedObservable.add(() => this.markDirty()); } - this.initialCameras.push({ - alpha: camera.alpha, beta: camera.beta, - radius: camera.radius, target: camera.target.clone(), - }); - return camera; - } - - // ── Render ───────────────────────────────────────────────────────── - - private readonly handleContextLost = (event: Event) => { - event.preventDefault(); - this.contextLost = true; - if (this.rendering) { - this.engine.stopRenderLoop(); - this.rendering = false; - } - }; - - private readonly handleContextRestored = () => { - this.contextLost = false; - this.engine.resize(); - this.startRenderLoop(); - this.markDirty(); - }; - - private renderFrame(): void { - if (!this.canRender() || !this.dirty || this.contextLost) return; - this.dirty = false; - const engine = this.engine; - const scene = this.scene; - engine.clear(scene.clearColor, true, true); - for (const cell of this.cells) { - engine.setViewport(cell.camera.viewport); - const vp = cell.camera.viewport; - const cw = engine.getRenderWidth(); - const ch = engine.getRenderHeight(); - engine.enableScissor(vp.x * cw, vp.y * ch, vp.width * cw, vp.height * ch); - scene.activeCamera = cell.camera; - scene.render(); - engine.disableScissor(); - } - } - - private startRenderLoop(): void { - if (this.rendering) return; - this.rendering = true; - this.engine.runRenderLoop(() => this.renderFrame()); - } - - // ── Public API ───────────────────────────────────────────────────── - - captureSnapshot(): string | null { - const canvas = this.engine.getRenderingCanvas(); - if (!canvas) return null; - this.renderFrame(); - return canvas.toDataURL("image/png"); - } - - getEngine(): Engine { - return this.engine; - } - - getScene(): Scene { - return this.scene; - } - - getCellCount(): number { - return this.cells.length; - } - - getCanvas(): HTMLCanvasElement | null { - return this.engine.getRenderingCanvas(); - } - - /** Primary camera for annotations (first cell). */ - getPrimaryCamera(): ArcRotateCamera | null { - return this.cells[0]?.camera ?? null; - } - - setRenderScale(scale: number): number { - const clamped = Math.max(0.25, Math.min(scale, 2.0)); - const mobileBoost = isMobile() ? 1.5 : 1; - this.engine.setHardwareScalingLevel(mobileBoost / clamped); - return clamped; - } - - resetView(): void { - for (let i = 0; i < this.cells.length; i++) { - const cam = this.cells[i].camera; - const init = this.initialCameras[i]; - if (init) { - cam.alpha = init.alpha; - cam.beta = init.beta; - cam.radius = init.radius; - cam.target = init.target.clone(); - } - } - } - - toggleWireframe(): boolean { - this.wireframeEnabled = !this.wireframeEnabled; - for (const cell of this.cells) { - for (const m of cell.meshes) { - if (m.material instanceof StandardMaterial) { - m.material.wireframe = this.wireframeEnabled; - } - } - } - return this.wireframeEnabled; - } - - exportModelInfo(): string { - if (this.cells.length === 0) return ""; - const lines: string[] = []; - lines.push("## Grid Models — Model Info"); - lines.push(""); - lines.push("| # | Model | Meshes | Triangles | Vertices | Materials |"); - lines.push("|---|-------|--------|-----------|----------|-----------|"); - - for (let i = 0; i < this.cells.length; i++) { - const cell = this.cells[i]; - const root = cell.meshes[0]; - if (!root) continue; - const name = root.name || `Model ${i + 1}`; - const summary = createBabylonModelPreviewSummary( - name, - this.getCellBounds(cell.meshes), - cell.meshes, - ); - lines.push( - `| ${i + 1} | ${escapeTableCell(name)} | ${summary.meshCount} | ${summary.triangleCount.toLocaleString()} | ${summary.vertexCount.toLocaleString()} | ${summary.materialCount} |`, - ); - } - lines.push(""); - return lines.join("\n"); - } - - destroy(): void { - this.engine.stopRenderLoop(); - for (const cell of this.cells) cell.camera.detachControl(); - const canvas = this.engine.getRenderingCanvas(); - canvas?.removeEventListener("wheel", this.preventCanvasWheelScroll); - this.resizeObs.disconnect(); - this.scene.dispose(); - this.engine.dispose(); - this.cells = []; - } -} - -export function createBabylonGridRenderer(canvas: HTMLCanvasElement): PreviewGridRenderer { - return new BabylonGridRenderer(canvas); -} - +import { Engine } from "@babylonjs/core/Engines/engine.js"; +import { Scene } from "@babylonjs/core/scene.js"; +import { ArcRotateCamera } from "@babylonjs/core/Cameras/arcRotateCamera.js"; +import { HemisphericLight } from "@babylonjs/core/Lights/hemisphericLight.js"; +import { Vector3 } from "@babylonjs/core/Maths/math.vector.js"; +import { Color3, Color4 } from "@babylonjs/core/Maths/math.color.js"; +import { Viewport } from "@babylonjs/core/Maths/math.viewport.js"; +import { ImportMeshAsync } from "@babylonjs/core/Loading/sceneLoader.js"; +import type { AbstractMesh } from "@babylonjs/core/Meshes/abstractMesh.js"; +import { TransformNode } from "@babylonjs/core/Meshes/transformNode.js"; +import { StandardMaterial } from "@babylonjs/core/Materials/standardMaterial.js"; +import type { ModelConfig, GridBlockConfig, ModelPlacement, CellLayout, PresetResult } from "../../domain/models"; +import "./loaders/register"; +import { ensureLoadersRegistered } from "./loaders/register"; +import { + createBabylonModelPreviewSummary, + getBabylonMeshesPreviewBounds, + getBabylonRenderableMeshes, + getBabylonTopLevelImportedMeshes, +} from "./mesh-preview"; +import { arrayBufferToBase64 } from "../../utils/base64"; +import { isMobile } from "../../utils/device"; +import { + getPreviewBoundsCenter, + getPreviewBoundsRadius, +} from "../preview/bounds"; +import { + createPreviewOrbitCameraFit, + createPreviewOrbitCameraFitFromRadius, +} from "../preview/camera-fit"; +import type { PreviewGridRenderer } from "../preview/grid"; + +/** Babylon.js uses 32-bit layerMask — one bit per cell, so max 32 cells. */ +const MAX_CELLS = 32; + +function escapeTableCell(value: string): string { + return value.replace(/\|/g, "\\|").replace(/\r?\n/g, " "); +} + +function toBabylonVector3(value: { x: number; y: number; z: number }): Vector3 { + return new Vector3(value.x, value.y, value.z); +} + +interface GridCell { + meshes: AbstractMesh[]; + camera: ArcRotateCamera; +} + +/** + * Renders multiple models in a single Babylon Scene using per-cell viewports. + * One Engine / one WebGL context regardless of grid size. + */ +class BabylonGridRenderer implements PreviewGridRenderer { + private engine: Engine; + private scene: Scene; + private cells: GridCell[] = []; + private initialCameras: { alpha: number; beta: number; radius: number; target: Vector3 }[] = []; + private wireframeEnabled = false; + private rendering = false; + private dirty = true; + private contextLost = false; + private resizeObs: ResizeObserver; + private readonly preventCanvasWheelScroll = (event: WheelEvent) => { + event.preventDefault(); + event.stopPropagation(); + }; + + private canRender(): boolean { + const canvas = this.engine.getRenderingCanvas(); + return !!canvas?.isConnected && canvas.clientWidth > 0 && canvas.clientHeight > 0; + } + + private markDirty(): void { + this.dirty = true; + } + + private getCellBounds(meshes: readonly AbstractMesh[]) { + const bounds = getBabylonMeshesPreviewBounds(meshes); + if (!bounds) { + throw new Error("Grid cell has no renderable meshes"); + } + return bounds; + } + + constructor(canvas: HTMLCanvasElement) { + canvas.className = "ai3d-canvas-full"; + canvas.addEventListener("wheel", this.preventCanvasWheelScroll, { passive: false }); + this.engine = new Engine(canvas, true, { preserveDrawingBuffer: true }); + canvas.addEventListener("webglcontextlost", this.handleContextLost); + canvas.addEventListener("webglcontextrestored", this.handleContextRestored); + this.scene = new Scene(this.engine); + this.scene.clearColor = new Color4(0.12, 0.12, 0.14, 1); + this.scene.autoClear = false; + new HemisphericLight("default-light", new Vector3(0, 1, 0.5), this.scene); + + this.resizeObs = new ResizeObserver(() => { this.engine.resize(); this.markDirty(); }); + this.resizeObs.observe(canvas); + window.requestAnimationFrame(() => this.engine.resize()); + } + + async loadModels( + models: ModelConfig[], + config: GridBlockConfig, + readFile: (path: string) => Promise, + ): Promise { + await ensureLoadersRegistered(); + + const effectiveModels = models.length > MAX_CELLS + ? (console.warn(`[AI3D Grid] Capping ${models.length} models to ${MAX_CELLS} (layerMask limit)`), models.slice(0, MAX_CELLS)) + : models; + + const cols = config.columns ?? Math.min(effectiveModels.length, 3); + const gapX = config.gapX ?? 0.02; + const gapY = config.gapY ?? 0.02; + const rows = Math.ceil(effectiveModels.length / cols); + const cellW = (1 - gapX * (cols + 1)) / cols; + const cellH = (1 - gapY * (rows + 1)) / rows; + + for (let i = 0; i < effectiveModels.length; i++) { + const model = effectiveModels[i]; + const col = i % cols; + const row = Math.floor(i / cols); + const x = gapX + col * (cellW + gapX); + const y = gapY + (rows - 1 - row) * (cellH + gapY); + + try { + await this.loadOne(model, readFile, x, y, cellW, cellH, i); + } catch (err) { + console.error(`[AI3D Grid] Failed to load ${model.path}:`, err); + } + } + + this.startRenderLoop(); + this.markDirty(); + this.engine.resize(); + } + + /** + * Load models using a preset layout (placements + cells). + * Models with the same path share geometry (loaded once, placed at different positions). + */ + async loadWithPreset( + result: PresetResult, + readFile: (path: string) => Promise, + ): Promise { + await ensureLoadersRegistered(); + + // Load each unique model placement (deduplicated by path+position) + const effectivePlacements = result.placements.length > MAX_CELLS + ? (console.warn(`[AI3D Preset] Capping ${result.placements.length} placements to ${MAX_CELLS} (layerMask limit)`), result.placements.slice(0, MAX_CELLS)) + : result.placements; + + const loadedMeshes: AbstractMesh[][] = []; + for (let i = 0; i < effectivePlacements.length; i++) { + const placement = effectivePlacements[i]; + try { + const meshes = await this.loadPlacementMesh(placement, readFile, i); + loadedMeshes.push(meshes); + } catch (err) { + console.error(`[AI3D Preset] Failed to load ${placement.path}:`, err); + loadedMeshes.push([]); + } + } + + // Compute overall scene bounding box (for "gallery" mode cameras) + const allSceneMeshes = loadedMeshes.flat(); + let sceneCenter = Vector3.Zero(); + let sceneRadius = 1; + const sceneBounds = getBabylonMeshesPreviewBounds(allSceneMeshes); + if (sceneBounds) { + sceneCenter = toBabylonVector3(getPreviewBoundsCenter(sceneBounds)); + sceneRadius = getPreviewBoundsRadius(sceneBounds); + } + + // Create cells from layout definitions. + // Single-cell presets (gallery) get ALL placements merged into one cell. + const isSingleCell = result.cells.length === 1; + + for (const cellDef of result.cells) { + const primaryMeshes = loadedMeshes[cellDef.modelIndex]; + if (!primaryMeshes || primaryMeshes.length === 0) continue; + + let cellMeshes: AbstractMesh[]; + let combinedMask: number; + + if (isSingleCell) { + // Single cell: include ALL loaded placements + cellMeshes = []; + combinedMask = 0; + for (let i = 0; i < loadedMeshes.length; i++) { + if (loadedMeshes[i].length > 0) { + cellMeshes.push(...loadedMeshes[i]); + combinedMask |= 1 << i; + } + } + } else { + // Multi-cell: each cell gets its own placement only. + // Camera and meshes share the same single-bit mask. + cellMeshes = primaryMeshes ? [...primaryMeshes] : []; + combinedMask = 1 << cellDef.modelIndex; + } + + // Override mesh layerMasks + for (const mesh of cellMeshes) mesh.layerMask = combinedMask; + + const camera = this.createCameraFromDef( + cellDef, + primaryMeshes, + this.cells.length, + isSingleCell ? sceneCenter : undefined, + isSingleCell ? sceneRadius : undefined, + ); + camera.layerMask = combinedMask; + + this.cells.push({ meshes: cellMeshes, camera }); + } + + this.startRenderLoop(); + this.engine.resize(); + } + + /** + * Import a mesh from raw data using Babylon's SceneLoader. + * Shared by loadPlacementMesh() and loadOne(). + */ + private async importMesh( + path: string, + data: ArrayBuffer, + index: number, + ): Promise<{ root: AbstractMesh; renderableMeshes: AbstractMesh[]; topLevelMeshes: AbstractMesh[] }> { + const ext = path.split(".").pop()?.replace(".", "").toLowerCase() ?? "glb"; + const dataUrl = `data:application/octet-stream;base64,${arrayBufferToBase64(data)}`; + const extToLoader: Record = { + glb: ".glb", gltf: ".gltf", stl: ".stl", obj: ".obj", splat: ".splat", ply: ".ply", + }; + const fileExt = extToLoader[ext] ?? `.${ext}`; + + const result = await ImportMeshAsync(dataUrl, this.scene, { meshNames: "", pluginExtension: fileExt }); + if (result.meshes.length === 0) throw new Error(`No mesh in ${path}`); + + const root = result.meshes[0]; + const renderableMeshes = getBabylonRenderableMeshes(root, result.meshes); + const topLevelMeshes = getBabylonTopLevelImportedMeshes(result.meshes); + const cellMask = 1 << index; + for (const m of renderableMeshes) m.layerMask = cellMask; + if ("layerMask" in root) (root as unknown as { layerMask: number }).layerMask = cellMask; + + return { root, renderableMeshes, topLevelMeshes }; + } + + private async loadPlacementMesh( + placement: ModelPlacement, + readFile: (path: string) => Promise, + index: number, + ): Promise { + const data = await readFile(placement.path); + const { renderableMeshes, topLevelMeshes } = await this.importMesh(placement.path, data, index); + const placementRoot = new TransformNode(`placement-root-${index}`, this.scene); + for (const mesh of topLevelMeshes) { + mesh.parent = placementRoot; + } + + // Position in world space + if (placement.position) { + placementRoot.position = new Vector3(...placement.position); + } + if (placement.rotation) { + placementRoot.rotation = new Vector3(...placement.rotation); + } + if (placement.scale !== undefined) { + placementRoot.scaling = new Vector3(placement.scale, placement.scale, placement.scale); + } + + return renderableMeshes; + } + + private createCameraFromDef( + cellDef: CellLayout, + meshes: readonly AbstractMesh[], + globalIndex: number, + sceneCenter?: Vector3, + sceneRadius?: number, + ): ArcRotateCamera { + const bounds = this.getCellBounds(meshes); + const def = cellDef.camera; + const target = def.target + ? { x: def.target[0], y: def.target[1], z: def.target[2] } + : sceneCenter + ? { x: sceneCenter.x, y: sceneCenter.y, z: sceneCenter.z } + : getPreviewBoundsCenter(bounds); + const fit = createPreviewOrbitCameraFitFromRadius( + target, + sceneRadius ?? getPreviewBoundsRadius(bounds), + { radiusMultiplier: def.radiusMultiplier ?? 2.5 }, + ); + + const camera = new ArcRotateCamera( + `cell-cam-${globalIndex}`, + def.alpha, + def.beta, + fit.radius, + toBabylonVector3(fit.target), + this.scene, + ); + camera.fov = ((def.fov ?? 45) * Math.PI) / 180; + camera.minZ = fit.near; + camera.maxZ = fit.far; + camera.lowerRadiusLimit = fit.lowerRadiusLimit; + camera.upperRadiusLimit = fit.upperRadiusLimit; + camera.wheelPrecision = 30; + camera.viewport = new Viewport( + cellDef.viewport.x, + cellDef.viewport.y, + cellDef.viewport.w, + cellDef.viewport.h, + ); + camera.layerMask = 1 << globalIndex; + const canvas = this.engine.getRenderingCanvas(); + if (canvas) { camera.attachControl(canvas, true); camera.onViewMatrixChangedObservable.add(() => this.markDirty()); } + this.initialCameras.push({ + alpha: camera.alpha, beta: camera.beta, + radius: camera.radius, target: camera.target.clone(), + }); + return camera; + } + + private async loadOne( + model: ModelConfig, + readFile: (path: string) => Promise, + vx: number, + vy: number, + vw: number, + vh: number, + index: number, + ): Promise { + const data = await readFile(model.path); + const ext = model.path.split(".").pop()?.replace(".", "").toLowerCase() ?? "glb"; + const { renderableMeshes } = await this.importMesh(model.path, data, index); + + // Apply STL color if specified + if (ext === "stl" && model.color) { + const color = Color3.FromHexString(model.color); + for (const m of renderableMeshes) { + if (m.material instanceof StandardMaterial && m.material.name === "stl-mat") { + m.material.diffuseColor = color; + } + } + } + + // Apply wireframe if specified + if (ext === "stl" && model.wireframe !== undefined) { + for (const m of renderableMeshes) { + if (m.material instanceof StandardMaterial) m.material.wireframe = model.wireframe; + } + } + + // Create camera for this cell + const camera = this.createCellCamera(renderableMeshes, index, vx, vy, vw, vh); + + this.cells.push({ meshes: renderableMeshes, camera }); + } + + private createCellCamera( + meshes: readonly AbstractMesh[], + index: number, + vx: number, + vy: number, + vw: number, + vh: number, + ): ArcRotateCamera { + const fit = createPreviewOrbitCameraFit(this.getCellBounds(meshes)); + + const camera = new ArcRotateCamera( + `cell-cam-${index}`, + Math.PI / 4, + Math.PI / 3, + fit.radius, + toBabylonVector3(fit.target), + this.scene, + ); + camera.fov = (45 * Math.PI) / 180; + camera.minZ = fit.near; + camera.maxZ = fit.far; + camera.lowerRadiusLimit = fit.lowerRadiusLimit; + camera.upperRadiusLimit = fit.upperRadiusLimit; + camera.wheelPrecision = 30; + camera.viewport = new Viewport(vx, vy, vw, vh); + camera.layerMask = 1 << index; + const canvas = this.engine.getRenderingCanvas(); + if (canvas) { camera.attachControl(canvas, true); camera.onViewMatrixChangedObservable.add(() => this.markDirty()); } + this.initialCameras.push({ + alpha: camera.alpha, beta: camera.beta, + radius: camera.radius, target: camera.target.clone(), + }); + return camera; + } + + // ── Render ───────────────────────────────────────────────────────── + + private readonly handleContextLost = (event: Event) => { + event.preventDefault(); + this.contextLost = true; + if (this.rendering) { + this.engine.stopRenderLoop(); + this.rendering = false; + } + }; + + private readonly handleContextRestored = () => { + this.contextLost = false; + this.engine.resize(); + this.startRenderLoop(); + this.markDirty(); + }; + + private renderFrame(): void { + if (!this.canRender() || !this.dirty || this.contextLost) return; + this.dirty = false; + const engine = this.engine; + const scene = this.scene; + engine.clear(scene.clearColor, true, true); + for (const cell of this.cells) { + engine.setViewport(cell.camera.viewport); + const vp = cell.camera.viewport; + const cw = engine.getRenderWidth(); + const ch = engine.getRenderHeight(); + engine.enableScissor(vp.x * cw, vp.y * ch, vp.width * cw, vp.height * ch); + scene.activeCamera = cell.camera; + scene.render(); + engine.disableScissor(); + } + } + + private startRenderLoop(): void { + if (this.rendering) return; + this.rendering = true; + this.engine.runRenderLoop(() => this.renderFrame()); + } + + // ── Public API ───────────────────────────────────────────────────── + + captureSnapshot(): string | null { + const canvas = this.engine.getRenderingCanvas(); + if (!canvas) return null; + this.renderFrame(); + return canvas.toDataURL("image/png"); + } + + getEngine(): Engine { + return this.engine; + } + + getScene(): Scene { + return this.scene; + } + + getCellCount(): number { + return this.cells.length; + } + + getCanvas(): HTMLCanvasElement | null { + return this.engine.getRenderingCanvas(); + } + + /** Primary camera for annotations (first cell). */ + getPrimaryCamera(): ArcRotateCamera | null { + return this.cells[0]?.camera ?? null; + } + + setRenderScale(scale: number): number { + const clamped = Math.max(0.25, Math.min(scale, 2.0)); + const mobileBoost = isMobile() ? 1.5 : 1; + this.engine.setHardwareScalingLevel(mobileBoost / clamped); + return clamped; + } + + resetView(): void { + for (let i = 0; i < this.cells.length; i++) { + const cam = this.cells[i].camera; + const init = this.initialCameras[i]; + if (init) { + cam.alpha = init.alpha; + cam.beta = init.beta; + cam.radius = init.radius; + cam.target = init.target.clone(); + } + } + } + + toggleWireframe(): boolean { + this.wireframeEnabled = !this.wireframeEnabled; + for (const cell of this.cells) { + for (const m of cell.meshes) { + if (m.material instanceof StandardMaterial) { + m.material.wireframe = this.wireframeEnabled; + } + } + } + return this.wireframeEnabled; + } + + exportModelInfo(): string { + if (this.cells.length === 0) return ""; + const lines: string[] = []; + lines.push("## Grid Models — Model Info"); + lines.push(""); + lines.push("| # | Model | Meshes | Triangles | Vertices | Materials |"); + lines.push("|---|-------|--------|-----------|----------|-----------|"); + + for (let i = 0; i < this.cells.length; i++) { + const cell = this.cells[i]; + const root = cell.meshes[0]; + if (!root) continue; + const name = root.name || `Model ${i + 1}`; + const summary = createBabylonModelPreviewSummary( + name, + this.getCellBounds(cell.meshes), + cell.meshes, + ); + lines.push( + `| ${i + 1} | ${escapeTableCell(name)} | ${summary.meshCount} | ${summary.triangleCount.toLocaleString()} | ${summary.vertexCount.toLocaleString()} | ${summary.materialCount} |`, + ); + } + lines.push(""); + return lines.join("\n"); + } + + destroy(): void { + this.engine.stopRenderLoop(); + for (const cell of this.cells) cell.camera.detachControl(); + const canvas = this.engine.getRenderingCanvas(); + canvas?.removeEventListener("wheel", this.preventCanvasWheelScroll); + this.resizeObs.disconnect(); + this.scene.dispose(); + this.engine.dispose(); + this.cells = []; + } +} + +export function createBabylonGridRenderer(canvas: HTMLCanvasElement): PreviewGridRenderer { + return new BabylonGridRenderer(canvas); +} + diff --git a/src/render/babylon/scene.ts b/src/render/babylon/scene.ts index 447de08..2c0aff4 100644 --- a/src/render/babylon/scene.ts +++ b/src/render/babylon/scene.ts @@ -1,1708 +1,1709 @@ -import { Engine } from "@babylonjs/core/Engines/engine.js"; -import { Scene } from "@babylonjs/core/scene.js"; -import { ArcRotateCamera } from "@babylonjs/core/Cameras/arcRotateCamera.js"; -import { HemisphericLight } from "@babylonjs/core/Lights/hemisphericLight.js"; -import { DirectionalLight } from "@babylonjs/core/Lights/directionalLight.js"; -import { PointLight } from "@babylonjs/core/Lights/pointLight.js"; -import { SpotLight } from "@babylonjs/core/Lights/spotLight.js"; -import { Vector3, Matrix } from "@babylonjs/core/Maths/math.vector.js"; -import { Color3, Color4 } from "@babylonjs/core/Maths/math.color.js"; -import { Mesh } from "@babylonjs/core/Meshes/mesh.js"; -import { TransformNode } from "@babylonjs/core/Meshes/transformNode.js"; -import { MeshBuilder } from "@babylonjs/core/Meshes/meshBuilder.js"; -import { StandardMaterial } from "@babylonjs/core/Materials/standardMaterial.js"; -import { DynamicTexture } from "@babylonjs/core/Materials/Textures/dynamicTexture.js"; -import { Ray } from "@babylonjs/core/Culling/ray.js"; -import { ShadowGenerator } from "@babylonjs/core/Lights/Shadows/shadowGenerator.js"; -import "@babylonjs/core/Lights/Shadows/shadowGeneratorSceneComponent.js"; -import { AutoRotationBehavior } from "@babylonjs/core/Behaviors/Cameras/autoRotationBehavior.js"; -import { ImportMeshAsync } from "@babylonjs/core/Loading/sceneLoader.js"; -import type { AbstractMesh } from "@babylonjs/core/Meshes/abstractMesh.js"; -import type { Light } from "@babylonjs/core/Lights/light.js"; -import type { IShadowLight } from "@babylonjs/core/Lights/shadowLight.js"; -import type { - ModelPreviewSummary, - ModelEvidence, - ModelPartSummary, - CameraConfig, - LightConfig, - SceneConfig, - ThreeDBlockConfig, -} from "../../domain/models"; -import "./loaders/register"; -import { ensureLoadersRegistered } from "./loaders/register"; -import { loadSTLBuffer } from "./loaders/stl-loader"; -import { loadPLYBuffer } from "./loaders/ply-loader"; -import { setExplode, resetExplode } from "./explode"; -import { setupPicking, type PickResult } from "./picking"; -import { arrayBufferToBase64 } from "../../utils/base64"; -import { isMobile } from "../../utils/device"; -import { getPortableBasename, getPortableDirname, getPortableStem, joinPortablePath } from "../../utils/resolve-path"; -import { OrientationGizmo } from "./orientation-gizmo"; -import { createBabylonDisassemblyController } from "./disassembly"; -import { - createBabylonModelPreviewSummary, - createBabylonPartPreviewSummary, - getBabylonMeshesPreviewBounds, - getBabylonRenderableMeshes, - getBabylonRenderablePreviewBounds, - getBabylonTriangleCount, - getBabylonVertexCount, -} from "./mesh-preview"; -import { - getPreviewBoundsCenter, - getPreviewBoundsMaxSpan, - getPreviewBoundsRadius, - getPreviewBoundsSize, -} from "../preview/bounds"; -import { createPreviewOrbitCameraFit } from "../preview/camera-fit"; -import type { PreviewDisassemblyController } from "../preview/disassembly"; -import { - createPreviewLineOfSight, - isPreviewHitOccluded, - toPreviewWorldPoint, -} from "../preview/geometry"; -import { - createPreviewModelInfoMarkdown, - createPreviewPartInfoMarkdown, -} from "../preview/report"; -import { createPreviewPartSummary } from "../preview/summary"; -import { extractPreviewComponentIdentity, type PreviewComponentIdentity } from "../preview/component-identity"; -import type { - AnnotationViewportProvider, - PreviewAxis, - PreviewPickResult, - PreviewProjectionResult, - PreviewWorldPoint, - MeasurementScale, - WorkbenchPreview, -} from "../preview/types"; - -/** Guard against concurrent OBJ loads monkey-patching the same prototype. */ -let objMtlLock: Promise | null = null; -const OBJ_IMAGE_EXTS = ["jpg", "jpeg", "png", "bmp", "tga", "webp", "tif", "tiff"]; -const OBJ_TEXTURE_RE = /^\s*(map_Kd|map_Ka|map_Ks|map_Ns|map_d|map_bump|bump|disp|decal)\s+(.+)/i; -const FOCUS_DIM_VISIBILITY = 0.242; -const FOCUS_WORLD_POINT_ANIMATION_MS = 320; - -function isShadowLight(light: Light): light is IShadowLight { - const className = light.getClassName(); - return className === "DirectionalLight" || className === "PointLight" || className === "SpotLight"; -} - -function isGaussianSplattingMesh(mesh: AbstractMesh): boolean { - return mesh.getClassName() === "GaussianSplattingMesh"; -} - -function getBabylonNodeDisplayName(node: { name?: string; metadata?: unknown }, fallback: string): string { - const identity = extractPreviewComponentIdentity(node.metadata, { name: node.name }); - return identity.displayName?.trim() || node.name || fallback; -} - -function getBabylonComponentPath(node: { name?: string; parent?: unknown; metadata?: unknown }): string { - const names: string[] = []; - let current: unknown = node; - while (current && typeof current === "object" && "name" in current) { - const currentNode = current as { name?: string; parent?: unknown; metadata?: unknown }; - const name = getBabylonNodeDisplayName(currentNode, "node"); - if (name.trim()) names.push(name); - current = currentNode.parent; - } - return names.reverse().join("/"); -} - -function getPartDisplayName(identity: PreviewComponentIdentity, fallback: string): string { - return identity.displayName?.trim() || identity.partNumber || identity.componentId || fallback; -} - -function parseGltfJson(data: ArrayBuffer, extLower: string): Record | null { - try { - if (extLower === "gltf") { - return JSON.parse(new TextDecoder().decode(new Uint8Array(data))) as Record; - } - if (extLower !== "glb") { - return null; - } - const view = new DataView(data); - if (view.byteLength < 20 || view.getUint32(0, true) !== 0x46546c67) { - return null; - } - const jsonChunkLength = view.getUint32(12, true); - const jsonChunkType = view.getUint32(16, true); - if (jsonChunkType !== 0x4e4f534a || 20 + jsonChunkLength > view.byteLength) { - return null; - } - const jsonBytes = new Uint8Array(data, 20, jsonChunkLength); - return JSON.parse(new TextDecoder().decode(jsonBytes)) as Record; - } catch { - return null; - } -} - -function collectGltfComponentMetadata(data: ArrayBuffer, extLower: string): Map { - const json = parseGltfJson(data, extLower); - const metadata = new Map(); - if (!json) return metadata; - - const nodes = Array.isArray(json.nodes) ? json.nodes : []; - for (const node of nodes) { - if (!node || typeof node !== "object") continue; - const record = node as Record; - const name = typeof record.name === "string" ? record.name : ""; - if (name && record.extras) { - metadata.set(`node:${name}`, record.extras); - } - } - - const meshes = Array.isArray(json.meshes) ? json.meshes : []; - for (const mesh of meshes) { - if (!mesh || typeof mesh !== "object") continue; - const record = mesh as Record; - const name = typeof record.name === "string" ? record.name : ""; - if (name && record.extras) { - metadata.set(`mesh:${name}`, record.extras); - } - } - - return metadata; -} - -function mergeMetadataFallback(primary: unknown, fallback: unknown): unknown { - if (fallback === undefined) return primary; - if (primary === undefined || primary === null) return fallback; - return { metadata: primary, extras: fallback }; -} - -function isBabylonMesh(value: unknown): value is AbstractMesh { - return !!value && typeof value === "object" && "getBoundingInfo" in value; -} - -function toBabylonVector3(value: { x: number; y: number; z: number }): Vector3 { - return new Vector3(value.x, value.y, value.z); -} - -function firstMtlPath(value: string): string { - const trimmed = value.replace(/\s+#.*$/, "").trim(); - if (trimmed.startsWith("\"")) { - const end = trimmed.indexOf("\"", 1); - if (end > 1) return trimmed.slice(1, end); - } - return trimmed; -} - -function firstTexturePath(value: string): string { - const tokens = value.trim().split(/\s+/); - const pathStart = tokens.findIndex((token) => !token.startsWith("-") && !/^[-+]?\d*\.?\d+$/.test(token)); - return tokens.slice(Math.max(0, pathStart)).join(" ").replace(/^"|"$/g, ""); -} - -function guessTextureMime(path: string): string { - const ext = path.split(".").pop()?.toLowerCase() ?? "png"; - if (ext === "jpg" || ext === "jpeg") return "image/jpeg"; - if (ext === "png") return "image/png"; - if (ext === "bmp") return "image/bmp"; - if (ext === "tga") return "image/x-tga"; - if (ext === "webp") return "image/webp"; - return `image/${ext}`; -} - -function buildObjTextureCandidates(modelDir: string, rawPath: string, modelPath: string): string[] { - const texFilename = getPortableBasename(rawPath); - const texBase = texFilename.replace(/\.[^.]+$/, ""); - const objBasename = getPortableStem(modelPath); - const candidates = [ - joinPortablePath(modelDir, rawPath), - joinPortablePath(modelDir, texFilename), - ]; - if (objBasename) { - for (const ext of OBJ_IMAGE_EXTS) { - candidates.push(joinPortablePath(modelDir, `${objBasename}.${ext}`)); - } - } - for (const ext of OBJ_IMAGE_EXTS) { - const alt = `${texBase}.${ext}`; - if (alt !== texFilename) { - candidates.push(joinPortablePath(modelDir, alt)); - } - } - return candidates; -} - -export class BabylonModelPreview implements WorkbenchPreview { - private static readonly annotationIdentity = Matrix.Identity(); - private static readonly annotationWorldPoint = Vector3.Zero(); - private static readonly annotationProjection = Vector3.Zero(); - private static readonly annotationDirection = Vector3.Zero(); - private static readonly annotationRay = new Ray(Vector3.Zero(), Vector3.Zero(), 1); - private engine: Engine; - private scene: Scene; - private camera: ArcRotateCamera; - private rootMesh: Mesh | null = null; - private loadedMeshes: AbstractMesh[] = []; - private loadedTransformNodes: TransformNode[] = []; - private loadedExt: string = ""; - private rendering = false; - private contextLost = false; - private viewportVisible = true; - private viewportObserver: IntersectionObserver | null = null; - private cleanupPicking: (() => void) | null = null; - private resizeObs: ResizeObserver; - private configLights: Light[] = []; - private shadowGenerator: ShadowGenerator | null = null; - private groundMesh: Mesh | null = null; - private gridMesh: Mesh | null = null; - private axisMeshes: Mesh[] = []; - private autoRotateBehavior: AutoRotationBehavior | null = null; - private wireframeEnabled = false; - private gizmo: OrientationGizmo | null = null; - private gizmoEnabled = false; - private disassembly: PreviewDisassemblyController | null = null; - private focusSelectionEnabled = false; - private focusedMesh: AbstractMesh | null = null; - private readonly originalMeshVisibility = new Map(); - private bboxMesh: Mesh | null = null; - private bboxEnabled = false; - private currentQuality: "low" | "medium" | "high" = "high"; - private resourceWarnings: string[] = []; - private gltfComponentMetadata = new Map(); - private animPlaying = false; - private initialCamera = { alpha: Math.PI / 4, beta: Math.PI / 3, radius: 5, target: Vector3.Zero() }; - private focusWorldPointFrame = 0; - private _lastPickResult: PickResult = { mesh: null, pickedPoint: null, screenX: 0, screenY: 0 }; - private _onPickCallbacks: Array<(result: PreviewPickResult) => void> = []; - private measurementActive = false; - private measurementScale: MeasurementScale = { x: 1, y: 1, z: 1 }; - private measurementUnit = "mm"; - private measurementSegments: Array<{ start: Vector3; end: Vector3; line: Mesh; label: Mesh }> = []; - private measurementMarkers: Mesh[] = []; - private pendingPoint: Vector3 | null = null; - private pendingMarker: Mesh | null = null; - private hoveredMarkerIndex = -1; - private lastPointerClient = { x: 0, y: 0 }; - private previewLine: Mesh | null = null; - private readonly handlePointerMove = (event: PointerEvent) => { - this.lastPointerClient = { x: event.clientX, y: event.clientY }; - if (!this.measurementActive) return; - if (this.pendingPoint) { - this.updatePreviewLine(); - } - if (this.measurementMarkers.length === 0) return; - const canvas = this.engine.getRenderingCanvas(); - if (!canvas) return; - const rect = canvas.getBoundingClientRect(); - const x = event.clientX - rect.left; - const y = event.clientY - rect.top; - const pickResult = this.scene.pick(x, y, (mesh) => this.measurementMarkers.includes(mesh as Mesh)); - const newHover = pickResult.hit ? this.measurementMarkers.indexOf(pickResult.pickedMesh as Mesh) : -1; - if (newHover !== this.hoveredMarkerIndex) { - if (this.hoveredMarkerIndex >= 0 && this.hoveredMarkerIndex < this.measurementMarkers.length) { - const prev = this.measurementMarkers[this.hoveredMarkerIndex]; - if (prev !== this.pendingMarker) { - prev.scaling.setAll(1); - (prev.material as StandardMaterial).diffuseColor = new Color3(1, 0.42, 0.42); - (prev.material as StandardMaterial).emissiveColor = new Color3(1, 0.42, 0.42); - } - } - if (newHover >= 0 && newHover < this.measurementMarkers.length) { - const next = this.measurementMarkers[newHover]; - next.scaling.setAll(1.6); - (next.material as StandardMaterial).diffuseColor = new Color3(1, 0.83, 0.23); - (next.material as StandardMaterial).emissiveColor = new Color3(1, 0.83, 0.23); - } - this.hoveredMarkerIndex = newHover; - } - }; - private readonly preventCanvasWheelScroll = (event: WheelEvent) => { - event.preventDefault(); - event.stopPropagation(); - }; - - private canRender(): boolean { - const canvas = this.engine.getRenderingCanvas(); - return !!canvas?.isConnected && canvas.clientWidth > 0 && canvas.clientHeight > 0; - } - - private ensureDisassemblyController(): PreviewDisassemblyController | null { - if (!this.rootMesh) { - return null; - } - if (!this.disassembly) { - this.disassembly = createBabylonDisassemblyController( - this.scene, - this.camera, - this.getRenderableMeshes(this.rootMesh), - ); - } - return this.disassembly; - } - - private isDisassemblyActive(): boolean { - return this.disassembly?.isEnabled() ?? false; - } - - constructor(canvas: HTMLCanvasElement) { - this.engine = new Engine(canvas, true, { preserveDrawingBuffer: true }); - this.scene = new Scene(this.engine); - this.scene.clearColor = new Color4(0.12, 0.12, 0.14, 1); - - this.camera = new ArcRotateCamera( - "cam", - Math.PI / 4, - Math.PI / 3, - 5, - Vector3.Zero(), - this.scene, - ); - this.camera.attachControl(canvas, true); - this.camera.lowerRadiusLimit = 0.1; - this.camera.wheelPrecision = 30; - canvas.addEventListener("wheel", this.preventCanvasWheelScroll, { passive: false }); - canvas.addEventListener("pointermove", this.handlePointerMove); - canvas.addEventListener("webglcontextlost", this.handleContextLost); - canvas.addEventListener("webglcontextrestored", this.handleContextRestored); - - this.scene.ambientColor = new Color3(0.3, 0.3, 0.3); - const hemi = new HemisphericLight("default-light", new Vector3(0, 1, 0.5), this.scene); - hemi.intensity = 1.2; - - this.resizeObs = new ResizeObserver(() => this.engine.resize()); - this.resizeObs.observe(canvas); - if (typeof IntersectionObserver !== "undefined") { - this.viewportObserver = new IntersectionObserver(this.handleViewportIntersection, { - root: null, - threshold: [0, 0.01], - }); - this.viewportObserver.observe(canvas); - } - // Force a resize after the canvas is mounted and has layout dimensions - window.requestAnimationFrame(() => this.engine.resize()); - } - - async loadModel( - data: ArrayBuffer, - ext: string, - readFile?: (path: string) => Promise, - modelPath?: string, - ): Promise { - await ensureLoadersRegistered(); - - if (this.rootMesh) { - const previousRoot = this.rootMesh; - previousRoot.dispose(true, true); - for (const mesh of this.loadedMeshes) { - if (mesh !== previousRoot && !mesh.isDisposed()) { - mesh.dispose(true, true); - } - } - this.rootMesh = null; - } - this.loadedMeshes = []; - this.loadedTransformNodes = []; - this.clearMeasurements(); - this.disassembly?.dispose(); - this.disassembly = null; - this.clearFocusedMesh(); - this.originalMeshVisibility.clear(); - - const extLower = ext.toLowerCase().replace(".", ""); - this.loadedExt = extLower; - this.resourceWarnings = []; - this.gltfComponentMetadata = collectGltfComponentMetadata(data, extLower); - const scene = this.scene; - - // Map extension to Babylon SceneLoader file extension - const extToLoader: Record = { - glb: ".glb", - gltf: ".gltf", - stl: ".stl", - obj: ".obj", - splat: ".splat", - ply: ".ply", - }; - const fileExt = extToLoader[extLower] ?? `.${extLower}`; - - // Use data URL instead of blob URL — Obsidian's Electron converts - // blob: URLs to blob:app://... which Babylon's GLTF loader cannot parse. - const dataUrl = `data:application/octet-stream;base64,${arrayBufferToBase64(data)}`; - - // OBJ: override _loadMTL to read MTL from vault instead of network fetch. - // Serialized via objMtlLock to prevent concurrent loads from clobbering the prototype. - if (extLower === "obj" && readFile && modelPath) { - if (objMtlLock) await objMtlLock; - let resolveLock!: () => void; - objMtlLock = new Promise(r => { resolveLock = r; }); - try { - const { OBJFileLoader } = await import("@babylonjs/loaders/OBJ/objFileLoader.js"); - const proto = OBJFileLoader.prototype as unknown as Record; - if (typeof proto._loadMTL !== "function") { - console.warn("[AI3D] OBJFileLoader._loadMTL not found — MTL vault resolution disabled"); - } - const originalLoadMTL = proto._loadMTL; - - // Pre-load MTL content from vault (if exists) - const objText = new TextDecoder().decode(new Uint8Array(data)); - const mtlMatch = objText.match(/mtllib\s+(.+)/); - let mtlContent: string | null = null; - if (mtlMatch && readFile && modelPath) { - const mtlFilename = firstMtlPath(mtlMatch[1]); - const modelDir = getPortableDirname(modelPath); - const mtlPath = joinPortablePath(modelDir, mtlFilename); - try { - const mtlData = await readFile(mtlPath); - const raw = new TextDecoder().decode(new Uint8Array(mtlData)); - const lines = raw.split("\n"); - - // Resolve texture files referenced in MTL from vault. - // Try: 1) full relative path, 2) same-dir filename, - // 3) OBJ-name with image extensions (e.g. bat.jpeg), - // 4) common basecolor/texture names in same dir - for (let i = 0; i < lines.length; i++) { - const m = lines[i].match(OBJ_TEXTURE_RE); - if (!m) continue; - const rawPath = firstTexturePath(m[2]); - const candidates = buildObjTextureCandidates(modelDir, rawPath, modelPath); - let resolved = false; - for (const cand of candidates) { - try { - const texBuf = await readFile(cand); - const dataUrl = `data:${guessTextureMime(cand)};base64,${arrayBufferToBase64(texBuf)}`; - lines[i] = `${m[1]} ${dataUrl}`; - resolved = true; - break; - } catch { /* try next candidate */ } - } - if (!resolved) { - this.resourceWarnings.push(`OBJ material texture not found: ${rawPath}`); - lines[i] = ""; // strip — prevents red-black checkerboard - } - } - - // If MTL has no Kd (diffuse color), add default light gray - const filtered = lines.filter(l => l !== ""); - const hasKd = filtered.some(l => /^\s*Kd\s+/i.test(l)); - if (!hasKd) { - const nmIdx = filtered.findIndex(l => /^\s*newmtl\s+/i.test(l)); - filtered.splice(nmIdx >= 0 ? nmIdx + 1 : 0, 0, "Kd 0.80 0.80 0.80"); - } - mtlContent = filtered.join("\n"); - } catch { - this.resourceWarnings.push(`OBJ material library not found: ${mtlPath}`); - } - } - - // Override _loadMTL to use vault content or skip (prevents network fetch) - proto._loadMTL = function(_url: string, _rootUrl: string, onSuccess: (data: string) => void) { - const content = mtlContent ?? ""; - onSuccess(content); - }; - - const result = await ImportMeshAsync(dataUrl, scene, { meshNames: "", pluginExtension: fileExt }); - this.loadedMeshes = result.meshes; - this.loadedTransformNodes = result.transformNodes; - if (result.meshes.length > 0) this.rootMesh = result.meshes[0] as Mesh; - - // Restore original _loadMTL - proto._loadMTL = originalLoadMTL; - } catch (e) { - console.error("[AI3D] OBJ load error:", e); - throw e; - } finally { - resolveLock(); - objMtlLock = null; - } - } else if (extLower === "stl") { - // Direct parse — Babylon v9 SceneLoader mishandles data URLs for custom plugins - this.rootMesh = loadSTLBuffer(scene, data); - if (this.rootMesh) this.loadedMeshes = [this.rootMesh]; - } else if (extLower === "ply") { - // Direct parse — same Babylon v9 data-URL issue as STL - this.rootMesh = loadPLYBuffer(scene, data); - if (this.rootMesh) this.loadedMeshes = [this.rootMesh]; - } else { - const result = await ImportMeshAsync(dataUrl, scene, { meshNames: "", pluginExtension: fileExt }); - this.loadedMeshes = result.meshes; - this.loadedTransformNodes = result.transformNodes; - if (result.meshes.length > 0) this.rootMesh = result.meshes[0] as Mesh; - } - - if (!this.rootMesh) { - throw new Error("No mesh found in model file"); - } - - // Disable backface culling on all materials to prevent invisible faces - // (CAD-converted models often have inconsistent face normals) - for (const m of this.getRenderableMeshes(this.rootMesh)) { - if (m.material) { - m.material.backFaceCulling = false; - } - } - - const fit = createPreviewOrbitCameraFit(this.getRenderableBounds(this.rootMesh)); - - this.camera.target = toBabylonVector3(fit.target); - this.camera.radius = fit.radius; - this.camera.lowerRadiusLimit = fit.lowerRadiusLimit; - this.camera.upperRadiusLimit = fit.upperRadiusLimit; - this.camera.minZ = fit.near; - this.camera.maxZ = fit.far; - - this.initialCamera = { - alpha: this.camera.alpha, - beta: this.camera.beta, - radius: this.camera.radius, - target: this.camera.target.clone(), - }; - - this.startRenderLoop(); - this.engine.resize(); - - this.cleanupPicking?.(); - this.cleanupPicking = setupPicking(this.scene, (result) => { - if (this.isDisassemblyActive()) return; - if (this.measurementActive && result.pickedPoint) { - this.addMeasurementPoint(toBabylonVector3(result.pickedPoint as { x: number; y: number; z: number })); - return; - } - this._lastPickResult = result; - if (this.focusSelectionEnabled && result.mesh) { - this.setFocusedMesh(result.mesh); - } - this._onPickCallbacks.forEach(cb => cb(result)); - }, () => !this.focusSelectionEnabled); - this.ensureDisassemblyController(); - - return this.computeSummary(this.rootMesh); - } - - // ── Config application ─────────────────────────────────────────── - - applyConfig(config: ThreeDBlockConfig): void { - if (config.camera) this.applyCameraConfig(config.camera); - if (config.lights) this.applyLightConfig(config.lights); - if (config.scene) this.applySceneConfig(config.scene); - if (config.stl && this.loadedExt === "stl") { - if (config.stl.color) this.setSTLColor(config.stl.color); - if (config.stl.wireframe !== undefined) this.setWireframe(config.stl.wireframe); - } - } - - applyCameraConfig(config: CameraConfig): void { - const canvas = this.engine.getRenderingCanvas(); - if (!canvas) return; - - if (config.mode === "orthographic") { - const radius = this.camera.radius; - const aspect = canvas.clientWidth / canvas.clientHeight; - const zoom = config.zoom ?? 1; - const size = radius / zoom; - - this.camera.mode = 1; // orthographic - this.camera.orthoLeft = -size * aspect; - this.camera.orthoRight = size * aspect; - this.camera.orthoTop = size; - this.camera.orthoBottom = -size; - } else { - this.camera.mode = 0; // perspective - if (config.fov) this.camera.fov = (config.fov * Math.PI) / 180; - } - - if (config.position) { - const [x, y, z] = config.position; - this.camera.setPosition(new Vector3(x, y, z)); - } - - if (config.lookAt) { - const [x, y, z] = config.lookAt; - this.camera.setTarget(new Vector3(x, y, z)); - } - - if (config.near !== undefined) this.camera.minZ = config.near; - if (config.far !== undefined) this.camera.maxZ = config.far; - } - - applyLightConfig(lights: LightConfig[]): void { - // Dispose previous config lights and shadow generator - for (const light of this.configLights) { - light.dispose(); - } - this.configLights = []; - this.shadowGenerator?.dispose(); - this.shadowGenerator = null; - - // Remove the default light when config lights are provided - const defaultLight = this.scene.getLightByName("default-light"); - if (defaultLight) { - defaultLight.dispose(); - } - - for (const cfg of lights) { - const light = this.createLight(cfg); - if (light) this.configLights.push(light); - } - } - - private createLight(cfg: LightConfig): Light | null { - const color = cfg.color ? Color3.FromHexString(cfg.color) : Color3.White(); - const intensity = cfg.intensity ?? 1; - - switch (cfg.type) { - case "hemisphere": { - const ground = cfg.groundColor - ? Color3.FromHexString(cfg.groundColor) - : new Color3(0.2, 0.2, 0.2); - const l = new HemisphericLight("hemi", new Vector3(0, 1, 0), this.scene); - l.diffuse = color; - l.groundColor = ground; - l.intensity = intensity; - return l; - } - case "directional": { - const dir = cfg.position - ? new Vector3(...cfg.position).normalize() - : new Vector3(-1, -2, -1).normalize(); - const l = new DirectionalLight("dir", dir, this.scene); - l.diffuse = color; - l.intensity = intensity; - if (cfg.castShadow && this.rootMesh) { - this.setupShadow(l); - } - return l; - } - case "point": { - const pos = cfg.position ? new Vector3(...cfg.position) : new Vector3(0, 5, 0); - const l = new PointLight("point", pos, this.scene); - l.diffuse = color; - l.intensity = intensity; - if (cfg.decay !== undefined) (l as unknown as Record).decay = cfg.decay; - return l; - } - case "spot": { - const pos = cfg.position ? new Vector3(...cfg.position) : new Vector3(0, 5, 0); - const target = cfg.target ? new Vector3(...cfg.target) : Vector3.Zero(); - const dir = target.subtract(pos).normalize(); - const angle = cfg.angle ? (cfg.angle * Math.PI) / 180 : Math.PI / 4; - const penumbra = cfg.penumbra ?? 0.5; - const l = new SpotLight("spot", pos, dir, angle, penumbra, this.scene); - l.diffuse = color; - l.intensity = intensity; - if (cfg.decay !== undefined) (l as unknown as Record).decay = cfg.decay; - if (cfg.castShadow && this.rootMesh) { - this.setupShadow(l); - } - return l; - } - case "attachToCam": { - const l = new PointLight("cam-light", Vector3.Zero(), this.scene); - l.diffuse = color; - l.intensity = intensity; - l.parent = this.camera; - return l; - } - default: - return null; - } - } - - private setupShadow(light: Light): void { - if (!this.rootMesh) return; - // ShadowGenerator requires a ShadowLight (DirectionalLight | PointLight | SpotLight). - // HemisphericLight cannot cast shadows — silently skip. - if (!isShadowLight(light)) { - console.warn("[AI3D] Light type does not support shadows:", light.name); - return; - } - const sg = new ShadowGenerator(1024, light); - sg.useBlurExponentialShadowMap = true; - sg.blurKernel = 32; - for (const m of this.getRenderableMeshes(this.rootMesh)) { - sg.addShadowCaster(m); - m.receiveShadows = true; - } - this.shadowGenerator = sg; - } - - applySceneConfig(config: SceneConfig): void { - if (config.background !== undefined) { - const c = Color4.FromColor3(Color3.FromHexString(config.background), config.transparent ? 0 : 1); - this.scene.clearColor = c; - } - - if (config.autoRotate) { - if (!this.autoRotateBehavior) { - this.autoRotateBehavior = new AutoRotationBehavior(); - this.autoRotateBehavior.idleRotationSpeed = config.autoRotateSpeed ?? 0.5; - this.autoRotateBehavior.idleRotationWaitTime = 1000; - this.autoRotateBehavior.idleRotationSpinupTime = 500; - this.camera.addBehavior(this.autoRotateBehavior); - } else { - this.autoRotateBehavior.idleRotationSpeed = config.autoRotateSpeed ?? 0.5; - } - } - - if (config.groundShadow && this.rootMesh) { - this.createGround(); - } - - if (config.grid) { - this.createGrid(); - } - - if (config.axis) { - this.createAxis(); - } - } - - private createGround(): void { - if (!this.rootMesh || this.groundMesh) return; - const bounds = this.getRenderableBounds(this.rootMesh); - const boundsSize = getPreviewBoundsSize(bounds); - const size = Math.max(boundsSize.x, boundsSize.z) * 3; - const y = bounds.min.y; - - this.groundMesh = MeshBuilder.CreateGround("ground", { width: size, height: size }, this.scene); - this.groundMesh.position.y = y; - const mat = new StandardMaterial("ground-mat", this.scene); - mat.diffuseColor = new Color3(0.15, 0.15, 0.15); - mat.specularColor = Color3.Black(); - mat.alpha = 0.5; - this.groundMesh.material = mat; - this.groundMesh.receiveShadows = true; - } - - private createGrid(): void { - if (!this.rootMesh || this.gridMesh) return; - const bounds = this.getRenderableBounds(this.rootMesh); - const boundsSize = getPreviewBoundsSize(bounds); - const size = Math.max(boundsSize.x, boundsSize.z) * 2; - const y = bounds.min.y - 0.01; - - this.gridMesh = MeshBuilder.CreateGround("grid", { width: size, height: size, subdivisions: 20 }, this.scene); - this.gridMesh.position.y = y; - const mat = new StandardMaterial("grid-mat", this.scene); - mat.wireframe = true; - mat.diffuseColor = new Color3(0.3, 0.3, 0.3); - mat.emissiveColor = new Color3(0.1, 0.1, 0.1); - this.gridMesh.material = mat; - } - - private createAxis(): void { - if (!this.rootMesh || this.axisMeshes.length > 0) return; - const bounds = this.getRenderableBounds(this.rootMesh); - const len = getPreviewBoundsMaxSpan(bounds) * 1.5; - const origin = toBabylonVector3(bounds.min); - const radius = getPreviewBoundsRadius(bounds) * 0.01; - - const axes: [string, Color3, Vector3][] = [ - ["x", Color3.Red(), new Vector3(len, 0, 0)], - ["y", Color3.Green(), new Vector3(0, len, 0)], - ["z", Color3.Blue(), new Vector3(0, 0, len)], - ]; - - for (const [name, color, dir] of axes) { - const tube = MeshBuilder.CreateTube(`axis-${name}`, { - path: [origin, origin.add(dir)], - radius, - tessellation: 8, - }, this.scene); - const mat = new StandardMaterial(`axis-${name}-mat`, this.scene); - mat.emissiveColor = color; - mat.diffuseColor = Color3.Black(); - tube.material = mat; - this.axisMeshes.push(tube); - } - } - - setSTLColor(hex: string): void { - if (!this.rootMesh) return; - const color = Color3.FromHexString(hex); - for (const m of this.getRenderableMeshes(this.rootMesh)) { - if (m.material && m.material.name === "stl-mat") { - const mat = m.material as StandardMaterial; - mat.diffuseColor = color; - mat.emissiveColor = color.scale(0.1); - } - } - } - - setWireframe(enabled: boolean): void { - if (!this.rootMesh) return; - if (isGaussianSplattingMesh(this.rootMesh)) return; - this.wireframeEnabled = enabled; - this.scene.forceWireframe = enabled; - } - - toggleWireframe(): boolean { - this.setWireframe(!this.wireframeEnabled); - return this.wireframeEnabled; - } - - hasAnimations(): boolean { - return this.scene.animationGroups.length > 0; - } - - toggleAnimation(): boolean { - const groups = this.scene.animationGroups; - if (groups.length === 0) return false; - this.animPlaying = !this.animPlaying; - for (const g of groups) { - if (this.animPlaying) { - g.play(true); - } else { - g.pause(); - } - } - return this.animPlaying; - } - - toggleMeasurement(): boolean { - this.measurementActive = !this.measurementActive; - if (!this.measurementActive) { - this.clearMeasurements(); - } - return this.measurementActive; - } - - isMeasurementActive(): boolean { - return this.measurementActive; - } - - clearMeasurements(): void { - this.measurementActive = false; - this.pendingPoint = null; - this.pendingMarker = null; - this.hoveredMarkerIndex = -1; - this.removePreviewLine(); - for (const segment of this.measurementSegments) { - segment.line.dispose(); - segment.label.dispose(); - } - this.measurementSegments = []; - for (const marker of this.measurementMarkers) { - marker.dispose(); - } - this.measurementMarkers = []; - } - - - setMeasurementScale(scale: MeasurementScale): void { - this.measurementScale = { ...scale }; - this.updateMeasurementLabels(); - } - - getMeasurementScale(): MeasurementScale { - return { ...this.measurementScale }; - } - - getMeasurementBounds(): { x: number; y: number; z: number } | null { - if (!this.rootMesh) return null; - const bounds = this.getRenderableBounds(this.rootMesh); - if (!bounds) return null; - return { - x: bounds.max.x - bounds.min.x, - y: bounds.max.y - bounds.min.y, - z: bounds.max.z - bounds.min.z, - }; - } - - private getRealDistance(start: Vector3, end: Vector3): number { - const dx = (end.x - start.x) * this.measurementScale.x; - const dy = (end.y - start.y) * this.measurementScale.y; - const dz = (end.z - start.z) * this.measurementScale.z; - return Math.sqrt(dx * dx + dy * dy + dz * dz); - } - - private formatMeasurementDistance(distance: number): string { - const unit = this.measurementUnit; - if (unit === "um" || unit === "μm") { - return distance < 1000 ? `${distance.toFixed(2)} μm` : `${(distance / 1000).toFixed(2)} mm`; - } - if (unit === "mm") { - return distance < 1 ? `${(distance * 1000).toFixed(2)} μm` : distance < 1000 ? `${distance.toFixed(2)} mm` : `${(distance / 1000).toFixed(3)} m`; - } - if (unit === "cm") { - return distance < 1 ? `${(distance * 10).toFixed(2)} mm` : distance < 100 ? `${distance.toFixed(2)} cm` : `${(distance / 100).toFixed(3)} m`; - } - if (unit === "m") { - return distance < 0.01 ? `${(distance * 1000).toFixed(2)} mm` : distance < 1 ? `${distance.toFixed(3)} m` : `${distance.toFixed(2)} m`; - } - return `${distance.toFixed(3)} ${unit}`; - } - - updateMeasurementLabels(): void { - if (this.measurementSegments.length === 0) return; - const markerSize = this.getMeasurementMarkerSize() * 4; - for (const segment of this.measurementSegments) { - const distance = this.getRealDistance(segment.start, segment.end); - const labelText = this.formatMeasurementDistance(distance); - segment.label.dispose(false, true); - const mid = Vector3.Center(segment.start, segment.end); - segment.label = this.createMeasurementLabelMesh(labelText, mid, markerSize); - } - } - - setAnimationSpeed(speed: number): void { - for (const g of this.scene.animationGroups) { - g.speedRatio = speed; - } - } - - captureSnapshot(): string | null { - const canvas = this.engine.getRenderingCanvas(); - if (!canvas) return null; - this.scene.render(); - return canvas.toDataURL("image/png"); - } - - toggleOrientationGizmo(): boolean { - this.gizmoEnabled = !this.gizmoEnabled; - if (this.gizmoEnabled && !this.gizmo) { - this.gizmo = new OrientationGizmo(this.engine, this.camera); - } - return this.gizmoEnabled; - } - - isOrientationGizmoEnabled(): boolean { - return this.gizmoEnabled; - } - - /** - * Set render resolution scale directly (1.0 = native). - * Returns the applied scale value. - */ - setRenderScale(scale: number): number { - const clamped = Math.max(0.25, Math.min(scale, 2.0)); - const qualityScale = { low: 2, medium: 1.33, high: 1 }[this.currentQuality]; - const mobileBoost = isMobile() ? 1.5 : 1; - this.engine.setHardwareScalingLevel(qualityScale * mobileBoost / clamped); - return clamped; - } - - getPerformanceSnapshot() { - return { - backend: "babylon" as const, - renderScale: Number((1 / this.engine.getHardwareScalingLevel()).toFixed(2)), - quality: this.currentQuality, - meshCount: this.rootMesh ? this.getRenderableMeshes(this.rootMesh).length : 0, - }; - } - - toggleBoundingBox(): boolean { - this.bboxEnabled = !this.bboxEnabled; - if (this.bboxEnabled) { - if (!this.rootMesh) return this.bboxEnabled; - if (this.bboxMesh) this.bboxMesh.dispose(); - const bounds = this.getRenderableBounds(this.rootMesh); - const center = toBabylonVector3(getPreviewBoundsCenter(bounds)); - const size = toBabylonVector3(getPreviewBoundsSize(bounds)); - - this.bboxMesh = MeshBuilder.CreateBox("bbox", { - width: size.x, height: size.y, depth: size.z, - }, this.scene); - this.bboxMesh.position = center; - const mat = new StandardMaterial("bbox-mat", this.scene); - mat.wireframe = true; - mat.emissiveColor = new Color3(1, 1, 0); - mat.disableLighting = true; - mat.alpha = 0.6; - this.bboxMesh.material = mat; - } else { - this.bboxMesh?.dispose(); - this.bboxMesh = null; - } - return this.bboxEnabled; - } - - toggleFocusSelection(): boolean { - const nextEnabled = !this.focusSelectionEnabled; - if (nextEnabled && this.isDisassemblyActive()) { - this.disassembly?.setEnabled(false); - } - this.focusSelectionEnabled = nextEnabled; - if (!this.focusSelectionEnabled) { - this.clearFocusedMesh(); - } else if (this._lastPickResult.mesh) { - this.setFocusedMesh(this._lastPickResult.mesh); - } - return this.focusSelectionEnabled; - } - - isFocusSelectionEnabled(): boolean { - return this.focusSelectionEnabled; - } - - toggleDisassembly(): boolean { - const controller = this.ensureDisassemblyController(); - if (!controller) return false; - const nextEnabled = !controller.isEnabled(); - if (nextEnabled) { - this.focusSelectionEnabled = false; - this.clearFocusedMesh(); - } - return controller.setEnabled(nextEnabled); - } - - resetDisassembly(): void { - this.disassembly?.reset(); - } - - isDisassemblyEnabled(): boolean { - return this.isDisassemblyActive(); - } - - // ── Existing API ───────────────────────────────────────────────── - - setExplode(factor: number, axis: PreviewAxis) { - if (this.rootMesh) setExplode(this.rootMesh, factor, axis, this.loadedMeshes); - } - - resetExplode() { - if (this.rootMesh) resetExplode(this.rootMesh, this.loadedMeshes); - } - - resetView(): void { - if (this.rootMesh) resetExplode(this.rootMesh, this.loadedMeshes); - this.resetDisassembly(); - this.clearFocusedMesh(); - this.camera.mode = 0; // perspective - this.camera.alpha = this.initialCamera.alpha; - this.camera.beta = this.initialCamera.beta; - this.camera.radius = this.initialCamera.radius; - this.camera.target = this.initialCamera.target.clone(); - } - - exportModelInfo(modelPath?: string): string { - if (!this.rootMesh) return ""; - const summary = this.computeSummary(this.rootMesh); - const renderableMeshes = this.getRenderableMeshes(this.rootMesh); - const isSplat = isGaussianSplattingMesh(this.rootMesh); - const name = modelPath ? getPortableBasename(modelPath) || summary.rootName : summary.rootName; - return createPreviewModelInfoMarkdown({ - title: name, - format: this.loadedExt.toUpperCase(), - summary, - meshBreakdown: renderableMeshes.map((mesh) => ({ - name: mesh.name, - triangleCount: isSplat ? null : getBabylonTriangleCount(mesh), - vertexCount: getBabylonVertexCount(mesh), - materialName: mesh.material?.name ?? null, - })), - materialNames: renderableMeshes.map((mesh) => mesh.material?.name), - }); - } - - getModelEvidence(): ModelEvidence | null { - if (!this.rootMesh) return null; - const renderableMeshes = this.getRenderableMeshes(this.rootMesh); - const groupedPartCandidates = this.computeComponentPartSummaries(renderableMeshes); - const meshParts = renderableMeshes - .filter((mesh) => !groupedPartCandidates.groupedMeshes.has(mesh)) - .map((mesh) => this.computePartSummary(mesh)); - const parts = groupedPartCandidates.parts.length > 0 ? [...groupedPartCandidates.parts, ...meshParts] : meshParts; - const materialNames = new Set(); - for (const mesh of renderableMeshes) { - if (mesh.material?.name) materialNames.add(mesh.material.name); - } - return { - summary: this.computeSummary(this.rootMesh), - parts, - materialNames: Array.from(materialNames).sort((left, right) => left.localeCompare(right)), - resourceWarnings: [...this.resourceWarnings], - capturedAt: new Date().toISOString(), - }; - } - - getSelectedPartInfo(): ModelPartSummary | null { - const mesh = this.focusedMesh ?? this._lastPickResult.mesh; - const renderable = mesh ? this.findRenderableMesh(mesh) : null; - if (!renderable || renderable.isDisposed()) return null; - return this.computePartSummary(renderable); - } - - exportSelectedPartInfo(): string { - const part = this.getSelectedPartInfo(); - return part ? createPreviewPartInfoMarkdown(part) : ""; - } - - getPickWorldPoint(result: PreviewPickResult): PreviewWorldPoint | null { - if (result.pickedPoint && typeof result.pickedPoint === "object") { - return toPreviewWorldPoint(result.pickedPoint as { x: number; y: number; z: number }); - } - - if (isBabylonMesh(result.mesh)) { - const center = result.mesh.getBoundingInfo().boundingBox.centerWorld; - return toPreviewWorldPoint(center); - } - - return null; - } - - focusWorldPoint(point: PreviewWorldPoint): void { - const target = new Vector3(point.x, point.y, point.z); - const start = this.camera.target.clone(); - const startedAt = performance.now(); - - if (this.focusWorldPointFrame) { - activeWindow.cancelAnimationFrame(this.focusWorldPointFrame); - this.focusWorldPointFrame = 0; - } - - const tick = (now: number) => { - const t = Math.min(1, Math.max(0, (now - startedAt) / FOCUS_WORLD_POINT_ANIMATION_MS)); - const ease = t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2; - this.camera.target = Vector3.Lerp(start, target, ease); - if (t < 1 && !this.scene.isDisposed) { - this.focusWorldPointFrame = window.requestAnimationFrame(tick); - return; - } - this.focusWorldPointFrame = 0; - }; - this.focusWorldPointFrame = window.requestAnimationFrame(tick); - } - - private getAnnotationCameraStateKey(): string { - return `${this.camera.alpha.toFixed(3)}_${this.camera.beta.toFixed(3)}_${this.camera.radius.toFixed(3)}_${this.camera.target.x.toFixed(2)}_${this.camera.target.y.toFixed(2)}_${this.camera.target.z.toFixed(2)}`; - } - - private projectAnnotationWorldPoint(point: PreviewWorldPoint, result: PreviewProjectionResult): boolean { - const canvas = this.engine.getRenderingCanvas(); - if (!canvas || this.scene.isDisposed) { - return false; - } - - const rw = this.engine.getRenderWidth(); - const rh = this.engine.getRenderHeight(); - if (rw === 0 || rh === 0 || canvas.clientWidth === 0 || canvas.clientHeight === 0) { - return false; - } - - const worldPoint = BabylonModelPreview.annotationWorldPoint; - worldPoint.set(point.x, point.y, point.z); - - Vector3.ProjectToRef( - worldPoint, - BabylonModelPreview.annotationIdentity, - this.scene.getTransformMatrix(), - this.camera.viewport.toGlobal(rw, rh), - BabylonModelPreview.annotationProjection, - ); - - const scaleX = canvas.clientWidth / rw; - const scaleY = canvas.clientHeight / rh; - result.screenX = BabylonModelPreview.annotationProjection.x * scaleX; - result.screenY = BabylonModelPreview.annotationProjection.y * scaleY; - result.depth = BabylonModelPreview.annotationProjection.z; - return true; - } - - private isAnnotationWorldPointOccluded(point: PreviewWorldPoint): boolean { - if (this.scene.isDisposed) { - return false; - } - - const lineOfSight = createPreviewLineOfSight( - toPreviewWorldPoint(this.camera.position), - point, - ); - if (!lineOfSight) { - return false; - } - const direction = BabylonModelPreview.annotationDirection; - const ray = BabylonModelPreview.annotationRay; - - direction.set(lineOfSight.direction.x, lineOfSight.direction.y, lineOfSight.direction.z); - ray.origin = this.camera.position; - ray.direction = direction; - ray.length = lineOfSight.distance; - - const pickInfo = this.scene.pickWithRay(ray); - return !!pickInfo?.hit - && isPreviewHitOccluded(pickInfo.distance, lineOfSight.distance, lineOfSight.epsilon); - } - - getAnnotationProvider(): AnnotationViewportProvider { - const canvas = this.engine.getRenderingCanvas(); - if (!canvas) { - throw new Error("Preview canvas is unavailable"); - } - return { - canvas, - observeRender: (callback) => { - const obs = this.scene.onAfterRenderCameraObservable.add((camera) => { - if (camera === this.camera) { - callback(); - } - }); - return { - remove: () => this.scene.onAfterRenderCameraObservable.remove(obs), - }; - }, - getCameraStateKey: () => this.getAnnotationCameraStateKey(), - projectWorldPoint: (point, result) => this.projectAnnotationWorldPoint(point, result), - isWorldPointOccluded: (point) => this.isAnnotationWorldPointOccluded(point), - }; - } - - getCanvas(): HTMLCanvasElement | null { - return this.engine.getRenderingCanvas(); - } - - getLastPickResult(): PreviewPickResult { - return this._lastPickResult; - } - - onPick(callback: (result: PreviewPickResult) => void): () => void { - this._onPickCallbacks.push(callback); - return () => { - this._onPickCallbacks = this._onPickCallbacks.filter(cb => cb !== callback); - }; - } - - /** - * Apply render quality preset and optional resolution scale. - * - low: 0.5x resolution, no shadow blur - * - medium: 0.75x resolution, basic shadow blur - * - high: 1.0x resolution, full shadow blur (default) - * @param renderScale User-controlled resolution multiplier (1.0 = native). - * Lower values = less pixels = better performance. - */ - setRenderQuality(quality: "low" | "medium" | "high", renderScale = 1.0): void { - this.currentQuality = quality; - const scaleMap = { low: 2, medium: 1.33, high: 1 }; - const mobileBoost = isMobile() ? 1.5 : 1; - // hardwareScalingLevel: higher = fewer pixels. renderScale < 1 = fewer pixels. - const scale = scaleMap[quality] * mobileBoost / Math.max(renderScale, 0.25); - this.engine.setHardwareScalingLevel(scale); - - if (this.shadowGenerator) { - const blurMap = { low: 0, medium: 16, high: 32 }; - this.shadowGenerator.blurKernel = blurMap[quality]; - if (quality === "low") { - this.shadowGenerator.useBlurExponentialShadowMap = false; - this.shadowGenerator.useExponentialShadowMap = true; - } else { - this.shadowGenerator.useBlurExponentialShadowMap = true; - this.shadowGenerator.useExponentialShadowMap = false; - } - } - } - - destroy() { - this.engine.stopRenderLoop(); - if (this.focusWorldPointFrame) { - activeWindow.cancelAnimationFrame(this.focusWorldPointFrame); - this.focusWorldPointFrame = 0; - } - this._onPickCallbacks = []; - this.cleanupPicking?.(); - this.cleanupPicking = null; - this.gizmo?.dispose(); - this.gizmo = null; - this.disassembly?.dispose(); - this.disassembly = null; - this.clearMeasurements(); - this.clearFocusedMesh(); - this.originalMeshVisibility.clear(); - this.bboxMesh?.dispose(); - this.bboxMesh = null; - this.camera.detachControl(); - const canvas = this.engine.getRenderingCanvas(); - canvas?.removeEventListener("wheel", this.preventCanvasWheelScroll); - canvas?.removeEventListener("pointermove", this.handlePointerMove); - canvas?.removeEventListener("webglcontextlost", this.handleContextLost); - canvas?.removeEventListener("webglcontextrestored", this.handleContextRestored); - this.viewportObserver?.disconnect(); - this.viewportObserver = null; - this.resizeObs.disconnect(); - if (this.autoRotateBehavior) { - this.camera.removeBehavior(this.autoRotateBehavior); - this.autoRotateBehavior = null; - } - for (const l of this.configLights) l.dispose(); - this.configLights = []; - this.shadowGenerator?.dispose(); - this.shadowGenerator = null; - this.groundMesh?.dispose(); - this.groundMesh = null; - this.gridMesh?.dispose(); - this.gridMesh = null; - for (const a of this.axisMeshes) a.dispose(); - this.axisMeshes = []; - this.scene.dispose(); - this.engine.dispose(); - } - - private startRenderLoop() { - if (this.rendering || !this.viewportVisible || this.contextLost) return; - this.rendering = true; - this.engine.runRenderLoop(() => { - if (!this.canRender() || !this.viewportVisible || this.contextLost) { - this.engine.stopRenderLoop(); - this.rendering = false; - return; - } - this.scene.render(); - if (this.gizmo && this.gizmoEnabled) { - this.gizmo.syncWith(this.camera); - this.gizmo.render(); - } - }); - } - - private readonly handleViewportIntersection = (entries: IntersectionObserverEntry[]) => { - const visible = entries.some((entry) => entry.isIntersecting); - if (visible === this.viewportVisible) return; - this.viewportVisible = visible; - if (visible) { - this.startRenderLoop(); - } else if (this.rendering) { - this.engine.stopRenderLoop(); - this.rendering = false; - } - }; - - private readonly handleContextLost = (event: Event) => { - event.preventDefault(); - this.contextLost = true; - if (this.rendering) { - this.engine.stopRenderLoop(); - this.rendering = false; - } - }; - - private readonly handleContextRestored = () => { - this.contextLost = false; - this.engine.resize(); - this.startRenderLoop(); - }; - - private getRenderableMeshes(root: Mesh): AbstractMesh[] { - return getBabylonRenderableMeshes(root, this.loadedMeshes); - } - - private getRenderableBounds(root: Mesh) { - return getBabylonRenderablePreviewBounds(root, this.loadedMeshes); - } - - private setFocusedMesh(mesh: AbstractMesh | null): void { - if (!this.rootMesh) return; - const target = mesh ? this.findRenderableMesh(mesh) : null; - if (!target || target.isDisposed()) { - this.clearFocusedMesh(); - return; - } - if (this.focusedMesh === target) return; - - const renderableMeshes = this.getRenderableMeshes(this.rootMesh); - for (const candidate of renderableMeshes) { - if (!this.originalMeshVisibility.has(candidate.uniqueId)) { - this.originalMeshVisibility.set(candidate.uniqueId, candidate.visibility); - } - const selected = candidate === target; - candidate.visibility = selected ? 1 : FOCUS_DIM_VISIBILITY; - candidate.renderOutline = selected; - candidate.outlineColor = new Color3(0.18, 0.76, 1); - candidate.outlineWidth = selected ? 0.045 : 0; - } - this.focusedMesh = target; - } - - private clearFocusedMesh(): void { - if (!this.rootMesh) { - this.focusedMesh = null; - return; - } - - for (const mesh of this.getRenderableMeshes(this.rootMesh)) { - const originalVisibility = this.originalMeshVisibility.get(mesh.uniqueId); - if (originalVisibility !== undefined) { - mesh.visibility = originalVisibility; - } - mesh.renderOutline = false; - mesh.outlineWidth = 0; - } - this.originalMeshVisibility.clear(); - this.focusedMesh = null; - } - - private findRenderableMesh(mesh: AbstractMesh): AbstractMesh | null { - if (!this.rootMesh) return null; - const renderableMeshes = this.getRenderableMeshes(this.rootMesh); - if (renderableMeshes.includes(mesh)) return mesh; - - let parent = mesh.parent; - while (parent && "uniqueId" in parent) { - const parentMesh = parent as AbstractMesh; - if (renderableMeshes.includes(parentMesh)) return parentMesh; - parent = parent.parent; - } - - return null; - } - - private computePartSummary(mesh: AbstractMesh): ModelPartSummary { - const name = mesh.name || `mesh-${mesh.uniqueId}`; - const metadata = mergeMetadataFallback( - mesh.metadata, - this.gltfComponentMetadata.get(`node:${name}`) ?? this.gltfComponentMetadata.get(`mesh:${name}`), - ); - const identity = extractPreviewComponentIdentity(metadata, { - name, - path: getBabylonComponentPath(mesh), - }); - return { - ...createBabylonPartPreviewSummary(mesh), - name: getPartDisplayName(identity, name), - source: identity.hasExplicitIdentity ? "component" : "mesh", - meshNames: [name], - childCount: 1, - componentId: identity.componentId, - occurrenceId: identity.occurrenceId, - partNumber: identity.partNumber, - componentPath: identity.componentPath, - }; - } - - private computeComponentPartSummaries(renderableMeshes: readonly AbstractMesh[]): { - parts: ModelPartSummary[]; - groupedMeshes: Set; - } { - const renderableSet = new Set(renderableMeshes); - const parts: ModelPartSummary[] = []; - const groupedMeshes = new Set(); - const candidates: Array<{ - node: TransformNode; - childMeshes: AbstractMesh[]; - identity: PreviewComponentIdentity; - }> = []; - for (const node of this.loadedTransformNodes) { - const childMeshes = node.getChildMeshes(false).filter((mesh) => renderableSet.has(mesh)); - const nodeName = getBabylonNodeDisplayName(node, `component-${node.uniqueId}`); - const metadata = mergeMetadataFallback(node.metadata, this.gltfComponentMetadata.get(`node:${nodeName}`)); - const identity = extractPreviewComponentIdentity(metadata, { - name: getBabylonNodeDisplayName(node, `component-${node.uniqueId}`), - path: getBabylonComponentPath(node), - }); - if (childMeshes.length < 1 || childMeshes.length === renderableMeshes.length) { - continue; - } - if (!identity.hasExplicitIdentity && (!node.name.trim() || childMeshes.length < 2)) { - continue; - } - candidates.push({ node, childMeshes, identity }); - } - - candidates - .sort((left, right) => left.childMeshes.length - right.childMeshes.length) - .forEach(({ node, childMeshes, identity }) => { - const availableMeshes = childMeshes.filter((mesh) => !groupedMeshes.has(mesh)); - if (availableMeshes.length < 1) return; - if (!identity.hasExplicitIdentity && availableMeshes.length < 2) return; - for (const mesh of availableMeshes) { - groupedMeshes.add(mesh); - } - const bounds = getBabylonMeshesPreviewBounds(availableMeshes); - if (!bounds) return; - const materialNames = new Set(); - let triangleCount = 0; - let vertexCount = 0; - for (const mesh of availableMeshes) { - triangleCount += getBabylonTriangleCount(mesh); - vertexCount += getBabylonVertexCount(mesh); - if (mesh.material?.name) { - materialNames.add(mesh.material.name); - } - } - parts.push(createPreviewPartSummary({ - name: getPartDisplayName(identity, getBabylonNodeDisplayName(node, `component-${node.uniqueId}`)), - triangleCount, - vertexCount, - materialName: materialNames.size === 0 - ? null - : materialNames.size === 1 - ? Array.from(materialNames)[0] - : `${materialNames.size} materials`, - boundingSize: getPreviewBoundsSize(bounds), - center: getPreviewBoundsCenter(bounds), - source: identity.hasExplicitIdentity ? "component" : "group", - meshNames: availableMeshes.map((mesh) => mesh.name || `mesh-${mesh.uniqueId}`), - childCount: availableMeshes.length, - componentId: identity.componentId, - occurrenceId: identity.occurrenceId, - partNumber: identity.partNumber, - componentPath: identity.componentPath, - })); - }); - return { parts, groupedMeshes }; - } - - private getMeasurementMarkerSize(): number { - if (!this.rootMesh) return 0.02; - const bounds = this.getRenderableBounds(this.rootMesh); - if (!bounds) return 0.02; - const maxSpan = Math.max(bounds.max.x - bounds.min.x, bounds.max.y - bounds.min.y, bounds.max.z - bounds.min.z, 0.001); - return maxSpan * 0.015; - } - - private findNearestMarkerIndex(point: Vector3): number { - const threshold = this.getMeasurementMarkerSize() * 2.5; - for (let i = 0; i < this.measurementMarkers.length; i++) { - if (Vector3.Distance(this.measurementMarkers[i].position, point) < threshold) { - return i; - } - } - return -1; - } - - private addMeasurementPoint(point: Vector3): void { - const existingIndex = this.findNearestMarkerIndex(point); - const usePoint = existingIndex >= 0 - ? this.measurementMarkers[existingIndex].position.clone() - : point; - - if (this.pendingPoint) { - if (Vector3.Distance(usePoint, this.pendingPoint) < 0.0001) { - return; - } - if (existingIndex < 0) { - const size = this.getMeasurementMarkerSize(); - const marker = MeshBuilder.CreateSphere("measure-marker", { diameter: size }, this.scene); - marker.position = usePoint; - marker.isPickable = false; - const mat = new StandardMaterial("measure-marker-mat", this.scene); - mat.diffuseColor = new Color3(1, 0.42, 0.42); - mat.emissiveColor = new Color3(1, 0.42, 0.42); - marker.material = mat; - marker.renderingGroupId = 2; - this.measurementMarkers.push(marker); - } - this.createMeasurementSegment(this.pendingPoint, usePoint); - if (this.pendingMarker) { - this.pendingMarker.scaling.setAll(1); - (this.pendingMarker.material as StandardMaterial).diffuseColor = new Color3(1, 0.42, 0.42); - (this.pendingMarker.material as StandardMaterial).emissiveColor = new Color3(1, 0.42, 0.42); - } - this.pendingPoint = null; - this.pendingMarker = null; - this.removePreviewLine(); - } else { - if (existingIndex < 0) { - const size = this.getMeasurementMarkerSize(); - const marker = MeshBuilder.CreateSphere("measure-marker", { diameter: size }, this.scene); - marker.position = usePoint; - marker.isPickable = false; - const mat = new StandardMaterial("measure-marker-mat", this.scene); - mat.diffuseColor = new Color3(1, 0.42, 0.42); - mat.emissiveColor = new Color3(1, 0.42, 0.42); - marker.material = mat; - marker.renderingGroupId = 2; - this.measurementMarkers.push(marker); - this.pendingMarker = marker; - } else { - this.pendingMarker = this.measurementMarkers[existingIndex]; - } - this.pendingMarker.scaling.setAll(1.6); - (this.pendingMarker.material as StandardMaterial).diffuseColor = new Color3(0.32, 0.81, 0.4); - (this.pendingMarker.material as StandardMaterial).emissiveColor = new Color3(0.32, 0.81, 0.4); - this.pendingPoint = usePoint; - this.ensurePreviewLine(); - } - } - - private createMeasurementSegment(start: Vector3, end: Vector3): void { - const line = MeshBuilder.CreateLines("measure-line", { points: [start, end] }, this.scene); - (line as any).color = new Color3(1, 0.42, 0.42); - line.isPickable = false; - line.renderingGroupId = 2; - - const distance = this.getRealDistance(start, end); - const labelText = this.formatMeasurementDistance(distance); - const mid = Vector3.Center(start, end); - const label = this.createMeasurementLabelMesh(labelText, mid, this.getMeasurementMarkerSize() * 4); - - this.measurementSegments.push({ start, end, line, label }); - } - - private createMeasurementLabelMesh(text: string, position: Vector3, scale: number): Mesh { - const plane = MeshBuilder.CreatePlane("measure-label", { width: scale * 4, height: scale }, this.scene); - plane.position = position; - plane.billboardMode = Mesh.BILLBOARDMODE_ALL; - plane.isPickable = false; - plane.renderingGroupId = 2; - - const texture = new DynamicTexture("measure-label-tex", { width: 512, height: 128 }, this.scene); - const ctx = texture.getContext() as CanvasRenderingContext2D; - ctx.fillStyle = "rgba(32, 36, 46, 0.9)"; - ctx.fillRect(0, 0, 512, 128); - ctx.strokeStyle = "#ff6b6b"; - ctx.lineWidth = 4; - ctx.strokeRect(0, 0, 512, 128); - ctx.fillStyle = "#ffffff"; - ctx.font = "bold 48px sans-serif"; - ctx.textAlign = "center"; - ctx.textBaseline = "middle"; - ctx.fillText(text, 256, 64); - texture.update(); - - const mat = new StandardMaterial("measure-label-mat", this.scene); - mat.diffuseTexture = texture; - mat.emissiveColor = new Color3(1, 1, 1); - mat.disableLighting = true; - mat.opacityTexture = texture; - plane.material = mat; - return plane; - } - - private ensurePreviewLine(): void { - if (this.previewLine) return; - this.previewLine = MeshBuilder.CreateLines("measure-preview", { points: [Vector3.Zero(), Vector3.Zero()] }, this.scene); - (this.previewLine as any).color = new Color3(1, 1, 1); - (this.previewLine as any).alpha = 0.5; - this.previewLine.isPickable = false; - this.previewLine.renderingGroupId = 2; - } - - private updatePreviewLine(): void { - if (!this.pendingPoint || !this.previewLine || !this.rootMesh) return; - const canvas = this.engine.getRenderingCanvas(); - if (!canvas) return; - const rect = canvas.getBoundingClientRect(); - const x = this.lastPointerClient.x - rect.left; - const y = this.lastPointerClient.y - rect.top; - const pickResult = this.scene.pick(x, y, (mesh) => mesh !== this.previewLine && !this.measurementMarkers.includes(mesh as Mesh)); - let endPoint: Vector3; - if (pickResult.hit && pickResult.pickedPoint) { - endPoint = pickResult.pickedPoint; - } else { - const ray = this.scene.createPickingRay(x, y, Matrix.Identity(), this.camera); - endPoint = this.pendingPoint.add(ray.direction.scale(5)); - } - this.previewLine.dispose(); - this.previewLine = MeshBuilder.CreateLines("measure-preview", { points: [this.pendingPoint, endPoint] }, this.scene); - (this.previewLine as any).color = new Color3(1, 1, 1); - (this.previewLine as any).alpha = 0.5; - this.previewLine.isPickable = false; - this.previewLine.renderingGroupId = 2; - } - - private removePreviewLine(): void { - if (!this.previewLine) return; - this.previewLine.dispose(); - this.previewLine = null; - } - - private computeSummary(root: Mesh): ModelPreviewSummary { - const allMeshes = this.getRenderableMeshes(root); - const isSplat = isGaussianSplattingMesh(root); - const vertexCount = allMeshes.reduce((total, mesh) => total + getBabylonVertexCount(mesh), 0); - return createBabylonModelPreviewSummary( - root.name, - this.getRenderableBounds(root), - allMeshes, - { splatCount: isSplat ? vertexCount : undefined, resourceWarnings: this.resourceWarnings }, - ); - } -} - -export function createBabylonModelPreview(canvas: HTMLCanvasElement): WorkbenchPreview { - return new BabylonModelPreview(canvas); -} +import { Engine } from "@babylonjs/core/Engines/engine.js"; +import { Scene } from "@babylonjs/core/scene.js"; +import { ArcRotateCamera } from "@babylonjs/core/Cameras/arcRotateCamera.js"; +import { HemisphericLight } from "@babylonjs/core/Lights/hemisphericLight.js"; +import { DirectionalLight } from "@babylonjs/core/Lights/directionalLight.js"; +import { PointLight } from "@babylonjs/core/Lights/pointLight.js"; +import { SpotLight } from "@babylonjs/core/Lights/spotLight.js"; +import { Vector3, Matrix } from "@babylonjs/core/Maths/math.vector.js"; +import { Color3, Color4 } from "@babylonjs/core/Maths/math.color.js"; +import { Mesh } from "@babylonjs/core/Meshes/mesh.js"; +import { LinesMesh } from "@babylonjs/core/Meshes/linesMesh.js"; +import { TransformNode } from "@babylonjs/core/Meshes/transformNode.js"; +import { MeshBuilder } from "@babylonjs/core/Meshes/meshBuilder.js"; +import { StandardMaterial } from "@babylonjs/core/Materials/standardMaterial.js"; +import { DynamicTexture } from "@babylonjs/core/Materials/Textures/dynamicTexture.js"; +import { Ray } from "@babylonjs/core/Culling/ray.js"; +import { ShadowGenerator } from "@babylonjs/core/Lights/Shadows/shadowGenerator.js"; +import "@babylonjs/core/Lights/Shadows/shadowGeneratorSceneComponent.js"; +import { AutoRotationBehavior } from "@babylonjs/core/Behaviors/Cameras/autoRotationBehavior.js"; +import { ImportMeshAsync } from "@babylonjs/core/Loading/sceneLoader.js"; +import type { AbstractMesh } from "@babylonjs/core/Meshes/abstractMesh.js"; +import type { Light } from "@babylonjs/core/Lights/light.js"; +import type { IShadowLight } from "@babylonjs/core/Lights/shadowLight.js"; +import type { + ModelPreviewSummary, + ModelEvidence, + ModelPartSummary, + CameraConfig, + LightConfig, + SceneConfig, + ThreeDBlockConfig, +} from "../../domain/models"; +import "./loaders/register"; +import { ensureLoadersRegistered } from "./loaders/register"; +import { loadSTLBuffer } from "./loaders/stl-loader"; +import { loadPLYBuffer } from "./loaders/ply-loader"; +import { setExplode, resetExplode } from "./explode"; +import { setupPicking, type PickResult } from "./picking"; +import { arrayBufferToBase64 } from "../../utils/base64"; +import { isMobile } from "../../utils/device"; +import { getPortableBasename, getPortableDirname, getPortableStem, joinPortablePath } from "../../utils/resolve-path"; +import { OrientationGizmo } from "./orientation-gizmo"; +import { createBabylonDisassemblyController } from "./disassembly"; +import { + createBabylonModelPreviewSummary, + createBabylonPartPreviewSummary, + getBabylonMeshesPreviewBounds, + getBabylonRenderableMeshes, + getBabylonRenderablePreviewBounds, + getBabylonTriangleCount, + getBabylonVertexCount, +} from "./mesh-preview"; +import { + getPreviewBoundsCenter, + getPreviewBoundsMaxSpan, + getPreviewBoundsRadius, + getPreviewBoundsSize, +} from "../preview/bounds"; +import { createPreviewOrbitCameraFit } from "../preview/camera-fit"; +import type { PreviewDisassemblyController } from "../preview/disassembly"; +import { + createPreviewLineOfSight, + isPreviewHitOccluded, + toPreviewWorldPoint, +} from "../preview/geometry"; +import { + createPreviewModelInfoMarkdown, + createPreviewPartInfoMarkdown, +} from "../preview/report"; +import { createPreviewPartSummary } from "../preview/summary"; +import { extractPreviewComponentIdentity, type PreviewComponentIdentity } from "../preview/component-identity"; +import type { + AnnotationViewportProvider, + PreviewAxis, + PreviewPickResult, + PreviewProjectionResult, + PreviewWorldPoint, + MeasurementScale, + WorkbenchPreview, +} from "../preview/types"; + +/** Guard against concurrent OBJ loads monkey-patching the same prototype. */ +let objMtlLock: Promise | null = null; +const OBJ_IMAGE_EXTS = ["jpg", "jpeg", "png", "bmp", "tga", "webp", "tif", "tiff"]; +const OBJ_TEXTURE_RE = /^\s*(map_Kd|map_Ka|map_Ks|map_Ns|map_d|map_bump|bump|disp|decal)\s+(.+)/i; +const FOCUS_DIM_VISIBILITY = 0.242; +const FOCUS_WORLD_POINT_ANIMATION_MS = 320; + +function isShadowLight(light: Light): light is IShadowLight { + const className = light.getClassName(); + return className === "DirectionalLight" || className === "PointLight" || className === "SpotLight"; +} + +function isGaussianSplattingMesh(mesh: AbstractMesh): boolean { + return mesh.getClassName() === "GaussianSplattingMesh"; +} + +function getBabylonNodeDisplayName(node: { name?: string; metadata?: unknown }, fallback: string): string { + const identity = extractPreviewComponentIdentity(node.metadata, { name: node.name }); + return identity.displayName?.trim() || node.name || fallback; +} + +function getBabylonComponentPath(node: { name?: string; parent?: unknown; metadata?: unknown }): string { + const names: string[] = []; + let current: unknown = node; + while (current && typeof current === "object" && "name" in current) { + const currentNode = current as { name?: string; parent?: unknown; metadata?: unknown }; + const name = getBabylonNodeDisplayName(currentNode, "node"); + if (name.trim()) names.push(name); + current = currentNode.parent; + } + return names.reverse().join("/"); +} + +function getPartDisplayName(identity: PreviewComponentIdentity, fallback: string): string { + return identity.displayName?.trim() || identity.partNumber || identity.componentId || fallback; +} + +function parseGltfJson(data: ArrayBuffer, extLower: string): Record | null { + try { + if (extLower === "gltf") { + return JSON.parse(new TextDecoder().decode(new Uint8Array(data))) as Record; + } + if (extLower !== "glb") { + return null; + } + const view = new DataView(data); + if (view.byteLength < 20 || view.getUint32(0, true) !== 0x46546c67) { + return null; + } + const jsonChunkLength = view.getUint32(12, true); + const jsonChunkType = view.getUint32(16, true); + if (jsonChunkType !== 0x4e4f534a || 20 + jsonChunkLength > view.byteLength) { + return null; + } + const jsonBytes = new Uint8Array(data, 20, jsonChunkLength); + return JSON.parse(new TextDecoder().decode(jsonBytes)) as Record; + } catch { + return null; + } +} + +function collectGltfComponentMetadata(data: ArrayBuffer, extLower: string): Map { + const json = parseGltfJson(data, extLower); + const metadata = new Map(); + if (!json) return metadata; + + const nodes = Array.isArray(json.nodes) ? json.nodes : []; + for (const node of nodes) { + if (!node || typeof node !== "object") continue; + const record = node as Record; + const name = typeof record.name === "string" ? record.name : ""; + if (name && record.extras) { + metadata.set(`node:${name}`, record.extras); + } + } + + const meshes = Array.isArray(json.meshes) ? json.meshes : []; + for (const mesh of meshes) { + if (!mesh || typeof mesh !== "object") continue; + const record = mesh as Record; + const name = typeof record.name === "string" ? record.name : ""; + if (name && record.extras) { + metadata.set(`mesh:${name}`, record.extras); + } + } + + return metadata; +} + +function mergeMetadataFallback(primary: unknown, fallback: unknown): unknown { + if (fallback === undefined) return primary; + if (primary === undefined || primary === null) return fallback; + return { metadata: primary, extras: fallback }; +} + +function isBabylonMesh(value: unknown): value is AbstractMesh { + return !!value && typeof value === "object" && "getBoundingInfo" in value; +} + +function toBabylonVector3(value: { x: number; y: number; z: number }): Vector3 { + return new Vector3(value.x, value.y, value.z); +} + +function firstMtlPath(value: string): string { + const trimmed = value.replace(/\s+#.*$/, "").trim(); + if (trimmed.startsWith("\"")) { + const end = trimmed.indexOf("\"", 1); + if (end > 1) return trimmed.slice(1, end); + } + return trimmed; +} + +function firstTexturePath(value: string): string { + const tokens = value.trim().split(/\s+/); + const pathStart = tokens.findIndex((token) => !token.startsWith("-") && !/^[-+]?\d*\.?\d+$/.test(token)); + return tokens.slice(Math.max(0, pathStart)).join(" ").replace(/^"|"$/g, ""); +} + +function guessTextureMime(path: string): string { + const ext = path.split(".").pop()?.toLowerCase() ?? "png"; + if (ext === "jpg" || ext === "jpeg") return "image/jpeg"; + if (ext === "png") return "image/png"; + if (ext === "bmp") return "image/bmp"; + if (ext === "tga") return "image/x-tga"; + if (ext === "webp") return "image/webp"; + return `image/${ext}`; +} + +function buildObjTextureCandidates(modelDir: string, rawPath: string, modelPath: string): string[] { + const texFilename = getPortableBasename(rawPath); + const texBase = texFilename.replace(/\.[^.]+$/, ""); + const objBasename = getPortableStem(modelPath); + const candidates = [ + joinPortablePath(modelDir, rawPath), + joinPortablePath(modelDir, texFilename), + ]; + if (objBasename) { + for (const ext of OBJ_IMAGE_EXTS) { + candidates.push(joinPortablePath(modelDir, `${objBasename}.${ext}`)); + } + } + for (const ext of OBJ_IMAGE_EXTS) { + const alt = `${texBase}.${ext}`; + if (alt !== texFilename) { + candidates.push(joinPortablePath(modelDir, alt)); + } + } + return candidates; +} + +export class BabylonModelPreview implements WorkbenchPreview { + private static readonly annotationIdentity = Matrix.Identity(); + private static readonly annotationWorldPoint = Vector3.Zero(); + private static readonly annotationProjection = Vector3.Zero(); + private static readonly annotationDirection = Vector3.Zero(); + private static readonly annotationRay = new Ray(Vector3.Zero(), Vector3.Zero(), 1); + private engine: Engine; + private scene: Scene; + private camera: ArcRotateCamera; + private rootMesh: Mesh | null = null; + private loadedMeshes: AbstractMesh[] = []; + private loadedTransformNodes: TransformNode[] = []; + private loadedExt: string = ""; + private rendering = false; + private contextLost = false; + private viewportVisible = true; + private viewportObserver: IntersectionObserver | null = null; + private cleanupPicking: (() => void) | null = null; + private resizeObs: ResizeObserver; + private configLights: Light[] = []; + private shadowGenerator: ShadowGenerator | null = null; + private groundMesh: Mesh | null = null; + private gridMesh: Mesh | null = null; + private axisMeshes: Mesh[] = []; + private autoRotateBehavior: AutoRotationBehavior | null = null; + private wireframeEnabled = false; + private gizmo: OrientationGizmo | null = null; + private gizmoEnabled = false; + private disassembly: PreviewDisassemblyController | null = null; + private focusSelectionEnabled = false; + private focusedMesh: AbstractMesh | null = null; + private readonly originalMeshVisibility = new Map(); + private bboxMesh: Mesh | null = null; + private bboxEnabled = false; + private currentQuality: "low" | "medium" | "high" = "high"; + private resourceWarnings: string[] = []; + private gltfComponentMetadata = new Map(); + private animPlaying = false; + private initialCamera = { alpha: Math.PI / 4, beta: Math.PI / 3, radius: 5, target: Vector3.Zero() }; + private focusWorldPointFrame = 0; + private _lastPickResult: PickResult = { mesh: null, pickedPoint: null, screenX: 0, screenY: 0 }; + private _onPickCallbacks: Array<(result: PreviewPickResult) => void> = []; + private measurementActive = false; + private measurementScale: MeasurementScale = { x: 1, y: 1, z: 1 }; + private measurementUnit = "mm"; + private measurementSegments: Array<{ start: Vector3; end: Vector3; line: Mesh; label: Mesh }> = []; + private measurementMarkers: Mesh[] = []; + private pendingPoint: Vector3 | null = null; + private pendingMarker: Mesh | null = null; + private hoveredMarkerIndex = -1; + private lastPointerClient = { x: 0, y: 0 }; + private previewLine: Mesh | null = null; + private readonly handlePointerMove = (event: PointerEvent) => { + this.lastPointerClient = { x: event.clientX, y: event.clientY }; + if (!this.measurementActive) return; + if (this.pendingPoint) { + this.updatePreviewLine(); + } + if (this.measurementMarkers.length === 0) return; + const canvas = this.engine.getRenderingCanvas(); + if (!canvas) return; + const rect = canvas.getBoundingClientRect(); + const x = event.clientX - rect.left; + const y = event.clientY - rect.top; + const pickResult = this.scene.pick(x, y, (mesh) => this.measurementMarkers.includes(mesh as Mesh)); + const newHover = pickResult.hit ? this.measurementMarkers.indexOf(pickResult.pickedMesh as Mesh) : -1; + if (newHover !== this.hoveredMarkerIndex) { + if (this.hoveredMarkerIndex >= 0 && this.hoveredMarkerIndex < this.measurementMarkers.length) { + const prev = this.measurementMarkers[this.hoveredMarkerIndex]; + if (prev !== this.pendingMarker) { + prev.scaling.setAll(1); + (prev.material as StandardMaterial).diffuseColor = new Color3(1, 0.42, 0.42); + (prev.material as StandardMaterial).emissiveColor = new Color3(1, 0.42, 0.42); + } + } + if (newHover >= 0 && newHover < this.measurementMarkers.length) { + const next = this.measurementMarkers[newHover]; + next.scaling.setAll(1.6); + (next.material as StandardMaterial).diffuseColor = new Color3(1, 0.83, 0.23); + (next.material as StandardMaterial).emissiveColor = new Color3(1, 0.83, 0.23); + } + this.hoveredMarkerIndex = newHover; + } + }; + private readonly preventCanvasWheelScroll = (event: WheelEvent) => { + event.preventDefault(); + event.stopPropagation(); + }; + + private canRender(): boolean { + const canvas = this.engine.getRenderingCanvas(); + return !!canvas?.isConnected && canvas.clientWidth > 0 && canvas.clientHeight > 0; + } + + private ensureDisassemblyController(): PreviewDisassemblyController | null { + if (!this.rootMesh) { + return null; + } + if (!this.disassembly) { + this.disassembly = createBabylonDisassemblyController( + this.scene, + this.camera, + this.getRenderableMeshes(this.rootMesh), + ); + } + return this.disassembly; + } + + private isDisassemblyActive(): boolean { + return this.disassembly?.isEnabled() ?? false; + } + + constructor(canvas: HTMLCanvasElement) { + this.engine = new Engine(canvas, true, { preserveDrawingBuffer: true }); + this.scene = new Scene(this.engine); + this.scene.clearColor = new Color4(0.12, 0.12, 0.14, 1); + + this.camera = new ArcRotateCamera( + "cam", + Math.PI / 4, + Math.PI / 3, + 5, + Vector3.Zero(), + this.scene, + ); + this.camera.attachControl(canvas, true); + this.camera.lowerRadiusLimit = 0.1; + this.camera.wheelPrecision = 30; + canvas.addEventListener("wheel", this.preventCanvasWheelScroll, { passive: false }); + canvas.addEventListener("pointermove", this.handlePointerMove); + canvas.addEventListener("webglcontextlost", this.handleContextLost); + canvas.addEventListener("webglcontextrestored", this.handleContextRestored); + + this.scene.ambientColor = new Color3(0.3, 0.3, 0.3); + const hemi = new HemisphericLight("default-light", new Vector3(0, 1, 0.5), this.scene); + hemi.intensity = 1.2; + + this.resizeObs = new ResizeObserver(() => this.engine.resize()); + this.resizeObs.observe(canvas); + if (typeof IntersectionObserver !== "undefined") { + this.viewportObserver = new IntersectionObserver(this.handleViewportIntersection, { + root: null, + threshold: [0, 0.01], + }); + this.viewportObserver.observe(canvas); + } + // Force a resize after the canvas is mounted and has layout dimensions + window.requestAnimationFrame(() => this.engine.resize()); + } + + async loadModel( + data: ArrayBuffer, + ext: string, + readFile?: (path: string) => Promise, + modelPath?: string, + ): Promise { + await ensureLoadersRegistered(); + + if (this.rootMesh) { + const previousRoot = this.rootMesh; + previousRoot.dispose(true, true); + for (const mesh of this.loadedMeshes) { + if (mesh !== previousRoot && !mesh.isDisposed()) { + mesh.dispose(true, true); + } + } + this.rootMesh = null; + } + this.loadedMeshes = []; + this.loadedTransformNodes = []; + this.clearMeasurements(); + this.disassembly?.dispose(); + this.disassembly = null; + this.clearFocusedMesh(); + this.originalMeshVisibility.clear(); + + const extLower = ext.toLowerCase().replace(".", ""); + this.loadedExt = extLower; + this.resourceWarnings = []; + this.gltfComponentMetadata = collectGltfComponentMetadata(data, extLower); + const scene = this.scene; + + // Map extension to Babylon SceneLoader file extension + const extToLoader: Record = { + glb: ".glb", + gltf: ".gltf", + stl: ".stl", + obj: ".obj", + splat: ".splat", + ply: ".ply", + }; + const fileExt = extToLoader[extLower] ?? `.${extLower}`; + + // Use data URL instead of blob URL — Obsidian's Electron converts + // blob: URLs to blob:app://... which Babylon's GLTF loader cannot parse. + const dataUrl = `data:application/octet-stream;base64,${arrayBufferToBase64(data)}`; + + // OBJ: override _loadMTL to read MTL from vault instead of network fetch. + // Serialized via objMtlLock to prevent concurrent loads from clobbering the prototype. + if (extLower === "obj" && readFile && modelPath) { + if (objMtlLock) await objMtlLock; + let resolveLock!: () => void; + objMtlLock = new Promise(r => { resolveLock = r; }); + try { + const { OBJFileLoader } = await import("@babylonjs/loaders/OBJ/objFileLoader.js"); + const proto = OBJFileLoader.prototype as unknown as Record; + if (typeof proto._loadMTL !== "function") { + console.warn("[AI3D] OBJFileLoader._loadMTL not found — MTL vault resolution disabled"); + } + const originalLoadMTL = proto._loadMTL; + + // Pre-load MTL content from vault (if exists) + const objText = new TextDecoder().decode(new Uint8Array(data)); + const mtlMatch = objText.match(/mtllib\s+(.+)/); + let mtlContent: string | null = null; + if (mtlMatch && readFile && modelPath) { + const mtlFilename = firstMtlPath(mtlMatch[1]); + const modelDir = getPortableDirname(modelPath); + const mtlPath = joinPortablePath(modelDir, mtlFilename); + try { + const mtlData = await readFile(mtlPath); + const raw = new TextDecoder().decode(new Uint8Array(mtlData)); + const lines = raw.split("\n"); + + // Resolve texture files referenced in MTL from vault. + // Try: 1) full relative path, 2) same-dir filename, + // 3) OBJ-name with image extensions (e.g. bat.jpeg), + // 4) common basecolor/texture names in same dir + for (let i = 0; i < lines.length; i++) { + const m = lines[i].match(OBJ_TEXTURE_RE); + if (!m) continue; + const rawPath = firstTexturePath(m[2]); + const candidates = buildObjTextureCandidates(modelDir, rawPath, modelPath); + let resolved = false; + for (const cand of candidates) { + try { + const texBuf = await readFile(cand); + const dataUrl = `data:${guessTextureMime(cand)};base64,${arrayBufferToBase64(texBuf)}`; + lines[i] = `${m[1]} ${dataUrl}`; + resolved = true; + break; + } catch { /* try next candidate */ } + } + if (!resolved) { + this.resourceWarnings.push(`OBJ material texture not found: ${rawPath}`); + lines[i] = ""; // strip — prevents red-black checkerboard + } + } + + // If MTL has no Kd (diffuse color), add default light gray + const filtered = lines.filter(l => l !== ""); + const hasKd = filtered.some(l => /^\s*Kd\s+/i.test(l)); + if (!hasKd) { + const nmIdx = filtered.findIndex(l => /^\s*newmtl\s+/i.test(l)); + filtered.splice(nmIdx >= 0 ? nmIdx + 1 : 0, 0, "Kd 0.80 0.80 0.80"); + } + mtlContent = filtered.join("\n"); + } catch { + this.resourceWarnings.push(`OBJ material library not found: ${mtlPath}`); + } + } + + // Override _loadMTL to use vault content or skip (prevents network fetch) + proto._loadMTL = function(_url: string, _rootUrl: string, onSuccess: (data: string) => void) { + const content = mtlContent ?? ""; + onSuccess(content); + }; + + const result = await ImportMeshAsync(dataUrl, scene, { meshNames: "", pluginExtension: fileExt }); + this.loadedMeshes = result.meshes; + this.loadedTransformNodes = result.transformNodes; + if (result.meshes.length > 0) this.rootMesh = result.meshes[0] as Mesh; + + // Restore original _loadMTL + proto._loadMTL = originalLoadMTL; + } catch (e) { + console.error("[AI3D] OBJ load error:", e); + throw e; + } finally { + resolveLock(); + objMtlLock = null; + } + } else if (extLower === "stl") { + // Direct parse — Babylon v9 SceneLoader mishandles data URLs for custom plugins + this.rootMesh = loadSTLBuffer(scene, data); + if (this.rootMesh) this.loadedMeshes = [this.rootMesh]; + } else if (extLower === "ply") { + // Direct parse — same Babylon v9 data-URL issue as STL + this.rootMesh = loadPLYBuffer(scene, data); + if (this.rootMesh) this.loadedMeshes = [this.rootMesh]; + } else { + const result = await ImportMeshAsync(dataUrl, scene, { meshNames: "", pluginExtension: fileExt }); + this.loadedMeshes = result.meshes; + this.loadedTransformNodes = result.transformNodes; + if (result.meshes.length > 0) this.rootMesh = result.meshes[0] as Mesh; + } + + if (!this.rootMesh) { + throw new Error("No mesh found in model file"); + } + + // Disable backface culling on all materials to prevent invisible faces + // (CAD-converted models often have inconsistent face normals) + for (const m of this.getRenderableMeshes(this.rootMesh)) { + if (m.material) { + m.material.backFaceCulling = false; + } + } + + const fit = createPreviewOrbitCameraFit(this.getRenderableBounds(this.rootMesh)); + + this.camera.target = toBabylonVector3(fit.target); + this.camera.radius = fit.radius; + this.camera.lowerRadiusLimit = fit.lowerRadiusLimit; + this.camera.upperRadiusLimit = fit.upperRadiusLimit; + this.camera.minZ = fit.near; + this.camera.maxZ = fit.far; + + this.initialCamera = { + alpha: this.camera.alpha, + beta: this.camera.beta, + radius: this.camera.radius, + target: this.camera.target.clone(), + }; + + this.startRenderLoop(); + this.engine.resize(); + + this.cleanupPicking?.(); + this.cleanupPicking = setupPicking(this.scene, (result) => { + if (this.isDisassemblyActive()) return; + if (this.measurementActive && result.pickedPoint) { + this.addMeasurementPoint(toBabylonVector3(result.pickedPoint)); + return; + } + this._lastPickResult = result; + if (this.focusSelectionEnabled && result.mesh) { + this.setFocusedMesh(result.mesh); + } + this._onPickCallbacks.forEach(cb => cb(result)); + }, () => !this.focusSelectionEnabled); + this.ensureDisassemblyController(); + + return this.computeSummary(this.rootMesh); + } + + // ── Config application ─────────────────────────────────────────── + + applyConfig(config: ThreeDBlockConfig): void { + if (config.camera) this.applyCameraConfig(config.camera); + if (config.lights) this.applyLightConfig(config.lights); + if (config.scene) this.applySceneConfig(config.scene); + if (config.stl && this.loadedExt === "stl") { + if (config.stl.color) this.setSTLColor(config.stl.color); + if (config.stl.wireframe !== undefined) this.setWireframe(config.stl.wireframe); + } + } + + applyCameraConfig(config: CameraConfig): void { + const canvas = this.engine.getRenderingCanvas(); + if (!canvas) return; + + if (config.mode === "orthographic") { + const radius = this.camera.radius; + const aspect = canvas.clientWidth / canvas.clientHeight; + const zoom = config.zoom ?? 1; + const size = radius / zoom; + + this.camera.mode = 1; // orthographic + this.camera.orthoLeft = -size * aspect; + this.camera.orthoRight = size * aspect; + this.camera.orthoTop = size; + this.camera.orthoBottom = -size; + } else { + this.camera.mode = 0; // perspective + if (config.fov) this.camera.fov = (config.fov * Math.PI) / 180; + } + + if (config.position) { + const [x, y, z] = config.position; + this.camera.setPosition(new Vector3(x, y, z)); + } + + if (config.lookAt) { + const [x, y, z] = config.lookAt; + this.camera.setTarget(new Vector3(x, y, z)); + } + + if (config.near !== undefined) this.camera.minZ = config.near; + if (config.far !== undefined) this.camera.maxZ = config.far; + } + + applyLightConfig(lights: LightConfig[]): void { + // Dispose previous config lights and shadow generator + for (const light of this.configLights) { + light.dispose(); + } + this.configLights = []; + this.shadowGenerator?.dispose(); + this.shadowGenerator = null; + + // Remove the default light when config lights are provided + const defaultLight = this.scene.getLightByName("default-light"); + if (defaultLight) { + defaultLight.dispose(); + } + + for (const cfg of lights) { + const light = this.createLight(cfg); + if (light) this.configLights.push(light); + } + } + + private createLight(cfg: LightConfig): Light | null { + const color = cfg.color ? Color3.FromHexString(cfg.color) : Color3.White(); + const intensity = cfg.intensity ?? 1; + + switch (cfg.type) { + case "hemisphere": { + const ground = cfg.groundColor + ? Color3.FromHexString(cfg.groundColor) + : new Color3(0.2, 0.2, 0.2); + const l = new HemisphericLight("hemi", new Vector3(0, 1, 0), this.scene); + l.diffuse = color; + l.groundColor = ground; + l.intensity = intensity; + return l; + } + case "directional": { + const dir = cfg.position + ? new Vector3(...cfg.position).normalize() + : new Vector3(-1, -2, -1).normalize(); + const l = new DirectionalLight("dir", dir, this.scene); + l.diffuse = color; + l.intensity = intensity; + if (cfg.castShadow && this.rootMesh) { + this.setupShadow(l); + } + return l; + } + case "point": { + const pos = cfg.position ? new Vector3(...cfg.position) : new Vector3(0, 5, 0); + const l = new PointLight("point", pos, this.scene); + l.diffuse = color; + l.intensity = intensity; + if (cfg.decay !== undefined) (l as unknown as Record).decay = cfg.decay; + return l; + } + case "spot": { + const pos = cfg.position ? new Vector3(...cfg.position) : new Vector3(0, 5, 0); + const target = cfg.target ? new Vector3(...cfg.target) : Vector3.Zero(); + const dir = target.subtract(pos).normalize(); + const angle = cfg.angle ? (cfg.angle * Math.PI) / 180 : Math.PI / 4; + const penumbra = cfg.penumbra ?? 0.5; + const l = new SpotLight("spot", pos, dir, angle, penumbra, this.scene); + l.diffuse = color; + l.intensity = intensity; + if (cfg.decay !== undefined) (l as unknown as Record).decay = cfg.decay; + if (cfg.castShadow && this.rootMesh) { + this.setupShadow(l); + } + return l; + } + case "attachToCam": { + const l = new PointLight("cam-light", Vector3.Zero(), this.scene); + l.diffuse = color; + l.intensity = intensity; + l.parent = this.camera; + return l; + } + default: + return null; + } + } + + private setupShadow(light: Light): void { + if (!this.rootMesh) return; + // ShadowGenerator requires a ShadowLight (DirectionalLight | PointLight | SpotLight). + // HemisphericLight cannot cast shadows — silently skip. + if (!isShadowLight(light)) { + console.warn("[AI3D] Light type does not support shadows:", light.name); + return; + } + const sg = new ShadowGenerator(1024, light); + sg.useBlurExponentialShadowMap = true; + sg.blurKernel = 32; + for (const m of this.getRenderableMeshes(this.rootMesh)) { + sg.addShadowCaster(m); + m.receiveShadows = true; + } + this.shadowGenerator = sg; + } + + applySceneConfig(config: SceneConfig): void { + if (config.background !== undefined) { + const c = Color4.FromColor3(Color3.FromHexString(config.background), config.transparent ? 0 : 1); + this.scene.clearColor = c; + } + + if (config.autoRotate) { + if (!this.autoRotateBehavior) { + this.autoRotateBehavior = new AutoRotationBehavior(); + this.autoRotateBehavior.idleRotationSpeed = config.autoRotateSpeed ?? 0.5; + this.autoRotateBehavior.idleRotationWaitTime = 1000; + this.autoRotateBehavior.idleRotationSpinupTime = 500; + this.camera.addBehavior(this.autoRotateBehavior); + } else { + this.autoRotateBehavior.idleRotationSpeed = config.autoRotateSpeed ?? 0.5; + } + } + + if (config.groundShadow && this.rootMesh) { + this.createGround(); + } + + if (config.grid) { + this.createGrid(); + } + + if (config.axis) { + this.createAxis(); + } + } + + private createGround(): void { + if (!this.rootMesh || this.groundMesh) return; + const bounds = this.getRenderableBounds(this.rootMesh); + const boundsSize = getPreviewBoundsSize(bounds); + const size = Math.max(boundsSize.x, boundsSize.z) * 3; + const y = bounds.min.y; + + this.groundMesh = MeshBuilder.CreateGround("ground", { width: size, height: size }, this.scene); + this.groundMesh.position.y = y; + const mat = new StandardMaterial("ground-mat", this.scene); + mat.diffuseColor = new Color3(0.15, 0.15, 0.15); + mat.specularColor = Color3.Black(); + mat.alpha = 0.5; + this.groundMesh.material = mat; + this.groundMesh.receiveShadows = true; + } + + private createGrid(): void { + if (!this.rootMesh || this.gridMesh) return; + const bounds = this.getRenderableBounds(this.rootMesh); + const boundsSize = getPreviewBoundsSize(bounds); + const size = Math.max(boundsSize.x, boundsSize.z) * 2; + const y = bounds.min.y - 0.01; + + this.gridMesh = MeshBuilder.CreateGround("grid", { width: size, height: size, subdivisions: 20 }, this.scene); + this.gridMesh.position.y = y; + const mat = new StandardMaterial("grid-mat", this.scene); + mat.wireframe = true; + mat.diffuseColor = new Color3(0.3, 0.3, 0.3); + mat.emissiveColor = new Color3(0.1, 0.1, 0.1); + this.gridMesh.material = mat; + } + + private createAxis(): void { + if (!this.rootMesh || this.axisMeshes.length > 0) return; + const bounds = this.getRenderableBounds(this.rootMesh); + const len = getPreviewBoundsMaxSpan(bounds) * 1.5; + const origin = toBabylonVector3(bounds.min); + const radius = getPreviewBoundsRadius(bounds) * 0.01; + + const axes: [string, Color3, Vector3][] = [ + ["x", Color3.Red(), new Vector3(len, 0, 0)], + ["y", Color3.Green(), new Vector3(0, len, 0)], + ["z", Color3.Blue(), new Vector3(0, 0, len)], + ]; + + for (const [name, color, dir] of axes) { + const tube = MeshBuilder.CreateTube(`axis-${name}`, { + path: [origin, origin.add(dir)], + radius, + tessellation: 8, + }, this.scene); + const mat = new StandardMaterial(`axis-${name}-mat`, this.scene); + mat.emissiveColor = color; + mat.diffuseColor = Color3.Black(); + tube.material = mat; + this.axisMeshes.push(tube); + } + } + + setSTLColor(hex: string): void { + if (!this.rootMesh) return; + const color = Color3.FromHexString(hex); + for (const m of this.getRenderableMeshes(this.rootMesh)) { + if (m.material && m.material.name === "stl-mat") { + const mat = m.material as StandardMaterial; + mat.diffuseColor = color; + mat.emissiveColor = color.scale(0.1); + } + } + } + + setWireframe(enabled: boolean): void { + if (!this.rootMesh) return; + if (isGaussianSplattingMesh(this.rootMesh)) return; + this.wireframeEnabled = enabled; + this.scene.forceWireframe = enabled; + } + + toggleWireframe(): boolean { + this.setWireframe(!this.wireframeEnabled); + return this.wireframeEnabled; + } + + hasAnimations(): boolean { + return this.scene.animationGroups.length > 0; + } + + toggleAnimation(): boolean { + const groups = this.scene.animationGroups; + if (groups.length === 0) return false; + this.animPlaying = !this.animPlaying; + for (const g of groups) { + if (this.animPlaying) { + g.play(true); + } else { + g.pause(); + } + } + return this.animPlaying; + } + + toggleMeasurement(): boolean { + this.measurementActive = !this.measurementActive; + if (!this.measurementActive) { + this.clearMeasurements(); + } + return this.measurementActive; + } + + isMeasurementActive(): boolean { + return this.measurementActive; + } + + clearMeasurements(): void { + this.measurementActive = false; + this.pendingPoint = null; + this.pendingMarker = null; + this.hoveredMarkerIndex = -1; + this.removePreviewLine(); + for (const segment of this.measurementSegments) { + segment.line.dispose(); + segment.label.dispose(); + } + this.measurementSegments = []; + for (const marker of this.measurementMarkers) { + marker.dispose(); + } + this.measurementMarkers = []; + } + + + setMeasurementScale(scale: MeasurementScale): void { + this.measurementScale = { ...scale }; + this.updateMeasurementLabels(); + } + + getMeasurementScale(): MeasurementScale { + return { ...this.measurementScale }; + } + + getMeasurementBounds(): { x: number; y: number; z: number } | null { + if (!this.rootMesh) return null; + const bounds = this.getRenderableBounds(this.rootMesh); + if (!bounds) return null; + return { + x: bounds.max.x - bounds.min.x, + y: bounds.max.y - bounds.min.y, + z: bounds.max.z - bounds.min.z, + }; + } + + private getRealDistance(start: Vector3, end: Vector3): number { + const dx = (end.x - start.x) * this.measurementScale.x; + const dy = (end.y - start.y) * this.measurementScale.y; + const dz = (end.z - start.z) * this.measurementScale.z; + return Math.sqrt(dx * dx + dy * dy + dz * dz); + } + + private formatMeasurementDistance(distance: number): string { + const unit = this.measurementUnit; + if (unit === "um" || unit === "μm") { + return distance < 1000 ? `${distance.toFixed(2)} μm` : `${(distance / 1000).toFixed(2)} mm`; + } + if (unit === "mm") { + return distance < 1 ? `${(distance * 1000).toFixed(2)} μm` : distance < 1000 ? `${distance.toFixed(2)} mm` : `${(distance / 1000).toFixed(3)} m`; + } + if (unit === "cm") { + return distance < 1 ? `${(distance * 10).toFixed(2)} mm` : distance < 100 ? `${distance.toFixed(2)} cm` : `${(distance / 100).toFixed(3)} m`; + } + if (unit === "m") { + return distance < 0.01 ? `${(distance * 1000).toFixed(2)} mm` : distance < 1 ? `${distance.toFixed(3)} m` : `${distance.toFixed(2)} m`; + } + return `${distance.toFixed(3)} ${unit}`; + } + + updateMeasurementLabels(): void { + if (this.measurementSegments.length === 0) return; + const markerSize = this.getMeasurementMarkerSize() * 4; + for (const segment of this.measurementSegments) { + const distance = this.getRealDistance(segment.start, segment.end); + const labelText = this.formatMeasurementDistance(distance); + segment.label.dispose(false, true); + const mid = Vector3.Center(segment.start, segment.end); + segment.label = this.createMeasurementLabelMesh(labelText, mid, markerSize); + } + } + + setAnimationSpeed(speed: number): void { + for (const g of this.scene.animationGroups) { + g.speedRatio = speed; + } + } + + captureSnapshot(): string | null { + const canvas = this.engine.getRenderingCanvas(); + if (!canvas) return null; + this.scene.render(); + return canvas.toDataURL("image/png"); + } + + toggleOrientationGizmo(): boolean { + this.gizmoEnabled = !this.gizmoEnabled; + if (this.gizmoEnabled && !this.gizmo) { + this.gizmo = new OrientationGizmo(this.engine, this.camera); + } + return this.gizmoEnabled; + } + + isOrientationGizmoEnabled(): boolean { + return this.gizmoEnabled; + } + + /** + * Set render resolution scale directly (1.0 = native). + * Returns the applied scale value. + */ + setRenderScale(scale: number): number { + const clamped = Math.max(0.25, Math.min(scale, 2.0)); + const qualityScale = { low: 2, medium: 1.33, high: 1 }[this.currentQuality]; + const mobileBoost = isMobile() ? 1.5 : 1; + this.engine.setHardwareScalingLevel(qualityScale * mobileBoost / clamped); + return clamped; + } + + getPerformanceSnapshot() { + return { + backend: "babylon" as const, + renderScale: Number((1 / this.engine.getHardwareScalingLevel()).toFixed(2)), + quality: this.currentQuality, + meshCount: this.rootMesh ? this.getRenderableMeshes(this.rootMesh).length : 0, + }; + } + + toggleBoundingBox(): boolean { + this.bboxEnabled = !this.bboxEnabled; + if (this.bboxEnabled) { + if (!this.rootMesh) return this.bboxEnabled; + if (this.bboxMesh) this.bboxMesh.dispose(); + const bounds = this.getRenderableBounds(this.rootMesh); + const center = toBabylonVector3(getPreviewBoundsCenter(bounds)); + const size = toBabylonVector3(getPreviewBoundsSize(bounds)); + + this.bboxMesh = MeshBuilder.CreateBox("bbox", { + width: size.x, height: size.y, depth: size.z, + }, this.scene); + this.bboxMesh.position = center; + const mat = new StandardMaterial("bbox-mat", this.scene); + mat.wireframe = true; + mat.emissiveColor = new Color3(1, 1, 0); + mat.disableLighting = true; + mat.alpha = 0.6; + this.bboxMesh.material = mat; + } else { + this.bboxMesh?.dispose(); + this.bboxMesh = null; + } + return this.bboxEnabled; + } + + toggleFocusSelection(): boolean { + const nextEnabled = !this.focusSelectionEnabled; + if (nextEnabled && this.isDisassemblyActive()) { + this.disassembly?.setEnabled(false); + } + this.focusSelectionEnabled = nextEnabled; + if (!this.focusSelectionEnabled) { + this.clearFocusedMesh(); + } else if (this._lastPickResult.mesh) { + this.setFocusedMesh(this._lastPickResult.mesh); + } + return this.focusSelectionEnabled; + } + + isFocusSelectionEnabled(): boolean { + return this.focusSelectionEnabled; + } + + toggleDisassembly(): boolean { + const controller = this.ensureDisassemblyController(); + if (!controller) return false; + const nextEnabled = !controller.isEnabled(); + if (nextEnabled) { + this.focusSelectionEnabled = false; + this.clearFocusedMesh(); + } + return controller.setEnabled(nextEnabled); + } + + resetDisassembly(): void { + this.disassembly?.reset(); + } + + isDisassemblyEnabled(): boolean { + return this.isDisassemblyActive(); + } + + // ── Existing API ───────────────────────────────────────────────── + + setExplode(factor: number, axis: PreviewAxis) { + if (this.rootMesh) setExplode(this.rootMesh, factor, axis, this.loadedMeshes); + } + + resetExplode() { + if (this.rootMesh) resetExplode(this.rootMesh, this.loadedMeshes); + } + + resetView(): void { + if (this.rootMesh) resetExplode(this.rootMesh, this.loadedMeshes); + this.resetDisassembly(); + this.clearFocusedMesh(); + this.camera.mode = 0; // perspective + this.camera.alpha = this.initialCamera.alpha; + this.camera.beta = this.initialCamera.beta; + this.camera.radius = this.initialCamera.radius; + this.camera.target = this.initialCamera.target.clone(); + } + + exportModelInfo(modelPath?: string): string { + if (!this.rootMesh) return ""; + const summary = this.computeSummary(this.rootMesh); + const renderableMeshes = this.getRenderableMeshes(this.rootMesh); + const isSplat = isGaussianSplattingMesh(this.rootMesh); + const name = modelPath ? getPortableBasename(modelPath) || summary.rootName : summary.rootName; + return createPreviewModelInfoMarkdown({ + title: name, + format: this.loadedExt.toUpperCase(), + summary, + meshBreakdown: renderableMeshes.map((mesh) => ({ + name: mesh.name, + triangleCount: isSplat ? null : getBabylonTriangleCount(mesh), + vertexCount: getBabylonVertexCount(mesh), + materialName: mesh.material?.name ?? null, + })), + materialNames: renderableMeshes.map((mesh) => mesh.material?.name), + }); + } + + getModelEvidence(): ModelEvidence | null { + if (!this.rootMesh) return null; + const renderableMeshes = this.getRenderableMeshes(this.rootMesh); + const groupedPartCandidates = this.computeComponentPartSummaries(renderableMeshes); + const meshParts = renderableMeshes + .filter((mesh) => !groupedPartCandidates.groupedMeshes.has(mesh)) + .map((mesh) => this.computePartSummary(mesh)); + const parts = groupedPartCandidates.parts.length > 0 ? [...groupedPartCandidates.parts, ...meshParts] : meshParts; + const materialNames = new Set(); + for (const mesh of renderableMeshes) { + if (mesh.material?.name) materialNames.add(mesh.material.name); + } + return { + summary: this.computeSummary(this.rootMesh), + parts, + materialNames: Array.from(materialNames).sort((left, right) => left.localeCompare(right)), + resourceWarnings: [...this.resourceWarnings], + capturedAt: new Date().toISOString(), + }; + } + + getSelectedPartInfo(): ModelPartSummary | null { + const mesh = this.focusedMesh ?? this._lastPickResult.mesh; + const renderable = mesh ? this.findRenderableMesh(mesh) : null; + if (!renderable || renderable.isDisposed()) return null; + return this.computePartSummary(renderable); + } + + exportSelectedPartInfo(): string { + const part = this.getSelectedPartInfo(); + return part ? createPreviewPartInfoMarkdown(part) : ""; + } + + getPickWorldPoint(result: PreviewPickResult): PreviewWorldPoint | null { + if (result.pickedPoint && typeof result.pickedPoint === "object") { + return toPreviewWorldPoint(result.pickedPoint as { x: number; y: number; z: number }); + } + + if (isBabylonMesh(result.mesh)) { + const center = result.mesh.getBoundingInfo().boundingBox.centerWorld; + return toPreviewWorldPoint(center); + } + + return null; + } + + focusWorldPoint(point: PreviewWorldPoint): void { + const target = new Vector3(point.x, point.y, point.z); + const start = this.camera.target.clone(); + const startedAt = performance.now(); + + if (this.focusWorldPointFrame) { + activeWindow.cancelAnimationFrame(this.focusWorldPointFrame); + this.focusWorldPointFrame = 0; + } + + const tick = (now: number) => { + const t = Math.min(1, Math.max(0, (now - startedAt) / FOCUS_WORLD_POINT_ANIMATION_MS)); + const ease = t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2; + this.camera.target = Vector3.Lerp(start, target, ease); + if (t < 1 && !this.scene.isDisposed) { + this.focusWorldPointFrame = window.requestAnimationFrame(tick); + return; + } + this.focusWorldPointFrame = 0; + }; + this.focusWorldPointFrame = window.requestAnimationFrame(tick); + } + + private getAnnotationCameraStateKey(): string { + return `${this.camera.alpha.toFixed(3)}_${this.camera.beta.toFixed(3)}_${this.camera.radius.toFixed(3)}_${this.camera.target.x.toFixed(2)}_${this.camera.target.y.toFixed(2)}_${this.camera.target.z.toFixed(2)}`; + } + + private projectAnnotationWorldPoint(point: PreviewWorldPoint, result: PreviewProjectionResult): boolean { + const canvas = this.engine.getRenderingCanvas(); + if (!canvas || this.scene.isDisposed) { + return false; + } + + const rw = this.engine.getRenderWidth(); + const rh = this.engine.getRenderHeight(); + if (rw === 0 || rh === 0 || canvas.clientWidth === 0 || canvas.clientHeight === 0) { + return false; + } + + const worldPoint = BabylonModelPreview.annotationWorldPoint; + worldPoint.set(point.x, point.y, point.z); + + Vector3.ProjectToRef( + worldPoint, + BabylonModelPreview.annotationIdentity, + this.scene.getTransformMatrix(), + this.camera.viewport.toGlobal(rw, rh), + BabylonModelPreview.annotationProjection, + ); + + const scaleX = canvas.clientWidth / rw; + const scaleY = canvas.clientHeight / rh; + result.screenX = BabylonModelPreview.annotationProjection.x * scaleX; + result.screenY = BabylonModelPreview.annotationProjection.y * scaleY; + result.depth = BabylonModelPreview.annotationProjection.z; + return true; + } + + private isAnnotationWorldPointOccluded(point: PreviewWorldPoint): boolean { + if (this.scene.isDisposed) { + return false; + } + + const lineOfSight = createPreviewLineOfSight( + toPreviewWorldPoint(this.camera.position), + point, + ); + if (!lineOfSight) { + return false; + } + const direction = BabylonModelPreview.annotationDirection; + const ray = BabylonModelPreview.annotationRay; + + direction.set(lineOfSight.direction.x, lineOfSight.direction.y, lineOfSight.direction.z); + ray.origin = this.camera.position; + ray.direction = direction; + ray.length = lineOfSight.distance; + + const pickInfo = this.scene.pickWithRay(ray); + return !!pickInfo?.hit + && isPreviewHitOccluded(pickInfo.distance, lineOfSight.distance, lineOfSight.epsilon); + } + + getAnnotationProvider(): AnnotationViewportProvider { + const canvas = this.engine.getRenderingCanvas(); + if (!canvas) { + throw new Error("Preview canvas is unavailable"); + } + return { + canvas, + observeRender: (callback) => { + const obs = this.scene.onAfterRenderCameraObservable.add((camera) => { + if (camera === this.camera) { + callback(); + } + }); + return { + remove: () => this.scene.onAfterRenderCameraObservable.remove(obs), + }; + }, + getCameraStateKey: () => this.getAnnotationCameraStateKey(), + projectWorldPoint: (point, result) => this.projectAnnotationWorldPoint(point, result), + isWorldPointOccluded: (point) => this.isAnnotationWorldPointOccluded(point), + }; + } + + getCanvas(): HTMLCanvasElement | null { + return this.engine.getRenderingCanvas(); + } + + getLastPickResult(): PreviewPickResult { + return this._lastPickResult; + } + + onPick(callback: (result: PreviewPickResult) => void): () => void { + this._onPickCallbacks.push(callback); + return () => { + this._onPickCallbacks = this._onPickCallbacks.filter(cb => cb !== callback); + }; + } + + /** + * Apply render quality preset and optional resolution scale. + * - low: 0.5x resolution, no shadow blur + * - medium: 0.75x resolution, basic shadow blur + * - high: 1.0x resolution, full shadow blur (default) + * @param renderScale User-controlled resolution multiplier (1.0 = native). + * Lower values = less pixels = better performance. + */ + setRenderQuality(quality: "low" | "medium" | "high", renderScale = 1.0): void { + this.currentQuality = quality; + const scaleMap = { low: 2, medium: 1.33, high: 1 }; + const mobileBoost = isMobile() ? 1.5 : 1; + // hardwareScalingLevel: higher = fewer pixels. renderScale < 1 = fewer pixels. + const scale = scaleMap[quality] * mobileBoost / Math.max(renderScale, 0.25); + this.engine.setHardwareScalingLevel(scale); + + if (this.shadowGenerator) { + const blurMap = { low: 0, medium: 16, high: 32 }; + this.shadowGenerator.blurKernel = blurMap[quality]; + if (quality === "low") { + this.shadowGenerator.useBlurExponentialShadowMap = false; + this.shadowGenerator.useExponentialShadowMap = true; + } else { + this.shadowGenerator.useBlurExponentialShadowMap = true; + this.shadowGenerator.useExponentialShadowMap = false; + } + } + } + + destroy() { + this.engine.stopRenderLoop(); + if (this.focusWorldPointFrame) { + activeWindow.cancelAnimationFrame(this.focusWorldPointFrame); + this.focusWorldPointFrame = 0; + } + this._onPickCallbacks = []; + this.cleanupPicking?.(); + this.cleanupPicking = null; + this.gizmo?.dispose(); + this.gizmo = null; + this.disassembly?.dispose(); + this.disassembly = null; + this.clearMeasurements(); + this.clearFocusedMesh(); + this.originalMeshVisibility.clear(); + this.bboxMesh?.dispose(); + this.bboxMesh = null; + this.camera.detachControl(); + const canvas = this.engine.getRenderingCanvas(); + canvas?.removeEventListener("wheel", this.preventCanvasWheelScroll); + canvas?.removeEventListener("pointermove", this.handlePointerMove); + canvas?.removeEventListener("webglcontextlost", this.handleContextLost); + canvas?.removeEventListener("webglcontextrestored", this.handleContextRestored); + this.viewportObserver?.disconnect(); + this.viewportObserver = null; + this.resizeObs.disconnect(); + if (this.autoRotateBehavior) { + this.camera.removeBehavior(this.autoRotateBehavior); + this.autoRotateBehavior = null; + } + for (const l of this.configLights) l.dispose(); + this.configLights = []; + this.shadowGenerator?.dispose(); + this.shadowGenerator = null; + this.groundMesh?.dispose(); + this.groundMesh = null; + this.gridMesh?.dispose(); + this.gridMesh = null; + for (const a of this.axisMeshes) a.dispose(); + this.axisMeshes = []; + this.scene.dispose(); + this.engine.dispose(); + } + + private startRenderLoop() { + if (this.rendering || !this.viewportVisible || this.contextLost) return; + this.rendering = true; + this.engine.runRenderLoop(() => { + if (!this.canRender() || !this.viewportVisible || this.contextLost) { + this.engine.stopRenderLoop(); + this.rendering = false; + return; + } + this.scene.render(); + if (this.gizmo && this.gizmoEnabled) { + this.gizmo.syncWith(this.camera); + this.gizmo.render(); + } + }); + } + + private readonly handleViewportIntersection = (entries: IntersectionObserverEntry[]) => { + const visible = entries.some((entry) => entry.isIntersecting); + if (visible === this.viewportVisible) return; + this.viewportVisible = visible; + if (visible) { + this.startRenderLoop(); + } else if (this.rendering) { + this.engine.stopRenderLoop(); + this.rendering = false; + } + }; + + private readonly handleContextLost = (event: Event) => { + event.preventDefault(); + this.contextLost = true; + if (this.rendering) { + this.engine.stopRenderLoop(); + this.rendering = false; + } + }; + + private readonly handleContextRestored = () => { + this.contextLost = false; + this.engine.resize(); + this.startRenderLoop(); + }; + + private getRenderableMeshes(root: Mesh): AbstractMesh[] { + return getBabylonRenderableMeshes(root, this.loadedMeshes); + } + + private getRenderableBounds(root: Mesh) { + return getBabylonRenderablePreviewBounds(root, this.loadedMeshes); + } + + private setFocusedMesh(mesh: AbstractMesh | null): void { + if (!this.rootMesh) return; + const target = mesh ? this.findRenderableMesh(mesh) : null; + if (!target || target.isDisposed()) { + this.clearFocusedMesh(); + return; + } + if (this.focusedMesh === target) return; + + const renderableMeshes = this.getRenderableMeshes(this.rootMesh); + for (const candidate of renderableMeshes) { + if (!this.originalMeshVisibility.has(candidate.uniqueId)) { + this.originalMeshVisibility.set(candidate.uniqueId, candidate.visibility); + } + const selected = candidate === target; + candidate.visibility = selected ? 1 : FOCUS_DIM_VISIBILITY; + candidate.renderOutline = selected; + candidate.outlineColor = new Color3(0.18, 0.76, 1); + candidate.outlineWidth = selected ? 0.045 : 0; + } + this.focusedMesh = target; + } + + private clearFocusedMesh(): void { + if (!this.rootMesh) { + this.focusedMesh = null; + return; + } + + for (const mesh of this.getRenderableMeshes(this.rootMesh)) { + const originalVisibility = this.originalMeshVisibility.get(mesh.uniqueId); + if (originalVisibility !== undefined) { + mesh.visibility = originalVisibility; + } + mesh.renderOutline = false; + mesh.outlineWidth = 0; + } + this.originalMeshVisibility.clear(); + this.focusedMesh = null; + } + + private findRenderableMesh(mesh: AbstractMesh): AbstractMesh | null { + if (!this.rootMesh) return null; + const renderableMeshes = this.getRenderableMeshes(this.rootMesh); + if (renderableMeshes.includes(mesh)) return mesh; + + let parent = mesh.parent; + while (parent && "uniqueId" in parent) { + const parentMesh = parent as AbstractMesh; + if (renderableMeshes.includes(parentMesh)) return parentMesh; + parent = parent.parent; + } + + return null; + } + + private computePartSummary(mesh: AbstractMesh): ModelPartSummary { + const name = mesh.name || `mesh-${mesh.uniqueId}`; + const metadata = mergeMetadataFallback( + mesh.metadata, + this.gltfComponentMetadata.get(`node:${name}`) ?? this.gltfComponentMetadata.get(`mesh:${name}`), + ); + const identity = extractPreviewComponentIdentity(metadata, { + name, + path: getBabylonComponentPath(mesh), + }); + return { + ...createBabylonPartPreviewSummary(mesh), + name: getPartDisplayName(identity, name), + source: identity.hasExplicitIdentity ? "component" : "mesh", + meshNames: [name], + childCount: 1, + componentId: identity.componentId, + occurrenceId: identity.occurrenceId, + partNumber: identity.partNumber, + componentPath: identity.componentPath, + }; + } + + private computeComponentPartSummaries(renderableMeshes: readonly AbstractMesh[]): { + parts: ModelPartSummary[]; + groupedMeshes: Set; + } { + const renderableSet = new Set(renderableMeshes); + const parts: ModelPartSummary[] = []; + const groupedMeshes = new Set(); + const candidates: Array<{ + node: TransformNode; + childMeshes: AbstractMesh[]; + identity: PreviewComponentIdentity; + }> = []; + for (const node of this.loadedTransformNodes) { + const childMeshes = node.getChildMeshes(false).filter((mesh) => renderableSet.has(mesh)); + const nodeName = getBabylonNodeDisplayName(node, `component-${node.uniqueId}`); + const metadata = mergeMetadataFallback(node.metadata, this.gltfComponentMetadata.get(`node:${nodeName}`)); + const identity = extractPreviewComponentIdentity(metadata, { + name: getBabylonNodeDisplayName(node, `component-${node.uniqueId}`), + path: getBabylonComponentPath(node), + }); + if (childMeshes.length < 1 || childMeshes.length === renderableMeshes.length) { + continue; + } + if (!identity.hasExplicitIdentity && (!node.name.trim() || childMeshes.length < 2)) { + continue; + } + candidates.push({ node, childMeshes, identity }); + } + + candidates + .sort((left, right) => left.childMeshes.length - right.childMeshes.length) + .forEach(({ node, childMeshes, identity }) => { + const availableMeshes = childMeshes.filter((mesh) => !groupedMeshes.has(mesh)); + if (availableMeshes.length < 1) return; + if (!identity.hasExplicitIdentity && availableMeshes.length < 2) return; + for (const mesh of availableMeshes) { + groupedMeshes.add(mesh); + } + const bounds = getBabylonMeshesPreviewBounds(availableMeshes); + if (!bounds) return; + const materialNames = new Set(); + let triangleCount = 0; + let vertexCount = 0; + for (const mesh of availableMeshes) { + triangleCount += getBabylonTriangleCount(mesh); + vertexCount += getBabylonVertexCount(mesh); + if (mesh.material?.name) { + materialNames.add(mesh.material.name); + } + } + parts.push(createPreviewPartSummary({ + name: getPartDisplayName(identity, getBabylonNodeDisplayName(node, `component-${node.uniqueId}`)), + triangleCount, + vertexCount, + materialName: materialNames.size === 0 + ? null + : materialNames.size === 1 + ? Array.from(materialNames)[0] + : `${materialNames.size} materials`, + boundingSize: getPreviewBoundsSize(bounds), + center: getPreviewBoundsCenter(bounds), + source: identity.hasExplicitIdentity ? "component" : "group", + meshNames: availableMeshes.map((mesh) => mesh.name || `mesh-${mesh.uniqueId}`), + childCount: availableMeshes.length, + componentId: identity.componentId, + occurrenceId: identity.occurrenceId, + partNumber: identity.partNumber, + componentPath: identity.componentPath, + })); + }); + return { parts, groupedMeshes }; + } + + private getMeasurementMarkerSize(): number { + if (!this.rootMesh) return 0.02; + const bounds = this.getRenderableBounds(this.rootMesh); + if (!bounds) return 0.02; + const maxSpan = Math.max(bounds.max.x - bounds.min.x, bounds.max.y - bounds.min.y, bounds.max.z - bounds.min.z, 0.001); + return maxSpan * 0.015; + } + + private findNearestMarkerIndex(point: Vector3): number { + const threshold = this.getMeasurementMarkerSize() * 2.5; + for (let i = 0; i < this.measurementMarkers.length; i++) { + if (Vector3.Distance(this.measurementMarkers[i].position, point) < threshold) { + return i; + } + } + return -1; + } + + private addMeasurementPoint(point: Vector3): void { + const existingIndex = this.findNearestMarkerIndex(point); + const usePoint = existingIndex >= 0 + ? this.measurementMarkers[existingIndex].position.clone() + : point; + + if (this.pendingPoint) { + if (Vector3.Distance(usePoint, this.pendingPoint) < 0.0001) { + return; + } + if (existingIndex < 0) { + const size = this.getMeasurementMarkerSize(); + const marker = MeshBuilder.CreateSphere("measure-marker", { diameter: size }, this.scene); + marker.position = usePoint; + marker.isPickable = false; + const mat = new StandardMaterial("measure-marker-mat", this.scene); + mat.diffuseColor = new Color3(1, 0.42, 0.42); + mat.emissiveColor = new Color3(1, 0.42, 0.42); + marker.material = mat; + marker.renderingGroupId = 2; + this.measurementMarkers.push(marker); + } + this.createMeasurementSegment(this.pendingPoint, usePoint); + if (this.pendingMarker) { + this.pendingMarker.scaling.setAll(1); + (this.pendingMarker.material as StandardMaterial).diffuseColor = new Color3(1, 0.42, 0.42); + (this.pendingMarker.material as StandardMaterial).emissiveColor = new Color3(1, 0.42, 0.42); + } + this.pendingPoint = null; + this.pendingMarker = null; + this.removePreviewLine(); + } else { + if (existingIndex < 0) { + const size = this.getMeasurementMarkerSize(); + const marker = MeshBuilder.CreateSphere("measure-marker", { diameter: size }, this.scene); + marker.position = usePoint; + marker.isPickable = false; + const mat = new StandardMaterial("measure-marker-mat", this.scene); + mat.diffuseColor = new Color3(1, 0.42, 0.42); + mat.emissiveColor = new Color3(1, 0.42, 0.42); + marker.material = mat; + marker.renderingGroupId = 2; + this.measurementMarkers.push(marker); + this.pendingMarker = marker; + } else { + this.pendingMarker = this.measurementMarkers[existingIndex]; + } + this.pendingMarker.scaling.setAll(1.6); + (this.pendingMarker.material as StandardMaterial).diffuseColor = new Color3(0.32, 0.81, 0.4); + (this.pendingMarker.material as StandardMaterial).emissiveColor = new Color3(0.32, 0.81, 0.4); + this.pendingPoint = usePoint; + this.ensurePreviewLine(); + } + } + + private createMeasurementSegment(start: Vector3, end: Vector3): void { + const line = MeshBuilder.CreateLines("measure-line", { points: [start, end] }, this.scene); + line.color = new Color3(1, 0.42, 0.42); + line.isPickable = false; + line.renderingGroupId = 2; + + const distance = this.getRealDistance(start, end); + const labelText = this.formatMeasurementDistance(distance); + const mid = Vector3.Center(start, end); + const label = this.createMeasurementLabelMesh(labelText, mid, this.getMeasurementMarkerSize() * 4); + + this.measurementSegments.push({ start, end, line, label }); + } + + private createMeasurementLabelMesh(text: string, position: Vector3, scale: number): Mesh { + const plane = MeshBuilder.CreatePlane("measure-label", { width: scale * 4, height: scale }, this.scene); + plane.position = position; + plane.billboardMode = Mesh.BILLBOARDMODE_ALL; + plane.isPickable = false; + plane.renderingGroupId = 2; + + const texture = new DynamicTexture("measure-label-tex", { width: 512, height: 128 }, this.scene); + const ctx = texture.getContext() as CanvasRenderingContext2D; + ctx.fillStyle = "rgba(32, 36, 46, 0.9)"; + ctx.fillRect(0, 0, 512, 128); + ctx.strokeStyle = "#ff6b6b"; + ctx.lineWidth = 4; + ctx.strokeRect(0, 0, 512, 128); + ctx.fillStyle = "#ffffff"; + ctx.font = "bold 48px sans-serif"; + ctx.textAlign = "center"; + ctx.textBaseline = "middle"; + ctx.fillText(text, 256, 64); + texture.update(); + + const mat = new StandardMaterial("measure-label-mat", this.scene); + mat.diffuseTexture = texture; + mat.emissiveColor = new Color3(1, 1, 1); + mat.disableLighting = true; + mat.opacityTexture = texture; + plane.material = mat; + return plane; + } + + private ensurePreviewLine(): void { + if (this.previewLine) return; + this.previewLine = MeshBuilder.CreateLines("measure-preview", { points: [Vector3.Zero(), Vector3.Zero()] }, this.scene); + (this.previewLine as LinesMesh).color = new Color3(1, 1, 1); + (this.previewLine as LinesMesh).alpha = 0.5; + this.previewLine.isPickable = false; + this.previewLine.renderingGroupId = 2; + } + + private updatePreviewLine(): void { + if (!this.pendingPoint || !this.previewLine || !this.rootMesh) return; + const canvas = this.engine.getRenderingCanvas(); + if (!canvas) return; + const rect = canvas.getBoundingClientRect(); + const x = this.lastPointerClient.x - rect.left; + const y = this.lastPointerClient.y - rect.top; + const pickResult = this.scene.pick(x, y, (mesh) => mesh !== this.previewLine && !this.measurementMarkers.includes(mesh as Mesh)); + let endPoint: Vector3; + if (pickResult.hit && pickResult.pickedPoint) { + endPoint = pickResult.pickedPoint; + } else { + const ray = this.scene.createPickingRay(x, y, Matrix.Identity(), this.camera); + endPoint = this.pendingPoint.add(ray.direction.scale(5)); + } + this.previewLine.dispose(); + this.previewLine = MeshBuilder.CreateLines("measure-preview", { points: [this.pendingPoint, endPoint] }, this.scene); + (this.previewLine as LinesMesh).color = new Color3(1, 1, 1); + (this.previewLine as LinesMesh).alpha = 0.5; + this.previewLine.isPickable = false; + this.previewLine.renderingGroupId = 2; + } + + private removePreviewLine(): void { + if (!this.previewLine) return; + this.previewLine.dispose(); + this.previewLine = null; + } + + private computeSummary(root: Mesh): ModelPreviewSummary { + const allMeshes = this.getRenderableMeshes(root); + const isSplat = isGaussianSplattingMesh(root); + const vertexCount = allMeshes.reduce((total, mesh) => total + getBabylonVertexCount(mesh), 0); + return createBabylonModelPreviewSummary( + root.name, + this.getRenderableBounds(root), + allMeshes, + { splatCount: isSplat ? vertexCount : undefined, resourceWarnings: this.resourceWarnings }, + ); + } +} + +export function createBabylonModelPreview(canvas: HTMLCanvasElement): WorkbenchPreview { + return new BabylonModelPreview(canvas); +} diff --git a/src/render/three/scene.ts b/src/render/three/scene.ts index bcb1767..0162e1c 100644 --- a/src/render/three/scene.ts +++ b/src/render/three/scene.ts @@ -7,7 +7,6 @@ import { CanvasTexture, Color, DirectionalLight, - Float32BufferAttribute, GridHelper, HemisphereLight, Light, @@ -1912,7 +1911,7 @@ export class ThreeModelPreview implements WorkbenchPreview { } private createMeasurementLabelSprite(text: string, position: Vector3, scale: number): Sprite { - const canvas = document.createElement("canvas"); + const canvas = activeDocument.createEl("canvas"); const ctx = canvas.getContext("2d")!; canvas.width = 512; canvas.height = 128; diff --git a/src/settings.ts b/src/settings.ts index be01fdc..608ba6e 100644 --- a/src/settings.ts +++ b/src/settings.ts @@ -1,130 +1,130 @@ -import { App, Notice, PluginSettingTab, Setting } from "obsidian"; -import type AI3DModelWorkbench from "./main"; -import { DEFAULT_SETTINGS } from "./domain/constants"; -import { - describeConverterCommandSource, - inspectAllConverterCommands, - type ConverterDependencyCheck, - type ConverterCommandStatus, -} from "./io/conversion/command-discovery"; -import { t, setLocale, type Locale } from "./i18n"; -import { isMobile } from "./utils/device"; -import { getRuntimeProcess } from "./utils/node-shim"; - -const proc = getRuntimeProcess(); - -function getConverterCommandPlaceholders(): { - python: string; - freecad: string; - obj2gltf: string; - fbx2gltf: string; -} { - switch (proc?.platform) { - case "win32": - return { - python: "Path to python executable", - freecad: "Path to FreeCADCmd.exe", - obj2gltf: "Path to obj2gltf.cmd", - fbx2gltf: "Path to FBX2glTF.exe", - }; - case "darwin": - return { - python: "Path to python3", - freecad: "Path to FreeCADCmd", - obj2gltf: "Path to obj2gltf", - fbx2gltf: "Path to FBX2glTF", - }; - case "linux": - return { - python: "Path to python3", - freecad: "Path to freecadcmd", - obj2gltf: "Path to obj2gltf", - fbx2gltf: "Path to FBX2glTF", - }; - default: - return { - python: "Path to python executable", - freecad: "Path to FreeCAD command", - obj2gltf: "Path to obj2gltf", - fbx2gltf: "Path to FBX2glTF", - }; - } -} - -export class AI3DSettingTab extends PluginSettingTab { - private plugin: AI3DModelWorkbench; - private diagnosticsRunId = 0; - - constructor(app: App, plugin: AI3DModelWorkbench) { - super(app, plugin); - this.plugin = plugin; - } - - display(): void { - const { containerEl } = this; - containerEl.empty(); - setLocale(this.plugin.getSettings().locale); - const commandPlaceholders = getConverterCommandPlaceholders(); - const mobile = isMobile(); - let diagnosticsEl: HTMLDivElement | null = null; - - const createSecondaryMenu = (parent: HTMLElement, title: string, description: string): HTMLElement => { - const detailsEl = parent.createEl("details", { cls: "ai3d-settings-secondary-menu" }); - detailsEl.createEl("summary", { cls: "ai3d-settings-secondary-menu-summary", text: title }); - const bodyEl = detailsEl.createDiv({ cls: "ai3d-settings-secondary-menu-body" }); - bodyEl.createEl("p", { cls: "setting-item-description", text: description }); - return bodyEl; - }; - - const resetCommandDiagnostics = (): void => { - if (!diagnosticsEl) return; - this.diagnosticsRunId++; - diagnosticsEl.empty(); - diagnosticsEl.createEl("p", { text: t("settings.diagnostics.idle") }); - }; - - new Setting(containerEl).setName(t("settings.title")).setHeading(); - - // ── Language ───────────────────────────────────────────────── - - new Setting(containerEl) - .setName(t("settings.language")) - .setDesc(t("settings.language.desc")) - .addDropdown((dropdown) => - dropdown - .addOption("en", "English") - .addOption("zh-CN", "简体中文") - .setValue(this.plugin.getSettings().locale) - .onChange((val: string) => { - this.plugin.updateSettings({ locale: val as Locale }); - this.display(); - }), - ); - - // ── Folders ────────────────────────────────────────────────── - - new Setting(containerEl).setName(t("settings.folders")).setHeading(); - - new Setting(containerEl) - .setName(t("settings.sourceModelFolder")) - .setDesc(t("settings.sourceModelFolder.desc")) - .addText((text) => - text - .setPlaceholder(DEFAULT_SETTINGS.sourceModelFolder) - .setValue(this.plugin.getSettings().sourceModelFolder) - .onChange((val) => { - this.plugin.updateSettings({ sourceModelFolder: val }); - }), - ); - +import { App, Notice, PluginSettingTab, Setting } from "obsidian"; +import type AI3DModelWorkbench from "./main"; +import { DEFAULT_SETTINGS } from "./domain/constants"; +import { + describeConverterCommandSource, + inspectAllConverterCommands, + type ConverterDependencyCheck, + type ConverterCommandStatus, +} from "./io/conversion/command-discovery"; +import { t, setLocale, type Locale } from "./i18n"; +import { isMobile } from "./utils/device"; +import { getRuntimeProcess } from "./utils/node-shim"; + +const proc = getRuntimeProcess(); + +function getConverterCommandPlaceholders(): { + python: string; + freecad: string; + obj2gltf: string; + fbx2gltf: string; +} { + switch (proc?.platform) { + case "win32": + return { + python: "Path to python executable", + freecad: "Path to FreeCADCmd.exe", + obj2gltf: "Path to obj2gltf.cmd", + fbx2gltf: "Path to FBX2glTF.exe", + }; + case "darwin": + return { + python: "Path to python3", + freecad: "Path to FreeCADCmd", + obj2gltf: "Path to obj2gltf", + fbx2gltf: "Path to FBX2glTF", + }; + case "linux": + return { + python: "Path to python3", + freecad: "Path to freecadcmd", + obj2gltf: "Path to obj2gltf", + fbx2gltf: "Path to FBX2glTF", + }; + default: + return { + python: "Path to python executable", + freecad: "Path to FreeCAD command", + obj2gltf: "Path to obj2gltf", + fbx2gltf: "Path to FBX2glTF", + }; + } +} + +export class AI3DSettingTab extends PluginSettingTab { + private plugin: AI3DModelWorkbench; + private diagnosticsRunId = 0; + + constructor(app: App, plugin: AI3DModelWorkbench) { + super(app, plugin); + this.plugin = plugin; + } + + display(): void { + const { containerEl } = this; + containerEl.empty(); + setLocale(this.plugin.getSettings().locale); + const commandPlaceholders = getConverterCommandPlaceholders(); + const mobile = isMobile(); + let diagnosticsEl: HTMLDivElement | null = null; + + const createSecondaryMenu = (parent: HTMLElement, title: string, description: string): HTMLElement => { + const detailsEl = parent.createEl("details", { cls: "ai3d-settings-secondary-menu" }); + detailsEl.createEl("summary", { cls: "ai3d-settings-secondary-menu-summary", text: title }); + const bodyEl = detailsEl.createDiv({ cls: "ai3d-settings-secondary-menu-body" }); + bodyEl.createEl("p", { cls: "setting-item-description", text: description }); + return bodyEl; + }; + + const resetCommandDiagnostics = (): void => { + if (!diagnosticsEl) return; + this.diagnosticsRunId++; + diagnosticsEl.empty(); + diagnosticsEl.createEl("p", { text: t("settings.diagnostics.idle") }); + }; + + new Setting(containerEl).setName(t("settings.title")).setHeading(); + + // ── Language ───────────────────────────────────────────────── + + new Setting(containerEl) + .setName(t("settings.language")) + .setDesc(t("settings.language.desc")) + .addDropdown((dropdown) => + dropdown + .addOption("en", "English") + .addOption("zh-CN", "简体中文") + .setValue(this.plugin.getSettings().locale) + .onChange((val: string) => { + this.plugin.updateSettings({ locale: val as Locale }); + this.display(); + }), + ); + + // ── Folders ────────────────────────────────────────────────── + + new Setting(containerEl).setName(t("settings.folders")).setHeading(); + + new Setting(containerEl) + .setName(t("settings.sourceModelFolder")) + .setDesc(t("settings.sourceModelFolder.desc")) + .addText((text) => + text + .setPlaceholder(DEFAULT_SETTINGS.sourceModelFolder) + .setValue(this.plugin.getSettings().sourceModelFolder) + .onChange((val) => { + this.plugin.updateSettings({ sourceModelFolder: val }); + }), + ); + new Setting(containerEl) .setName(t("settings.reportFolder")) .setDesc(t("settings.reportFolder.desc")) .addText((text) => text - .setPlaceholder(DEFAULT_SETTINGS.reportFolder) - .setValue(this.plugin.getSettings().reportFolder) - .onChange((val) => { + .setPlaceholder(DEFAULT_SETTINGS.reportFolder) + .setValue(this.plugin.getSettings().reportFolder) + .onChange((val) => { this.plugin.updateSettings({ reportFolder: val }); }), ); @@ -143,40 +143,40 @@ export class AI3DSettingTab extends PluginSettingTab { new Setting(containerEl) .setName(t("settings.snapshotFolder")) - .setDesc(t("settings.snapshotFolder.desc")) - .addText((text) => - text - .setPlaceholder(DEFAULT_SETTINGS.snapshotFolder) - .setValue(this.plugin.getSettings().snapshotFolder) - .onChange((val) => { - this.plugin.updateSettings({ snapshotFolder: val }); - }), - ); - - // ── Behavior ───────────────────────────────────────────────── - - new Setting(containerEl).setName(t("settings.behavior")).setHeading(); - - new Setting(containerEl) - .setName(t("settings.autoGenerateKnowledgeNotes")) - .setDesc(t("settings.autoGenerateKnowledgeNotes.desc")) - .addToggle((toggle) => - toggle - .setValue(this.plugin.getSettings().autoGenerateKnowledgeNotes) - .onChange((val) => { - this.plugin.updateSettings({ autoGenerateKnowledgeNotes: val }); - }), - ); - + .setDesc(t("settings.snapshotFolder.desc")) + .addText((text) => + text + .setPlaceholder(DEFAULT_SETTINGS.snapshotFolder) + .setValue(this.plugin.getSettings().snapshotFolder) + .onChange((val) => { + this.plugin.updateSettings({ snapshotFolder: val }); + }), + ); + + // ── Behavior ───────────────────────────────────────────────── + + new Setting(containerEl).setName(t("settings.behavior")).setHeading(); + + new Setting(containerEl) + .setName(t("settings.autoGenerateKnowledgeNotes")) + .setDesc(t("settings.autoGenerateKnowledgeNotes.desc")) + .addToggle((toggle) => + toggle + .setValue(this.plugin.getSettings().autoGenerateKnowledgeNotes) + .onChange((val) => { + this.plugin.updateSettings({ autoGenerateKnowledgeNotes: val }); + }), + ); + new Setting(containerEl) .setName(t("settings.annotationPreviewMode")) .setDesc(t("settings.annotationPreviewMode.desc")) .addDropdown((dropdown) => - dropdown - .addOption("plain-text", t("settings.annotationPreviewMode.plainText")) - .addOption("markdown", t("settings.annotationPreviewMode.markdown")) - .setValue(this.plugin.getSettings().annotationPreviewMode) - .onChange((val: string) => { + dropdown + .addOption("plain-text", t("settings.annotationPreviewMode.plainText")) + .addOption("markdown", t("settings.annotationPreviewMode.markdown")) + .setValue(this.plugin.getSettings().annotationPreviewMode) + .onChange((val: string) => { this.plugin.updateSettings({ annotationPreviewMode: val as "plain-text" | "markdown" }); }), ); @@ -197,27 +197,27 @@ export class AI3DSettingTab extends PluginSettingTab { new Setting(containerEl) .setName(t("settings.previewRendererRollout")) - .setDesc(t("settings.previewRendererRollout.desc")) - .addDropdown((dropdown) => - dropdown - .addOption("babylon-safe", t("settings.previewRendererRollout.babylonSafe")) - .addOption("three-readonly-glb", t("settings.previewRendererRollout.readonly")) - .addOption("three-direct-glb", t("settings.previewRendererRollout.direct")) - .setValue(this.plugin.getSettings().previewRendererRollout) - .onChange((val: string) => { - this.plugin.updateSettings({ - previewRendererRollout: val as "babylon-safe" | "three-readonly-glb" | "three-direct-glb", - }); - }), - ); - + .setDesc(t("settings.previewRendererRollout.desc")) + .addDropdown((dropdown) => + dropdown + .addOption("babylon-safe", t("settings.previewRendererRollout.babylonSafe")) + .addOption("three-readonly-glb", t("settings.previewRendererRollout.readonly")) + .addOption("three-direct-glb", t("settings.previewRendererRollout.direct")) + .setValue(this.plugin.getSettings().previewRendererRollout) + .onChange((val: string) => { + this.plugin.updateSettings({ + previewRendererRollout: val as "babylon-safe" | "three-readonly-glb" | "three-direct-glb", + }); + }), + ); + new Setting(containerEl) .setName(t("settings.useThreeRenderer")) .setDesc(t("settings.useThreeRenderer.desc")) .addToggle((toggle) => toggle - .setValue(this.plugin.getSettings().useThreeRenderer) - .onChange((val) => { + .setValue(this.plugin.getSettings().useThreeRenderer) + .onChange((val) => { this.plugin.updateSettings({ useThreeRenderer: val }); }), ); @@ -235,40 +235,40 @@ export class AI3DSettingTab extends PluginSettingTab { new Setting(containerEl) .setName(t("settings.autoRotateDefault")) - .setDesc(t("settings.autoRotateDefault.desc")) - .addToggle((toggle) => - toggle - .setValue(this.plugin.getSettings().autoRotateDefault) - .onChange((val) => { - this.plugin.updateSettings({ autoRotateDefault: val }); - }), - ); - - new Setting(containerEl) - .setName(t("settings.snapshotNaming")) - .setDesc(t("settings.snapshotNaming.desc")) - .addDropdown((dropdown) => - dropdown - .addOption("model-name", t("settings.snapshotNaming.modelName")) - .addOption("timestamp", t("settings.snapshotNaming.timestamp")) - .setValue(this.plugin.getSettings().snapshotNaming) - .onChange((val: string) => { - this.plugin.updateSettings({ snapshotNaming: val as "timestamp" | "model-name" }); - }), - ); - + .setDesc(t("settings.autoRotateDefault.desc")) + .addToggle((toggle) => + toggle + .setValue(this.plugin.getSettings().autoRotateDefault) + .onChange((val) => { + this.plugin.updateSettings({ autoRotateDefault: val }); + }), + ); + + new Setting(containerEl) + .setName(t("settings.snapshotNaming")) + .setDesc(t("settings.snapshotNaming.desc")) + .addDropdown((dropdown) => + dropdown + .addOption("model-name", t("settings.snapshotNaming.modelName")) + .addOption("timestamp", t("settings.snapshotNaming.timestamp")) + .setValue(this.plugin.getSettings().snapshotNaming) + .onChange((val: string) => { + this.plugin.updateSettings({ snapshotNaming: val as "timestamp" | "model-name" }); + }), + ); + new Setting(containerEl) .setName(t("settings.logLevel")) .setDesc(t("settings.logLevel.desc")) .addDropdown((dropdown) => dropdown - .addOption("debug", "Debug") - .addOption("info", "Info") - .addOption("warn", "Warn") - .addOption("error", "Error") - .setValue(this.plugin.getSettings().logLevel) - .onChange((val: string) => { - this.plugin.updateSettings({ logLevel: val as "debug" | "info" | "warn" | "error" }); + .addOption("debug", "Debug") + .addOption("info", "Info") + .addOption("warn", "Warn") + .addOption("error", "Error") + .setValue(this.plugin.getSettings().logLevel) + .onChange((val: string) => { + this.plugin.updateSettings({ logLevel: val as "debug" | "info" | "warn" | "error" }); }), ); @@ -338,314 +338,314 @@ export class AI3DSettingTab extends PluginSettingTab { // ── Converters ─────────────────────────────────────────────── new Setting(containerEl).setName(t("settings.converters")).setHeading(); - - if (mobile) { - containerEl.createEl("p", { cls: "setting-item-description", text: t("settings.mobileSupport.desc") }); - } else { - const converterMenuEl = createSecondaryMenu( - containerEl, - t("settings.converterMenu"), - t("settings.converterMenu.desc"), - ); - - new Setting(converterMenuEl) - .setName(t("settings.enableCad")) - .setDesc(t("settings.enableCad.desc")) - .addToggle((toggle) => { - const enabled = this.plugin.getSettings().enabledConverterIds.includes("freecad"); - return toggle.setValue(enabled).onChange((val) => { - const current = this.plugin.getSettings().enabledConverterIds; - const next = val - ? Array.from(new Set([...current, "freecad"])) - : current.filter((id) => id !== "freecad"); - this.plugin.updateSettings({ enabledConverterIds: next }); - }); - }); - - new Setting(converterMenuEl) - .setName(t("settings.enableObj2gltf")) - .setDesc(t("settings.enableObj2gltf.desc")) - .addToggle((toggle) => { - const enabled = this.plugin.getSettings().enabledConverterIds.includes("obj2gltf"); - return toggle.setValue(enabled).onChange((val) => { - const current = this.plugin.getSettings().enabledConverterIds; - const next = val - ? Array.from(new Set([...current, "obj2gltf"])) - : current.filter((id) => id !== "obj2gltf"); - this.plugin.updateSettings({ enabledConverterIds: next }); - }); - }); - - new Setting(converterMenuEl) - .setName(t("settings.preferObj2gltf")) - .setDesc(t("settings.preferObj2gltf.desc")) - .addToggle((toggle) => - toggle - .setValue(this.plugin.getSettings().preferObj2gltfForObj) - .onChange((val) => { - this.plugin.updateSettings({ preferObj2gltfForObj: val }); - }), - ); - - new Setting(converterMenuEl) - .setName(t("settings.enableFbx2gltf")) - .setDesc(t("settings.enableFbx2gltf.desc")) - .addToggle((toggle) => { - const enabled = this.plugin.getSettings().enabledConverterIds.includes("fbx2gltf"); - return toggle.setValue(enabled).onChange((val) => { - const current = this.plugin.getSettings().enabledConverterIds; - const next = val - ? Array.from(new Set([...current, "fbx2gltf"])) - : current.filter((id) => id !== "fbx2gltf"); - this.plugin.updateSettings({ enabledConverterIds: next }); - }); - }); - - new Setting(converterMenuEl) - .setName(t("settings.enableMesh")) - .setDesc(t("settings.enableMesh.desc")) - .addToggle((toggle) => { - const enabled = this.plugin.getSettings().enabledConverterIds.includes("assimp"); - return toggle.setValue(enabled).onChange((val) => { - const current = this.plugin.getSettings().enabledConverterIds; - const next = val - ? Array.from(new Set([...current, "assimp"])) - : current.filter((id) => id !== "assimp"); - this.plugin.updateSettings({ enabledConverterIds: next }); - }); - }); - - new Setting(converterMenuEl) - .setName(t("settings.enableSldprt")) - .setDesc(t("settings.enableSldprt.desc")) - .addToggle((toggle) => { - const enabled = this.plugin.getSettings().enabledConverterIds.includes("sldprt"); - return toggle.setValue(enabled).onChange((val) => { - const current = this.plugin.getSettings().enabledConverterIds; - const next = val - ? Array.from(new Set([...current, "sldprt"])) - : current.filter((id) => id !== "sldprt"); - this.plugin.updateSettings({ enabledConverterIds: next }); - }); - }); - - const diagnosticsMenuEl = createSecondaryMenu( - containerEl, - t("settings.environmentInspector"), - t("settings.environmentInspector.desc"), - ); - - // ── Converter Paths ────────────────────────────────────────── - - new Setting(diagnosticsMenuEl).setName(t("settings.paths")).setHeading(); - - new Setting(diagnosticsMenuEl) - .setName(t("settings.pythonCmd")) - .setDesc(t("settings.pythonCmd.desc")) - .addText((text) => - text - .setPlaceholder(commandPlaceholders.python) - .setValue(this.plugin.getSettings().freecadCommand) - .onChange((val) => { - this.plugin.updateSettings({ freecadCommand: val.trim() }); - resetCommandDiagnostics(); - }), - ); - - new Setting(diagnosticsMenuEl) - .setName(t("settings.freecadCmd")) - .setDesc(t("settings.freecadCmd.desc")) - .addText((text) => - text - .setPlaceholder(commandPlaceholders.freecad) - .setValue(this.plugin.getSettings().freecadcmdCommand) - .onChange((val) => { - this.plugin.updateSettings({ freecadcmdCommand: val.trim() }); - resetCommandDiagnostics(); - }), - ); - - new Setting(diagnosticsMenuEl) - .setName(t("settings.obj2gltfCmd")) - .setDesc(t("settings.obj2gltfCmd.desc")) - .addText((text) => - text - .setPlaceholder(commandPlaceholders.obj2gltf) - .setValue(this.plugin.getSettings().obj2gltfCommand) - .onChange((val) => { - this.plugin.updateSettings({ obj2gltfCommand: val.trim() }); - resetCommandDiagnostics(); - }), - ); - - new Setting(diagnosticsMenuEl) - .setName(t("settings.fbx2gltfCmd")) - .setDesc(t("settings.fbx2gltfCmd.desc")) - .addText((text) => - text - .setPlaceholder(commandPlaceholders.fbx2gltf) - .setValue(this.plugin.getSettings().fbx2gltfCommand) - .onChange((val) => { - this.plugin.updateSettings({ fbx2gltfCommand: val.trim() }); - resetCommandDiagnostics(); - }), - ); - - new Setting(diagnosticsMenuEl) - .setName(t("settings.assimpCmd")) - .setDesc(t("settings.assimpCmd.desc")) - .addText((text) => - text - .setPlaceholder(commandPlaceholders.python) - .setValue(this.plugin.getSettings().assimpCommand) - .onChange((val) => { - this.plugin.updateSettings({ assimpCommand: val.trim() }); - resetCommandDiagnostics(); - }), - ); - - // ── Diagnostics ────────────────────────────────────────────── - - const diagnosticsSetting = new Setting(diagnosticsMenuEl) - .setName(t("settings.diagnostics")) - .setDesc(t("settings.diagnostics.desc")); - - diagnosticsSetting.addButton((button) => - button - .setButtonText(t("settings.diagnostics.checkNow")) - .onClick(async () => { - button.setDisabled(true); - button.setButtonText(t("settings.diagnostics.checking")); - if (diagnosticsEl) { - await this.renderCommandDiagnostics(diagnosticsEl); - } - button.setButtonText(t("settings.diagnostics.checkNow")); - button.setDisabled(false); - new Notice(t("settings.diagnostics.refreshed")); - }), - ); - - diagnosticsEl = diagnosticsMenuEl.createDiv({ cls: "ai3d-settings-diagnostics" }); - resetCommandDiagnostics(); - - } - - // ── Performance ────────────────────────────────────────────── - - new Setting(containerEl).setName(t("settings.performance")).setHeading(); - - new Setting(containerEl) - .setName(t("settings.canvasHeight")) - .setDesc(t("settings.canvasHeight.desc")) - .addSlider((slider) => - slider - .setLimits(200, 800, 25) - .setValue(this.plugin.getSettings().defaultCanvasHeight) - .setDynamicTooltip() - .onChange((val) => { - this.plugin.updateSettings({ defaultCanvasHeight: val }); - }), - ); - - new Setting(containerEl) - .setName(t("settings.autoRotateSpeed")) - .setDesc(t("settings.autoRotateSpeed.desc")) - .addSlider((slider) => - slider - .setLimits(0.1, 2.0, 0.1) - .setValue(this.plugin.getSettings().autoRotateSpeed) - .setDynamicTooltip() - .onChange((val) => { - this.plugin.updateSettings({ autoRotateSpeed: val }); - }), - ); - - new Setting(containerEl) - .setName(t("settings.renderQuality")) - .setDesc(t("settings.renderQuality.desc")) - .addDropdown((dropdown) => - dropdown - .addOption("low", "Low") - .addOption("medium", "Medium") - .addOption("high", "High") - .setValue(this.plugin.getSettings().renderQuality) - .onChange((val: string) => { - this.plugin.updateSettings({ renderQuality: val as "low" | "medium" | "high" }); - }), - ); - - new Setting(containerEl) - .setName(t("settings.renderScale")) - .setDesc(t("settings.renderScale.desc")) - .addSlider((slider) => - slider - .setLimits(0.25, 2.0, 0.25) - .setValue(this.plugin.getSettings().renderScale) - .setDynamicTooltip() - .onChange((val) => { - this.plugin.updateSettings({ renderScale: val }); - }), - ); - } - - private async renderCommandDiagnostics(containerEl: HTMLElement): Promise { - const runId = ++this.diagnosticsRunId; - containerEl.empty(); - containerEl.createEl("p", { text: t("settings.diagnostics.checkingAvailability") }); - - const statuses = await inspectAllConverterCommands(this.plugin.getSettings()); - if (runId !== this.diagnosticsRunId) { - return; - } - - containerEl.empty(); - for (const status of statuses) { - this.renderCommandStatus(containerEl, status); - } - } - - private renderCommandStatus(containerEl: HTMLElement, status: ConverterCommandStatus): void { - const block = containerEl.createDiv({ cls: "ai3d-settings-status-block" }); - - block.createEl("strong", { - text: `${status.label}: ${status.available ? t("settings.diagnostics.available") : t("settings.diagnostics.notFound")}`, - }); - - const lines = [ - `${t("settings.diagnostics.sourceLabel")}: ${describeConverterCommandSource(status.source)}`, - `${t("settings.diagnostics.commandLabel")}: ${status.command}`, - status.resolvedPath && status.resolvedPath !== status.command ? `${t("settings.diagnostics.resolvedPathLabel")}: ${status.resolvedPath}` : "", - status.detail, - ].filter(Boolean); - - for (const line of lines) { - block.createDiv({ text: line }); - } - - for (const check of status.dependencyChecks ?? []) { - this.renderDependencyCheck(block, check); - } - } - - private renderDependencyCheck(containerEl: HTMLElement, check: ConverterDependencyCheck): void { - const label = (() => { - switch (check.kind) { - case "cad-python": - return t("settings.diagnostics.cadPythonCheck"); - case "mesh-python": - return t("settings.diagnostics.meshPythonCheck"); - case "freecadcmd-cli": - return t("settings.diagnostics.freecadCmdCheck"); - case "obj2gltf-cli": - return t("settings.diagnostics.obj2gltfCheck"); - case "fbx2gltf-cli": - return t("settings.diagnostics.fbx2gltfCheck"); - } - })(); - const summary = check.ok ? t("settings.diagnostics.selfCheckOk") : t("settings.diagnostics.selfCheckFailed"); - containerEl.createDiv({ text: `${t("settings.diagnostics.selfCheckLabel")}: ${label} - ${summary}` }); - if (check.detail) { - containerEl.createDiv({ text: check.detail }); - } - } -} + + if (mobile) { + containerEl.createEl("p", { cls: "setting-item-description", text: t("settings.mobileSupport.desc") }); + } else { + const converterMenuEl = createSecondaryMenu( + containerEl, + t("settings.converterMenu"), + t("settings.converterMenu.desc"), + ); + + new Setting(converterMenuEl) + .setName(t("settings.enableCad")) + .setDesc(t("settings.enableCad.desc")) + .addToggle((toggle) => { + const enabled = this.plugin.getSettings().enabledConverterIds.includes("freecad"); + return toggle.setValue(enabled).onChange((val) => { + const current = this.plugin.getSettings().enabledConverterIds; + const next = val + ? Array.from(new Set([...current, "freecad"])) + : current.filter((id) => id !== "freecad"); + this.plugin.updateSettings({ enabledConverterIds: next }); + }); + }); + + new Setting(converterMenuEl) + .setName(t("settings.enableObj2gltf")) + .setDesc(t("settings.enableObj2gltf.desc")) + .addToggle((toggle) => { + const enabled = this.plugin.getSettings().enabledConverterIds.includes("obj2gltf"); + return toggle.setValue(enabled).onChange((val) => { + const current = this.plugin.getSettings().enabledConverterIds; + const next = val + ? Array.from(new Set([...current, "obj2gltf"])) + : current.filter((id) => id !== "obj2gltf"); + this.plugin.updateSettings({ enabledConverterIds: next }); + }); + }); + + new Setting(converterMenuEl) + .setName(t("settings.preferObj2gltf")) + .setDesc(t("settings.preferObj2gltf.desc")) + .addToggle((toggle) => + toggle + .setValue(this.plugin.getSettings().preferObj2gltfForObj) + .onChange((val) => { + this.plugin.updateSettings({ preferObj2gltfForObj: val }); + }), + ); + + new Setting(converterMenuEl) + .setName(t("settings.enableFbx2gltf")) + .setDesc(t("settings.enableFbx2gltf.desc")) + .addToggle((toggle) => { + const enabled = this.plugin.getSettings().enabledConverterIds.includes("fbx2gltf"); + return toggle.setValue(enabled).onChange((val) => { + const current = this.plugin.getSettings().enabledConverterIds; + const next = val + ? Array.from(new Set([...current, "fbx2gltf"])) + : current.filter((id) => id !== "fbx2gltf"); + this.plugin.updateSettings({ enabledConverterIds: next }); + }); + }); + + new Setting(converterMenuEl) + .setName(t("settings.enableMesh")) + .setDesc(t("settings.enableMesh.desc")) + .addToggle((toggle) => { + const enabled = this.plugin.getSettings().enabledConverterIds.includes("assimp"); + return toggle.setValue(enabled).onChange((val) => { + const current = this.plugin.getSettings().enabledConverterIds; + const next = val + ? Array.from(new Set([...current, "assimp"])) + : current.filter((id) => id !== "assimp"); + this.plugin.updateSettings({ enabledConverterIds: next }); + }); + }); + + new Setting(converterMenuEl) + .setName(t("settings.enableSldprt")) + .setDesc(t("settings.enableSldprt.desc")) + .addToggle((toggle) => { + const enabled = this.plugin.getSettings().enabledConverterIds.includes("sldprt"); + return toggle.setValue(enabled).onChange((val) => { + const current = this.plugin.getSettings().enabledConverterIds; + const next = val + ? Array.from(new Set([...current, "sldprt"])) + : current.filter((id) => id !== "sldprt"); + this.plugin.updateSettings({ enabledConverterIds: next }); + }); + }); + + const diagnosticsMenuEl = createSecondaryMenu( + containerEl, + t("settings.environmentInspector"), + t("settings.environmentInspector.desc"), + ); + + // ── Converter Paths ────────────────────────────────────────── + + new Setting(diagnosticsMenuEl).setName(t("settings.paths")).setHeading(); + + new Setting(diagnosticsMenuEl) + .setName(t("settings.pythonCmd")) + .setDesc(t("settings.pythonCmd.desc")) + .addText((text) => + text + .setPlaceholder(commandPlaceholders.python) + .setValue(this.plugin.getSettings().freecadCommand) + .onChange((val) => { + this.plugin.updateSettings({ freecadCommand: val.trim() }); + resetCommandDiagnostics(); + }), + ); + + new Setting(diagnosticsMenuEl) + .setName(t("settings.freecadCmd")) + .setDesc(t("settings.freecadCmd.desc")) + .addText((text) => + text + .setPlaceholder(commandPlaceholders.freecad) + .setValue(this.plugin.getSettings().freecadcmdCommand) + .onChange((val) => { + this.plugin.updateSettings({ freecadcmdCommand: val.trim() }); + resetCommandDiagnostics(); + }), + ); + + new Setting(diagnosticsMenuEl) + .setName(t("settings.obj2gltfCmd")) + .setDesc(t("settings.obj2gltfCmd.desc")) + .addText((text) => + text + .setPlaceholder(commandPlaceholders.obj2gltf) + .setValue(this.plugin.getSettings().obj2gltfCommand) + .onChange((val) => { + this.plugin.updateSettings({ obj2gltfCommand: val.trim() }); + resetCommandDiagnostics(); + }), + ); + + new Setting(diagnosticsMenuEl) + .setName(t("settings.fbx2gltfCmd")) + .setDesc(t("settings.fbx2gltfCmd.desc")) + .addText((text) => + text + .setPlaceholder(commandPlaceholders.fbx2gltf) + .setValue(this.plugin.getSettings().fbx2gltfCommand) + .onChange((val) => { + this.plugin.updateSettings({ fbx2gltfCommand: val.trim() }); + resetCommandDiagnostics(); + }), + ); + + new Setting(diagnosticsMenuEl) + .setName(t("settings.assimpCmd")) + .setDesc(t("settings.assimpCmd.desc")) + .addText((text) => + text + .setPlaceholder(commandPlaceholders.python) + .setValue(this.plugin.getSettings().assimpCommand) + .onChange((val) => { + this.plugin.updateSettings({ assimpCommand: val.trim() }); + resetCommandDiagnostics(); + }), + ); + + // ── Diagnostics ────────────────────────────────────────────── + + const diagnosticsSetting = new Setting(diagnosticsMenuEl) + .setName(t("settings.diagnostics")) + .setDesc(t("settings.diagnostics.desc")); + + diagnosticsSetting.addButton((button) => + button + .setButtonText(t("settings.diagnostics.checkNow")) + .onClick(async () => { + button.setDisabled(true); + button.setButtonText(t("settings.diagnostics.checking")); + if (diagnosticsEl) { + await this.renderCommandDiagnostics(diagnosticsEl); + } + button.setButtonText(t("settings.diagnostics.checkNow")); + button.setDisabled(false); + new Notice(t("settings.diagnostics.refreshed")); + }), + ); + + diagnosticsEl = diagnosticsMenuEl.createDiv({ cls: "ai3d-settings-diagnostics" }); + resetCommandDiagnostics(); + + } + + // ── Performance ────────────────────────────────────────────── + + new Setting(containerEl).setName(t("settings.performance")).setHeading(); + + new Setting(containerEl) + .setName(t("settings.canvasHeight")) + .setDesc(t("settings.canvasHeight.desc")) + .addSlider((slider) => + slider + .setLimits(200, 800, 25) + .setValue(this.plugin.getSettings().defaultCanvasHeight) + .setDynamicTooltip() + .onChange((val) => { + this.plugin.updateSettings({ defaultCanvasHeight: val }); + }), + ); + + new Setting(containerEl) + .setName(t("settings.autoRotateSpeed")) + .setDesc(t("settings.autoRotateSpeed.desc")) + .addSlider((slider) => + slider + .setLimits(0.1, 2.0, 0.1) + .setValue(this.plugin.getSettings().autoRotateSpeed) + .setDynamicTooltip() + .onChange((val) => { + this.plugin.updateSettings({ autoRotateSpeed: val }); + }), + ); + + new Setting(containerEl) + .setName(t("settings.renderQuality")) + .setDesc(t("settings.renderQuality.desc")) + .addDropdown((dropdown) => + dropdown + .addOption("low", "Low") + .addOption("medium", "Medium") + .addOption("high", "High") + .setValue(this.plugin.getSettings().renderQuality) + .onChange((val: string) => { + this.plugin.updateSettings({ renderQuality: val as "low" | "medium" | "high" }); + }), + ); + + new Setting(containerEl) + .setName(t("settings.renderScale")) + .setDesc(t("settings.renderScale.desc")) + .addSlider((slider) => + slider + .setLimits(0.25, 2.0, 0.25) + .setValue(this.plugin.getSettings().renderScale) + .setDynamicTooltip() + .onChange((val) => { + this.plugin.updateSettings({ renderScale: val }); + }), + ); + } + + private async renderCommandDiagnostics(containerEl: HTMLElement): Promise { + const runId = ++this.diagnosticsRunId; + containerEl.empty(); + containerEl.createEl("p", { text: t("settings.diagnostics.checkingAvailability") }); + + const statuses = await inspectAllConverterCommands(this.plugin.getSettings()); + if (runId !== this.diagnosticsRunId) { + return; + } + + containerEl.empty(); + for (const status of statuses) { + this.renderCommandStatus(containerEl, status); + } + } + + private renderCommandStatus(containerEl: HTMLElement, status: ConverterCommandStatus): void { + const block = containerEl.createDiv({ cls: "ai3d-settings-status-block" }); + + block.createEl("strong", { + text: `${status.label}: ${status.available ? t("settings.diagnostics.available") : t("settings.diagnostics.notFound")}`, + }); + + const lines = [ + `${t("settings.diagnostics.sourceLabel")}: ${describeConverterCommandSource(status.source)}`, + `${t("settings.diagnostics.commandLabel")}: ${status.command}`, + status.resolvedPath && status.resolvedPath !== status.command ? `${t("settings.diagnostics.resolvedPathLabel")}: ${status.resolvedPath}` : "", + status.detail, + ].filter(Boolean); + + for (const line of lines) { + block.createDiv({ text: line }); + } + + for (const check of status.dependencyChecks ?? []) { + this.renderDependencyCheck(block, check); + } + } + + private renderDependencyCheck(containerEl: HTMLElement, check: ConverterDependencyCheck): void { + const label = (() => { + switch (check.kind) { + case "cad-python": + return t("settings.diagnostics.cadPythonCheck"); + case "mesh-python": + return t("settings.diagnostics.meshPythonCheck"); + case "freecadcmd-cli": + return t("settings.diagnostics.freecadCmdCheck"); + case "obj2gltf-cli": + return t("settings.diagnostics.obj2gltfCheck"); + case "fbx2gltf-cli": + return t("settings.diagnostics.fbx2gltfCheck"); + } + })(); + const summary = check.ok ? t("settings.diagnostics.selfCheckOk") : t("settings.diagnostics.selfCheckFailed"); + containerEl.createDiv({ text: `${t("settings.diagnostics.selfCheckLabel")}: ${label} - ${summary}` }); + if (check.detail) { + containerEl.createDiv({ text: check.detail }); + } + } +} diff --git a/src/view/inline/code-block.ts b/src/view/inline/code-block.ts index 55a62f8..6fba192 100644 --- a/src/view/inline/code-block.ts +++ b/src/view/inline/code-block.ts @@ -1,670 +1,670 @@ -import type { App, MarkdownPostProcessorContext } from "obsidian"; -import { isDisabledSplatExtension, isSupportedModelExtension, listSupportedModelExtensions } from "../../io/formats/registry"; -import type { PluginSettings, AnnotationPin } from "../../domain/models"; -import { AnnotationManager } from "../../render/preview/annotations"; -import type { PreviewGridRenderer } from "../../render/preview/grid"; -import { createLoggedGridRenderer, createLoggedModelPreview } from "../../render/preview/selection"; -import type { ModelPreview } from "../../render/preview/types"; -import { supportsAnnotationPreview, supportsMeasurementPreview } from "../../render/preview/types"; -import { readBinaryPath, resolveVaultAbsolutePath, resolveVaultPath } from "../../utils/resolve-path"; -import { getPreset, composeSections } from "../../render/presets"; -import { createHelperButtons, type HelperToolbar } from "./helper-buttons"; -import type { ThreeDBlockConfig, ModelConfig, GridBlockConfig, ComposeSection } from "../../domain/models"; -import { createConversionManager } from "../../io/conversion/factory"; -import type { ConvertedAssetCache } from "../../io/cache/converted-asset-cache"; -import { prepareModelInput } from "../../io/model-pipeline"; -import { toPreviewSource } from "../../io/preview/preview-source"; -import { listPreferredConversionExts } from "../../io/formats/route-preferences"; -import { createLoadingOverlay } from "./loading-overlay"; -import { createNoteReader } from "../../utils/note-reader"; -import { describeModelLoadFailure, isMissingConverterError } from "../../io/conversion/errors"; -import { formatT, t } from "../../i18n"; -import { renderModelLoadFailure, renderModelPerformanceFeedback } from "../model-load-feedback"; -import { isMobile } from "../../utils/device"; -import { createLogger } from "../../utils/log"; - -const log = createLogger("inline-code-block"); - -interface PreparedInlineModel { - sourcePath: string; - effectivePath: string; - effectiveExt: string; - model: ModelConfig; - warnings: string[]; -} - -async function prepareInlineModel( - app: App, - entry: string | ModelConfig, - settings: PluginSettings, - convertedAssetCache: ConvertedAssetCache, -): Promise { - const inputModel = typeof entry === "string" ? { path: entry } : entry; - const sourcePath = resolveVaultPath(app, inputModel.path); - if (!sourcePath) { - throw new Error(formatT("workbench.fileNotFound", { path: inputModel.path })); - } - - const sourceExt = sourcePath.split(".").pop()?.toLowerCase() ?? ""; - if (!isSupportedModelExtension(sourceExt)) { - if (isDisabledSplatExtension(sourceExt)) { - throw new Error(t("codeBlock.splatDisabled")); - } - throw new Error(formatT("codeBlock.unsupportedFormat", { - ext: `.${sourceExt}`, - formats: listSupportedModelExtensions().join(", "), - })); - } - - const absolutePath = resolveVaultAbsolutePath(app, sourcePath) ?? undefined; - const conversionManager = createConversionManager(settings); - const prepared = await prepareModelInput({ - path: sourcePath, - absolutePath, - preferConversionExts: listPreferredConversionExts(settings), - conversionManager, - convertedAssetCache, - }); - const source = toPreviewSource(prepared); - - return { - sourcePath, - effectivePath: source.path, - effectiveExt: source.ext, - warnings: source.warnings, - model: { - ...inputModel, - path: source.path, - }, - }; -} - -async function prepareInlineSection( - app: App, - section: ComposeSection, - settings: PluginSettings, - convertedAssetCache: ConvertedAssetCache, -): Promise { - const models: ModelConfig[] = []; - for (const entry of section.models) { - const prepared = await prepareInlineModel(app, entry, settings, convertedAssetCache); - models.push(prepared.model); - } - - return { - ...section, - models, - }; -} - -function appendMobileInlineHint(parent: HTMLElement): void { - if (!isMobile()) return; - parent.createDiv({ cls: "ai3d-mobile-mode-hint ai3d-mobile-mode-hint--inline", text: t("codeBlock.mobileHint") }); -} - -/** - * Register the ```3d code block processor. - * - * Supports two formats: - * - * Simple: ```3d path/to/model.glb``` - * JSON: ```3d - * { "models": [{ "path": "model.glb" }], "scene": { "autoRotate": true } } - * ``` - */ -export function registerCodeBlockProcessor( - app: App, - getSettings: () => PluginSettings, - convertedAssetCache: ConvertedAssetCache, - getAnnotations?: (modelPath: string) => AnnotationPin[], -) { - return { - id: "3d", - handler: ( - source: string, - el: HTMLElement, - _ctx: MarkdownPostProcessorContext, - ) => { - const trimmed = source.trim(); - if (!trimmed) { - el.createDiv({ cls: "ai3d-inline-empty", text: t("codeBlock.noModelPathOrConfig") }); - return; - } - - // Determine format: JSON object or simple path - let config: ThreeDBlockConfig; - const isJson = trimmed.startsWith("{") || trimmed.startsWith("["); - - if (isJson) { - try { - const parsed = JSON.parse(trimmed) as unknown; - config = normalizeConfig(parsed); - } catch (err) { - const errorEl = el.createDiv({ cls: "ai3d-json-error" }); - const lineMatch = String(err).match(/position\s+(\d+)/); - let errorMsg = formatT("codeBlock.jsonParseError", { error: String(err) }); - if (lineMatch) { - const pos = parseInt(lineMatch[1], 10); - const lines = trimmed.substring(0, pos).split("\n"); - errorMsg += formatT("codeBlock.jsonParseLine", { line: String(lines.length) }); - } - errorEl.createEl("pre", { text: errorMsg }); - return; - } - } else { - // Simple path format - config = { models: [{ path: trimmed }] }; - } - - if (!config.models || config.models.length === 0) { - el.createDiv({ cls: "ai3d-inline-empty", text: t("codeBlock.noModelsInConfig") }); - return; - } - - // Validate first model path (for now, single model inline preview) - if (config.models.length > 1) { - console.warn(`[AI3D] \`\`\`3d only supports one model; ${config.models.length - 1} additional models ignored. Use \`\`\`3dgrid for multi-model.`); - } - const modelCfg = config.models[0]; - const modelPath = resolveVaultPath(app,modelCfg.path); - if (!modelPath) { - el.createDiv({ - cls: "ai3d-inline-empty", - text: formatT("workbench.fileNotFound", { path: modelCfg.path }), - }); - return; - } - - const ext = modelPath.split(".").pop()?.toLowerCase() ?? ""; - if (!isSupportedModelExtension(ext)) { - el.createDiv({ - cls: "ai3d-inline-empty", - text: isDisabledSplatExtension(ext) ? t("codeBlock.splatDisabled") : formatT("codeBlock.unsupportedFormat", { - ext: `.${ext}`, - formats: listSupportedModelExtensions().join(", "), - }), - }); - return; - } - - // Create preview host with custom dimensions - const settings = getSettings(); - const host = el.createDiv({ cls: "ai3d-preview-host" }); - if (config.height) { - host.style.setProperty("--min-height", typeof config.height === "number" ? `${config.height}px` : config.height); - } - if (config.width) { - host.style.setProperty("--max-width", typeof config.width === "number" ? `${config.width}px` : config.width); - } - - const canvas = host.createEl("canvas", { cls: "ai3d-canvas-full" }); - canvas.tabIndex = 0; - canvas.addEventListener("keydown", (e) => { - if (destroyed || !preview) return; - const key = e.key.toLowerCase(); - if (key === "r") { preview.resetView?.(); e.preventDefault(); } - else if (key === "w") { preview.toggleWireframe?.(); e.preventDefault(); } - else if (key === "g") { preview.toggleOrientationGizmo?.(); e.preventDefault(); } - else if (key === "b") { preview.toggleBoundingBox?.(); e.preventDefault(); } - else if (key === " ") { preview.toggleAnimation?.(); e.preventDefault(); } - else if (key === "m") { if (supportsMeasurementPreview(preview)) { preview.toggleMeasurement(); } e.preventDefault(); } - }); - host.appendChild(canvas); - - // Add helper buttons - let preview: ModelPreview | null = null; - let annotationMgr: AnnotationManager | null = null; - let annotationVisible = true; - let destroyed = false; - let loaded = false; - - const toolbar: HelperToolbar = createHelperButtons(el, host, app, () => preview, () => modelPath, () => { - if (destroyed) return; - destroyed = true; - observer.disconnect(); - io.disconnect(); - annotationMgr?.destroy(); - annotationMgr = null; - preview?.destroy(); - preview = null; - host.remove(); - }, getSettings, () => { - annotationVisible = !annotationVisible; - if (annotationMgr) { - const overlay = host.querySelector(".ai3d-annotation-overlay"); - if (overlay) overlay.classList.toggle("is-hidden", !annotationVisible); - } - return annotationVisible; - }, undefined, { - labelKey: "helper.toggleAnnotationsVisibilityLabel", - activeTooltipKey: "helper.annotationsVisible", - inactiveTooltipKey: "helper.annotationsHidden", - }); - appendMobileInlineHint(el); - - // Auto-destroy when the DOM element is removed - const observer = new MutationObserver(() => { - if (destroyed) return; - if (!el.contains(host)) { - destroyed = true; - observer.disconnect(); - io.disconnect(); - annotationMgr?.destroy(); - annotationMgr = null; - preview?.destroy(); - preview = null; - } - }); - observer.observe(el, { childList: true }); - - async function loadPreview() { - if (loaded || destroyed || !modelPath) return; - loaded = true; - - const loading = createLoadingOverlay(host); - - try { - const absolutePath = resolveVaultAbsolutePath(app, modelPath) ?? undefined; - const conversionManager = createConversionManager(settings); - loading.setPhaseKey("loading.preparingModel"); - const prepared = await prepareModelInput({ - path: modelPath, - absolutePath, - preferConversionExts: listPreferredConversionExts(settings), - conversionManager, - convertedAssetCache, - }); - const source = toPreviewSource(prepared); - const pins = getAnnotations?.(modelPath) ?? []; - const previewOptions = { - ext: source.ext, - annotationMode: pins.length > 0 ? "readonly" : "none", - rendererRollout: settings.previewRendererRollout, - useThreeRenderer: settings.useThreeRenderer, - } as const; - const { preview: nextPreview } = await createLoggedModelPreview( - log, - { surface: "code-block", modelPath }, - canvas, - previewOptions, - ); - preview = nextPreview; - toolbar.syncCapabilities(); - loading.setPhaseKey("loading.loadingModel"); - const data = await readBinaryPath(app, source.path); - const readFile = async (p: string) => readBinaryPath(app, p); - - if (destroyed) { loading.hide(); return; } - const summary = await preview.loadModel(data, source.ext, readFile, source.path); - loading.setProgress(100); - renderModelPerformanceFeedback(host, summary); - - if (destroyed) { loading.hide(); return; } - if (config.scene?.autoRotate === undefined && settings.autoRotateDefault) { - config.scene = { ...config.scene, autoRotate: true, autoRotateSpeed: settings.autoRotateSpeed }; - } - preview.applyConfig(config); - preview.setRenderQuality?.(settings.renderQuality, settings.renderScale); - toolbar.syncCapabilities(); - - // Readonly annotations - if (pins.length > 0 && supportsAnnotationPreview(preview)) { - const provider = preview.getAnnotationProvider(); - if (provider.canvas) { - annotationMgr = new AnnotationManager( - provider, - host, - "readonly", - pins, - undefined, - createNoteReader(app), - undefined, - { - app, - previewMode: settings.annotationPreviewMode, - displayMode: settings.annotationDisplayMode, - }, - ); - toolbar.showAnnotateButton(); - toolbar.updateAnnotationBadge(pins.length); - } - } - - if (ext === "stl" && modelCfg.color) { - preview.setSTLColor?.(modelCfg.color); - } - if (ext === "stl" && modelCfg.wireframe !== undefined) { - preview.setWireframe?.(modelCfg.wireframe); - } - - if (preview.hasAnimations?.()) { - toolbar.showAnimButton(); - } - - loading.hide(); - } catch (err) { - destroyed = true; - observer.disconnect(); - io.disconnect(); - loading.hide(); - preview?.destroy(); - preview = null; - host.replaceChildren(); - const failure = describeModelLoadFailure(err); - if (isMissingConverterError(err)) { - console.warn("[AI3D] Inline preview blocked by converter settings:", failure.message); - } else { - console.error("[AI3D] Inline preview failed:", err); - } - renderModelLoadFailure(host, failure); - } - } - - // Lazy-load: only create Engine when scrolled into view - const io = new IntersectionObserver((entries) => { - for (const entry of entries) { - if (entry.isIntersecting) { - io.disconnect(); - void loadPreview(); - } - } - }, { rootMargin: "200px" }); - io.observe(host); - }, - }; -} - -/** - * Normalize a raw parsed JSON object into ThreeDBlockConfig. - * Handles both single-model shorthand and full config. - */ -function normalizeConfig(raw: unknown): ThreeDBlockConfig { - // If it's a string, treat as simple path - if (typeof raw === "string") { - return { models: [{ path: raw }] }; - } - - if (typeof raw !== "object" || raw === null) { - return { models: [] }; - } - - const obj = raw as Record; - - // If it has a "path" property at top level, it's a single model config - if (typeof obj.path === "string") { - return { - models: [{ path: obj.path, color: obj.color as string | undefined, wireframe: obj.wireframe as boolean | undefined }], - camera: obj.camera as ThreeDBlockConfig["camera"], - lights: obj.lights as ThreeDBlockConfig["lights"], - scene: obj.scene as ThreeDBlockConfig["scene"], - stl: obj.stl as ThreeDBlockConfig["stl"], - width: obj.width as number | string | undefined, - height: obj.height as number | string | undefined, - }; - } - - // Full config with models array - const models: ModelConfig[] = Array.isArray(obj.models) - ? obj.models - .filter((m: unknown) => { - const p = typeof m === "string" ? m : m && typeof m === "object" && "path" in m ? (m as Record).path : undefined; - return typeof p === "string" && p.length > 0; - }) - .map((m: unknown) => { - if (typeof m === "string") return { path: m }; - const mo = m as Record; - return { path: mo.path as string, color: mo.color as string | undefined, wireframe: mo.wireframe as boolean | undefined }; - }) - : []; - - return { - models, - camera: obj.camera as ThreeDBlockConfig["camera"], - lights: obj.lights as ThreeDBlockConfig["lights"], - scene: obj.scene as ThreeDBlockConfig["scene"], - stl: obj.stl as ThreeDBlockConfig["stl"], - width: obj.width as number | string | undefined, - height: obj.height as number | string | undefined, - }; -} - -/** - * Register the ```3dgrid code block processor. - * - * Renders multiple models in a single Babylon Scene using per-cell viewports. - * One Engine / one WebGL context — no context limit risk. - * - * JSON config: - * ```3dgrid - * { "models": ["a.glb", "b.glb", "c.glb"], "columns": 3, "rowHeight": 300 } - * ``` - */ -export function registerGridCodeBlockProcessor( - app: App, - getSettings: () => PluginSettings, - convertedAssetCache: ConvertedAssetCache, -) { - return { - id: "3dgrid", - handler: ( - source: string, - el: HTMLElement, - _ctx: MarkdownPostProcessorContext, - ) => { - const trimmed = source.trim(); - if (!trimmed) { - el.createDiv({ cls: "ai3d-inline-empty", text: t("codeBlock.noConfigSpecified") }); - return; - } - - let config: GridBlockConfig; - try { - config = JSON.parse(trimmed) as GridBlockConfig; - } catch (err) { - const errorEl = el.createDiv({ cls: "ai3d-json-error" }); - errorEl.createEl("pre", { text: `JSON parse error: ${String(err)}` }); - return; - } - - if (config.preset !== "compose" && (!config.models || config.models.length === 0)) { - el.createDiv({ cls: "ai3d-inline-empty", text: t("codeBlock.noModelsSpecified") }); - return; - } - - const settings = getSettings(); - const gridLoading = createLoadingOverlay(el); - - void (async () => { - const preparedModels: PreparedInlineModel[] = []; - for (const entry of config.models ?? []) { - try { - const prepared = await prepareInlineModel(app, entry, settings, convertedAssetCache); - preparedModels.push(prepared); - } catch (err) { - gridLoading.hide(); - el.createDiv({ - cls: "ai3d-inline-empty", - text: err instanceof Error ? err.message : String(err), - }); - return; - } - } - const resolved: ModelConfig[] = preparedModels.map((item) => item.model); - let helperSourcePath = preparedModels[0]?.sourcePath ?? ""; - - // Create grid container - const gridHost = el.createDiv({ cls: "ai3d-grid-host" }); - const canvas = gridHost.createEl("canvas"); - canvas.tabIndex = 0; - canvas.addEventListener("keydown", (e) => { - if (destroyed || !renderer) return; - const key = e.key.toLowerCase(); - if (key === "r") { renderer.resetView?.(); e.preventDefault(); } - else if (key === "w") { renderer.toggleWireframe?.(); e.preventDefault(); } - }); - gridHost.appendChild(canvas); - - // Height controlled by CSS max-height only; rowHeight sets inline height (capped by CSS max-height) - if (typeof config.rowHeight === "number") { - const rows = config.preset === "compose" ? 1 : Math.ceil(resolved.length / (config.columns ?? Math.min(resolved.length, 3))); - gridHost.style.setProperty("--grid-height", `${config.rowHeight * rows}px`); - } - - let renderer: PreviewGridRenderer | null = null; - let destroyed = false; - let loaded = false; - - const gridToolbar: HelperToolbar = createHelperButtons(el, gridHost, app, () => renderer, () => helperSourcePath, () => { - if (destroyed) return; - destroyed = true; - observer.disconnect(); - gridIo.disconnect(); - renderer?.destroy(); - renderer = null; - gridHost.remove(); - }, getSettings); - appendMobileInlineHint(el); - - const observer = new MutationObserver(() => { - if (destroyed) return; - if (!el.contains(gridHost)) { - destroyed = true; - observer.disconnect(); - gridIo.disconnect(); - renderer?.destroy(); - renderer = null; - } - }); - observer.observe(el, { childList: true }); - - async function loadGrid() { - if (loaded || destroyed) return; - loaded = true; - gridLoading.setPhaseKey("codeBlock.renderingGrid"); - gridLoading.setProgress(-1); - - try { - const { renderer: nextRenderer } = await createLoggedGridRenderer( - log, - { - surface: "3dgrid", - preset: config.preset ?? "compare", - modelCount: config.models?.length ?? 0, - }, - canvas, - ); - renderer = nextRenderer; - gridToolbar.syncCapabilities(); - const activeRenderer = renderer; - const readFile = async (path: string) => readBinaryPath(app, path); - - if (config.preset === "compose") { - if (!config.sections || config.sections.length === 0) { - gridLoading.hide(); - gridHost.createDiv({ cls: "ai3d-inline-empty", text: t("codeBlock.composeRequiresSections") }); - renderer.destroy(); - renderer = null; - return; - } - const preparedSections: ComposeSection[] = []; - for (const section of config.sections) { - try { - if (!helperSourcePath) { - const firstEntry = section.models[0]; - if (firstEntry) { - const rawPath = typeof firstEntry === "string" ? firstEntry : firstEntry.path; - helperSourcePath = resolveVaultPath(app, rawPath) ?? rawPath; - } - } - const preparedSection = await prepareInlineSection(app, section, settings, convertedAssetCache); - preparedSections.push(preparedSection); - } catch (err) { - gridLoading.hide(); - gridHost.createDiv({ - cls: "ai3d-inline-empty", - text: err instanceof Error ? err.message : String(err), - }); - activeRenderer.destroy(); - renderer = null; - return; - } - } - const result = composeSections( - preparedSections, - config.direction ?? "horizontal", - Number(config.params?.gap) || 0.02, - (entry) => { - if (typeof entry === "string") return null; - return entry; - }, - getPreset, - ); - if (!result) { - gridLoading.hide(); - gridHost.createDiv({ cls: "ai3d-inline-empty", text: t("codeBlock.composeNoValidSections") }); - activeRenderer.destroy(); - renderer = null; - return; - } - await activeRenderer.loadWithPreset(result, readFile); - } else if (config.preset) { - const preset = getPreset(config.preset); - if (!preset) { - gridLoading.hide(); - gridHost.createDiv({ - cls: "ai3d-inline-empty", - text: formatT("codeBlock.unknownPreset", { preset: config.preset }), - }); - activeRenderer.destroy(); - renderer = null; - return; - } - const result = preset.compute(resolved, config.params ?? {}); - if (!result) { - gridLoading.hide(); - gridHost.createDiv({ - cls: "ai3d-inline-empty", - text: formatT("codeBlock.presetRequiresModels", { - preset: config.preset, - min: String(preset.minModels), - max: String(preset.maxModels), - count: String(resolved.length), - }), - }); - activeRenderer.destroy(); - renderer = null; - return; - } - await activeRenderer.loadWithPreset(result, readFile); - } else { - await activeRenderer.loadModels(resolved, config, readFile); - } - - if (destroyed) { gridLoading.hide(); return; } - gridLoading.hide(); - } catch (err) { - destroyed = true; - observer.disconnect(); - gridIo.disconnect(); - gridLoading.hide(); - renderer?.destroy(); - renderer = null; - console.error("[AI3D Grid] Failed:", err); - gridHost.createDiv({ cls: "ai3d-inline-empty", text: formatT("codeBlock.gridFailed", { reason: String(err) }) }); - } - } - - // Lazy-load: only create Engine when scrolled into view - const gridIo = new IntersectionObserver((entries) => { - for (const entry of entries) { - if (entry.isIntersecting) { - gridIo.disconnect(); - void loadGrid(); - } - } - }, { rootMargin: "200px" }); - gridIo.observe(gridHost); - })(); // end async IIFE - }, - }; -} +import type { App, MarkdownPostProcessorContext } from "obsidian"; +import { isDisabledSplatExtension, isSupportedModelExtension, listSupportedModelExtensions } from "../../io/formats/registry"; +import type { PluginSettings, AnnotationPin } from "../../domain/models"; +import { AnnotationManager } from "../../render/preview/annotations"; +import type { PreviewGridRenderer } from "../../render/preview/grid"; +import { createLoggedGridRenderer, createLoggedModelPreview } from "../../render/preview/selection"; +import type { ModelPreview } from "../../render/preview/types"; +import { supportsAnnotationPreview, supportsMeasurementPreview } from "../../render/preview/types"; +import { readBinaryPath, resolveVaultAbsolutePath, resolveVaultPath } from "../../utils/resolve-path"; +import { getPreset, composeSections } from "../../render/presets"; +import { createHelperButtons, type HelperToolbar } from "./helper-buttons"; +import type { ThreeDBlockConfig, ModelConfig, GridBlockConfig, ComposeSection } from "../../domain/models"; +import { createConversionManager } from "../../io/conversion/factory"; +import type { ConvertedAssetCache } from "../../io/cache/converted-asset-cache"; +import { prepareModelInput } from "../../io/model-pipeline"; +import { toPreviewSource } from "../../io/preview/preview-source"; +import { listPreferredConversionExts } from "../../io/formats/route-preferences"; +import { createLoadingOverlay } from "./loading-overlay"; +import { createNoteReader } from "../../utils/note-reader"; +import { describeModelLoadFailure, isMissingConverterError } from "../../io/conversion/errors"; +import { formatT, t } from "../../i18n"; +import { renderModelLoadFailure, renderModelPerformanceFeedback } from "../model-load-feedback"; +import { isMobile } from "../../utils/device"; +import { createLogger } from "../../utils/log"; + +const log = createLogger("inline-code-block"); + +interface PreparedInlineModel { + sourcePath: string; + effectivePath: string; + effectiveExt: string; + model: ModelConfig; + warnings: string[]; +} + +async function prepareInlineModel( + app: App, + entry: string | ModelConfig, + settings: PluginSettings, + convertedAssetCache: ConvertedAssetCache, +): Promise { + const inputModel = typeof entry === "string" ? { path: entry } : entry; + const sourcePath = resolveVaultPath(app, inputModel.path); + if (!sourcePath) { + throw new Error(formatT("workbench.fileNotFound", { path: inputModel.path })); + } + + const sourceExt = sourcePath.split(".").pop()?.toLowerCase() ?? ""; + if (!isSupportedModelExtension(sourceExt)) { + if (isDisabledSplatExtension(sourceExt)) { + throw new Error(t("codeBlock.splatDisabled")); + } + throw new Error(formatT("codeBlock.unsupportedFormat", { + ext: `.${sourceExt}`, + formats: listSupportedModelExtensions().join(", "), + })); + } + + const absolutePath = resolveVaultAbsolutePath(app, sourcePath) ?? undefined; + const conversionManager = createConversionManager(settings); + const prepared = await prepareModelInput({ + path: sourcePath, + absolutePath, + preferConversionExts: listPreferredConversionExts(settings), + conversionManager, + convertedAssetCache, + }); + const source = toPreviewSource(prepared); + + return { + sourcePath, + effectivePath: source.path, + effectiveExt: source.ext, + warnings: source.warnings, + model: { + ...inputModel, + path: source.path, + }, + }; +} + +async function prepareInlineSection( + app: App, + section: ComposeSection, + settings: PluginSettings, + convertedAssetCache: ConvertedAssetCache, +): Promise { + const models: ModelConfig[] = []; + for (const entry of section.models) { + const prepared = await prepareInlineModel(app, entry, settings, convertedAssetCache); + models.push(prepared.model); + } + + return { + ...section, + models, + }; +} + +function appendMobileInlineHint(parent: HTMLElement): void { + if (!isMobile()) return; + parent.createDiv({ cls: "ai3d-mobile-mode-hint ai3d-mobile-mode-hint--inline", text: t("codeBlock.mobileHint") }); +} + +/** + * Register the ```3d code block processor. + * + * Supports two formats: + * + * Simple: ```3d path/to/model.glb``` + * JSON: ```3d + * { "models": [{ "path": "model.glb" }], "scene": { "autoRotate": true } } + * ``` + */ +export function registerCodeBlockProcessor( + app: App, + getSettings: () => PluginSettings, + convertedAssetCache: ConvertedAssetCache, + getAnnotations?: (modelPath: string) => AnnotationPin[], +) { + return { + id: "3d", + handler: ( + source: string, + el: HTMLElement, + _ctx: MarkdownPostProcessorContext, + ) => { + const trimmed = source.trim(); + if (!trimmed) { + el.createDiv({ cls: "ai3d-inline-empty", text: t("codeBlock.noModelPathOrConfig") }); + return; + } + + // Determine format: JSON object or simple path + let config: ThreeDBlockConfig; + const isJson = trimmed.startsWith("{") || trimmed.startsWith("["); + + if (isJson) { + try { + const parsed = JSON.parse(trimmed) as unknown; + config = normalizeConfig(parsed); + } catch (err) { + const errorEl = el.createDiv({ cls: "ai3d-json-error" }); + const lineMatch = String(err).match(/position\s+(\d+)/); + let errorMsg = formatT("codeBlock.jsonParseError", { error: String(err) }); + if (lineMatch) { + const pos = parseInt(lineMatch[1], 10); + const lines = trimmed.substring(0, pos).split("\n"); + errorMsg += formatT("codeBlock.jsonParseLine", { line: String(lines.length) }); + } + errorEl.createEl("pre", { text: errorMsg }); + return; + } + } else { + // Simple path format + config = { models: [{ path: trimmed }] }; + } + + if (!config.models || config.models.length === 0) { + el.createDiv({ cls: "ai3d-inline-empty", text: t("codeBlock.noModelsInConfig") }); + return; + } + + // Validate first model path (for now, single model inline preview) + if (config.models.length > 1) { + console.warn(`[AI3D] \`\`\`3d only supports one model; ${config.models.length - 1} additional models ignored. Use \`\`\`3dgrid for multi-model.`); + } + const modelCfg = config.models[0]; + const modelPath = resolveVaultPath(app,modelCfg.path); + if (!modelPath) { + el.createDiv({ + cls: "ai3d-inline-empty", + text: formatT("workbench.fileNotFound", { path: modelCfg.path }), + }); + return; + } + + const ext = modelPath.split(".").pop()?.toLowerCase() ?? ""; + if (!isSupportedModelExtension(ext)) { + el.createDiv({ + cls: "ai3d-inline-empty", + text: isDisabledSplatExtension(ext) ? t("codeBlock.splatDisabled") : formatT("codeBlock.unsupportedFormat", { + ext: `.${ext}`, + formats: listSupportedModelExtensions().join(", "), + }), + }); + return; + } + + // Create preview host with custom dimensions + const settings = getSettings(); + const host = el.createDiv({ cls: "ai3d-preview-host" }); + if (config.height) { + host.style.setProperty("--min-height", typeof config.height === "number" ? `${config.height}px` : config.height); + } + if (config.width) { + host.style.setProperty("--max-width", typeof config.width === "number" ? `${config.width}px` : config.width); + } + + const canvas = host.createEl("canvas", { cls: "ai3d-canvas-full" }); + canvas.tabIndex = 0; + canvas.addEventListener("keydown", (e) => { + if (destroyed || !preview) return; + const key = e.key.toLowerCase(); + if (key === "r") { preview.resetView?.(); e.preventDefault(); } + else if (key === "w") { preview.toggleWireframe?.(); e.preventDefault(); } + else if (key === "g") { preview.toggleOrientationGizmo?.(); e.preventDefault(); } + else if (key === "b") { preview.toggleBoundingBox?.(); e.preventDefault(); } + else if (key === " ") { preview.toggleAnimation?.(); e.preventDefault(); } + else if (key === "m") { if (supportsMeasurementPreview(preview)) { preview.toggleMeasurement(); } e.preventDefault(); } + }); + host.appendChild(canvas); + + // Add helper buttons + let preview: ModelPreview | null = null; + let annotationMgr: AnnotationManager | null = null; + let annotationVisible = true; + let destroyed = false; + let loaded = false; + + const toolbar: HelperToolbar = createHelperButtons(el, host, app, () => preview, () => modelPath, () => { + if (destroyed) return; + destroyed = true; + observer.disconnect(); + io.disconnect(); + annotationMgr?.destroy(); + annotationMgr = null; + preview?.destroy(); + preview = null; + host.remove(); + }, getSettings, () => { + annotationVisible = !annotationVisible; + if (annotationMgr) { + const overlay = host.querySelector(".ai3d-annotation-overlay"); + if (overlay) overlay.classList.toggle("is-hidden", !annotationVisible); + } + return annotationVisible; + }, undefined, { + labelKey: "helper.toggleAnnotationsVisibilityLabel", + activeTooltipKey: "helper.annotationsVisible", + inactiveTooltipKey: "helper.annotationsHidden", + }); + appendMobileInlineHint(el); + + // Auto-destroy when the DOM element is removed + const observer = new MutationObserver(() => { + if (destroyed) return; + if (!el.contains(host)) { + destroyed = true; + observer.disconnect(); + io.disconnect(); + annotationMgr?.destroy(); + annotationMgr = null; + preview?.destroy(); + preview = null; + } + }); + observer.observe(el, { childList: true }); + + async function loadPreview() { + if (loaded || destroyed || !modelPath) return; + loaded = true; + + const loading = createLoadingOverlay(host); + + try { + const absolutePath = resolveVaultAbsolutePath(app, modelPath) ?? undefined; + const conversionManager = createConversionManager(settings); + loading.setPhaseKey("loading.preparingModel"); + const prepared = await prepareModelInput({ + path: modelPath, + absolutePath, + preferConversionExts: listPreferredConversionExts(settings), + conversionManager, + convertedAssetCache, + }); + const source = toPreviewSource(prepared); + const pins = getAnnotations?.(modelPath) ?? []; + const previewOptions = { + ext: source.ext, + annotationMode: pins.length > 0 ? "readonly" : "none", + rendererRollout: settings.previewRendererRollout, + useThreeRenderer: settings.useThreeRenderer, + } as const; + const { preview: nextPreview } = await createLoggedModelPreview( + log, + { surface: "code-block", modelPath }, + canvas, + previewOptions, + ); + preview = nextPreview; + toolbar.syncCapabilities(); + loading.setPhaseKey("loading.loadingModel"); + const data = await readBinaryPath(app, source.path); + const readFile = async (p: string) => readBinaryPath(app, p); + + if (destroyed) { loading.hide(); return; } + const summary = await preview.loadModel(data, source.ext, readFile, source.path); + loading.setProgress(100); + renderModelPerformanceFeedback(host, summary); + + if (destroyed) { loading.hide(); return; } + if (config.scene?.autoRotate === undefined && settings.autoRotateDefault) { + config.scene = { ...config.scene, autoRotate: true, autoRotateSpeed: settings.autoRotateSpeed }; + } + preview.applyConfig(config); + preview.setRenderQuality?.(settings.renderQuality, settings.renderScale); + toolbar.syncCapabilities(); + + // Readonly annotations + if (pins.length > 0 && supportsAnnotationPreview(preview)) { + const provider = preview.getAnnotationProvider(); + if (provider.canvas) { + annotationMgr = new AnnotationManager( + provider, + host, + "readonly", + pins, + undefined, + createNoteReader(app), + undefined, + { + app, + previewMode: settings.annotationPreviewMode, + displayMode: settings.annotationDisplayMode, + }, + ); + toolbar.showAnnotateButton(); + toolbar.updateAnnotationBadge(pins.length); + } + } + + if (ext === "stl" && modelCfg.color) { + preview.setSTLColor?.(modelCfg.color); + } + if (ext === "stl" && modelCfg.wireframe !== undefined) { + preview.setWireframe?.(modelCfg.wireframe); + } + + if (preview.hasAnimations?.()) { + toolbar.showAnimButton(); + } + + loading.hide(); + } catch (err) { + destroyed = true; + observer.disconnect(); + io.disconnect(); + loading.hide(); + preview?.destroy(); + preview = null; + host.replaceChildren(); + const failure = describeModelLoadFailure(err); + if (isMissingConverterError(err)) { + console.warn("[AI3D] Inline preview blocked by converter settings:", failure.message); + } else { + console.error("[AI3D] Inline preview failed:", err); + } + renderModelLoadFailure(host, failure); + } + } + + // Lazy-load: only create Engine when scrolled into view + const io = new IntersectionObserver((entries) => { + for (const entry of entries) { + if (entry.isIntersecting) { + io.disconnect(); + void loadPreview(); + } + } + }, { rootMargin: "200px" }); + io.observe(host); + }, + }; +} + +/** + * Normalize a raw parsed JSON object into ThreeDBlockConfig. + * Handles both single-model shorthand and full config. + */ +function normalizeConfig(raw: unknown): ThreeDBlockConfig { + // If it's a string, treat as simple path + if (typeof raw === "string") { + return { models: [{ path: raw }] }; + } + + if (typeof raw !== "object" || raw === null) { + return { models: [] }; + } + + const obj = raw as Record; + + // If it has a "path" property at top level, it's a single model config + if (typeof obj.path === "string") { + return { + models: [{ path: obj.path, color: obj.color as string | undefined, wireframe: obj.wireframe as boolean | undefined }], + camera: obj.camera as ThreeDBlockConfig["camera"], + lights: obj.lights as ThreeDBlockConfig["lights"], + scene: obj.scene as ThreeDBlockConfig["scene"], + stl: obj.stl as ThreeDBlockConfig["stl"], + width: obj.width as number | string | undefined, + height: obj.height as number | string | undefined, + }; + } + + // Full config with models array + const models: ModelConfig[] = Array.isArray(obj.models) + ? obj.models + .filter((m: unknown) => { + const p = typeof m === "string" ? m : m && typeof m === "object" && "path" in m ? (m as Record).path : undefined; + return typeof p === "string" && p.length > 0; + }) + .map((m: unknown) => { + if (typeof m === "string") return { path: m }; + const mo = m as Record; + return { path: mo.path as string, color: mo.color as string | undefined, wireframe: mo.wireframe as boolean | undefined }; + }) + : []; + + return { + models, + camera: obj.camera as ThreeDBlockConfig["camera"], + lights: obj.lights as ThreeDBlockConfig["lights"], + scene: obj.scene as ThreeDBlockConfig["scene"], + stl: obj.stl as ThreeDBlockConfig["stl"], + width: obj.width as number | string | undefined, + height: obj.height as number | string | undefined, + }; +} + +/** + * Register the ```3dgrid code block processor. + * + * Renders multiple models in a single Babylon Scene using per-cell viewports. + * One Engine / one WebGL context — no context limit risk. + * + * JSON config: + * ```3dgrid + * { "models": ["a.glb", "b.glb", "c.glb"], "columns": 3, "rowHeight": 300 } + * ``` + */ +export function registerGridCodeBlockProcessor( + app: App, + getSettings: () => PluginSettings, + convertedAssetCache: ConvertedAssetCache, +) { + return { + id: "3dgrid", + handler: ( + source: string, + el: HTMLElement, + _ctx: MarkdownPostProcessorContext, + ) => { + const trimmed = source.trim(); + if (!trimmed) { + el.createDiv({ cls: "ai3d-inline-empty", text: t("codeBlock.noConfigSpecified") }); + return; + } + + let config: GridBlockConfig; + try { + config = JSON.parse(trimmed) as GridBlockConfig; + } catch (err) { + const errorEl = el.createDiv({ cls: "ai3d-json-error" }); + errorEl.createEl("pre", { text: `JSON parse error: ${String(err)}` }); + return; + } + + if (config.preset !== "compose" && (!config.models || config.models.length === 0)) { + el.createDiv({ cls: "ai3d-inline-empty", text: t("codeBlock.noModelsSpecified") }); + return; + } + + const settings = getSettings(); + const gridLoading = createLoadingOverlay(el); + + void (async () => { + const preparedModels: PreparedInlineModel[] = []; + for (const entry of config.models ?? []) { + try { + const prepared = await prepareInlineModel(app, entry, settings, convertedAssetCache); + preparedModels.push(prepared); + } catch (err) { + gridLoading.hide(); + el.createDiv({ + cls: "ai3d-inline-empty", + text: err instanceof Error ? err.message : String(err), + }); + return; + } + } + const resolved: ModelConfig[] = preparedModels.map((item) => item.model); + let helperSourcePath = preparedModels[0]?.sourcePath ?? ""; + + // Create grid container + const gridHost = el.createDiv({ cls: "ai3d-grid-host" }); + const canvas = gridHost.createEl("canvas"); + canvas.tabIndex = 0; + canvas.addEventListener("keydown", (e) => { + if (destroyed || !renderer) return; + const key = e.key.toLowerCase(); + if (key === "r") { renderer.resetView?.(); e.preventDefault(); } + else if (key === "w") { renderer.toggleWireframe?.(); e.preventDefault(); } + }); + gridHost.appendChild(canvas); + + // Height controlled by CSS max-height only; rowHeight sets inline height (capped by CSS max-height) + if (typeof config.rowHeight === "number") { + const rows = config.preset === "compose" ? 1 : Math.ceil(resolved.length / (config.columns ?? Math.min(resolved.length, 3))); + gridHost.style.setProperty("--grid-height", `${config.rowHeight * rows}px`); + } + + let renderer: PreviewGridRenderer | null = null; + let destroyed = false; + let loaded = false; + + const gridToolbar: HelperToolbar = createHelperButtons(el, gridHost, app, () => renderer, () => helperSourcePath, () => { + if (destroyed) return; + destroyed = true; + observer.disconnect(); + gridIo.disconnect(); + renderer?.destroy(); + renderer = null; + gridHost.remove(); + }, getSettings); + appendMobileInlineHint(el); + + const observer = new MutationObserver(() => { + if (destroyed) return; + if (!el.contains(gridHost)) { + destroyed = true; + observer.disconnect(); + gridIo.disconnect(); + renderer?.destroy(); + renderer = null; + } + }); + observer.observe(el, { childList: true }); + + async function loadGrid() { + if (loaded || destroyed) return; + loaded = true; + gridLoading.setPhaseKey("codeBlock.renderingGrid"); + gridLoading.setProgress(-1); + + try { + const { renderer: nextRenderer } = await createLoggedGridRenderer( + log, + { + surface: "3dgrid", + preset: config.preset ?? "compare", + modelCount: config.models?.length ?? 0, + }, + canvas, + ); + renderer = nextRenderer; + gridToolbar.syncCapabilities(); + const activeRenderer = renderer; + const readFile = async (path: string) => readBinaryPath(app, path); + + if (config.preset === "compose") { + if (!config.sections || config.sections.length === 0) { + gridLoading.hide(); + gridHost.createDiv({ cls: "ai3d-inline-empty", text: t("codeBlock.composeRequiresSections") }); + renderer.destroy(); + renderer = null; + return; + } + const preparedSections: ComposeSection[] = []; + for (const section of config.sections) { + try { + if (!helperSourcePath) { + const firstEntry = section.models[0]; + if (firstEntry) { + const rawPath = typeof firstEntry === "string" ? firstEntry : firstEntry.path; + helperSourcePath = resolveVaultPath(app, rawPath) ?? rawPath; + } + } + const preparedSection = await prepareInlineSection(app, section, settings, convertedAssetCache); + preparedSections.push(preparedSection); + } catch (err) { + gridLoading.hide(); + gridHost.createDiv({ + cls: "ai3d-inline-empty", + text: err instanceof Error ? err.message : String(err), + }); + activeRenderer.destroy(); + renderer = null; + return; + } + } + const result = composeSections( + preparedSections, + config.direction ?? "horizontal", + Number(config.params?.gap) || 0.02, + (entry) => { + if (typeof entry === "string") return null; + return entry; + }, + getPreset, + ); + if (!result) { + gridLoading.hide(); + gridHost.createDiv({ cls: "ai3d-inline-empty", text: t("codeBlock.composeNoValidSections") }); + activeRenderer.destroy(); + renderer = null; + return; + } + await activeRenderer.loadWithPreset(result, readFile); + } else if (config.preset) { + const preset = getPreset(config.preset); + if (!preset) { + gridLoading.hide(); + gridHost.createDiv({ + cls: "ai3d-inline-empty", + text: formatT("codeBlock.unknownPreset", { preset: config.preset }), + }); + activeRenderer.destroy(); + renderer = null; + return; + } + const result = preset.compute(resolved, config.params ?? {}); + if (!result) { + gridLoading.hide(); + gridHost.createDiv({ + cls: "ai3d-inline-empty", + text: formatT("codeBlock.presetRequiresModels", { + preset: config.preset, + min: String(preset.minModels), + max: String(preset.maxModels), + count: String(resolved.length), + }), + }); + activeRenderer.destroy(); + renderer = null; + return; + } + await activeRenderer.loadWithPreset(result, readFile); + } else { + await activeRenderer.loadModels(resolved, config, readFile); + } + + if (destroyed) { gridLoading.hide(); return; } + gridLoading.hide(); + } catch (err) { + destroyed = true; + observer.disconnect(); + gridIo.disconnect(); + gridLoading.hide(); + renderer?.destroy(); + renderer = null; + console.error("[AI3D Grid] Failed:", err); + gridHost.createDiv({ cls: "ai3d-inline-empty", text: formatT("codeBlock.gridFailed", { reason: String(err) }) }); + } + } + + // Lazy-load: only create Engine when scrolled into view + const gridIo = new IntersectionObserver((entries) => { + for (const entry of entries) { + if (entry.isIntersecting) { + gridIo.disconnect(); + void loadGrid(); + } + } + }, { rootMargin: "200px" }); + gridIo.observe(gridHost); + })(); // end async IIFE + }, + }; +} diff --git a/src/view/inline/helper-buttons.ts b/src/view/inline/helper-buttons.ts index 9825315..c890067 100644 --- a/src/view/inline/helper-buttons.ts +++ b/src/view/inline/helper-buttons.ts @@ -608,15 +608,15 @@ export function createHelperButtons( // Calibration panel const calibratePanel = parentEl.createDiv({ cls: "ai3d-calibrate-panel is-hidden" }); - const calibrateTitle = calibratePanel.createEl("div", { cls: "ai3d-calibrate-title", text: t("helper.calibrateTitle") }); + calibratePanel.createDiv({ cls: "ai3d-calibrate-title", text: t("helper.calibrateTitle") }); const boundsRow = calibratePanel.createDiv({ cls: "ai3d-calibrate-row" }); - boundsRow.createEl("span", { cls: "ai3d-calibrate-label", text: t("helper.calibrateCurrent") }); - const boundsX = boundsRow.createEl("span", { cls: "ai3d-calibrate-readonly" }); - const boundsY = boundsRow.createEl("span", { cls: "ai3d-calibrate-readonly" }); - const boundsZ = boundsRow.createEl("span", { cls: "ai3d-calibrate-readonly" }); + boundsRow.createSpan({ cls: "ai3d-calibrate-label", text: t("helper.calibrateCurrent") }); + const boundsX = boundsRow.createSpan({ cls: "ai3d-calibrate-readonly" }); + const boundsY = boundsRow.createSpan({ cls: "ai3d-calibrate-readonly" }); + const boundsZ = boundsRow.createSpan({ cls: "ai3d-calibrate-readonly" }); const realRow = calibratePanel.createDiv({ cls: "ai3d-calibrate-row" }); - realRow.createEl("span", { cls: "ai3d-calibrate-label", text: t("helper.calibrateReal") }); + realRow.createSpan({ cls: "ai3d-calibrate-label", text: t("helper.calibrateReal") }); const inputX = realRow.createEl("input", { cls: "ai3d-calibrate-input", attr: { type: "number", step: "any", placeholder: "X" } }); const inputY = realRow.createEl("input", { cls: "ai3d-calibrate-input", attr: { type: "number", step: "any", placeholder: "Y" } }); const inputZ = realRow.createEl("input", { cls: "ai3d-calibrate-input", attr: { type: "number", step: "any", placeholder: "Z" } }); diff --git a/tsconfig.json b/tsconfig.json index ddf3152..79f3e2e 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,27 +1,27 @@ -{ - "compilerOptions": { - "baseUrl": ".", - "target": "ES2018", - "module": "ESNext", - "moduleResolution": "node", - "allowJs": false, - "strict": true, - "strictNullChecks": true, - "noImplicitAny": true, - "resolveJsonModule": true, - "esModuleInterop": true, - "isolatedModules": true, - "skipLibCheck": true, - "inlineSourceMap": true, - "inlineSources": true, - "types": [ - "node" - ], - "lib": [ - "DOM", - "ES2018" - ] - }, +{ + "compilerOptions": { + "baseUrl": ".", + "target": "ES2018", + "module": "ESNext", + "moduleResolution": "node", + "allowJs": false, + "strict": true, + "strictNullChecks": true, + "noImplicitAny": true, + "resolveJsonModule": true, + "esModuleInterop": true, + "isolatedModules": true, + "skipLibCheck": true, + "inlineSourceMap": true, + "inlineSources": true, + "types": [ + "node" + ], + "lib": [ + "DOM", + "ES2018" + ] + }, "include": [ "src/**/*.ts", "scripts/**/*.ts"