diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..e2fd8fa
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,29 @@
+name: CI
+
+on:
+ pull_request:
+ push:
+ branches:
+ - main
+
+permissions:
+ contents: read
+
+jobs:
+ test:
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ python-version: ["3.10", "3.12", "3.14"]
+ steps:
+ - uses: actions/checkout@v6
+ - uses: actions/setup-python@v6
+ with:
+ python-version: ${{ matrix.python-version }}
+ cache: pip
+ - run: python -m pip install -r requirements.txt pytest
+ - run: python -m compileall -q .
+ - run: pytest -q
+ - run: node --input-type=module --check < web/visualization.js
+ - run: node --check web/js/threeVisualizer.mjs
diff --git a/.github/workflows/publish_action.yml b/.github/workflows/publish_action.yml
index 828f300..023b689 100644
--- a/.github/workflows/publish_action.yml
+++ b/.github/workflows/publish_action.yml
@@ -11,11 +11,12 @@ jobs:
publish-node:
name: Publish Custom Node to registry
runs-on: ubuntu-latest
+ permissions:
+ contents: read
steps:
- name: Check out code
- uses: actions/checkout@v4
+ uses: actions/checkout@v6
- name: Publish Custom Node
- uses: Comfy-Org/publish-node-action@main
+ uses: Comfy-Org/publish-node-action@1.0.1
with:
- ## Add your own personal access token to your Github Repository secrets and reference it here.
- personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }}
\ No newline at end of file
+ personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }}
diff --git a/README.md b/README.md
index 9ec00c9..e55fecd 100644
--- a/README.md
+++ b/README.md
@@ -1,13 +1,60 @@
-# [DualView](https://dualview.ai)
+# ComfyUI Depth Visualization
-## Tools
+An interactive, in-node 3D preview for any ComfyUI reference image and depth
+map. The current implementation is compatible with the modern ComfyUI
+frontend, works offline, supports batches, and cleans up its WebGL resources
+when a node is removed.
-| Tool | Description |
-|------|-------------|
-| [DualView](https://dualview.ai) | Free side-by-side comparison tool for VLM outputs, images, videos, and AI prompts |
+
-## Works with any Depth Map and visualizes the applied version of it inside ComfyUI
-
+## Features
+
+- Interactive orbit, pan, and zoom controls
+- Adjustable positive or negative displacement
+- Batch frame selector with single-image broadcasting
+- PNG screenshots
+- Baked depth-mesh export as GLB, GLTF, or OBJ
+- Local, pinned Three.js assets with no runtime CDN dependency
+- Correct copy/paste, collapse, resize, and node-removal behavior
+- Stale-load cancellation and visible error reporting
+
+## Installation
+
+Install with ComfyUI Manager, or clone the repository manually:
+
+```bash
+cd ComfyUI/custom_nodes
+git clone https://github.com/gokayfem/ComfyUI-Depth-Visualization.git
+python -m pip install -r ComfyUI-Depth-Visualization/requirements.txt
+```
+
+Restart ComfyUI after installation.
+
+## Usage
+
+1. Add **Depth Viewer** from `visualization/3D`.
+2. Connect a reference `IMAGE` and a depth-map `IMAGE`.
+3. Queue the workflow.
+4. Drag to orbit, scroll to zoom, or right-drag to pan.
+
+When one input contains a single image and the other contains a batch, the
+single image is reused for every frame. Other unequal batch sizes produce a
+clear validation error instead of silently dropping images.
+
+Mesh export bakes the current depth slider value into the vertices. GLB is the
+recommended portable format; OBJ contains geometry only.
+
+## Development
+
+```bash
+python -m pip install pytest
+pytest -q
+```
+
+The browser assets are vendored from Three.js 0.185.1. Its MIT license is in
+`web/vendor/THREE-LICENSE.txt`.
## Acknowledgements
-[flowtyone](https://github.com/flowtyone/ComfyUI-Flowty-TripoSR)
+
+The original viewer was inspired by
+[ComfyUI-Flowty-TripoSR](https://github.com/flowtyone/ComfyUI-Flowty-TripoSR).
diff --git a/__init__.py b/__init__.py
index f918094..3a9de08 100644
--- a/__init__.py
+++ b/__init__.py
@@ -1,12 +1,71 @@
-import sys
-from os import path
+"""Depth-map preview node for ComfyUI."""
-sys.path.insert(0, path.dirname(__file__))
-from folder_paths import get_save_image_path, get_output_directory
-from PIL import Image
+from __future__ import annotations
+
+import os
+from typing import Any
+
+import folder_paths
import numpy as np
+from PIL import Image
+
+
+def _as_pil(image: Any, *, grayscale: bool = False) -> Image.Image:
+ """Convert one ComfyUI IMAGE tensor to a web-safe PIL image."""
+ array = image.detach().cpu().float().numpy()
+ array = np.nan_to_num(array, nan=0.0, posinf=1.0, neginf=0.0)
+ array = np.clip(array, 0.0, 1.0)
+
+ if array.ndim == 2:
+ mode = "L"
+ elif array.ndim == 3 and array.shape[-1] == 1:
+ array = array[..., 0]
+ mode = "L"
+ elif array.ndim == 3 and array.shape[-1] >= 3:
+ array = array[..., :3]
+ mode = "RGB"
+ else:
+ raise ValueError(f"Expected an HxW, HxWx1, or HxWx3+ image, got {array.shape}.")
+
+ converted = Image.fromarray((array * 255.0).round().astype(np.uint8), mode=mode)
+ return converted.convert("L" if grayscale else "RGB")
+
+
+def _batch_item(batch: Any, index: int, target_count: int, name: str) -> Any:
+ count = len(batch)
+ if count == target_count:
+ return batch[index]
+ if count == 1:
+ return batch[0]
+ raise ValueError(
+ f"{name} has {count} images but the other input has {target_count}. "
+ "Batch sizes must match, or one input must contain a single image."
+ )
+
+
+def _save_image(
+ image: Image.Image,
+ *,
+ prefix: str,
+ suffix: str,
+ batch_number: int,
+) -> dict[str, str]:
+ output_dir = folder_paths.get_temp_directory()
+ full_folder, filename, counter, subfolder, _ = folder_paths.get_save_image_path(
+ prefix,
+ output_dir,
+ image.width,
+ image.height,
+ )
+ filename = filename.replace("%batch_num%", str(batch_number))
+ image_name = f"{filename}_{counter:05}_{suffix}.png"
+ image.save(os.path.join(full_folder, image_name), compress_level=1)
+ return {"filename": image_name, "subfolder": subfolder, "type": "temp"}
+
class DepthViewer:
+ """Preview an image displaced by a matching depth map in an interactive 3D view."""
+
@classmethod
def INPUT_TYPES(cls):
return {
@@ -16,60 +75,52 @@ class DepthViewer:
}
}
-
- def __init__(self):
- self.saved_reference = []
- self.saved_depth = []
- self.full_output_folder, self.filename, self.counter, self.subfolder, self.filename_prefix = get_save_image_path("imagesave", get_output_directory())
-
RETURN_TYPES = ()
OUTPUT_NODE = True
FUNCTION = "process_images"
- CATEGORY = "DepthViewer"
+ CATEGORY = "visualization/3D"
+ DESCRIPTION = (
+ "Interactively previews an image as a depth-displaced mesh. "
+ "Supports image batches and browser-side PNG, OBJ, GLTF, and GLB export."
+ )
+
def process_images(self, reference_image, depth_map):
- self.saved_reference.clear()
- self.saved_depth.clear()
- image = reference_image[0].detach().cpu().numpy()
- depth = depth_map[0].detach().cpu().numpy()
+ reference_count = len(reference_image)
+ depth_count = len(depth_map)
+ batch_count = max(reference_count, depth_count)
- image = Image.fromarray(np.clip(255. * image, 0, 255).astype(np.uint8)).convert('RGB')
- depth = Image.fromarray(np.clip(255. * depth, 0, 255).astype(np.uint8))
+ references: list[dict[str, str]] = []
+ depths: list[dict[str, str]] = []
+ for index in range(batch_count):
+ reference = _as_pil(
+ _batch_item(reference_image, index, batch_count, "reference_image")
+ )
+ depth = _as_pil(
+ _batch_item(depth_map, index, batch_count, "depth_map"),
+ grayscale=True,
+ )
+ references.append(
+ _save_image(
+ reference,
+ prefix="depth_viewer",
+ suffix="reference",
+ batch_number=index,
+ )
+ )
+ depths.append(
+ _save_image(
+ depth,
+ prefix="depth_viewer",
+ suffix="depth",
+ batch_number=index,
+ )
+ )
- return self.display([image], [depth])
+ return {"ui": {"reference_image": references, "depth_map": depths}}
- def display(self, reference_image, depth_map):
- for (batch_number, (single_image, single_depth)) in enumerate(zip(reference_image, depth_map)):
- filename_with_batch_num = self.filename.replace("%batch_num%", str(batch_number))
-
- image_file = f"{filename_with_batch_num}_{self.counter:05}_reference.png"
- single_image.save(path.join(self.full_output_folder, image_file))
-
- depth_file = f"{filename_with_batch_num}_{self.counter:05}_depth.png"
- single_depth.save(path.join(self.full_output_folder, depth_file))
-
- self.saved_reference.append({
- "filename": image_file,
- "subfolder": self.subfolder,
- "type": "output"
- })
-
- self.saved_depth.append({
- "filename": depth_file,
- "subfolder": self.subfolder,
- "type": "output"
- })
- self.counter += 1
-
- return {"ui": {"reference_image": self.saved_reference, "depth_map": self.saved_depth}}
-
-NODE_CLASS_MAPPINGS = {
- "DepthViewer": DepthViewer,
-}
-
-NODE_DISPLAY_NAME_MAPPINGS = {
- "DepthViewer": "DepthViewer",
-}
+NODE_CLASS_MAPPINGS = {"DepthViewer": DepthViewer}
+NODE_DISPLAY_NAME_MAPPINGS = {"DepthViewer": "Depth Viewer"}
WEB_DIRECTORY = "./web"
-__all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS', 'WEB_DIRECTORY']
+__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"]
diff --git a/conftest.py b/conftest.py
new file mode 100644
index 0000000..f7e8fc7
--- /dev/null
+++ b/conftest.py
@@ -0,0 +1,12 @@
+"""Minimal ComfyUI module shim used while pytest collects this package."""
+
+from __future__ import annotations
+
+import sys
+import types
+
+
+try:
+ import folder_paths # noqa: F401
+except ModuleNotFoundError:
+ sys.modules["folder_paths"] = types.ModuleType("folder_paths")
diff --git a/pyproject.toml b/pyproject.toml
index d6fe363..99c0858 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,12 +1,17 @@
[project]
name = "comfyui-depth-visualization"
-description = "Works with any Depth Map and visualizes the applied version it inside ComfyUI"
-version = "1.0.2"
-license = "LICENSE"
-dependencies = ["Pillow>=10.1.0"]
+description = "Interactive, batch-aware depth-map visualization and mesh export for ComfyUI"
+version = "2.0.0"
+requires-python = ">=3.10"
+license = { file = "LICENSE.txt" }
+dependencies = [
+ "numpy>=1.25.0",
+ "Pillow>=10.1.0",
+]
[project.urls]
Repository = "https://github.com/gokayfem/ComfyUI-Depth-Visualization"
+Issues = "https://github.com/gokayfem/ComfyUI-Depth-Visualization/issues"
[tool.comfy]
PublisherId = "gokayfem"
diff --git a/requirements.txt b/requirements.txt
index 7182b41..e689584 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1 +1,2 @@
+numpy>=1.25.0
Pillow>=10.1.0
diff --git a/tests/test_frontend_assets.py b/tests/test_frontend_assets.py
new file mode 100644
index 0000000..408b782
--- /dev/null
+++ b/tests/test_frontend_assets.py
@@ -0,0 +1,35 @@
+from pathlib import Path
+
+
+ROOT = Path(__file__).parents[1]
+
+
+def test_only_extension_entrypoint_uses_js_suffix():
+ javascript_files = sorted(
+ path.relative_to(ROOT).as_posix() for path in (ROOT / "web").rglob("*.js")
+ )
+ assert javascript_files == ["web/visualization.js"]
+
+
+def test_frontend_has_no_runtime_cdn_dependency():
+ frontend_text = "\n".join(
+ path.read_text(encoding="utf-8")
+ for path in (ROOT / "web").rglob("*")
+ if path.suffix in {".html", ".js", ".mjs", ".css"}
+ and "vendor" not in path.parts
+ )
+ assert "https://" not in frontend_text
+ assert "http://" not in frontend_text
+ assert "@latest" not in frontend_text
+
+
+def test_vendored_three_modules_are_present():
+ vendor = ROOT / "web" / "vendor"
+ expected = {
+ "three.module.min.mjs",
+ "OrbitControls.mjs",
+ "GLTFExporter.mjs",
+ "OBJExporter.mjs",
+ "THREE-LICENSE.txt",
+ }
+ assert expected.issubset({path.name for path in vendor.iterdir()})
diff --git a/tests/test_nodes.py b/tests/test_nodes.py
new file mode 100644
index 0000000..6c5920d
--- /dev/null
+++ b/tests/test_nodes.py
@@ -0,0 +1,94 @@
+from __future__ import annotations
+
+import importlib.util
+import sys
+import types
+from pathlib import Path
+
+import numpy as np
+import pytest
+
+
+class FakeTensor:
+ def __init__(self, array):
+ self.array = np.asarray(array, dtype=np.float32)
+
+ def detach(self):
+ return self
+
+ def cpu(self):
+ return self
+
+ def float(self):
+ return self
+
+ def numpy(self):
+ return self.array
+
+
+class FakeBatch:
+ def __init__(self, arrays):
+ self.items = [FakeTensor(array) for array in arrays]
+
+ def __len__(self):
+ return len(self.items)
+
+ def __getitem__(self, index):
+ return self.items[index]
+
+
+@pytest.fixture()
+def depth_module(tmp_path, monkeypatch):
+ folder_paths = types.ModuleType("folder_paths")
+ folder_paths.get_temp_directory = lambda: str(tmp_path)
+
+ def get_save_image_path(prefix, output_dir, width, height):
+ assert width > 0 and height > 0
+ return output_dir, f"{prefix}_%batch_num%", 1, "", prefix
+
+ folder_paths.get_save_image_path = get_save_image_path
+ monkeypatch.setitem(sys.modules, "folder_paths", folder_paths)
+
+ module_path = Path(__file__).parents[1] / "__init__.py"
+ spec = importlib.util.spec_from_file_location("depth_viewer_test_module", module_path)
+ module = importlib.util.module_from_spec(spec)
+ assert spec.loader
+ spec.loader.exec_module(module)
+ return module, tmp_path
+
+
+def test_processes_full_batch_and_broadcasts_single_depth(depth_module):
+ module, output_dir = depth_module
+ reference = FakeBatch(
+ [
+ np.zeros((8, 12, 3)),
+ np.ones((8, 12, 3)),
+ ]
+ )
+ depth = FakeBatch([np.full((8, 12, 1), 0.5)])
+
+ result = module.DepthViewer().process_images(reference, depth)["ui"]
+
+ assert len(result["reference_image"]) == 2
+ assert len(result["depth_map"]) == 2
+ for descriptor in result["reference_image"] + result["depth_map"]:
+ assert descriptor["type"] == "temp"
+ assert (output_dir / descriptor["filename"]).is_file()
+
+
+def test_rejects_incompatible_batch_sizes(depth_module):
+ module, _ = depth_module
+ reference = FakeBatch([np.zeros((4, 4, 3)) for _ in range(2)])
+ depth = FakeBatch([np.zeros((4, 4, 1)) for _ in range(3)])
+
+ with pytest.raises(ValueError, match="Batch sizes must match"):
+ module.DepthViewer().process_images(reference, depth)
+
+
+def test_sanitizes_non_finite_pixels(depth_module):
+ module, _ = depth_module
+ image = FakeTensor([[[np.nan, np.inf, -np.inf]]])
+
+ converted = np.asarray(module._as_pil(image))
+
+ assert converted.tolist() == [[[0, 255, 0]]]
diff --git a/web/html/threeVisualizer.html b/web/html/threeVisualizer.html
index 6527421..640aa02 100644
--- a/web/html/threeVisualizer.html
+++ b/web/html/threeVisualizer.html
@@ -1,33 +1,58 @@
-
+
-
-
-
-
-
-
+
+
+
+ Depth Viewer
+
+
+
+
+
+
+ Waiting for output…
+
-
-
-
-
-
-
-
-
-
-
+
+
+
+
diff --git a/web/js/threeVisualizer.js b/web/js/threeVisualizer.js
deleted file mode 100644
index 580bbcf..0000000
--- a/web/js/threeVisualizer.js
+++ /dev/null
@@ -1,199 +0,0 @@
-import * as THREE from 'three';
-import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
-import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
-
-let apiURL = '';
-
-// Listen for messages from the parent window
-window.addEventListener('message', function(event) {
- if (event.data.type === 'init') {
- apiURL = event.data.apiURL;
- } else if (event.data.type === 'update') {
- main(event.data.referenceImage, event.data.depthMap);
- }
-}, false);
-
-const visualizer = document.getElementById("visualizer");
-const container = document.getElementById("container");
-const progressDialog = document.getElementById("progress-dialog");
-const progressIndicator = document.getElementById("progress-indicator");
-
-const renderer = new THREE.WebGLRenderer({ antialias: true, extensions: {
- derivatives: true
-}});
-renderer.setPixelRatio(window.devicePixelRatio);
-renderer.setSize(window.innerWidth, window.innerHeight);
-container.appendChild(renderer.domElement);
-
-const pmremGenerator = new THREE.PMREMGenerator(renderer);
-
-// scene
-const scene = new THREE.Scene();
-scene.background = new THREE.Color(0x000000);
-scene.environment = pmremGenerator.fromScene(new RoomEnvironment(renderer), 0.04).texture;
-
-const ambientLight = new THREE.AmbientLight(0xffffff);
-
-const camera = new THREE.PerspectiveCamera(40, window.innerWidth / window.innerHeight, 0.1, 1000);
-camera.position.set(0, 0, 10);
-const pointLight = new THREE.PointLight(0xffffff, 15);
-camera.add(pointLight);
-
-const controls = new OrbitControls(camera, renderer.domElement);
-controls.target.set(0, 0, 0);
-controls.update();
-controls.enablePan = true;
-controls.enableDamping = true;
-
-// Handle window resize event
-window.onresize = function () {
- camera.aspect = window.innerWidth / window.innerHeight;
- camera.updateProjectionMatrix();
-
- renderer.setSize(window.innerWidth, window.innerHeight);
-};
-
-var lastReferenceImage = "";
-var lastDepthMap = "";
-var needUpdate = false;
-
-function frameUpdate() {
- var referenceImage = visualizer.getAttribute("reference_image");
- var depthMap = visualizer.getAttribute("depth_map");
- if (referenceImage == lastReferenceImage && depthMap == lastDepthMap) {
- if (needUpdate) {
- controls.update();
- renderer.render(scene, camera);
- }
- requestAnimationFrame(frameUpdate);
- } else {
- needUpdate = false;
- scene.clear();
- progressDialog.open = true;
- lastReferenceImage = referenceImage;
- lastDepthMap = depthMap;
- main(JSON.parse(lastReferenceImage), JSON.parse(lastDepthMap));
- }
-}
-
-const onProgress = function (xhr) {
- if (xhr.lengthComputable) {
- progressIndicator.value = xhr.loaded / xhr.total * 100;
- }
-};
-
-const onError = function (e) {
- console.error(e);
-};
-
-async function main(referenceImageParams, depthMapParams) {
- let referenceTexture, depthTexture;
- let imageWidth = 10; // Default width
- let imageHeight = 10; // Default height, will be updated based on the image's aspect ratio
-
- if (referenceImageParams?.filename) {
- const referenceImageUrl = `${apiURL}/view?` + new URLSearchParams(referenceImageParams).toString();
- const referenceImageExt = referenceImageParams.filename.slice(referenceImageParams.filename.lastIndexOf(".") + 1);
-
- if (referenceImageExt === "png" || referenceImageExt === "jpg" || referenceImageExt === "jpeg") {
- const referenceImageLoader = new THREE.TextureLoader();
- referenceTexture = await new Promise((resolve, reject) => {
- referenceImageLoader.load(referenceImageUrl, (texture) => {
- // Once the image is loaded, update the width and height based on the image's aspect ratio
- imageWidth = 10; // Keep the width as 10
- imageHeight = texture.image.height / (texture.image.width / 10);
- resolve(texture);
- }, undefined, reject);
- });
- }
- }
-
- if (depthMapParams?.filename) {
- const depthMapUrl = `${apiURL}/view?` + new URLSearchParams(depthMapParams).toString();
- const depthMapExt = depthMapParams.filename.slice(depthMapParams.filename.lastIndexOf(".") + 1);
-
- if (depthMapExt === "png" || depthMapExt === "jpg" || depthMapExt === "jpeg") {
- const depthMapLoader = new THREE.TextureLoader();
- depthTexture = await depthMapLoader.loadAsync(depthMapUrl);
- }
- }
-
- if (referenceTexture && depthTexture) {
- const depthMaterial = new THREE.ShaderMaterial({
- uniforms: {
- referenceTexture: { value: referenceTexture },
- depthTexture: { value: depthTexture },
- depthScale: { value: 5.0 },
- ambientLightColor: { value: new THREE.Color(0.2, 0.2, 0.2) },
- lightPosition: { value: new THREE.Vector3(2, 2, 2) },
- lightColor: { value: new THREE.Color(1, 1, 1) },
- lightIntensity: { value: 1.0 },
- shininess: { value: 30 },
- },
- vertexShader: `
- uniform sampler2D depthTexture;
- uniform float depthScale;
-
- varying vec2 vUv;
- varying float vDepth;
- varying vec3 vNormal;
- varying vec3 vViewPosition;
-
- void main() {
- vUv = uv;
-
- float depth = texture2D(depthTexture, uv).r;
- vec3 displacement = normal * depth * depthScale;
- vec3 displacedPosition = position + displacement;
-
- vec4 worldPosition = modelMatrix * vec4(displacedPosition, 1.0);
- vNormal = normalize(normalMatrix * normal);
- vViewPosition = (viewMatrix * worldPosition).xyz;
-
- gl_Position = projectionMatrix * viewMatrix * worldPosition;
-
- vDepth = depth;
- }
- `,
- fragmentShader: `
- uniform sampler2D referenceTexture;
-
- varying vec2 vUv;
- varying float vDepth;
-
- void main() {
- vec4 referenceColor = texture2D(referenceTexture, vUv);
-
- // Directly use reference color without fog
- gl_FragColor = referenceColor;
- }
- `
- });
-
-
- const planeGeometry = new THREE.PlaneGeometry(imageWidth, imageHeight, 200, 200);
- const depthMesh = new THREE.Mesh(planeGeometry, depthMaterial);
- scene.add(depthMesh);
- }
-
- needUpdate = true;
-
- scene.add(ambientLight);
- scene.add(camera);
-
- progressDialog.close();
-
- frameUpdate();
-}
-
-document.getElementById('screenshotButton').addEventListener('click', takeScreenshot);
-
-function takeScreenshot() {
- renderer.render(scene, camera);
- const dataURL = renderer.domElement.toDataURL('image/png');
- const link = document.createElement('a');
- link.href = dataURL;
- link.download = "screenshot.png";
- link.click();
- console.log("Screenshot taken");
-}
diff --git a/web/js/threeVisualizer.mjs b/web/js/threeVisualizer.mjs
new file mode 100644
index 0000000..e005027
--- /dev/null
+++ b/web/js/threeVisualizer.mjs
@@ -0,0 +1,350 @@
+import * as THREE from "three";
+import { OrbitControls } from "../vendor/OrbitControls.mjs";
+import { GLTFExporter } from "../vendor/GLTFExporter.mjs";
+import { OBJExporter } from "../vendor/OBJExporter.mjs";
+
+const SOURCE = "gokayfem.depth-visualization";
+const container = document.querySelector("#canvas-container");
+const statusElement = document.querySelector("#status");
+const errorElement = document.querySelector("#error");
+const batchSelect = document.querySelector("#batch-select");
+const depthScale = document.querySelector("#depth-scale");
+const depthValue = document.querySelector("#depth-value");
+const exportButton = document.querySelector("#export-mesh");
+
+const renderer = new THREE.WebGLRenderer({
+ antialias: true,
+ alpha: false,
+ preserveDrawingBuffer: true,
+ powerPreference: "high-performance",
+});
+renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
+renderer.outputColorSpace = THREE.SRGBColorSpace;
+container.append(renderer.domElement);
+
+const scene = new THREE.Scene();
+scene.background = new THREE.Color(0x111318);
+
+const camera = new THREE.PerspectiveCamera(42, 1, 0.01, 1000);
+const controls = new OrbitControls(camera, renderer.domElement);
+controls.enableDamping = true;
+controls.dampingFactor = 0.08;
+controls.screenSpacePanning = true;
+
+scene.add(new THREE.HemisphereLight(0xffffff, 0x303040, 2.2));
+const keyLight = new THREE.DirectionalLight(0xffffff, 1.5);
+keyLight.position.set(4, 6, 8);
+scene.add(keyLight);
+
+let channel = null;
+let viewUrl = null;
+let output = null;
+let mesh = null;
+let updateVersion = 0;
+let animationFrame = null;
+let disposed = false;
+
+function setStatus(message) {
+ statusElement.textContent = message;
+ statusElement.hidden = false;
+ errorElement.hidden = true;
+}
+
+function setError(error) {
+ console.error("[Depth Viewer]", error);
+ errorElement.textContent = error instanceof Error ? error.message : String(error);
+ errorElement.hidden = false;
+ statusElement.hidden = true;
+}
+
+function resetCamera() {
+ camera.position.set(0, 0, 9);
+ controls.target.set(0, 0, 0);
+ controls.update();
+}
+
+function resize() {
+ const width = Math.max(container.clientWidth, 1);
+ const height = Math.max(container.clientHeight, 1);
+ renderer.setSize(width, height, false);
+ camera.aspect = width / height;
+ camera.updateProjectionMatrix();
+}
+
+new ResizeObserver(resize).observe(container);
+resetCamera();
+resize();
+
+function disposeMaterial(material) {
+ for (const value of Object.values(material)) {
+ if (value?.isTexture) {
+ value.dispose();
+ }
+ }
+ material.dispose();
+}
+
+function removeMesh() {
+ if (!mesh) {
+ return;
+ }
+ scene.remove(mesh);
+ mesh.geometry.dispose();
+ disposeMaterial(mesh.material);
+ mesh = null;
+ exportButton.disabled = true;
+}
+
+function imageUrl(descriptor) {
+ if (!viewUrl) {
+ throw new Error("The ComfyUI API URL has not been initialized.");
+ }
+ const url = new URL(viewUrl, window.location.origin);
+ url.search = new URLSearchParams({
+ filename: descriptor.filename,
+ subfolder: descriptor.subfolder ?? "",
+ type: descriptor.type ?? "temp",
+ }).toString();
+ return url.href;
+}
+
+function loadTexture(descriptor, colorTexture) {
+ return new Promise((resolve, reject) => {
+ new THREE.TextureLoader().load(
+ imageUrl(descriptor),
+ (texture) => {
+ texture.colorSpace = colorTexture
+ ? THREE.SRGBColorSpace
+ : THREE.NoColorSpace;
+ texture.anisotropy = Math.min(
+ 8,
+ renderer.capabilities.getMaxAnisotropy(),
+ );
+ resolve(texture);
+ },
+ undefined,
+ () => reject(new Error(`Unable to load ${descriptor.filename}.`)),
+ );
+ });
+}
+
+async function showFrame(index) {
+ if (!output) {
+ return;
+ }
+ const reference = output.reference_image[index] ?? output.reference_image[0];
+ const depth = output.depth_map[index] ?? output.depth_map[0];
+ if (!reference || !depth) {
+ setError("The selected frame is missing a reference image or depth map.");
+ return;
+ }
+
+ const version = ++updateVersion;
+ setStatus(`Loading frame ${index + 1}…`);
+ try {
+ const [referenceTexture, depthTexture] = await Promise.all([
+ loadTexture(reference, true),
+ loadTexture(depth, false),
+ ]);
+ if (version !== updateVersion || disposed) {
+ referenceTexture.dispose();
+ depthTexture.dispose();
+ return;
+ }
+
+ removeMesh();
+ const image = referenceTexture.image;
+ const aspect = image.width / Math.max(image.height, 1);
+ const width = 7;
+ const height = width / aspect;
+ const geometry = new THREE.PlaneGeometry(width, height, 256, 256);
+ const material = new THREE.MeshStandardMaterial({
+ map: referenceTexture,
+ displacementMap: depthTexture,
+ displacementScale: Number(depthScale.value),
+ displacementBias: -Number(depthScale.value) / 2,
+ roughness: 0.95,
+ metalness: 0,
+ side: THREE.DoubleSide,
+ });
+ mesh = new THREE.Mesh(geometry, material);
+ scene.add(mesh);
+ resetCamera();
+ statusElement.hidden = true;
+ exportButton.disabled = false;
+ } catch (error) {
+ if (version === updateVersion) {
+ removeMesh();
+ setError(error);
+ }
+ }
+}
+
+function setOutput(nextOutput) {
+ const referenceCount = nextOutput?.reference_image?.length ?? 0;
+ const depthCount = nextOutput?.depth_map?.length ?? 0;
+ const count = Math.max(referenceCount, depthCount);
+ if (!count) {
+ setError("ComfyUI returned no depth-viewer images.");
+ return;
+ }
+
+ output = nextOutput;
+ batchSelect.replaceChildren();
+ for (let index = 0; index < count; index += 1) {
+ const option = document.createElement("option");
+ option.value = String(index);
+ option.textContent = `${index + 1} / ${count}`;
+ batchSelect.append(option);
+ }
+ batchSelect.disabled = count === 1;
+ batchSelect.value = "0";
+ void showFrame(0);
+}
+
+function download(blob, filename) {
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement("a");
+ link.href = url;
+ link.download = filename;
+ link.click();
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
+}
+
+function bakedMesh() {
+ if (!mesh) {
+ throw new Error("Queue the node before exporting a mesh.");
+ }
+ const clone = new THREE.Mesh(
+ mesh.geometry.clone(),
+ new THREE.MeshStandardMaterial({
+ map: mesh.material.map,
+ roughness: mesh.material.roughness,
+ metalness: mesh.material.metalness,
+ side: THREE.DoubleSide,
+ }),
+ );
+
+ const depthImage = mesh.material.displacementMap.image;
+ const canvas = document.createElement("canvas");
+ canvas.width = depthImage.width;
+ canvas.height = depthImage.height;
+ const context = canvas.getContext("2d", { willReadFrequently: true });
+ context.drawImage(depthImage, 0, 0);
+ const pixels = context.getImageData(0, 0, canvas.width, canvas.height).data;
+ const positions = clone.geometry.attributes.position;
+ const uvs = clone.geometry.attributes.uv;
+ const scale = mesh.material.displacementScale;
+ const bias = mesh.material.displacementBias;
+
+ for (let index = 0; index < positions.count; index += 1) {
+ const x = Math.min(
+ canvas.width - 1,
+ Math.max(0, Math.round(uvs.getX(index) * (canvas.width - 1))),
+ );
+ const y = Math.min(
+ canvas.height - 1,
+ Math.max(0, Math.round((1 - uvs.getY(index)) * (canvas.height - 1))),
+ );
+ const depth = pixels[(y * canvas.width + x) * 4] / 255;
+ positions.setZ(index, depth * scale + bias);
+ }
+ positions.needsUpdate = true;
+ clone.geometry.computeVertexNormals();
+ return clone;
+}
+
+async function exportMesh() {
+ const format = document.querySelector("#export-format").value;
+ const exportable = bakedMesh();
+ try {
+ if (format === "obj") {
+ const data = new OBJExporter().parse(exportable);
+ download(new Blob([data], { type: "text/plain" }), "depth-mesh.obj");
+ return;
+ }
+
+ const binary = format === "glb";
+ const data = await new GLTFExporter().parseAsync(exportable, { binary });
+ const blob = binary
+ ? new Blob([data], { type: "model/gltf-binary" })
+ : new Blob([JSON.stringify(data, null, 2)], {
+ type: "model/gltf+json",
+ });
+ download(blob, `depth-mesh.${format}`);
+ } finally {
+ exportable.geometry.dispose();
+ exportable.material.dispose();
+ }
+}
+
+function takeScreenshot() {
+ renderer.render(scene, camera);
+ renderer.domElement.toBlob((blob) => {
+ if (blob) {
+ download(blob, "depth-preview.png");
+ }
+ }, "image/png");
+}
+
+function animate() {
+ if (disposed) {
+ return;
+ }
+ animationFrame = requestAnimationFrame(animate);
+ if (document.visibilityState === "visible") {
+ controls.update();
+ renderer.render(scene, camera);
+ }
+}
+animate();
+
+batchSelect.addEventListener("change", () => {
+ void showFrame(Number(batchSelect.value));
+});
+depthScale.addEventListener("input", () => {
+ const value = Number(depthScale.value);
+ depthValue.value = value.toFixed(2);
+ if (mesh) {
+ mesh.material.displacementScale = value;
+ mesh.material.displacementBias = -value / 2;
+ }
+});
+document.querySelector("#reset-camera").addEventListener("click", resetCamera);
+document.querySelector("#screenshot").addEventListener("click", takeScreenshot);
+exportButton.addEventListener("click", () => {
+ void exportMesh().catch(setError);
+});
+
+window.addEventListener("message", (event) => {
+ if (
+ event.origin !== window.location.origin
+ || event.source !== window.parent
+ || event.data?.source !== SOURCE
+ ) {
+ return;
+ }
+ if (event.data.type === "connect") {
+ channel = event.data.channel;
+ window.parent.postMessage(
+ { source: SOURCE, channel, type: "ready" },
+ window.location.origin,
+ );
+ return;
+ }
+ if (event.data.channel !== channel) {
+ return;
+ }
+ if (event.data.type === "initialize") {
+ viewUrl = event.data.viewUrl;
+ } else if (event.data.type === "update") {
+ setOutput(event.data.output);
+ } else if (event.data.type === "dispose") {
+ disposed = true;
+ updateVersion += 1;
+ cancelAnimationFrame(animationFrame);
+ removeMesh();
+ controls.dispose();
+ renderer.dispose();
+ }
+});
diff --git a/web/style/progressStyle.css b/web/style/progressStyle.css
deleted file mode 100644
index 91fc468..0000000
--- a/web/style/progressStyle.css
+++ /dev/null
@@ -1,36 +0,0 @@
-dialog {
- width: 100%;
- text-align: center;
- max-width: 20em;
- color: white;
- background-color: #000;
- border: none;
- position: relative;
- transform: translate(-50%, -50%);
-}
-
-#progress-container {
- position: absolute;
- top: 50%;
- left: 50%;
-}
-
-progress {
- width: 100%;
- height: 1em;
- border: none;
- background-color: #fff;
- color: #eee;
-}
-
-progress::-webkit-progress-bar {
- background-color: #333;
-}
-
-progress::-webkit-progress-value {
- background-color: #eee;
-}
-
-progress::-moz-progress-bar {
- background-color: #eee;
-}
\ No newline at end of file
diff --git a/web/style/threeStyle.css b/web/style/threeStyle.css
index 2b7392a..f20c80e 100644
--- a/web/style/threeStyle.css
+++ b/web/style/threeStyle.css
@@ -1,119 +1,124 @@
-body {
- margin: 0;
- background-color: #000;
- color: #fff;
- font-family: Monospace;
- font-size: 13px;
- line-height: 24px;
- overscroll-behavior: none;
+:root {
+ color-scheme: dark;
+ font-family: Inter, ui-sans-serif, system-ui, sans-serif;
+ background: #111318;
+ color: #f5f7fb;
}
-a {
- color: #ff0;
- text-decoration: none;
+* {
+ box-sizing: border-box;
}
-a:hover {
- text-decoration: underline;
+html,
+body,
+#viewer,
+#canvas-container {
+ width: 100%;
+ height: 100%;
+ margin: 0;
+ overflow: hidden;
+}
+
+#viewer {
+ position: relative;
+ min-height: 320px;
+ background:
+ radial-gradient(circle at 50% 15%, #252a35 0, #111318 55%);
+}
+
+#canvas-container canvas {
+ display: block;
+ width: 100%;
+ height: 100%;
+ touch-action: none;
+}
+
+#status,
+#error {
+ position: absolute;
+ inset: 50% auto auto 50%;
+ max-width: min(30rem, calc(100% - 2rem));
+ padding: 0.7rem 0.9rem;
+ border: 1px solid #3a4150;
+ border-radius: 8px;
+ background: rgb(17 19 24 / 90%);
+ box-shadow: 0 8px 30px rgb(0 0 0 / 35%);
+ transform: translate(-50%, -50%);
+ text-align: center;
+}
+
+#error {
+ border-color: #b64c5c;
+ color: #ffd7dc;
+}
+
+.toolbar {
+ position: absolute;
+ inset: auto 0.65rem 0.65rem;
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.45rem;
+ align-items: center;
+ padding: 0.5rem;
+ border: 1px solid rgb(255 255 255 / 12%);
+ border-radius: 10px;
+ background: rgb(17 19 24 / 88%);
+ box-shadow: 0 8px 30px rgb(0 0 0 / 30%);
+ backdrop-filter: blur(10px);
+}
+
+.toolbar label {
+ display: flex;
+ gap: 0.35rem;
+ align-items: center;
+ color: #c9cfda;
+ font-size: 0.75rem;
+}
+
+.range-control {
+ flex: 1 1 11rem;
+}
+
+.range-control input {
+ min-width: 5rem;
+ flex: 1;
+}
+
+.range-control output {
+ width: 2.8rem;
+ color: #f5f7fb;
+ font-variant-numeric: tabular-nums;
+}
+
+button,
+select {
+ min-height: 2rem;
+ padding: 0.35rem 0.55rem;
+ border: 1px solid #454d5d;
+ border-radius: 6px;
+ background: #242a35;
+ color: inherit;
+ font: inherit;
}
button {
- cursor: pointer;
- text-transform: uppercase;
-}
-
-#info {
- position: absolute;
- top: 0px;
- width: 100%;
- padding: 10px;
- box-sizing: border-box;
- text-align: center;
- -moz-user-select: none;
- -webkit-user-select: none;
- -ms-user-select: none;
- user-select: none;
- pointer-events: none;
- z-index: 1; /* TODO Solve this in HTML */
-}
-
-a, button, input, select {
- pointer-events: auto;
-}
-
-.lil-gui {
- z-index: 2 !important; /* TODO Solve this in HTML */
-}
-
-@media all and ( max-width: 640px ) {
- .lil-gui.root {
- right: auto;
- top: auto;
- max-height: 50%;
- max-width: 80%;
- bottom: 0;
- left: 0;
- }
-}
-
-#overlay {
- position: absolute;
- font-size: 16px;
- z-index: 2;
- top: 0;
- left: 0;
- width: 100%;
- height: 100%;
- display: flex;
- align-items: center;
- justify-content: center;
- flex-direction: column;
- background: rgba(0,0,0,0.7);
-}
-
- #overlay button {
- background: transparent;
- border: 0;
- border: 1px solid rgb(255, 255, 255);
- border-radius: 4px;
- color: #ffffff;
- padding: 12px 18px;
- text-transform: uppercase;
- cursor: pointer;
- }
-
-#notSupported {
- width: 50%;
- margin: auto;
- background-color: #f00;
- margin-top: 20px;
- padding: 10px;
-}
-
-#screenshotButton {
- position: absolute;
- bottom: 10px; /* Adjust as needed */
- left: 10px; /* Position to the left */
- z-index: 10; /* Ensure this is above the canvas's z-index */
- padding: 5px 5px;
- border: none;
- border-radius: 5px;
- background: linear-gradient(145deg, #007bff, #0056b3);
- color: #ffffff;
- font-size: 10px;
cursor: pointer;
- box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
- transition: background 0.3s ease-in-out, transform 0.2s ease;
}
-#screenshotButton:hover {
- background: linear-gradient(145deg, #0056b3, #007bff);
- transform: translateY(-2px);
- box-shadow: 0 6px 8px rgba(0, 0, 0, 0.15);
+button:hover:not(:disabled) {
+ border-color: #6b8cff;
+ background: #30394a;
}
-#screenshotButton:active {
- background: #0056b3;
- transform: translateY(1px);
- box-shadow: 0 3px 5px rgba(0, 0, 0, 0.2);
-}
\ No newline at end of file
+button:focus-visible,
+select:focus-visible,
+input:focus-visible {
+ outline: 2px solid #7d9aff;
+ outline-offset: 2px;
+}
+
+button:disabled,
+select:disabled {
+ cursor: not-allowed;
+ opacity: 0.5;
+}
diff --git a/web/vendor/GLTFExporter.mjs b/web/vendor/GLTFExporter.mjs
new file mode 100644
index 0000000..ab3bb95
--- /dev/null
+++ b/web/vendor/GLTFExporter.mjs
@@ -0,0 +1,3840 @@
+import {
+ BufferAttribute,
+ ClampToEdgeWrapping,
+ Color,
+ DoubleSide,
+ InterpolateDiscrete,
+ InterpolateLinear,
+ NoColorSpace,
+ LinearFilter,
+ LinearMipmapLinearFilter,
+ LinearMipmapNearestFilter,
+ MathUtils,
+ Matrix4,
+ MirroredRepeatWrapping,
+ NearestFilter,
+ NearestMipmapLinearFilter,
+ NearestMipmapNearestFilter,
+ PropertyBinding,
+ RGBAFormat,
+ RepeatWrapping,
+ Scene,
+ Source,
+ SRGBColorSpace,
+ CompressedTexture,
+ Vector3,
+ Quaternion,
+ REVISION,
+ ImageUtils
+} from 'three';
+
+/**
+ * The KHR_mesh_quantization extension allows these extra attribute component types
+ *
+ * @see https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_mesh_quantization/README.md#extending-mesh-attributes
+ */
+const KHR_mesh_quantization_ExtraAttrTypes = {
+ POSITION: [
+ 'byte',
+ 'byte normalized',
+ 'unsigned byte',
+ 'unsigned byte normalized',
+ 'short',
+ 'short normalized',
+ 'unsigned short',
+ 'unsigned short normalized',
+ ],
+ NORMAL: [
+ 'byte normalized',
+ 'short normalized',
+ ],
+ TANGENT: [
+ 'byte normalized',
+ 'short normalized',
+ ],
+ TEXCOORD: [
+ 'byte',
+ 'byte normalized',
+ 'unsigned byte',
+ 'short',
+ 'short normalized',
+ 'unsigned short',
+ ],
+};
+
+/**
+ * An exporter for `glTF` 2.0.
+ *
+ * glTF (GL Transmission Format) is an [open format specification](https://github.com/KhronosGroup/glTF/tree/master/specification/2.0)
+ * for efficient delivery and loading of 3D content. Assets may be provided either in JSON (.gltf)
+ * or binary (.glb) format. External files store textures (.jpg, .png) and additional binary
+ * data (.bin). A glTF asset may deliver one or more scenes, including meshes, materials,
+ * textures, skins, skeletons, morph targets, animations, lights, and/or cameras.
+ *
+ * GLTFExporter supports the [glTF 2.0 extensions](https://github.com/KhronosGroup/glTF/tree/master/extensions/):
+ *
+ * - KHR_lights_punctual
+ * - KHR_materials_clearcoat
+ * - KHR_materials_dispersion
+ * - KHR_materials_emissive_strength
+ * - KHR_materials_ior
+ * - KHR_materials_iridescence
+ * - KHR_materials_specular
+ * - KHR_materials_sheen
+ * - KHR_materials_transmission
+ * - KHR_materials_unlit
+ * - KHR_materials_volume
+ * - KHR_mesh_quantization
+ * - KHR_texture_transform
+ * - EXT_materials_bump
+ * - EXT_mesh_gpu_instancing
+ * - EXT_texture_webp
+ *
+ * The following glTF 2.0 extension is supported by an external user plugin:
+ *
+ * - [KHR_materials_variants](https://github.com/takahirox/three-gltf-extensions)
+ *
+ * ```js
+ * const exporter = new GLTFExporter();
+ * const data = await exporter.parseAsync( scene, options );
+ * ```
+ *
+ * @three_import import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js';
+ */
+class GLTFExporter {
+
+ /**
+ * Constructs a new glTF exporter.
+ */
+ constructor() {
+
+ /**
+ * A reference to a texture utils module.
+ *
+ * @type {?(WebGLTextureUtils|WebGPUTextureUtils)}
+ * @default null
+ */
+ this.textureUtils = null;
+
+ this.pluginCallbacks = [];
+
+ this.register( function ( writer ) {
+
+ return new GLTFLightExtension( writer );
+
+ } );
+
+ this.register( function ( writer ) {
+
+ return new GLTFMaterialsUnlitExtension( writer );
+
+ } );
+
+ this.register( function ( writer ) {
+
+ return new GLTFMaterialsTransmissionExtension( writer );
+
+ } );
+
+ this.register( function ( writer ) {
+
+ return new GLTFMaterialsVolumeExtension( writer );
+
+ } );
+
+ this.register( function ( writer ) {
+
+ return new GLTFMaterialsIorExtension( writer );
+
+ } );
+
+ this.register( function ( writer ) {
+
+ return new GLTFMaterialsSpecularExtension( writer );
+
+ } );
+
+ this.register( function ( writer ) {
+
+ return new GLTFMaterialsClearcoatExtension( writer );
+
+ } );
+
+ this.register( function ( writer ) {
+
+ return new GLTFMaterialsDispersionExtension( writer );
+
+ } );
+
+ this.register( function ( writer ) {
+
+ return new GLTFMaterialsIridescenceExtension( writer );
+
+ } );
+
+ this.register( function ( writer ) {
+
+ return new GLTFMaterialsSheenExtension( writer );
+
+ } );
+
+ this.register( function ( writer ) {
+
+ return new GLTFMaterialsAnisotropyExtension( writer );
+
+ } );
+
+ this.register( function ( writer ) {
+
+ return new GLTFMaterialsEmissiveStrengthExtension( writer );
+
+ } );
+
+ this.register( function ( writer ) {
+
+ return new GLTFMaterialsBumpExtension( writer );
+
+ } );
+
+ this.register( function ( writer ) {
+
+ return new GLTFMeshGpuInstancing( writer );
+
+ } );
+
+ }
+
+ /**
+ * Registers a plugin callback. This API is internally used to implement the various
+ * glTF extensions but can also used by third-party code to add additional logic
+ * to the exporter.
+ *
+ * @param {function(writer:GLTFWriter)} callback - The callback function to register.
+ * @return {GLTFExporter} A reference to this exporter.
+ */
+ register( callback ) {
+
+ if ( this.pluginCallbacks.indexOf( callback ) === - 1 ) {
+
+ this.pluginCallbacks.push( callback );
+
+ }
+
+ return this;
+
+ }
+
+ /**
+ * Unregisters a plugin callback.
+ *
+ * @param {Function} callback - The callback function to unregister.
+ * @return {GLTFExporter} A reference to this exporter.
+ */
+ unregister( callback ) {
+
+ if ( this.pluginCallbacks.indexOf( callback ) !== - 1 ) {
+
+ this.pluginCallbacks.splice( this.pluginCallbacks.indexOf( callback ), 1 );
+
+ }
+
+ return this;
+
+ }
+
+ /**
+ * Sets the texture utils for this exporter. Only relevant when compressed textures have to be exported.
+ *
+ * Depending on whether you use {@link WebGLRenderer} or {@link WebGPURenderer}, you must inject the
+ * corresponding texture utils {@link WebGLTextureUtils} or {@link WebGPUTextureUtils}.
+ *
+ * @param {WebGLTextureUtils|WebGPUTextureUtils} utils - The texture utils.
+ * @return {GLTFExporter} A reference to this exporter.
+ */
+ setTextureUtils( utils ) {
+
+ this.textureUtils = utils;
+
+ return this;
+
+ }
+
+ /**
+ * Parses the given scenes and generates the glTF output.
+ *
+ * @param {Scene|Array} input - A scene or an array of scenes.
+ * @param {GLTFExporter~OnDone} onDone - A callback function that is executed when the export has finished.
+ * @param {GLTFExporter~OnError} onError - A callback function that is executed when an error happens.
+ * @param {GLTFExporter~Options} options - options
+ */
+ parse( input, onDone, onError, options ) {
+
+ const writer = new GLTFWriter();
+ const plugins = [];
+
+ for ( let i = 0, il = this.pluginCallbacks.length; i < il; i ++ ) {
+
+ plugins.push( this.pluginCallbacks[ i ]( writer ) );
+
+ }
+
+ writer.setPlugins( plugins );
+ writer.setTextureUtils( this.textureUtils );
+ writer.writeAsync( input, onDone, options ).catch( onError );
+
+ }
+
+ /**
+ * Async version of {@link GLTFExporter#parse}.
+ *
+ * @param {Scene|Array} input - A scene or an array of scenes.
+ * @param {GLTFExporter~Options} options - options.
+ * @return {Promise} A Promise that resolved with the exported glTF data.
+ */
+ parseAsync( input, options ) {
+
+ const scope = this;
+
+ return new Promise( function ( resolve, reject ) {
+
+ scope.parse( input, resolve, reject, options );
+
+ } );
+
+ }
+
+}
+
+//------------------------------------------------------------------------------
+// Constants
+//------------------------------------------------------------------------------
+
+const WEBGL_CONSTANTS = {
+ POINTS: 0x0000,
+ LINES: 0x0001,
+ LINE_LOOP: 0x0002,
+ LINE_STRIP: 0x0003,
+ TRIANGLES: 0x0004,
+ TRIANGLE_STRIP: 0x0005,
+ TRIANGLE_FAN: 0x0006,
+
+ BYTE: 0x1400,
+ UNSIGNED_BYTE: 0x1401,
+ SHORT: 0x1402,
+ UNSIGNED_SHORT: 0x1403,
+ INT: 0x1404,
+ UNSIGNED_INT: 0x1405,
+ FLOAT: 0x1406,
+
+ ARRAY_BUFFER: 0x8892,
+ ELEMENT_ARRAY_BUFFER: 0x8893,
+
+ NEAREST: 0x2600,
+ LINEAR: 0x2601,
+ NEAREST_MIPMAP_NEAREST: 0x2700,
+ LINEAR_MIPMAP_NEAREST: 0x2701,
+ NEAREST_MIPMAP_LINEAR: 0x2702,
+ LINEAR_MIPMAP_LINEAR: 0x2703,
+
+ CLAMP_TO_EDGE: 33071,
+ MIRRORED_REPEAT: 33648,
+ REPEAT: 10497
+};
+
+const KHR_MESH_QUANTIZATION = 'KHR_mesh_quantization';
+
+const THREE_TO_WEBGL = {};
+
+THREE_TO_WEBGL[ NearestFilter ] = WEBGL_CONSTANTS.NEAREST;
+THREE_TO_WEBGL[ NearestMipmapNearestFilter ] = WEBGL_CONSTANTS.NEAREST_MIPMAP_NEAREST;
+THREE_TO_WEBGL[ NearestMipmapLinearFilter ] = WEBGL_CONSTANTS.NEAREST_MIPMAP_LINEAR;
+THREE_TO_WEBGL[ LinearFilter ] = WEBGL_CONSTANTS.LINEAR;
+THREE_TO_WEBGL[ LinearMipmapNearestFilter ] = WEBGL_CONSTANTS.LINEAR_MIPMAP_NEAREST;
+THREE_TO_WEBGL[ LinearMipmapLinearFilter ] = WEBGL_CONSTANTS.LINEAR_MIPMAP_LINEAR;
+
+THREE_TO_WEBGL[ ClampToEdgeWrapping ] = WEBGL_CONSTANTS.CLAMP_TO_EDGE;
+THREE_TO_WEBGL[ RepeatWrapping ] = WEBGL_CONSTANTS.REPEAT;
+THREE_TO_WEBGL[ MirroredRepeatWrapping ] = WEBGL_CONSTANTS.MIRRORED_REPEAT;
+
+const PATH_PROPERTIES = {
+ scale: 'scale',
+ position: 'translation',
+ quaternion: 'rotation',
+ morphTargetInfluences: 'weights'
+};
+
+const DEFAULT_SPECULAR_COLOR = new Color();
+
+// GLB constants
+// https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification
+
+const GLB_HEADER_BYTES = 12;
+const GLB_HEADER_MAGIC = 0x46546C67;
+const GLB_VERSION = 2;
+
+const GLB_CHUNK_PREFIX_BYTES = 8;
+const GLB_CHUNK_TYPE_JSON = 0x4E4F534A;
+const GLB_CHUNK_TYPE_BIN = 0x004E4942;
+
+//------------------------------------------------------------------------------
+// Utility functions
+//------------------------------------------------------------------------------
+
+/**
+ * Compare two arrays
+ *
+ * @private
+ * @param {Array} array1 Array 1 to compare
+ * @param {Array} array2 Array 2 to compare
+ * @return {boolean} Returns true if both arrays are equal
+ */
+function equalArray( array1, array2 ) {
+
+ return ( array1.length === array2.length ) && array1.every( function ( element, index ) {
+
+ return element === array2[ index ];
+
+ } );
+
+}
+
+/**
+ * Converts a string to an ArrayBuffer.
+ *
+ * @private
+ * @param {string} text
+ * @return {ArrayBuffer}
+ */
+function stringToArrayBuffer( text ) {
+
+ return new TextEncoder().encode( text ).buffer;
+
+}
+
+/**
+ * Is identity matrix
+ *
+ * @private
+ * @param {Matrix4} matrix
+ * @returns {boolean} Returns true, if parameter is identity matrix
+ */
+function isIdentityMatrix( matrix ) {
+
+ return equalArray( matrix.elements, [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] );
+
+}
+
+/**
+ * Get the min and max vectors from the given attribute
+ *
+ * @private
+ * @param {BufferAttribute} attribute Attribute to find the min/max in range from start to start + count
+ * @param {number} start Start index
+ * @param {number} count Range to cover
+ * @return {Object} Object containing the `min` and `max` values (As an array of attribute.itemSize components)
+ */
+function getMinMax( attribute, start, count ) {
+
+ const output = {
+
+ min: new Array( attribute.itemSize ).fill( Number.POSITIVE_INFINITY ),
+ max: new Array( attribute.itemSize ).fill( Number.NEGATIVE_INFINITY )
+
+ };
+
+ for ( let i = start; i < start + count; i ++ ) {
+
+ for ( let a = 0; a < attribute.itemSize; a ++ ) {
+
+ let value;
+
+ if ( attribute.itemSize > 4 ) {
+
+ // no support for interleaved data for itemSize > 4
+
+ value = attribute.array[ i * attribute.itemSize + a ];
+
+ } else {
+
+ if ( a === 0 ) value = attribute.getX( i );
+ else if ( a === 1 ) value = attribute.getY( i );
+ else if ( a === 2 ) value = attribute.getZ( i );
+ else if ( a === 3 ) value = attribute.getW( i );
+
+ if ( attribute.normalized === true ) {
+
+ value = MathUtils.normalize( value, attribute.array );
+
+ }
+
+ }
+
+ output.min[ a ] = Math.min( output.min[ a ], value );
+ output.max[ a ] = Math.max( output.max[ a ], value );
+
+ }
+
+ }
+
+ return output;
+
+}
+
+/**
+ * Get the required size + padding for a buffer, rounded to the next 4-byte boundary.
+ * https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#data-alignment
+ *
+ * @private
+ * @param {number} bufferSize The size the original buffer. Should be an integer.
+ * @returns {number} new buffer size with required padding as an integer.
+ *
+ */
+function getPaddedBufferSize( bufferSize ) {
+
+ return Math.ceil( bufferSize / 4 ) * 4;
+
+}
+
+/**
+ * Returns a buffer aligned to 4-byte boundary.
+ *
+ * @private
+ * @param {ArrayBuffer} arrayBuffer Buffer to pad
+ * @param {number} [paddingByte=0] Should be an integer
+ * @returns {ArrayBuffer} The same buffer if it's already aligned to 4-byte boundary or a new buffer
+ */
+function getPaddedArrayBuffer( arrayBuffer, paddingByte = 0 ) {
+
+ const paddedLength = getPaddedBufferSize( arrayBuffer.byteLength );
+
+ if ( paddedLength !== arrayBuffer.byteLength ) {
+
+ const array = new Uint8Array( paddedLength );
+ array.set( new Uint8Array( arrayBuffer ) );
+
+ if ( paddingByte !== 0 ) {
+
+ for ( let i = arrayBuffer.byteLength; i < paddedLength; i ++ ) {
+
+ array[ i ] = paddingByte;
+
+ }
+
+ }
+
+ return array.buffer;
+
+ }
+
+ return arrayBuffer;
+
+}
+
+function getCanvas() {
+
+ if ( typeof document === 'undefined' && typeof OffscreenCanvas !== 'undefined' ) {
+
+ return new OffscreenCanvas( 1, 1 );
+
+ }
+
+ return document.createElement( 'canvas' );
+
+}
+
+function getToBlobPromise( canvas, mimeType ) {
+
+ if ( typeof OffscreenCanvas !== 'undefined' && canvas instanceof OffscreenCanvas ) {
+
+ let quality;
+
+ // Blink's implementation of convertToBlob seems to default to a quality level of 100%
+ // Use the Blink default quality levels of toBlob instead so that file sizes are comparable.
+ if ( mimeType === 'image/jpeg' ) {
+
+ quality = 0.92;
+
+ } else if ( mimeType === 'image/webp' ) {
+
+ quality = 0.8;
+
+ }
+
+ return canvas.convertToBlob( {
+
+ type: mimeType,
+ quality: quality
+
+ } );
+
+ } else {
+
+ // HTMLCanvasElement code path
+
+ return new Promise( ( resolve ) => canvas.toBlob( resolve, mimeType ) );
+
+ }
+
+}
+
+/**
+ * Writer
+ *
+ * @private
+ */
+class GLTFWriter {
+
+ constructor() {
+
+ this.plugins = [];
+
+ this.options = {};
+ this.pending = [];
+ this.buffers = [];
+
+ this.byteOffset = 0;
+ this.buffers = [];
+ this.nodeMap = new Map();
+ this.skins = [];
+
+ this.extensionsUsed = {};
+ this.extensionsRequired = {};
+
+ this.uids = new Map();
+ this.uid = 0;
+
+ this.json = {
+ asset: {
+ version: '2.0',
+ generator: 'THREE.GLTFExporter r' + REVISION
+ }
+ };
+
+ this.cache = {
+ meshes: new Map(),
+ attributes: new Map(),
+ attributesNormalized: new Map(),
+ materials: new Map(),
+ textures: new Map(),
+ images: new Map()
+ };
+
+ this.textureUtils = null;
+
+ }
+
+ setPlugins( plugins ) {
+
+ this.plugins = plugins;
+
+ }
+
+ setTextureUtils( utils ) {
+
+ this.textureUtils = utils;
+
+ }
+
+ /**
+ * Parse scenes and generate GLTF output
+ *
+ * @param {Scene|Array} input Scene or Array of THREE.Scenes
+ * @param {Function} onDone Callback on completed
+ * @param {Object} options options
+ */
+ async writeAsync( input, onDone, options = {} ) {
+
+ this.options = Object.assign( {
+ // default options
+ binary: false,
+ trs: false,
+ onlyVisible: true,
+ maxTextureSize: Infinity,
+ animations: [],
+ includeCustomExtensions: false
+ }, options );
+
+ if ( this.options.animations.length > 0 ) {
+
+ // Only TRS properties, and not matrices, may be targeted by animation.
+ this.options.trs = true;
+
+ }
+
+ await this.processInputAsync( input );
+
+ await Promise.all( this.pending );
+
+ const writer = this;
+ const buffers = writer.buffers;
+ const json = writer.json;
+ options = writer.options;
+
+ const extensionsUsed = writer.extensionsUsed;
+ const extensionsRequired = writer.extensionsRequired;
+
+ // Merge buffers.
+ const blob = new Blob( buffers, { type: 'application/octet-stream' } );
+
+ // Declare extensions.
+ const extensionsUsedList = Object.keys( extensionsUsed );
+ const extensionsRequiredList = Object.keys( extensionsRequired );
+
+ if ( extensionsUsedList.length > 0 ) json.extensionsUsed = extensionsUsedList;
+ if ( extensionsRequiredList.length > 0 ) json.extensionsRequired = extensionsRequiredList;
+
+ // Update bytelength of the single buffer.
+ if ( json.buffers && json.buffers.length > 0 ) json.buffers[ 0 ].byteLength = blob.size;
+
+ if ( options.binary === true ) {
+
+ // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification
+
+ const reader = new FileReader();
+ reader.readAsArrayBuffer( blob );
+ reader.onloadend = function () {
+
+ // Binary chunk.
+ const binaryChunk = getPaddedArrayBuffer( reader.result );
+ const binaryChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
+ binaryChunkPrefix.setUint32( 0, binaryChunk.byteLength, true );
+ binaryChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_BIN, true );
+
+ // JSON chunk.
+ const jsonChunk = getPaddedArrayBuffer( stringToArrayBuffer( JSON.stringify( json ) ), 0x20 );
+ const jsonChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
+ jsonChunkPrefix.setUint32( 0, jsonChunk.byteLength, true );
+ jsonChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_JSON, true );
+
+ // GLB header.
+ const header = new ArrayBuffer( GLB_HEADER_BYTES );
+ const headerView = new DataView( header );
+ headerView.setUint32( 0, GLB_HEADER_MAGIC, true );
+ headerView.setUint32( 4, GLB_VERSION, true );
+ const totalByteLength = GLB_HEADER_BYTES
+ + jsonChunkPrefix.byteLength + jsonChunk.byteLength
+ + binaryChunkPrefix.byteLength + binaryChunk.byteLength;
+ headerView.setUint32( 8, totalByteLength, true );
+
+ const glbBlob = new Blob( [
+ header,
+ jsonChunkPrefix,
+ jsonChunk,
+ binaryChunkPrefix,
+ binaryChunk
+ ], { type: 'application/octet-stream' } );
+
+ const glbReader = new FileReader();
+ glbReader.readAsArrayBuffer( glbBlob );
+ glbReader.onloadend = function () {
+
+ onDone( glbReader.result );
+
+ };
+
+ };
+
+ } else {
+
+ if ( json.buffers && json.buffers.length > 0 ) {
+
+ const reader = new FileReader();
+ reader.readAsDataURL( blob );
+ reader.onloadend = function () {
+
+ const base64data = reader.result;
+ json.buffers[ 0 ].uri = base64data;
+ onDone( json );
+
+ };
+
+ } else {
+
+ onDone( json );
+
+ }
+
+ }
+
+
+ }
+
+ /**
+ * Serializes a userData.
+ *
+ * @param {THREE.Object3D|THREE.Material|THREE.BufferGeometry|THREE.AnimationClip} object
+ * @param {Object} objectDef
+ */
+ serializeUserData( object, objectDef ) {
+
+ if ( Object.keys( object.userData ).length === 0 ) return;
+
+ const options = this.options;
+ const extensionsUsed = this.extensionsUsed;
+
+ try {
+
+ const json = JSON.parse( JSON.stringify( object.userData ) );
+
+ if ( options.includeCustomExtensions && json.gltfExtensions ) {
+
+ if ( objectDef.extensions === undefined ) objectDef.extensions = {};
+
+ for ( const extensionName in json.gltfExtensions ) {
+
+ objectDef.extensions[ extensionName ] = json.gltfExtensions[ extensionName ];
+ extensionsUsed[ extensionName ] = true;
+
+ }
+
+ delete json.gltfExtensions;
+
+ }
+
+ if ( Object.keys( json ).length > 0 ) objectDef.extras = json;
+
+ } catch ( error ) {
+
+ console.warn( 'THREE.GLTFExporter: userData of \'' + object.name + '\' ' +
+ 'won\'t be serialized because of JSON.stringify error - ' + error.message );
+
+ }
+
+ }
+
+ /**
+ * Returns ids for buffer attributes.
+ *
+ * @param {Object} attribute
+ * @param {boolean} [isRelativeCopy=false]
+ * @return {number} An integer
+ */
+ getUID( attribute, isRelativeCopy = false ) {
+
+ if ( this.uids.has( attribute ) === false ) {
+
+ const uids = new Map();
+
+ uids.set( true, this.uid ++ );
+ uids.set( false, this.uid ++ );
+
+ this.uids.set( attribute, uids );
+
+ }
+
+ const uids = this.uids.get( attribute );
+
+ return uids.get( isRelativeCopy );
+
+ }
+
+ /**
+ * Checks if normal attribute values are normalized.
+ *
+ * @param {BufferAttribute} normal
+ * @returns {boolean}
+ */
+ isNormalizedNormalAttribute( normal ) {
+
+ const cache = this.cache;
+
+ if ( cache.attributesNormalized.has( normal ) ) return false;
+
+ const v = new Vector3();
+
+ for ( let i = 0, il = normal.count; i < il; i ++ ) {
+
+ // 0.0005 is from glTF-validator
+ if ( Math.abs( v.fromBufferAttribute( normal, i ).length() - 1.0 ) > 0.0005 ) return false;
+
+ }
+
+ return true;
+
+ }
+
+ /**
+ * Creates normalized normal buffer attribute.
+ *
+ * @param {BufferAttribute} normal
+ * @returns {BufferAttribute}
+ *
+ */
+ createNormalizedNormalAttribute( normal ) {
+
+ const cache = this.cache;
+
+ if ( cache.attributesNormalized.has( normal ) ) return cache.attributesNormalized.get( normal );
+
+ const attribute = normal.clone();
+ const v = new Vector3();
+
+ for ( let i = 0, il = attribute.count; i < il; i ++ ) {
+
+ v.fromBufferAttribute( attribute, i );
+
+ if ( v.x === 0 && v.y === 0 && v.z === 0 ) {
+
+ // if values can't be normalized set (1, 0, 0)
+ v.setX( 1.0 );
+
+ } else {
+
+ v.normalize();
+
+ }
+
+ attribute.setXYZ( i, v.x, v.y, v.z );
+
+ }
+
+ cache.attributesNormalized.set( normal, attribute );
+
+ return attribute;
+
+ }
+
+ /**
+ * Applies a texture transform, if present, to the map definition. Requires
+ * the KHR_texture_transform extension.
+ *
+ * @param {Object} mapDef
+ * @param {THREE.Texture} texture
+ */
+ applyTextureTransform( mapDef, texture ) {
+
+ let didTransform = false;
+ const transformDef = {};
+
+ if ( texture.offset.x !== 0 || texture.offset.y !== 0 ) {
+
+ transformDef.offset = texture.offset.toArray();
+ didTransform = true;
+
+ }
+
+ if ( texture.rotation !== 0 ) {
+
+ transformDef.rotation = texture.rotation;
+ didTransform = true;
+
+ }
+
+ if ( texture.repeat.x !== 1 || texture.repeat.y !== 1 ) {
+
+ transformDef.scale = texture.repeat.toArray();
+ didTransform = true;
+
+ }
+
+ if ( didTransform ) {
+
+ mapDef.extensions = mapDef.extensions || {};
+ mapDef.extensions[ 'KHR_texture_transform' ] = transformDef;
+ this.extensionsUsed[ 'KHR_texture_transform' ] = true;
+
+ }
+
+ }
+
+ async buildMetalRoughTextureAsync( metalnessMap, roughnessMap ) {
+
+ if ( metalnessMap === roughnessMap ) return metalnessMap;
+
+ function getEncodingConversion( map ) {
+
+ if ( map.colorSpace === SRGBColorSpace ) {
+
+ return function SRGBToLinear( c ) {
+
+ return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
+
+ };
+
+ }
+
+ return function LinearToLinear( c ) {
+
+ return c;
+
+ };
+
+ }
+
+ if ( metalnessMap instanceof CompressedTexture ) {
+
+ metalnessMap = await this.decompressTextureAsync( metalnessMap );
+
+ }
+
+ if ( roughnessMap instanceof CompressedTexture ) {
+
+ roughnessMap = await this.decompressTextureAsync( roughnessMap );
+
+ }
+
+ const metalness = metalnessMap ? metalnessMap.image : null;
+ const roughness = roughnessMap ? roughnessMap.image : null;
+
+ const width = Math.max( metalness ? metalness.width : 0, roughness ? roughness.width : 0 );
+ const height = Math.max( metalness ? metalness.height : 0, roughness ? roughness.height : 0 );
+
+ const canvas = getCanvas();
+ canvas.width = width;
+ canvas.height = height;
+
+ const context = canvas.getContext( '2d', {
+ willReadFrequently: true,
+ } );
+ context.fillStyle = '#00ffff';
+ context.fillRect( 0, 0, width, height );
+
+ const composite = context.getImageData( 0, 0, width, height );
+
+ if ( metalness ) {
+
+ context.drawImage( metalness, 0, 0, width, height );
+
+ const convert = getEncodingConversion( metalnessMap );
+ const data = context.getImageData( 0, 0, width, height ).data;
+
+ for ( let i = 2; i < data.length; i += 4 ) {
+
+ composite.data[ i ] = convert( data[ i ] / 256 ) * 256;
+
+ }
+
+ }
+
+ if ( roughness ) {
+
+ context.drawImage( roughness, 0, 0, width, height );
+
+ const convert = getEncodingConversion( roughnessMap );
+ const data = context.getImageData( 0, 0, width, height ).data;
+
+ for ( let i = 1; i < data.length; i += 4 ) {
+
+ composite.data[ i ] = convert( data[ i ] / 256 ) * 256;
+
+ }
+
+ }
+
+ context.putImageData( composite, 0, 0 );
+
+ //
+
+ const reference = metalnessMap || roughnessMap;
+
+ const texture = reference.clone();
+
+ texture.source = new Source( canvas );
+ texture.colorSpace = NoColorSpace;
+ texture.channel = ( metalnessMap || roughnessMap ).channel;
+
+ if ( metalnessMap && roughnessMap && metalnessMap.channel !== roughnessMap.channel ) {
+
+ console.warn( 'THREE.GLTFExporter: UV channels for metalnessMap and roughnessMap textures must match.' );
+
+ }
+
+ console.warn( 'THREE.GLTFExporter: Merged metalnessMap and roughnessMap textures.' );
+
+ return texture;
+
+ }
+
+
+ /**
+ * Builds a copy of the given normal map with the red and/or green channels
+ * inverted (`color = 255 - color`). This is used to bake the sign of
+ * `material.normalScale` and the tangent-space convention into the texture,
+ * since glTF only supports OpenGL-style normal maps with a univariate,
+ * positive scale.
+ *
+ * @param {THREE.Texture} normalMap The source normal map.
+ * @param {boolean} flipX Whether to invert the red channel (normal X).
+ * @param {boolean} flipY Whether to invert the green channel (normal Y).
+ * @return {Promise} The derived normal map texture.
+ */
+ async buildNormalMapTextureAsync( normalMap, flipX, flipY ) {
+
+ if ( normalMap instanceof CompressedTexture ) {
+
+ normalMap = await this.decompressTextureAsync( normalMap );
+
+ }
+
+ const image = normalMap.image;
+
+ const canvas = getCanvas();
+ canvas.width = image.width;
+ canvas.height = image.height;
+
+ const context = canvas.getContext( '2d', {
+ willReadFrequently: true,
+ } );
+
+ context.drawImage( image, 0, 0, canvas.width, canvas.height );
+
+ const imageData = context.getImageData( 0, 0, canvas.width, canvas.height );
+ const data = imageData.data;
+
+ for ( let i = 0; i < data.length; i += 4 ) {
+
+ if ( flipX ) data[ i + 0 ] = 255 - data[ i + 0 ];
+ if ( flipY ) data[ i + 1 ] = 255 - data[ i + 1 ];
+
+ }
+
+ context.putImageData( imageData, 0, 0 );
+
+ const texture = normalMap.clone();
+ texture.source = new Source( canvas );
+
+ return texture;
+
+ }
+
+ async decompressTextureAsync( texture, maxTextureSize = Infinity ) {
+
+ if ( this.textureUtils === null ) {
+
+ throw new Error( 'THREE.GLTFExporter: setTextureUtils() must be called to process compressed textures.' );
+
+ }
+
+ return await this.textureUtils.decompress( texture, maxTextureSize );
+
+ }
+
+ /**
+ * Process a buffer to append to the default one.
+ * @param {ArrayBuffer} buffer
+ * @return {0}
+ */
+ processBuffer( buffer ) {
+
+ const json = this.json;
+ const buffers = this.buffers;
+
+ if ( ! json.buffers ) json.buffers = [ { byteLength: 0 } ];
+
+ // All buffers are merged before export.
+ buffers.push( buffer );
+
+ return 0;
+
+ }
+
+ /**
+ * Process and generate a BufferView
+ * @param {BufferAttribute} attribute
+ * @param {number} componentType
+ * @param {number} start
+ * @param {number} count
+ * @param {number} [target] Target usage of the BufferView
+ * @return {Object}
+ */
+ processBufferView( attribute, componentType, start, count, target ) {
+
+ const json = this.json;
+
+ if ( ! json.bufferViews ) json.bufferViews = [];
+
+ // Create a new dataview and dump the attribute's array into it
+
+ let componentSize;
+
+ switch ( componentType ) {
+
+ case WEBGL_CONSTANTS.BYTE:
+ case WEBGL_CONSTANTS.UNSIGNED_BYTE:
+
+ componentSize = 1;
+
+ break;
+
+ case WEBGL_CONSTANTS.SHORT:
+ case WEBGL_CONSTANTS.UNSIGNED_SHORT:
+
+ componentSize = 2;
+
+ break;
+
+ default:
+
+ componentSize = 4;
+
+ }
+
+ let byteStride = attribute.itemSize * componentSize;
+
+ if ( target === WEBGL_CONSTANTS.ARRAY_BUFFER ) {
+
+ // Each element of a vertex attribute MUST be aligned to 4-byte boundaries
+ // inside a bufferView
+ byteStride = Math.ceil( byteStride / 4 ) * 4;
+
+ }
+
+ const byteLength = getPaddedBufferSize( count * byteStride );
+ const dataView = new DataView( new ArrayBuffer( byteLength ) );
+ let offset = 0;
+
+ for ( let i = start; i < start + count; i ++ ) {
+
+ for ( let a = 0; a < attribute.itemSize; a ++ ) {
+
+ let value;
+
+ if ( attribute.itemSize > 4 ) {
+
+ // no support for interleaved data for itemSize > 4
+
+ value = attribute.array[ i * attribute.itemSize + a ];
+
+ } else {
+
+ if ( a === 0 ) value = attribute.getX( i );
+ else if ( a === 1 ) value = attribute.getY( i );
+ else if ( a === 2 ) value = attribute.getZ( i );
+ else if ( a === 3 ) value = attribute.getW( i );
+
+ if ( attribute.normalized === true ) {
+
+ value = MathUtils.normalize( value, attribute.array );
+
+ }
+
+ }
+
+ if ( componentType === WEBGL_CONSTANTS.FLOAT ) {
+
+ dataView.setFloat32( offset, value, true );
+
+ } else if ( componentType === WEBGL_CONSTANTS.INT ) {
+
+ dataView.setInt32( offset, value, true );
+
+ } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_INT ) {
+
+ dataView.setUint32( offset, value, true );
+
+ } else if ( componentType === WEBGL_CONSTANTS.SHORT ) {
+
+ dataView.setInt16( offset, value, true );
+
+ } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ) {
+
+ dataView.setUint16( offset, value, true );
+
+ } else if ( componentType === WEBGL_CONSTANTS.BYTE ) {
+
+ dataView.setInt8( offset, value );
+
+ } else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE ) {
+
+ dataView.setUint8( offset, value );
+
+ }
+
+ offset += componentSize;
+
+ }
+
+ if ( ( offset % byteStride ) !== 0 ) {
+
+ offset += byteStride - ( offset % byteStride );
+
+ }
+
+ }
+
+ const bufferViewDef = {
+
+ buffer: this.processBuffer( dataView.buffer ),
+ byteOffset: this.byteOffset,
+ byteLength: byteLength
+
+ };
+
+ if ( target !== undefined ) bufferViewDef.target = target;
+
+ if ( target === WEBGL_CONSTANTS.ARRAY_BUFFER ) {
+
+ // Only define byteStride for vertex attributes.
+ bufferViewDef.byteStride = byteStride;
+
+ }
+
+ this.byteOffset += byteLength;
+
+ json.bufferViews.push( bufferViewDef );
+
+ // @TODO Merge bufferViews where possible.
+ const output = {
+
+ id: json.bufferViews.length - 1,
+ byteLength: 0
+
+ };
+
+ return output;
+
+ }
+
+ /**
+ * Process and generate a BufferView from an image Blob.
+ * @param {Blob} blob
+ * @return {Promise} An integer
+ */
+ processBufferViewImage( blob ) {
+
+ const writer = this;
+ const json = writer.json;
+
+ if ( ! json.bufferViews ) json.bufferViews = [];
+
+ return new Promise( function ( resolve ) {
+
+ const reader = new FileReader();
+ reader.readAsArrayBuffer( blob );
+ reader.onloadend = function () {
+
+ const buffer = getPaddedArrayBuffer( reader.result );
+
+ const bufferViewDef = {
+ buffer: writer.processBuffer( buffer ),
+ byteOffset: writer.byteOffset,
+ byteLength: buffer.byteLength
+ };
+
+ writer.byteOffset += buffer.byteLength;
+ resolve( json.bufferViews.push( bufferViewDef ) - 1 );
+
+ };
+
+ } );
+
+ }
+
+ /**
+ * Process attribute to generate an accessor
+ * @param {BufferAttribute} attribute Attribute to process
+ * @param {?BufferGeometry} [geometry] Geometry used for truncated draw range
+ * @param {number} [start=0]
+ * @param {number} [count=Infinity]
+ * @return {?number} Index of the processed accessor on the "accessors" array
+ */
+ processAccessor( attribute, geometry, start, count ) {
+
+ const json = this.json;
+
+ const types = {
+
+ 1: 'SCALAR',
+ 2: 'VEC2',
+ 3: 'VEC3',
+ 4: 'VEC4',
+ 9: 'MAT3',
+ 16: 'MAT4'
+
+ };
+
+ let componentType;
+
+ // Detect the component type of the attribute array
+ if ( attribute.array.constructor === Float32Array ) {
+
+ componentType = WEBGL_CONSTANTS.FLOAT;
+
+ } else if ( attribute.array.constructor === Int32Array ) {
+
+ componentType = WEBGL_CONSTANTS.INT;
+
+ } else if ( attribute.array.constructor === Uint32Array ) {
+
+ componentType = WEBGL_CONSTANTS.UNSIGNED_INT;
+
+ } else if ( attribute.array.constructor === Int16Array ) {
+
+ componentType = WEBGL_CONSTANTS.SHORT;
+
+ } else if ( attribute.array.constructor === Uint16Array ) {
+
+ componentType = WEBGL_CONSTANTS.UNSIGNED_SHORT;
+
+ } else if ( attribute.array.constructor === Int8Array ) {
+
+ componentType = WEBGL_CONSTANTS.BYTE;
+
+ } else if ( attribute.array.constructor === Uint8Array ) {
+
+ componentType = WEBGL_CONSTANTS.UNSIGNED_BYTE;
+
+ } else {
+
+ throw new Error( 'THREE.GLTFExporter: Unsupported bufferAttribute component type: ' + attribute.array.constructor.name );
+
+ }
+
+ if ( start === undefined ) start = 0;
+ if ( count === undefined || count === Infinity ) count = attribute.count;
+
+ // Skip creating an accessor if the attribute doesn't have data to export
+ if ( count === 0 ) return null;
+
+ const minMax = getMinMax( attribute, start, count );
+ let bufferViewTarget;
+
+ // If geometry isn't provided, don't infer the target usage of the bufferView. For
+ // animation samplers, target must not be set.
+ if ( geometry !== undefined ) {
+
+ bufferViewTarget = attribute === geometry.index ? WEBGL_CONSTANTS.ELEMENT_ARRAY_BUFFER : WEBGL_CONSTANTS.ARRAY_BUFFER;
+
+ }
+
+ const bufferView = this.processBufferView( attribute, componentType, start, count, bufferViewTarget );
+
+ const accessorDef = {
+
+ bufferView: bufferView.id,
+ byteOffset: bufferView.byteOffset,
+ componentType: componentType,
+ count: count,
+ max: minMax.max,
+ min: minMax.min,
+ type: types[ attribute.itemSize ]
+
+ };
+
+ if ( attribute.normalized === true ) accessorDef.normalized = true;
+ if ( ! json.accessors ) json.accessors = [];
+
+ return json.accessors.push( accessorDef ) - 1;
+
+ }
+
+ /**
+ * Process image
+ * @param {Image} image to process
+ * @param {number} format Identifier of the format (RGBAFormat)
+ * @param {boolean} flipY before writing out the image
+ * @param {string} mimeType export format
+ * @return {number} Index of the processed texture in the "images" array
+ */
+ processImage( image, format, flipY, mimeType = 'image/png' ) {
+
+ if ( image !== null ) {
+
+ const writer = this;
+ const cache = writer.cache;
+ const json = writer.json;
+ const options = writer.options;
+ const pending = writer.pending;
+
+ if ( ! cache.images.has( image ) ) cache.images.set( image, {} );
+
+ const cachedImages = cache.images.get( image );
+
+ const key = mimeType + ':flipY/' + flipY.toString();
+
+ if ( cachedImages[ key ] !== undefined ) return cachedImages[ key ];
+
+ if ( ! json.images ) json.images = [];
+
+ const imageDef = { mimeType: mimeType };
+
+ const canvas = getCanvas();
+
+ canvas.width = Math.min( image.width, options.maxTextureSize );
+ canvas.height = Math.min( image.height, options.maxTextureSize );
+
+ const ctx = canvas.getContext( '2d', {
+ willReadFrequently: true,
+ } );
+
+ if ( flipY === true ) {
+
+ ctx.translate( 0, canvas.height );
+ ctx.scale( 1, - 1 );
+
+ }
+
+ if ( image.data !== undefined ) { // THREE.DataTexture
+
+ if ( format !== RGBAFormat ) {
+
+ console.error( 'GLTFExporter: Only RGBAFormat is supported.', format );
+
+ }
+
+ if ( image.width > options.maxTextureSize || image.height > options.maxTextureSize ) {
+
+ console.warn( 'GLTFExporter: Image size is bigger than maxTextureSize', image );
+
+ }
+
+ const data = new Uint8ClampedArray( image.height * image.width * 4 );
+
+ for ( let i = 0; i < data.length; i += 4 ) {
+
+ data[ i + 0 ] = image.data[ i + 0 ];
+ data[ i + 1 ] = image.data[ i + 1 ];
+ data[ i + 2 ] = image.data[ i + 2 ];
+ data[ i + 3 ] = image.data[ i + 3 ];
+
+ }
+
+ ctx.putImageData( new ImageData( data, image.width, image.height ), 0, 0 );
+
+ } else {
+
+ if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
+ ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
+ ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ||
+ ( typeof OffscreenCanvas !== 'undefined' && image instanceof OffscreenCanvas ) ) {
+
+ ctx.drawImage( image, 0, 0, canvas.width, canvas.height );
+
+ } else {
+
+ throw new Error( 'THREE.GLTFExporter: Invalid image type. Use HTMLImageElement, HTMLCanvasElement, ImageBitmap or OffscreenCanvas.' );
+
+ }
+
+ }
+
+ if ( options.binary === true ) {
+
+ pending.push(
+
+ getToBlobPromise( canvas, mimeType )
+ .then( blob => writer.processBufferViewImage( blob ) )
+ .then( bufferViewIndex => {
+
+ imageDef.bufferView = bufferViewIndex;
+
+ } )
+
+ );
+
+ } else {
+
+ imageDef.uri = ImageUtils.getDataURL( canvas, mimeType );
+
+ }
+
+ const index = json.images.push( imageDef ) - 1;
+ cachedImages[ key ] = index;
+ return index;
+
+ } else {
+
+ throw new Error( 'THREE.GLTFExporter: No valid image data found. Unable to process texture.' );
+
+ }
+
+ }
+
+ /**
+ * Process sampler
+ * @param {Texture} map Texture to process
+ * @return {number} Index of the processed texture in the "samplers" array
+ */
+ processSampler( map ) {
+
+ const json = this.json;
+
+ if ( ! json.samplers ) json.samplers = [];
+
+ const samplerDef = {
+ magFilter: THREE_TO_WEBGL[ map.magFilter ],
+ minFilter: THREE_TO_WEBGL[ map.minFilter ],
+ wrapS: THREE_TO_WEBGL[ map.wrapS ],
+ wrapT: THREE_TO_WEBGL[ map.wrapT ]
+ };
+
+ return json.samplers.push( samplerDef ) - 1;
+
+ }
+
+ /**
+ * Process texture
+ * @param {Texture} map Map to process
+ * @return {Promise} Index of the processed texture in the "textures" array
+ */
+ async processTextureAsync( map ) {
+
+ const writer = this;
+ const options = writer.options;
+ const cache = this.cache;
+ const json = this.json;
+
+ if ( cache.textures.has( map ) ) return cache.textures.get( map );
+
+ if ( ! json.textures ) json.textures = [];
+
+ // make non-readable textures (e.g. CompressedTexture) readable by blitting them into a new texture
+ if ( map instanceof CompressedTexture ) {
+
+ map = await this.decompressTextureAsync( map, options.maxTextureSize );
+
+ }
+
+ const mimeType = map.userData.mimeType;
+
+ const imageIndex = this.processImage( map.image, map.format, map.flipY, mimeType );
+
+ const textureDef = {
+ sampler: this.processSampler( map )
+ };
+
+ if ( mimeType === 'image/webp' ) {
+
+ textureDef.extensions = textureDef.extensions || {};
+ textureDef.extensions[ 'EXT_texture_webp' ] = {
+ source: imageIndex
+ };
+
+ this.extensionsUsed[ 'EXT_texture_webp' ] = true;
+ this.extensionsRequired[ 'EXT_texture_webp' ] = true;
+
+ } else {
+
+ textureDef.source = imageIndex;
+
+ }
+
+ if ( map.name ) textureDef.name = map.name;
+
+ await this._invokeAllAsync( async function ( ext ) {
+
+ ext.writeTexture && await ext.writeTexture( map, textureDef );
+
+ } );
+
+ const index = json.textures.push( textureDef ) - 1;
+ cache.textures.set( map, index );
+ return index;
+
+ }
+
+ /**
+ * Process material
+ * @param {THREE.Material} material Material to process
+ * @param {THREE.BufferGeometry} [geometry] Geometry the material is used with.
+ * @return {Promise} Index of the processed material in the "materials" array
+ */
+ async processMaterialAsync( material, geometry ) {
+
+ const cache = this.cache;
+ const json = this.json;
+
+ // Whether the geometry provides explicit tangents. The exported normal map depends on
+ // this, so it is part of the material cache key.
+ const hasTangent = geometry !== undefined && geometry.hasAttribute( 'tangent' );
+ const cacheKey = material.normalMap ? material.uuid + ':' + hasTangent : material.uuid;
+
+ if ( cache.materials.has( cacheKey ) ) return cache.materials.get( cacheKey );
+
+ if ( material.isShaderMaterial ) {
+
+ console.warn( 'GLTFExporter: THREE.ShaderMaterial not supported.' );
+ return null;
+
+ }
+
+ if ( ! json.materials ) json.materials = [];
+
+ // @QUESTION Should we avoid including any attribute that has the default value?
+ const materialDef = { pbrMetallicRoughness: {} };
+
+ if ( material.isMeshStandardMaterial !== true && material.isMeshBasicMaterial !== true ) {
+
+ console.warn( 'GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results.' );
+
+ }
+
+ // pbrMetallicRoughness.baseColorFactor
+ const color = material.color.toArray().concat( [ material.opacity ] );
+
+ if ( ! equalArray( color, [ 1, 1, 1, 1 ] ) ) {
+
+ materialDef.pbrMetallicRoughness.baseColorFactor = color;
+
+ }
+
+ if ( material.isMeshStandardMaterial ) {
+
+ materialDef.pbrMetallicRoughness.metallicFactor = material.metalness;
+ materialDef.pbrMetallicRoughness.roughnessFactor = material.roughness;
+
+ } else {
+
+ materialDef.pbrMetallicRoughness.metallicFactor = 0;
+ materialDef.pbrMetallicRoughness.roughnessFactor = 1;
+
+ }
+
+ // pbrMetallicRoughness.metallicRoughnessTexture
+ if ( material.metalnessMap || material.roughnessMap ) {
+
+ const metalRoughTexture = await this.buildMetalRoughTextureAsync( material.metalnessMap, material.roughnessMap );
+
+ const metalRoughMapDef = {
+ index: await this.processTextureAsync( metalRoughTexture ),
+ texCoord: metalRoughTexture.channel
+ };
+ this.applyTextureTransform( metalRoughMapDef, metalRoughTexture );
+ materialDef.pbrMetallicRoughness.metallicRoughnessTexture = metalRoughMapDef;
+
+ }
+
+ // pbrMetallicRoughness.baseColorTexture
+ if ( material.map ) {
+
+ const baseColorMapDef = {
+ index: await this.processTextureAsync( material.map ),
+ texCoord: material.map.channel
+ };
+ this.applyTextureTransform( baseColorMapDef, material.map );
+ materialDef.pbrMetallicRoughness.baseColorTexture = baseColorMapDef;
+
+ }
+
+ if ( material.emissive ) {
+
+ const emissive = material.emissive;
+ const maxEmissiveComponent = Math.max( emissive.r, emissive.g, emissive.b );
+
+ if ( maxEmissiveComponent > 0 ) {
+
+ materialDef.emissiveFactor = material.emissive.toArray();
+
+ }
+
+ // emissiveTexture
+ if ( material.emissiveMap ) {
+
+ const emissiveMapDef = {
+ index: await this.processTextureAsync( material.emissiveMap ),
+ texCoord: material.emissiveMap.channel
+ };
+ this.applyTextureTransform( emissiveMapDef, material.emissiveMap );
+ materialDef.emissiveTexture = emissiveMapDef;
+
+ }
+
+ }
+
+ // normalTexture
+ if ( material.normalMap ) {
+
+ const normalScale = material.normalScale;
+
+ // glTF only supports OpenGL-style normal maps with a univariate, positive scale.
+ // A negative `normalScale` component is baked into the texture by inverting the
+ // corresponding channel. Meshes without explicit tangents use the opposite
+ // green-channel convention, so the green channel is inverted in that case too.
+ //
+ // The no-tangent green flip is the counterpart of GLTFLoader, which negates
+ // `normalScale.y` on import for the same case.
+ const flipX = normalScale.x < 0;
+ const flipY = hasTangent ? normalScale.y < 0 : normalScale.y > 0;
+
+ let normalMap = material.normalMap;
+
+ if ( flipX || flipY ) {
+
+ normalMap = await this.buildNormalMapTextureAsync( material.normalMap, flipX, flipY );
+
+ }
+
+ const normalMapDef = {
+ index: await this.processTextureAsync( normalMap ),
+ texCoord: material.normalMap.channel
+ };
+
+ if ( Math.abs( normalScale.x ) !== 1 ) {
+
+ // glTF normal scale is univariate. The magnitude of `x` is used; the sign of
+ // both components has already been baked into the texture above.
+ normalMapDef.scale = Math.abs( normalScale.x );
+
+ }
+
+ this.applyTextureTransform( normalMapDef, material.normalMap );
+ materialDef.normalTexture = normalMapDef;
+
+ }
+
+ // occlusionTexture
+ if ( material.aoMap ) {
+
+ const occlusionMapDef = {
+ index: await this.processTextureAsync( material.aoMap ),
+ texCoord: material.aoMap.channel
+ };
+
+ if ( material.aoMapIntensity !== 1.0 ) {
+
+ occlusionMapDef.strength = material.aoMapIntensity;
+
+ }
+
+ this.applyTextureTransform( occlusionMapDef, material.aoMap );
+ materialDef.occlusionTexture = occlusionMapDef;
+
+ }
+
+ // alphaMode
+ if ( material.transparent ) {
+
+ materialDef.alphaMode = 'BLEND';
+
+ } else {
+
+ if ( material.alphaTest > 0.0 ) {
+
+ materialDef.alphaMode = 'MASK';
+ materialDef.alphaCutoff = material.alphaTest;
+
+ }
+
+ }
+
+ // doubleSided
+ if ( material.side === DoubleSide ) materialDef.doubleSided = true;
+ if ( material.name !== '' ) materialDef.name = material.name;
+
+ this.serializeUserData( material, materialDef );
+
+ await this._invokeAllAsync( async function ( ext ) {
+
+ ext.writeMaterialAsync && await ext.writeMaterialAsync( material, materialDef );
+
+ } );
+
+ const index = json.materials.push( materialDef ) - 1;
+ cache.materials.set( cacheKey, index );
+ return index;
+
+ }
+
+ /**
+ * Process mesh
+ * @param {THREE.Mesh} mesh Mesh to process
+ * @return {Promise} Index of the processed mesh in the "meshes" array
+ */
+ async processMeshAsync( mesh ) {
+
+ const cache = this.cache;
+ const json = this.json;
+
+ const meshCacheKeyParts = [ mesh.geometry.uuid ];
+
+ if ( Array.isArray( mesh.material ) ) {
+
+ for ( let i = 0, l = mesh.material.length; i < l; i ++ ) {
+
+ meshCacheKeyParts.push( mesh.material[ i ].uuid );
+
+ }
+
+ } else {
+
+ meshCacheKeyParts.push( mesh.material.uuid );
+
+ }
+
+ const meshCacheKey = meshCacheKeyParts.join( ':' );
+
+ if ( cache.meshes.has( meshCacheKey ) ) return cache.meshes.get( meshCacheKey );
+
+ const geometry = mesh.geometry;
+
+ let mode;
+
+ // Use the correct mode
+ if ( mesh.isLineSegments ) {
+
+ mode = WEBGL_CONSTANTS.LINES;
+
+ } else if ( mesh.isLineLoop ) {
+
+ mode = WEBGL_CONSTANTS.LINE_LOOP;
+
+ } else if ( mesh.isLine ) {
+
+ mode = WEBGL_CONSTANTS.LINE_STRIP;
+
+ } else if ( mesh.isPoints ) {
+
+ mode = WEBGL_CONSTANTS.POINTS;
+
+ } else {
+
+ mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINES : WEBGL_CONSTANTS.TRIANGLES;
+
+ }
+
+ const meshDef = {};
+ const attributes = {};
+ const primitives = [];
+ const targets = [];
+
+ // Conversion between attributes names in threejs and gltf spec
+ const nameConversion = {
+ uv: 'TEXCOORD_0',
+ uv1: 'TEXCOORD_1',
+ uv2: 'TEXCOORD_2',
+ uv3: 'TEXCOORD_3',
+ color: 'COLOR_0',
+ skinWeight: 'WEIGHTS_0',
+ skinIndex: 'JOINTS_0'
+ };
+
+ const originalNormal = geometry.getAttribute( 'normal' );
+
+ if ( originalNormal !== undefined && ! this.isNormalizedNormalAttribute( originalNormal ) ) {
+
+ console.warn( 'THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one.' );
+
+ geometry.setAttribute( 'normal', this.createNormalizedNormalAttribute( originalNormal ) );
+
+ }
+
+ // @QUESTION Detect if .vertexColors = true?
+ // For every attribute create an accessor
+ let modifiedAttribute = null;
+
+ for ( let attributeName in geometry.attributes ) {
+
+ // Ignore morph target attributes, which are exported later.
+ if ( attributeName.slice( 0, 5 ) === 'morph' ) continue;
+
+ const attribute = geometry.attributes[ attributeName ];
+ attributeName = nameConversion[ attributeName ] || attributeName.toUpperCase();
+
+ // Prefix all geometry attributes except the ones specifically
+ // listed in the spec; non-spec attributes are considered custom.
+ const validVertexAttributes =
+ /^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/;
+
+ if ( ! validVertexAttributes.test( attributeName ) && ! attributeName.startsWith( '_' ) ) attributeName = '_' + attributeName;
+
+ if ( cache.attributes.has( this.getUID( attribute ) ) ) {
+
+ attributes[ attributeName ] = cache.attributes.get( this.getUID( attribute ) );
+ continue;
+
+ }
+
+ // Enforce glTF vertex attribute requirements:
+ // - JOINTS_0 must be UNSIGNED_BYTE or UNSIGNED_SHORT
+ // - Only custom attributes may be INT or UNSIGNED_INT
+ modifiedAttribute = null;
+ const array = attribute.array;
+
+ if ( attributeName === 'JOINTS_0' &&
+ ! ( array instanceof Uint16Array ) &&
+ ! ( array instanceof Uint8Array ) ) {
+
+ console.warn( 'GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.' );
+ modifiedAttribute = GLTFExporter.Utils.toTypedBufferAttribute( attribute, Uint16Array );
+
+ } else if ( ( array instanceof Uint32Array || array instanceof Int32Array ) && ! attributeName.startsWith( '_' ) ) {
+
+ console.warn( `GLTFExporter: Attribute "${ attributeName }" converted to type FLOAT.` );
+ modifiedAttribute = GLTFExporter.Utils.toTypedBufferAttribute( attribute, Float32Array );
+
+ }
+
+ const accessor = this.processAccessor( modifiedAttribute || attribute, geometry );
+
+ if ( accessor !== null ) {
+
+ if ( ! attributeName.startsWith( '_' ) ) {
+
+ this.detectMeshQuantization( attributeName, attribute );
+
+ }
+
+ attributes[ attributeName ] = accessor;
+ cache.attributes.set( this.getUID( attribute ), accessor );
+
+ }
+
+ }
+
+ if ( originalNormal !== undefined ) geometry.setAttribute( 'normal', originalNormal );
+
+ // Skip if no exportable attributes found
+ if ( Object.keys( attributes ).length === 0 ) return null;
+
+ // Morph targets
+ if ( mesh.morphTargetInfluences !== undefined && mesh.morphTargetInfluences.length > 0 ) {
+
+ const weights = [];
+ const targetNames = [];
+ const reverseDictionary = {};
+
+ if ( mesh.morphTargetDictionary !== undefined ) {
+
+ for ( const key in mesh.morphTargetDictionary ) {
+
+ reverseDictionary[ mesh.morphTargetDictionary[ key ] ] = key;
+
+ }
+
+ }
+
+ for ( let i = 0; i < mesh.morphTargetInfluences.length; ++ i ) {
+
+ const target = {};
+ let warned = false;
+
+ for ( const attributeName in geometry.morphAttributes ) {
+
+ // glTF 2.0 morph supports only POSITION/NORMAL/TANGENT.
+ // Three.js doesn't support TANGENT yet.
+
+ if ( attributeName !== 'position' && attributeName !== 'normal' ) {
+
+ if ( ! warned ) {
+
+ console.warn( 'GLTFExporter: Only POSITION and NORMAL morph are supported.' );
+ warned = true;
+
+ }
+
+ continue;
+
+ }
+
+ const attribute = geometry.morphAttributes[ attributeName ][ i ];
+ const gltfAttributeName = attributeName.toUpperCase();
+
+ // Three.js morph attribute has absolute values while the one of glTF has relative values.
+ //
+ // glTF 2.0 Specification:
+ // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#morph-targets
+
+ const baseAttribute = geometry.attributes[ attributeName ];
+
+ if ( cache.attributes.has( this.getUID( attribute, true ) ) ) {
+
+ target[ gltfAttributeName ] = cache.attributes.get( this.getUID( attribute, true ) );
+ continue;
+
+ }
+
+ // Clones attribute not to override
+ const relativeAttribute = attribute.clone();
+
+ if ( ! geometry.morphTargetsRelative ) {
+
+ for ( let j = 0, jl = attribute.count; j < jl; j ++ ) {
+
+ for ( let a = 0; a < attribute.itemSize; a ++ ) {
+
+ if ( a === 0 ) relativeAttribute.setX( j, attribute.getX( j ) - baseAttribute.getX( j ) );
+ if ( a === 1 ) relativeAttribute.setY( j, attribute.getY( j ) - baseAttribute.getY( j ) );
+ if ( a === 2 ) relativeAttribute.setZ( j, attribute.getZ( j ) - baseAttribute.getZ( j ) );
+ if ( a === 3 ) relativeAttribute.setW( j, attribute.getW( j ) - baseAttribute.getW( j ) );
+
+ }
+
+ }
+
+ }
+
+ target[ gltfAttributeName ] = this.processAccessor( relativeAttribute, geometry );
+ cache.attributes.set( this.getUID( baseAttribute, true ), target[ gltfAttributeName ] );
+
+ }
+
+ targets.push( target );
+
+ weights.push( mesh.morphTargetInfluences[ i ] );
+
+ if ( mesh.morphTargetDictionary !== undefined ) targetNames.push( reverseDictionary[ i ] );
+
+ }
+
+ meshDef.weights = weights;
+
+ if ( targetNames.length > 0 ) {
+
+ meshDef.extras = {};
+ meshDef.extras.targetNames = targetNames;
+
+ }
+
+ }
+
+ const isMultiMaterial = Array.isArray( mesh.material );
+
+ if ( isMultiMaterial && geometry.groups.length === 0 ) return null;
+
+ let didForceIndices = false;
+
+ if ( isMultiMaterial && geometry.index === null ) {
+
+ const indices = [];
+
+ for ( let i = 0, il = geometry.attributes.position.count; i < il; i ++ ) {
+
+ indices[ i ] = i;
+
+ }
+
+ geometry.setIndex( indices );
+
+ didForceIndices = true;
+
+ }
+
+ const materials = isMultiMaterial ? mesh.material : [ mesh.material ];
+ const groups = isMultiMaterial ? geometry.groups : [ { materialIndex: 0, start: undefined, count: undefined } ];
+
+ for ( let i = 0, il = groups.length; i < il; i ++ ) {
+
+ const primitive = {
+ mode: mode,
+ attributes: attributes,
+ };
+
+ this.serializeUserData( geometry, primitive );
+
+ if ( targets.length > 0 ) primitive.targets = targets;
+
+ if ( geometry.index !== null ) {
+
+ let cacheKey = this.getUID( geometry.index );
+
+ if ( groups[ i ].start !== undefined || groups[ i ].count !== undefined ) {
+
+ cacheKey += ':' + groups[ i ].start + ':' + groups[ i ].count;
+
+ }
+
+ if ( cache.attributes.has( cacheKey ) ) {
+
+ primitive.indices = cache.attributes.get( cacheKey );
+
+ } else {
+
+ primitive.indices = this.processAccessor( geometry.index, geometry, groups[ i ].start, groups[ i ].count );
+ cache.attributes.set( cacheKey, primitive.indices );
+
+ }
+
+ if ( primitive.indices === null ) delete primitive.indices;
+
+ }
+
+ const material = await this.processMaterialAsync( materials[ groups[ i ].materialIndex ], geometry );
+
+ if ( material !== null ) primitive.material = material;
+
+ primitives.push( primitive );
+
+ }
+
+ if ( didForceIndices === true ) {
+
+ geometry.setIndex( null );
+
+ }
+
+ meshDef.primitives = primitives;
+
+ if ( ! json.meshes ) json.meshes = [];
+
+ await this._invokeAllAsync( function ( ext ) {
+
+ ext.writeMesh && ext.writeMesh( mesh, meshDef );
+
+ } );
+
+ const index = json.meshes.push( meshDef ) - 1;
+ cache.meshes.set( meshCacheKey, index );
+ return index;
+
+ }
+
+ /**
+ * If a vertex attribute with a
+ * [non-standard data type](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#meshes-overview)
+ * is used, it is checked whether it is a valid data type according to the
+ * [KHR_mesh_quantization](https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Khronos/KHR_mesh_quantization/README.md)
+ * extension.
+ * In this case the extension is automatically added to the list of used extensions.
+ *
+ * @param {string} attributeName
+ * @param {THREE.BufferAttribute} attribute
+ */
+ detectMeshQuantization( attributeName, attribute ) {
+
+ if ( this.extensionsUsed[ KHR_MESH_QUANTIZATION ] ) return;
+
+ let attrType = undefined;
+
+ switch ( attribute.array.constructor ) {
+
+ case Int8Array:
+
+ attrType = 'byte';
+
+ break;
+
+ case Uint8Array:
+
+ attrType = 'unsigned byte';
+
+ break;
+
+ case Int16Array:
+
+ attrType = 'short';
+
+ break;
+
+ case Uint16Array:
+
+ attrType = 'unsigned short';
+
+ break;
+
+ default:
+
+ return;
+
+ }
+
+ if ( attribute.normalized ) attrType += ' normalized';
+
+ const attrNamePrefix = attributeName.split( '_', 1 )[ 0 ];
+
+ if ( KHR_mesh_quantization_ExtraAttrTypes[ attrNamePrefix ] && KHR_mesh_quantization_ExtraAttrTypes[ attrNamePrefix ].includes( attrType ) ) {
+
+ this.extensionsUsed[ KHR_MESH_QUANTIZATION ] = true;
+ this.extensionsRequired[ KHR_MESH_QUANTIZATION ] = true;
+
+ }
+
+ }
+
+ /**
+ * Process camera
+ * @param {THREE.Camera} camera Camera to process
+ * @return {number} Index of the processed mesh in the "camera" array
+ */
+ processCamera( camera ) {
+
+ const json = this.json;
+
+ if ( ! json.cameras ) json.cameras = [];
+
+ const isOrtho = camera.isOrthographicCamera;
+
+ const cameraDef = {
+ type: isOrtho ? 'orthographic' : 'perspective'
+ };
+
+ if ( isOrtho ) {
+
+ cameraDef.orthographic = {
+ xmag: camera.right * 2,
+ ymag: camera.top * 2,
+ zfar: camera.far <= 0 ? 0.001 : camera.far,
+ znear: camera.near < 0 ? 0 : camera.near
+ };
+
+ } else {
+
+ cameraDef.perspective = {
+ aspectRatio: camera.aspect,
+ yfov: MathUtils.degToRad( camera.fov ),
+ zfar: camera.far <= 0 ? 0.001 : camera.far,
+ znear: camera.near < 0 ? 0 : camera.near
+ };
+
+ }
+
+ // Question: Is saving "type" as name intentional?
+ if ( camera.name !== '' ) cameraDef.name = camera.type;
+
+ return json.cameras.push( cameraDef ) - 1;
+
+ }
+
+ /**
+ * Creates glTF animation entry from AnimationClip object.
+ *
+ * Status:
+ * - Only properties listed in PATH_PROPERTIES may be animated.
+ *
+ * @param {THREE.AnimationClip} clip
+ * @param {THREE.Object3D} root
+ * @return {?number}
+ */
+ processAnimation( clip, root ) {
+
+ const json = this.json;
+ const nodeMap = this.nodeMap;
+
+ if ( ! json.animations ) json.animations = [];
+
+ clip = GLTFExporter.Utils.mergeMorphTargetTracks( clip.clone(), root );
+
+ const tracks = clip.tracks;
+ const channels = [];
+ const samplers = [];
+
+ for ( let i = 0; i < tracks.length; ++ i ) {
+
+ const track = tracks[ i ];
+ const trackBinding = PropertyBinding.parseTrackName( track.name );
+ let trackNode = PropertyBinding.findNode( root, trackBinding.nodeName );
+ const trackProperty = PATH_PROPERTIES[ trackBinding.propertyName ];
+
+ if ( trackBinding.objectName === 'bones' ) {
+
+ if ( trackNode.isSkinnedMesh === true ) {
+
+ trackNode = trackNode.skeleton.getBoneByName( trackBinding.objectIndex );
+
+ } else {
+
+ trackNode = undefined;
+
+ }
+
+ }
+
+ if ( ! trackNode || ! trackProperty ) {
+
+ console.warn( 'THREE.GLTFExporter: Could not export animation track "%s".', track.name );
+ continue;
+
+ }
+
+ const inputItemSize = 1;
+ let outputItemSize = track.values.length / track.times.length;
+
+ if ( trackProperty === PATH_PROPERTIES.morphTargetInfluences ) {
+
+ outputItemSize /= trackNode.morphTargetInfluences.length;
+
+ }
+
+ let interpolation;
+
+ // @TODO export CubicInterpolant(InterpolateSmooth) as CUBICSPLINE
+
+ // Detecting glTF cubic spline interpolant by checking factory method's special property
+ // GLTFCubicSplineInterpolant is a custom interpolant and track doesn't return
+ // valid value from .getInterpolation().
+ if ( track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline === true ) {
+
+ interpolation = 'CUBICSPLINE';
+
+ // itemSize of CUBICSPLINE keyframe is 9
+ // (VEC3 * 3: inTangent, splineVertex, and outTangent)
+ // but needs to be stored as VEC3 so dividing by 3 here.
+ outputItemSize /= 3;
+
+ } else if ( track.getInterpolation() === InterpolateDiscrete ) {
+
+ interpolation = 'STEP';
+
+ } else {
+
+ interpolation = 'LINEAR';
+
+ }
+
+ samplers.push( {
+ input: this.processAccessor( new BufferAttribute( track.times, inputItemSize ) ),
+ output: this.processAccessor( new BufferAttribute( track.values, outputItemSize ) ),
+ interpolation: interpolation
+ } );
+
+ channels.push( {
+ sampler: samplers.length - 1,
+ target: {
+ node: nodeMap.get( trackNode ),
+ path: trackProperty
+ }
+ } );
+
+ }
+
+ const animationDef = {
+ name: clip.name || 'clip_' + json.animations.length,
+ samplers: samplers,
+ channels: channels
+ };
+
+ this.serializeUserData( clip, animationDef );
+
+ json.animations.push( animationDef );
+
+ return json.animations.length - 1;
+
+ }
+
+ /**
+ * @param {THREE.Object3D} object
+ * @return {?number}
+ */
+ processSkin( object ) {
+
+ const json = this.json;
+ const nodeMap = this.nodeMap;
+
+ const node = json.nodes[ nodeMap.get( object ) ];
+
+ const skeleton = object.skeleton;
+
+ if ( skeleton === undefined ) return null;
+
+ const rootJoint = object.skeleton.bones[ 0 ];
+
+ if ( rootJoint === undefined ) return null;
+
+ const joints = [];
+ const inverseBindMatrices = new Float32Array( skeleton.bones.length * 16 );
+ const temporaryBoneInverse = new Matrix4();
+
+ for ( let i = 0; i < skeleton.bones.length; ++ i ) {
+
+ joints.push( nodeMap.get( skeleton.bones[ i ] ) );
+ temporaryBoneInverse.copy( skeleton.boneInverses[ i ] );
+ temporaryBoneInverse.multiply( object.bindMatrix ).toArray( inverseBindMatrices, i * 16 );
+
+ }
+
+ if ( json.skins === undefined ) json.skins = [];
+
+ json.skins.push( {
+ inverseBindMatrices: this.processAccessor( new BufferAttribute( inverseBindMatrices, 16 ) ),
+ joints: joints,
+ skeleton: nodeMap.get( rootJoint )
+ } );
+
+ const skinIndex = node.skin = json.skins.length - 1;
+
+ return skinIndex;
+
+ }
+
+ /**
+ * Process Object3D node
+ * @param {THREE.Object3D} object Object3D to processNodeAsync
+ * @return {Promise} Index of the node in the nodes list
+ */
+ async processNodeAsync( object ) {
+
+ const json = this.json;
+ const options = this.options;
+ const nodeMap = this.nodeMap;
+
+ if ( ! json.nodes ) json.nodes = [];
+
+ // Handle pivot by creating a container node
+ if ( object.pivot !== null ) {
+
+ return await this._processNodeWithPivotAsync( object );
+
+ }
+
+ const nodeDef = {};
+
+ if ( options.trs ) {
+
+ const rotation = object.quaternion.toArray();
+ const position = object.position.toArray();
+ const scale = object.scale.toArray();
+
+ if ( ! equalArray( rotation, [ 0, 0, 0, 1 ] ) ) {
+
+ nodeDef.rotation = rotation;
+
+ }
+
+ if ( ! equalArray( position, [ 0, 0, 0 ] ) ) {
+
+ nodeDef.translation = position;
+
+ }
+
+ if ( ! equalArray( scale, [ 1, 1, 1 ] ) ) {
+
+ nodeDef.scale = scale;
+
+ }
+
+ } else {
+
+ if ( object.matrixAutoUpdate ) {
+
+ object.updateMatrix();
+
+ }
+
+ if ( isIdentityMatrix( object.matrix ) === false ) {
+
+ nodeDef.matrix = object.matrix.elements;
+
+ }
+
+ }
+
+ // We don't export empty strings name because it represents no-name in Three.js.
+ if ( object.name !== '' ) nodeDef.name = String( object.name );
+
+ this.serializeUserData( object, nodeDef );
+
+ if ( object.isMesh || object.isLine || object.isPoints ) {
+
+ const meshIndex = await this.processMeshAsync( object );
+
+ if ( meshIndex !== null ) nodeDef.mesh = meshIndex;
+
+ } else if ( object.isCamera ) {
+
+ nodeDef.camera = this.processCamera( object );
+
+ }
+
+ if ( object.isSkinnedMesh ) this.skins.push( object );
+
+ const nodeIndex = json.nodes.push( nodeDef ) - 1;
+ nodeMap.set( object, nodeIndex );
+
+ if ( object.children.length > 0 ) {
+
+ const children = [];
+
+ for ( let i = 0, l = object.children.length; i < l; i ++ ) {
+
+ const child = object.children[ i ];
+
+ if ( child.visible || options.onlyVisible === false ) {
+
+ const childNodeIndex = await this.processNodeAsync( child );
+
+ if ( childNodeIndex !== null ) children.push( childNodeIndex );
+
+ }
+
+ }
+
+ if ( children.length > 0 ) nodeDef.children = children;
+
+ }
+
+ await this._invokeAllAsync( function ( ext ) {
+
+ ext.writeNode && ext.writeNode( object, nodeDef );
+
+ } );
+
+ return nodeIndex;
+
+ }
+
+ /**
+ * Process Object3D node with pivot using container approach
+ * @param {THREE.Object3D} object Object3D with pivot
+ * @return {Promise} Index of the container node
+ */
+ async _processNodeWithPivotAsync( object ) {
+
+ const json = this.json;
+ const options = this.options;
+ const nodeMap = this.nodeMap;
+
+ const pivot = object.pivot;
+
+ // Container node: holds position + pivot offset, rotation, scale
+ // Animations will target this node
+ const containerDef = {};
+
+ const rotation = object.quaternion.toArray();
+ const position = [
+ object.position.x + pivot.x,
+ object.position.y + pivot.y,
+ object.position.z + pivot.z
+ ];
+ const scale = object.scale.toArray();
+
+ if ( ! equalArray( rotation, [ 0, 0, 0, 1 ] ) ) {
+
+ containerDef.rotation = rotation;
+
+ }
+
+ if ( ! equalArray( position, [ 0, 0, 0 ] ) ) {
+
+ containerDef.translation = position;
+
+ }
+
+ if ( ! equalArray( scale, [ 1, 1, 1 ] ) ) {
+
+ containerDef.scale = scale;
+
+ }
+
+ // Store pivot in extras for round-trip reconstruction
+ containerDef.extras = { pivot: pivot.toArray() };
+
+ if ( object.name !== '' ) containerDef.name = String( object.name );
+
+ this.serializeUserData( object, containerDef );
+
+ const containerIndex = json.nodes.push( containerDef ) - 1;
+
+ // Map original object to container so animations target it
+ nodeMap.set( object, containerIndex );
+
+ // Child node: holds mesh with -pivot offset
+ const childDef = {};
+
+ const childPosition = [ - pivot.x, - pivot.y, - pivot.z ];
+
+ if ( ! equalArray( childPosition, [ 0, 0, 0 ] ) ) {
+
+ childDef.translation = childPosition;
+
+ }
+
+ if ( object.isMesh || object.isLine || object.isPoints ) {
+
+ const meshIndex = await this.processMeshAsync( object );
+
+ if ( meshIndex !== null ) childDef.mesh = meshIndex;
+
+ } else if ( object.isCamera ) {
+
+ childDef.camera = this.processCamera( object );
+
+ }
+
+ if ( object.isSkinnedMesh ) this.skins.push( object );
+
+ const childIndex = json.nodes.push( childDef ) - 1;
+
+ // Build children array for container
+ const containerChildren = [ childIndex ];
+
+ // Process object's children as children of the child node
+ if ( object.children.length > 0 ) {
+
+ const grandchildren = [];
+
+ for ( let i = 0, l = object.children.length; i < l; i ++ ) {
+
+ const child = object.children[ i ];
+
+ if ( child.visible || options.onlyVisible === false ) {
+
+ const childNodeIndex = await this.processNodeAsync( child );
+
+ if ( childNodeIndex !== null ) grandchildren.push( childNodeIndex );
+
+ }
+
+ }
+
+ if ( grandchildren.length > 0 ) childDef.children = grandchildren;
+
+ }
+
+ containerDef.children = containerChildren;
+
+ await this._invokeAllAsync( function ( ext ) {
+
+ ext.writeNode && ext.writeNode( object, containerDef );
+
+ } );
+
+ return containerIndex;
+
+ }
+
+ /**
+ * Process Scene
+ * @param {Scene} scene Scene to process
+ */
+ async processSceneAsync( scene ) {
+
+ const json = this.json;
+ const options = this.options;
+
+ if ( ! json.scenes ) {
+
+ json.scenes = [];
+ json.scene = 0;
+
+ }
+
+ const sceneDef = {};
+
+ if ( scene.name !== '' ) sceneDef.name = scene.name;
+
+ json.scenes.push( sceneDef );
+
+ const nodes = [];
+
+ for ( let i = 0, l = scene.children.length; i < l; i ++ ) {
+
+ const child = scene.children[ i ];
+
+ if ( child.visible || options.onlyVisible === false ) {
+
+ const nodeIndex = await this.processNodeAsync( child );
+
+ if ( nodeIndex !== null ) nodes.push( nodeIndex );
+
+ }
+
+ }
+
+ if ( nodes.length > 0 ) sceneDef.nodes = nodes;
+
+ this.serializeUserData( scene, sceneDef );
+
+ }
+
+ /**
+ * Creates a Scene to hold a list of objects and parse it
+ * @param {Array} objects List of objects to process
+ */
+ async processObjectsAsync( objects ) {
+
+ const scene = new Scene();
+ scene.name = 'AuxScene';
+
+ for ( let i = 0; i < objects.length; i ++ ) {
+
+ // We push directly to children instead of calling `add` to prevent
+ // modify the .parent and break its original scene and hierarchy
+ scene.children.push( objects[ i ] );
+
+ }
+
+ await this.processSceneAsync( scene );
+
+ }
+
+ /**
+ * @param {THREE.Object3D|Array} input
+ */
+ async processInputAsync( input ) {
+
+ const options = this.options;
+
+ input = input instanceof Array ? input : [ input ];
+
+ await this._invokeAllAsync( function ( ext ) {
+
+ ext.beforeParse && ext.beforeParse( input );
+
+ } );
+
+ const objectsWithoutScene = [];
+
+ for ( let i = 0; i < input.length; i ++ ) {
+
+ if ( input[ i ] instanceof Scene ) {
+
+ await this.processSceneAsync( input[ i ] );
+
+ } else {
+
+ objectsWithoutScene.push( input[ i ] );
+
+ }
+
+ }
+
+ if ( objectsWithoutScene.length > 0 ) {
+
+ await this.processObjectsAsync( objectsWithoutScene );
+
+ }
+
+ for ( let i = 0; i < this.skins.length; ++ i ) {
+
+ this.processSkin( this.skins[ i ] );
+
+ }
+
+ // animations
+
+ if ( input.length === 1 ) {
+
+ // default: single input, flat animations array
+
+ for ( let i = 0; i < options.animations.length; ++ i ) {
+
+ this.processAnimation( options.animations[ i ], input[ 0 ] );
+
+ }
+
+ } else {
+
+ // multi-input with multi-dimensional animations array
+
+ for ( let i = 0; i < input.length; i ++ ) {
+
+ const animations = options.animations[ i ] || [];
+
+ for ( let j = 0; j < animations.length; ++ j ) {
+
+ this.processAnimation( animations[ j ], input[ i ] );
+
+ }
+
+ }
+
+ }
+
+ await this._invokeAllAsync( function ( ext ) {
+
+ ext.afterParse && ext.afterParse( input );
+
+ } );
+
+ }
+
+ async _invokeAllAsync( func ) {
+
+ for ( let i = 0, il = this.plugins.length; i < il; i ++ ) {
+
+ await func( this.plugins[ i ] );
+
+ }
+
+ }
+
+}
+
+/**
+ * Punctual Lights Extension
+ *
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
+ *
+ * @private
+ */
+class GLTFLightExtension {
+
+ constructor( writer ) {
+
+ this.writer = writer;
+ this.name = 'KHR_lights_punctual';
+
+ }
+
+ writeNode( light, nodeDef ) {
+
+ if ( ! light.isLight ) return;
+
+ if ( ! light.isDirectionalLight && ! light.isPointLight && ! light.isSpotLight ) {
+
+ console.warn( 'THREE.GLTFExporter: Only directional, point, and spot lights are supported.', light );
+ return;
+
+ }
+
+ const writer = this.writer;
+ const json = writer.json;
+ const extensionsUsed = writer.extensionsUsed;
+
+ const lightDef = {};
+
+ if ( light.name ) lightDef.name = light.name;
+
+ lightDef.color = light.color.toArray();
+
+ lightDef.intensity = light.intensity;
+
+ if ( light.isDirectionalLight ) {
+
+ lightDef.type = 'directional';
+
+ } else if ( light.isPointLight ) {
+
+ lightDef.type = 'point';
+
+ if ( light.distance > 0 ) lightDef.range = light.distance;
+
+ } else if ( light.isSpotLight ) {
+
+ lightDef.type = 'spot';
+
+ if ( light.distance > 0 ) lightDef.range = light.distance;
+
+ lightDef.spot = {};
+ lightDef.spot.innerConeAngle = ( 1.0 - light.penumbra ) * light.angle;
+ lightDef.spot.outerConeAngle = light.angle;
+
+ }
+
+ if ( light.decay !== undefined && light.decay !== 2 ) {
+
+ console.warn( 'THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, '
+ + 'and expects light.decay=2.' );
+
+ }
+
+ if ( light.target
+ && ( light.target.parent !== light
+ || light.target.position.x !== 0
+ || light.target.position.y !== 0
+ || light.target.position.z !== - 1 ) ) {
+
+ console.warn( 'THREE.GLTFExporter: Light direction may be lost. For best results, '
+ + 'make light.target a child of the light with position 0,0,-1.' );
+
+ }
+
+ if ( ! extensionsUsed[ this.name ] ) {
+
+ json.extensions = json.extensions || {};
+ json.extensions[ this.name ] = { lights: [] };
+ extensionsUsed[ this.name ] = true;
+
+ }
+
+ const lights = json.extensions[ this.name ].lights;
+ lights.push( lightDef );
+
+ nodeDef.extensions = nodeDef.extensions || {};
+ nodeDef.extensions[ this.name ] = { light: lights.length - 1 };
+
+ }
+
+}
+
+/**
+ * Unlit Materials Extension
+ *
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
+ *
+ * @private
+ */
+class GLTFMaterialsUnlitExtension {
+
+ constructor( writer ) {
+
+ this.writer = writer;
+ this.name = 'KHR_materials_unlit';
+
+ }
+
+ async writeMaterialAsync( material, materialDef ) {
+
+ if ( ! material.isMeshBasicMaterial ) return;
+
+ const writer = this.writer;
+ const extensionsUsed = writer.extensionsUsed;
+
+ materialDef.extensions = materialDef.extensions || {};
+ materialDef.extensions[ this.name ] = {};
+
+ extensionsUsed[ this.name ] = true;
+
+ materialDef.pbrMetallicRoughness.metallicFactor = 0.0;
+ materialDef.pbrMetallicRoughness.roughnessFactor = 0.9;
+
+ }
+
+}
+
+/**
+ * Clearcoat Materials Extension
+ *
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat
+ *
+ * @private
+ */
+class GLTFMaterialsClearcoatExtension {
+
+ constructor( writer ) {
+
+ this.writer = writer;
+ this.name = 'KHR_materials_clearcoat';
+
+ }
+
+ async writeMaterialAsync( material, materialDef ) {
+
+ if ( ! material.isMeshPhysicalMaterial || material.clearcoat === 0 ) return;
+
+ const writer = this.writer;
+ const extensionsUsed = writer.extensionsUsed;
+
+ const extensionDef = {};
+
+ extensionDef.clearcoatFactor = material.clearcoat;
+
+ if ( material.clearcoatMap ) {
+
+ const clearcoatMapDef = {
+ index: await writer.processTextureAsync( material.clearcoatMap ),
+ texCoord: material.clearcoatMap.channel
+ };
+ writer.applyTextureTransform( clearcoatMapDef, material.clearcoatMap );
+ extensionDef.clearcoatTexture = clearcoatMapDef;
+
+ }
+
+ extensionDef.clearcoatRoughnessFactor = material.clearcoatRoughness;
+
+ if ( material.clearcoatRoughnessMap ) {
+
+ const clearcoatRoughnessMapDef = {
+ index: await writer.processTextureAsync( material.clearcoatRoughnessMap ),
+ texCoord: material.clearcoatRoughnessMap.channel
+ };
+ writer.applyTextureTransform( clearcoatRoughnessMapDef, material.clearcoatRoughnessMap );
+ extensionDef.clearcoatRoughnessTexture = clearcoatRoughnessMapDef;
+
+ }
+
+ if ( material.clearcoatNormalMap ) {
+
+ const clearcoatNormalMapDef = {
+ index: await writer.processTextureAsync( material.clearcoatNormalMap ),
+ texCoord: material.clearcoatNormalMap.channel
+ };
+
+ if ( material.clearcoatNormalScale.x !== 1 ) clearcoatNormalMapDef.scale = material.clearcoatNormalScale.x;
+
+ writer.applyTextureTransform( clearcoatNormalMapDef, material.clearcoatNormalMap );
+ extensionDef.clearcoatNormalTexture = clearcoatNormalMapDef;
+
+ }
+
+ materialDef.extensions = materialDef.extensions || {};
+ materialDef.extensions[ this.name ] = extensionDef;
+
+ extensionsUsed[ this.name ] = true;
+
+
+ }
+
+}
+
+/**
+ * Materials dispersion Extension
+ *
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_dispersion
+ *
+ * @private
+ */
+class GLTFMaterialsDispersionExtension {
+
+ constructor( writer ) {
+
+ this.writer = writer;
+ this.name = 'KHR_materials_dispersion';
+
+ }
+
+ async writeMaterialAsync( material, materialDef ) {
+
+ if ( ! material.isMeshPhysicalMaterial || material.dispersion === 0 ) return;
+
+ const writer = this.writer;
+ const extensionsUsed = writer.extensionsUsed;
+
+ const extensionDef = {};
+
+ extensionDef.dispersion = material.dispersion;
+
+ materialDef.extensions = materialDef.extensions || {};
+ materialDef.extensions[ this.name ] = extensionDef;
+
+ extensionsUsed[ this.name ] = true;
+
+ }
+
+}
+
+/**
+ * Iridescence Materials Extension
+ *
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_iridescence
+ *
+ * @private
+ */
+class GLTFMaterialsIridescenceExtension {
+
+ constructor( writer ) {
+
+ this.writer = writer;
+ this.name = 'KHR_materials_iridescence';
+
+ }
+
+ async writeMaterialAsync( material, materialDef ) {
+
+ if ( ! material.isMeshPhysicalMaterial || material.iridescence === 0 ) return;
+
+ const writer = this.writer;
+ const extensionsUsed = writer.extensionsUsed;
+
+ const extensionDef = {};
+
+ extensionDef.iridescenceFactor = material.iridescence;
+
+ if ( material.iridescenceMap ) {
+
+ const iridescenceMapDef = {
+ index: await writer.processTextureAsync( material.iridescenceMap ),
+ texCoord: material.iridescenceMap.channel
+ };
+ writer.applyTextureTransform( iridescenceMapDef, material.iridescenceMap );
+ extensionDef.iridescenceTexture = iridescenceMapDef;
+
+ }
+
+ extensionDef.iridescenceIor = material.iridescenceIOR;
+ extensionDef.iridescenceThicknessMinimum = material.iridescenceThicknessRange[ 0 ];
+ extensionDef.iridescenceThicknessMaximum = material.iridescenceThicknessRange[ 1 ];
+
+ if ( material.iridescenceThicknessMap ) {
+
+ const iridescenceThicknessMapDef = {
+ index: await writer.processTextureAsync( material.iridescenceThicknessMap ),
+ texCoord: material.iridescenceThicknessMap.channel
+ };
+ writer.applyTextureTransform( iridescenceThicknessMapDef, material.iridescenceThicknessMap );
+ extensionDef.iridescenceThicknessTexture = iridescenceThicknessMapDef;
+
+ }
+
+ materialDef.extensions = materialDef.extensions || {};
+ materialDef.extensions[ this.name ] = extensionDef;
+
+ extensionsUsed[ this.name ] = true;
+
+ }
+
+}
+
+/**
+ * Transmission Materials Extension
+ *
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission
+ *
+ * @private
+ */
+class GLTFMaterialsTransmissionExtension {
+
+ constructor( writer ) {
+
+ this.writer = writer;
+ this.name = 'KHR_materials_transmission';
+
+ }
+
+ async writeMaterialAsync( material, materialDef ) {
+
+ if ( ! material.isMeshPhysicalMaterial || material.transmission === 0 ) return;
+
+ const writer = this.writer;
+ const extensionsUsed = writer.extensionsUsed;
+
+ const extensionDef = {};
+
+ extensionDef.transmissionFactor = material.transmission;
+
+ if ( material.transmissionMap ) {
+
+ const transmissionMapDef = {
+ index: await writer.processTextureAsync( material.transmissionMap ),
+ texCoord: material.transmissionMap.channel
+ };
+ writer.applyTextureTransform( transmissionMapDef, material.transmissionMap );
+ extensionDef.transmissionTexture = transmissionMapDef;
+
+ }
+
+ materialDef.extensions = materialDef.extensions || {};
+ materialDef.extensions[ this.name ] = extensionDef;
+
+ extensionsUsed[ this.name ] = true;
+
+ }
+
+}
+
+/**
+ * Materials Volume Extension
+ *
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_volume
+ *
+ * @private
+ */
+class GLTFMaterialsVolumeExtension {
+
+ constructor( writer ) {
+
+ this.writer = writer;
+ this.name = 'KHR_materials_volume';
+
+ }
+
+ async writeMaterialAsync( material, materialDef ) {
+
+ if ( ! material.isMeshPhysicalMaterial || material.transmission === 0 ) return;
+
+ const writer = this.writer;
+ const extensionsUsed = writer.extensionsUsed;
+
+ const extensionDef = {};
+
+ extensionDef.thicknessFactor = material.thickness;
+
+ if ( material.thicknessMap ) {
+
+ const thicknessMapDef = {
+ index: await writer.processTextureAsync( material.thicknessMap ),
+ texCoord: material.thicknessMap.channel
+ };
+ writer.applyTextureTransform( thicknessMapDef, material.thicknessMap );
+ extensionDef.thicknessTexture = thicknessMapDef;
+
+ }
+
+ if ( material.attenuationDistance !== Infinity ) {
+
+ extensionDef.attenuationDistance = material.attenuationDistance;
+
+ }
+
+ extensionDef.attenuationColor = material.attenuationColor.toArray();
+
+ materialDef.extensions = materialDef.extensions || {};
+ materialDef.extensions[ this.name ] = extensionDef;
+
+ extensionsUsed[ this.name ] = true;
+
+ }
+
+}
+
+/**
+ * Materials ior Extension
+ *
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_ior
+ *
+ * @private
+ */
+class GLTFMaterialsIorExtension {
+
+ constructor( writer ) {
+
+ this.writer = writer;
+ this.name = 'KHR_materials_ior';
+
+ }
+
+ async writeMaterialAsync( material, materialDef ) {
+
+ if ( ! material.isMeshPhysicalMaterial || material.ior === 1.5 ) return;
+
+ const writer = this.writer;
+ const extensionsUsed = writer.extensionsUsed;
+
+ const extensionDef = {};
+
+ extensionDef.ior = material.ior;
+
+ materialDef.extensions = materialDef.extensions || {};
+ materialDef.extensions[ this.name ] = extensionDef;
+
+ extensionsUsed[ this.name ] = true;
+
+ }
+
+}
+
+/**
+ * Materials specular Extension
+ *
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_specular
+ *
+ * @private
+ */
+class GLTFMaterialsSpecularExtension {
+
+ constructor( writer ) {
+
+ this.writer = writer;
+ this.name = 'KHR_materials_specular';
+
+ }
+
+ async writeMaterialAsync( material, materialDef ) {
+
+ if ( ! material.isMeshPhysicalMaterial || ( material.specularIntensity === 1.0 &&
+ material.specularColor.equals( DEFAULT_SPECULAR_COLOR ) &&
+ ! material.specularIntensityMap && ! material.specularColorMap ) ) return;
+
+ const writer = this.writer;
+ const extensionsUsed = writer.extensionsUsed;
+
+ const extensionDef = {};
+
+ if ( material.specularIntensityMap ) {
+
+ const specularIntensityMapDef = {
+ index: await writer.processTextureAsync( material.specularIntensityMap ),
+ texCoord: material.specularIntensityMap.channel
+ };
+ writer.applyTextureTransform( specularIntensityMapDef, material.specularIntensityMap );
+ extensionDef.specularTexture = specularIntensityMapDef;
+
+ }
+
+ if ( material.specularColorMap ) {
+
+ const specularColorMapDef = {
+ index: await writer.processTextureAsync( material.specularColorMap ),
+ texCoord: material.specularColorMap.channel
+ };
+ writer.applyTextureTransform( specularColorMapDef, material.specularColorMap );
+ extensionDef.specularColorTexture = specularColorMapDef;
+
+ }
+
+ extensionDef.specularFactor = material.specularIntensity;
+ extensionDef.specularColorFactor = material.specularColor.toArray();
+
+ materialDef.extensions = materialDef.extensions || {};
+ materialDef.extensions[ this.name ] = extensionDef;
+
+ extensionsUsed[ this.name ] = true;
+
+ }
+
+}
+
+/**
+ * Sheen Materials Extension
+ *
+ * Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_sheen
+ *
+ * @private
+ */
+class GLTFMaterialsSheenExtension {
+
+ constructor( writer ) {
+
+ this.writer = writer;
+ this.name = 'KHR_materials_sheen';
+
+ }
+
+ async writeMaterialAsync( material, materialDef ) {
+
+ if ( ! material.isMeshPhysicalMaterial || material.sheen == 0.0 ) return;
+
+ const writer = this.writer;
+ const extensionsUsed = writer.extensionsUsed;
+
+ const extensionDef = {};
+
+ if ( material.sheenRoughnessMap ) {
+
+ const sheenRoughnessMapDef = {
+ index: await writer.processTextureAsync( material.sheenRoughnessMap ),
+ texCoord: material.sheenRoughnessMap.channel
+ };
+ writer.applyTextureTransform( sheenRoughnessMapDef, material.sheenRoughnessMap );
+ extensionDef.sheenRoughnessTexture = sheenRoughnessMapDef;
+
+ }
+
+ if ( material.sheenColorMap ) {
+
+ const sheenColorMapDef = {
+ index: await writer.processTextureAsync( material.sheenColorMap ),
+ texCoord: material.sheenColorMap.channel
+ };
+ writer.applyTextureTransform( sheenColorMapDef, material.sheenColorMap );
+ extensionDef.sheenColorTexture = sheenColorMapDef;
+
+ }
+
+ extensionDef.sheenRoughnessFactor = material.sheenRoughness;
+ extensionDef.sheenColorFactor = material.sheenColor.toArray();
+
+ materialDef.extensions = materialDef.extensions || {};
+ materialDef.extensions[ this.name ] = extensionDef;
+
+ extensionsUsed[ this.name ] = true;
+
+ }
+
+}
+
+/**
+ * Anisotropy Materials Extension
+ *
+ * Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_anisotropy
+ *
+ * @private
+ */
+class GLTFMaterialsAnisotropyExtension {
+
+ constructor( writer ) {
+
+ this.writer = writer;
+ this.name = 'KHR_materials_anisotropy';
+
+ }
+
+ async writeMaterialAsync( material, materialDef ) {
+
+ if ( ! material.isMeshPhysicalMaterial || material.anisotropy == 0.0 ) return;
+
+ const writer = this.writer;
+ const extensionsUsed = writer.extensionsUsed;
+
+ const extensionDef = {};
+
+ if ( material.anisotropyMap ) {
+
+ const anisotropyMapDef = { index: await writer.processTextureAsync( material.anisotropyMap ) };
+ writer.applyTextureTransform( anisotropyMapDef, material.anisotropyMap );
+ extensionDef.anisotropyTexture = anisotropyMapDef;
+
+ }
+
+ extensionDef.anisotropyStrength = material.anisotropy;
+ extensionDef.anisotropyRotation = material.anisotropyRotation;
+
+ materialDef.extensions = materialDef.extensions || {};
+ materialDef.extensions[ this.name ] = extensionDef;
+
+ extensionsUsed[ this.name ] = true;
+
+ }
+
+}
+
+/**
+ * Materials Emissive Strength Extension
+ *
+ * Specification: https://github.com/KhronosGroup/glTF/blob/5768b3ce0ef32bc39cdf1bef10b948586635ead3/extensions/2.0/Khronos/KHR_materials_emissive_strength/README.md
+ *
+ * @private
+ */
+class GLTFMaterialsEmissiveStrengthExtension {
+
+ constructor( writer ) {
+
+ this.writer = writer;
+ this.name = 'KHR_materials_emissive_strength';
+
+ }
+
+ async writeMaterialAsync( material, materialDef ) {
+
+ if ( ! material.isMeshStandardMaterial || material.emissiveIntensity === 1.0 ) return;
+
+ const writer = this.writer;
+ const extensionsUsed = writer.extensionsUsed;
+
+ const extensionDef = {};
+
+ extensionDef.emissiveStrength = material.emissiveIntensity;
+
+ materialDef.extensions = materialDef.extensions || {};
+ materialDef.extensions[ this.name ] = extensionDef;
+
+ extensionsUsed[ this.name ] = true;
+
+ }
+
+}
+
+
+/**
+ * Materials bump Extension
+ *
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/EXT_materials_bump
+ *
+ * @private
+ */
+class GLTFMaterialsBumpExtension {
+
+ constructor( writer ) {
+
+ this.writer = writer;
+ this.name = 'EXT_materials_bump';
+
+ }
+
+ async writeMaterialAsync( material, materialDef ) {
+
+ if ( ! material.isMeshStandardMaterial || (
+ material.bumpScale === 1 &&
+ ! material.bumpMap ) ) return;
+
+ const writer = this.writer;
+ const extensionsUsed = writer.extensionsUsed;
+
+ const extensionDef = {};
+
+ if ( material.bumpMap ) {
+
+ const bumpMapDef = {
+ index: await writer.processTextureAsync( material.bumpMap ),
+ texCoord: material.bumpMap.channel
+ };
+ writer.applyTextureTransform( bumpMapDef, material.bumpMap );
+ extensionDef.bumpTexture = bumpMapDef;
+
+ }
+
+ extensionDef.bumpFactor = material.bumpScale;
+
+ materialDef.extensions = materialDef.extensions || {};
+ materialDef.extensions[ this.name ] = extensionDef;
+
+ extensionsUsed[ this.name ] = true;
+
+ }
+
+}
+
+/**
+ * GPU Instancing Extension
+ *
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_mesh_gpu_instancing
+ *
+ * @private
+ */
+class GLTFMeshGpuInstancing {
+
+ constructor( writer ) {
+
+ this.writer = writer;
+ this.name = 'EXT_mesh_gpu_instancing';
+
+ }
+
+ writeNode( object, nodeDef ) {
+
+ if ( ! object.isInstancedMesh ) return;
+
+ const writer = this.writer;
+
+ const mesh = object;
+
+ const translationAttr = new Float32Array( mesh.count * 3 );
+ const rotationAttr = new Float32Array( mesh.count * 4 );
+ const scaleAttr = new Float32Array( mesh.count * 3 );
+
+ const matrix = new Matrix4();
+ const position = new Vector3();
+ const quaternion = new Quaternion();
+ const scale = new Vector3();
+
+ for ( let i = 0; i < mesh.count; i ++ ) {
+
+ mesh.getMatrixAt( i, matrix );
+ matrix.decompose( position, quaternion, scale );
+
+ position.toArray( translationAttr, i * 3 );
+ quaternion.toArray( rotationAttr, i * 4 );
+ scale.toArray( scaleAttr, i * 3 );
+
+ }
+
+ const attributes = {
+ TRANSLATION: writer.processAccessor( new BufferAttribute( translationAttr, 3 ) ),
+ ROTATION: writer.processAccessor( new BufferAttribute( rotationAttr, 4 ) ),
+ SCALE: writer.processAccessor( new BufferAttribute( scaleAttr, 3 ) ),
+ };
+
+ if ( mesh.instanceColor )
+ attributes._COLOR_0 = writer.processAccessor( mesh.instanceColor );
+
+ nodeDef.extensions = nodeDef.extensions || {};
+ nodeDef.extensions[ this.name ] = { attributes };
+
+ writer.extensionsUsed[ this.name ] = true;
+ writer.extensionsRequired[ this.name ] = true;
+
+ }
+
+}
+
+/**
+ * Static utility functions
+ *
+ * @private
+ */
+GLTFExporter.Utils = {
+
+ insertKeyframe: function ( track, time ) {
+
+ const tolerance = 0.001; // 1ms
+ const valueSize = track.getValueSize();
+
+ const times = new track.TimeBufferType( track.times.length + 1 );
+ const values = new track.ValueBufferType( track.values.length + valueSize );
+ const interpolant = track.createInterpolant( new track.ValueBufferType( valueSize ) );
+
+ let index;
+
+ if ( track.times.length === 0 ) {
+
+ times[ 0 ] = time;
+
+ for ( let i = 0; i < valueSize; i ++ ) {
+
+ values[ i ] = 0;
+
+ }
+
+ index = 0;
+
+ } else if ( time < track.times[ 0 ] ) {
+
+ if ( Math.abs( track.times[ 0 ] - time ) < tolerance ) return 0;
+
+ times[ 0 ] = time;
+ times.set( track.times, 1 );
+
+ values.set( interpolant.evaluate( time ), 0 );
+ values.set( track.values, valueSize );
+
+ index = 0;
+
+ } else if ( time > track.times[ track.times.length - 1 ] ) {
+
+ if ( Math.abs( track.times[ track.times.length - 1 ] - time ) < tolerance ) {
+
+ return track.times.length - 1;
+
+ }
+
+ times[ times.length - 1 ] = time;
+ times.set( track.times, 0 );
+
+ values.set( track.values, 0 );
+ values.set( interpolant.evaluate( time ), track.values.length );
+
+ index = times.length - 1;
+
+ } else {
+
+ for ( let i = 0; i < track.times.length; i ++ ) {
+
+ if ( Math.abs( track.times[ i ] - time ) < tolerance ) return i;
+
+ if ( track.times[ i ] < time && track.times[ i + 1 ] > time ) {
+
+ times.set( track.times.slice( 0, i + 1 ), 0 );
+ times[ i + 1 ] = time;
+ times.set( track.times.slice( i + 1 ), i + 2 );
+
+ values.set( track.values.slice( 0, ( i + 1 ) * valueSize ), 0 );
+ values.set( interpolant.evaluate( time ), ( i + 1 ) * valueSize );
+ values.set( track.values.slice( ( i + 1 ) * valueSize ), ( i + 2 ) * valueSize );
+
+ index = i + 1;
+
+ break;
+
+ }
+
+ }
+
+ }
+
+ track.times = times;
+ track.values = values;
+
+ return index;
+
+ },
+
+ mergeMorphTargetTracks: function ( clip, root ) {
+
+ const tracks = [];
+ const mergedTracks = {};
+ const sourceTracks = clip.tracks;
+
+ for ( let i = 0; i < sourceTracks.length; ++ i ) {
+
+ let sourceTrack = sourceTracks[ i ];
+ const sourceTrackBinding = PropertyBinding.parseTrackName( sourceTrack.name );
+ const sourceTrackNode = PropertyBinding.findNode( root, sourceTrackBinding.nodeName );
+
+ if ( sourceTrackBinding.propertyName !== 'morphTargetInfluences' || sourceTrackBinding.propertyIndex === undefined ) {
+
+ // Tracks that don't affect morph targets, or that affect all morph targets together, can be left as-is.
+ tracks.push( sourceTrack );
+ continue;
+
+ }
+
+ if ( sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodDiscrete
+ && sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodLinear ) {
+
+ if ( sourceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
+
+ // This should never happen, because glTF morph target animations
+ // affect all targets already.
+ throw new Error( 'THREE.GLTFExporter: Cannot merge tracks with glTF CUBICSPLINE interpolation.' );
+
+ }
+
+ console.warn( 'THREE.GLTFExporter: Morph target interpolation mode not yet supported. Using LINEAR instead.' );
+
+ sourceTrack = sourceTrack.clone();
+ sourceTrack.setInterpolation( InterpolateLinear );
+
+ }
+
+ const targetCount = sourceTrackNode.morphTargetInfluences.length;
+ const targetIndex = sourceTrackNode.morphTargetDictionary[ sourceTrackBinding.propertyIndex ];
+
+ if ( targetIndex === undefined ) {
+
+ throw new Error( 'THREE.GLTFExporter: Morph target name not found: ' + sourceTrackBinding.propertyIndex );
+
+ }
+
+ let mergedTrack;
+
+ // If this is the first time we've seen this object, create a new
+ // track to store merged keyframe data for each morph target.
+ if ( mergedTracks[ sourceTrackNode.uuid ] === undefined ) {
+
+ mergedTrack = sourceTrack.clone();
+
+ const values = new mergedTrack.ValueBufferType( targetCount * mergedTrack.times.length );
+
+ for ( let j = 0; j < mergedTrack.times.length; j ++ ) {
+
+ values[ j * targetCount + targetIndex ] = mergedTrack.values[ j ];
+
+ }
+
+ // We need to take into consideration the intended target node
+ // of our original un-merged morphTarget animation.
+ mergedTrack.name = ( sourceTrackBinding.nodeName || '' ) + '.morphTargetInfluences';
+ mergedTrack.values = values;
+
+ mergedTracks[ sourceTrackNode.uuid ] = mergedTrack;
+ tracks.push( mergedTrack );
+
+ continue;
+
+ }
+
+ const sourceInterpolant = sourceTrack.createInterpolant( new sourceTrack.ValueBufferType( 1 ) );
+
+ mergedTrack = mergedTracks[ sourceTrackNode.uuid ];
+
+ // For every existing keyframe of the merged track, write a (possibly
+ // interpolated) value from the source track.
+ for ( let j = 0; j < mergedTrack.times.length; j ++ ) {
+
+ mergedTrack.values[ j * targetCount + targetIndex ] = sourceInterpolant.evaluate( mergedTrack.times[ j ] );
+
+ }
+
+ // For every existing keyframe of the source track, write a (possibly
+ // new) keyframe to the merged track. Values from the previous loop may
+ // be written again, but keyframes are de-duplicated.
+ for ( let j = 0; j < sourceTrack.times.length; j ++ ) {
+
+ const keyframeIndex = this.insertKeyframe( mergedTrack, sourceTrack.times[ j ] );
+ mergedTrack.values[ keyframeIndex * targetCount + targetIndex ] = sourceTrack.values[ j ];
+
+ }
+
+ }
+
+ clip.tracks = tracks;
+
+ return clip;
+
+ },
+
+ toTypedBufferAttribute: function ( srcAttribute, TypedArray ) {
+
+ const dstAttribute = new BufferAttribute( new TypedArray( srcAttribute.count * srcAttribute.itemSize ), srcAttribute.itemSize, false );
+
+ if ( ! srcAttribute.normalized && ! srcAttribute.isInterleavedBufferAttribute ) {
+
+ dstAttribute.array.set( srcAttribute.array );
+
+ return dstAttribute;
+
+ }
+
+ for ( let i = 0, il = srcAttribute.count; i < il; i ++ ) {
+
+ for ( let j = 0; j < srcAttribute.itemSize; j ++ ) {
+
+ dstAttribute.setComponent( i, j, srcAttribute.getComponent( i, j ) );
+
+ }
+
+ }
+
+ return dstAttribute;
+
+ }
+
+};
+
+/**
+ * Export options of `GLTFExporter`.
+ *
+ * @typedef {Object} GLTFExporter~Options
+ * @property {boolean} [trs=false] - Export position, rotation and scale instead of matrix per node.
+ * @property {boolean} [onlyVisible=true] - Export only visible 3D objects.
+ * @property {boolean} [binary=false] - Export in binary (.glb) format, returning an ArrayBuffer.
+ * @property {number} [maxTextureSize=Infinity] - Restricts the image maximum size (both width and height) to the given value.
+ * @property {Array|Array>} [animations=[]] - List of animations to be included in the export. When exporting a single 3D object or scene, this is a flat list of clips.
+ * When exporting an array of multiple scenes, this must be a nested array with one list of clips per scene, matched to the input by index.
+ * @property {boolean} [includeCustomExtensions=false] - Export custom glTF extensions defined on an object's `userData.gltfExtensions` property.
+ **/
+
+/**
+ * onDone callback of `GLTFExporter`.
+ *
+ * @callback GLTFExporter~OnDone
+ * @param {ArrayBuffer|string} result - The generated .gltf (JSON) or .glb (binary).
+ */
+
+/**
+ * onError callback of `GLTFExporter`.
+ *
+ * @callback GLTFExporter~OnError
+ * @param {Error} error - The error object.
+ */
+
+export { GLTFExporter };
diff --git a/web/vendor/OBJExporter.mjs b/web/vendor/OBJExporter.mjs
new file mode 100644
index 0000000..9960b90
--- /dev/null
+++ b/web/vendor/OBJExporter.mjs
@@ -0,0 +1,308 @@
+import {
+ Color,
+ ColorManagement,
+ Matrix3,
+ SRGBColorSpace,
+ Vector2,
+ Vector3
+} from 'three';
+
+/**
+ * An exporter for OBJ.
+ *
+ * `OBJExporter` is not able to export material data into MTL files so only geometry data are supported.
+ *
+ * ```js
+ * const exporter = new OBJExporter();
+ * const data = exporter.parse( scene );
+ * ```
+ *
+ * @three_import import { OBJExporter } from 'three/addons/exporters/OBJExporter.js';
+ */
+class OBJExporter {
+
+ /**
+ * Parses the given 3D object and generates the OBJ output.
+ *
+ * If the 3D object is composed of multiple children and geometry, they are merged into a single mesh in the file.
+ *
+ * @param {Object3D} object - The 3D object to export.
+ * @return {string} The exported OBJ.
+ */
+ parse( object ) {
+
+ let output = '';
+
+ let indexVertex = 0;
+ let indexVertexUvs = 0;
+ let indexNormals = 0;
+
+ const vertex = new Vector3();
+ const color = new Color();
+ const normal = new Vector3();
+ const uv = new Vector2();
+
+ const face = [];
+
+ function parseMesh( mesh ) {
+
+ let nbVertex = 0;
+ let nbNormals = 0;
+ let nbVertexUvs = 0;
+
+ const geometry = mesh.geometry;
+
+ const normalMatrixWorld = new Matrix3();
+
+ // shortcuts
+ const vertices = geometry.getAttribute( 'position' );
+ const normals = geometry.getAttribute( 'normal' );
+ const uvs = geometry.getAttribute( 'uv' );
+ const indices = geometry.getIndex();
+
+ // name of the mesh object
+ output += 'o ' + mesh.name + '\n';
+
+ // name of the mesh material
+ if ( mesh.material && mesh.material.name ) {
+
+ output += 'usemtl ' + mesh.material.name + '\n';
+
+ }
+
+ // vertices
+
+ if ( vertices !== undefined ) {
+
+ for ( let i = 0, l = vertices.count; i < l; i ++, nbVertex ++ ) {
+
+ vertex.fromBufferAttribute( vertices, i );
+
+ // transform the vertex to world space
+ vertex.applyMatrix4( mesh.matrixWorld );
+
+ // transform the vertex to export format
+ output += 'v ' + vertex.x + ' ' + vertex.y + ' ' + vertex.z + '\n';
+
+ }
+
+ }
+
+ // uvs
+
+ if ( uvs !== undefined ) {
+
+ for ( let i = 0, l = uvs.count; i < l; i ++, nbVertexUvs ++ ) {
+
+ uv.fromBufferAttribute( uvs, i );
+
+ // transform the uv to export format
+ output += 'vt ' + uv.x + ' ' + uv.y + '\n';
+
+ }
+
+ }
+
+ // normals
+
+ if ( normals !== undefined ) {
+
+ normalMatrixWorld.getNormalMatrix( mesh.matrixWorld );
+
+ for ( let i = 0, l = normals.count; i < l; i ++, nbNormals ++ ) {
+
+ normal.fromBufferAttribute( normals, i );
+
+ // transform the normal to world space
+ normal.applyMatrix3( normalMatrixWorld ).normalize();
+
+ // transform the normal to export format
+ output += 'vn ' + normal.x + ' ' + normal.y + ' ' + normal.z + '\n';
+
+ }
+
+ }
+
+ // faces
+
+ if ( indices !== null ) {
+
+ for ( let i = 0, l = indices.count; i < l; i += 3 ) {
+
+ for ( let m = 0; m < 3; m ++ ) {
+
+ const j = indices.getX( i + m ) + 1;
+
+ face[ m ] = ( indexVertex + j ) + ( normals || uvs ? '/' + ( uvs ? ( indexVertexUvs + j ) : '' ) + ( normals ? '/' + ( indexNormals + j ) : '' ) : '' );
+
+ }
+
+ // transform the face to export format
+ output += 'f ' + face.join( ' ' ) + '\n';
+
+ }
+
+ } else {
+
+ for ( let i = 0, l = vertices.count; i < l; i += 3 ) {
+
+ for ( let m = 0; m < 3; m ++ ) {
+
+ const j = i + m + 1;
+
+ face[ m ] = ( indexVertex + j ) + ( normals || uvs ? '/' + ( uvs ? ( indexVertexUvs + j ) : '' ) + ( normals ? '/' + ( indexNormals + j ) : '' ) : '' );
+
+ }
+
+ // transform the face to export format
+ output += 'f ' + face.join( ' ' ) + '\n';
+
+ }
+
+ }
+
+ // update index
+ indexVertex += nbVertex;
+ indexVertexUvs += nbVertexUvs;
+ indexNormals += nbNormals;
+
+ }
+
+ function parseLine( line ) {
+
+ let nbVertex = 0;
+
+ const geometry = line.geometry;
+ const type = line.type;
+
+ // shortcuts
+ const vertices = geometry.getAttribute( 'position' );
+
+ // name of the line object
+ output += 'o ' + line.name + '\n';
+
+ if ( vertices !== undefined ) {
+
+ for ( let i = 0, l = vertices.count; i < l; i ++, nbVertex ++ ) {
+
+ vertex.fromBufferAttribute( vertices, i );
+
+ // transform the vertex to world space
+ vertex.applyMatrix4( line.matrixWorld );
+
+ // transform the vertex to export format
+ output += 'v ' + vertex.x + ' ' + vertex.y + ' ' + vertex.z + '\n';
+
+ }
+
+ }
+
+ if ( type === 'Line' ) {
+
+ output += 'l ';
+
+ for ( let j = 1, l = vertices.count; j <= l; j ++ ) {
+
+ output += ( indexVertex + j ) + ' ';
+
+ }
+
+ output += '\n';
+
+ }
+
+ if ( type === 'LineSegments' ) {
+
+ for ( let j = 1, k = j + 1, l = vertices.count; j < l; j += 2, k = j + 1 ) {
+
+ output += 'l ' + ( indexVertex + j ) + ' ' + ( indexVertex + k ) + '\n';
+
+ }
+
+ }
+
+ // update index
+ indexVertex += nbVertex;
+
+ }
+
+ function parsePoints( points ) {
+
+ let nbVertex = 0;
+
+ const geometry = points.geometry;
+
+ const vertices = geometry.getAttribute( 'position' );
+ const colors = geometry.getAttribute( 'color' );
+
+ output += 'o ' + points.name + '\n';
+
+ if ( vertices !== undefined ) {
+
+ for ( let i = 0, l = vertices.count; i < l; i ++, nbVertex ++ ) {
+
+ vertex.fromBufferAttribute( vertices, i );
+ vertex.applyMatrix4( points.matrixWorld );
+
+ output += 'v ' + vertex.x + ' ' + vertex.y + ' ' + vertex.z;
+
+ if ( colors !== undefined ) {
+
+ color.fromBufferAttribute( colors, i );
+
+ ColorManagement.workingToColorSpace( color, SRGBColorSpace );
+
+ output += ' ' + color.r + ' ' + color.g + ' ' + color.b;
+
+ }
+
+ output += '\n';
+
+ }
+
+ output += 'p ';
+
+ for ( let j = 1, l = vertices.count; j <= l; j ++ ) {
+
+ output += ( indexVertex + j ) + ' ';
+
+ }
+
+ output += '\n';
+
+ }
+
+ // update index
+ indexVertex += nbVertex;
+
+ }
+
+ object.traverse( function ( child ) {
+
+ if ( child.isMesh === true ) {
+
+ parseMesh( child );
+
+ }
+
+ if ( child.isLine === true ) {
+
+ parseLine( child );
+
+ }
+
+ if ( child.isPoints === true ) {
+
+ parsePoints( child );
+
+ }
+
+ } );
+
+ return output;
+
+ }
+
+}
+
+export { OBJExporter };
diff --git a/web/vendor/OrbitControls.mjs b/web/vendor/OrbitControls.mjs
new file mode 100644
index 0000000..6060cd4
--- /dev/null
+++ b/web/vendor/OrbitControls.mjs
@@ -0,0 +1,1963 @@
+import {
+ Controls,
+ MOUSE,
+ Quaternion,
+ Spherical,
+ TOUCH,
+ Vector2,
+ Vector3,
+ Plane,
+ Ray,
+ MathUtils
+} from 'three';
+
+/**
+ * Fires when the camera has been transformed by the controls.
+ *
+ * @event OrbitControls#change
+ * @type {Object}
+ */
+const _changeEvent = { type: 'change' };
+
+/**
+ * Fires when an interaction was initiated.
+ *
+ * @event OrbitControls#start
+ * @type {Object}
+ */
+const _startEvent = { type: 'start' };
+
+/**
+ * Fires when an interaction has finished.
+ *
+ * @event OrbitControls#end
+ * @type {Object}
+ */
+const _endEvent = { type: 'end' };
+
+const _ray = new Ray();
+const _plane = new Plane();
+const _TILT_LIMIT = Math.cos( 70 * MathUtils.DEG2RAD );
+
+const _v = new Vector3();
+const _twoPI = 2 * Math.PI;
+
+const _STATE = {
+ NONE: - 1,
+ ROTATE: 0,
+ DOLLY: 1,
+ PAN: 2,
+ TOUCH_ROTATE: 3,
+ TOUCH_PAN: 4,
+ TOUCH_DOLLY_PAN: 5,
+ TOUCH_DOLLY_ROTATE: 6
+};
+const _EPS = 0.000001;
+
+
+/**
+ * Orbit controls allow the camera to orbit around a target.
+ *
+ * OrbitControls performs orbiting, dollying (zooming), and panning. Unlike {@link TrackballControls},
+ * it maintains the "up" direction `object.up` (+Y by default).
+ *
+ * - Orbit: Left mouse / touch: one-finger move.
+ * - Zoom: Middle mouse, or mousewheel / touch: two-finger spread or squish.
+ * - Pan: Right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move.
+ *
+ * ```js
+ * const controls = new OrbitControls( camera, renderer.domElement );
+ *
+ * // controls.update() must be called after any manual changes to the camera's transform
+ * camera.position.set( 0, 20, 100 );
+ * controls.update();
+ *
+ * function animate() {
+ *
+ * // required if controls.enableDamping or controls.autoRotate are set to true
+ * controls.update();
+ *
+ * renderer.render( scene, camera );
+ *
+ * }
+ * ```
+ *
+ * @augments Controls
+ * @three_import import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
+ */
+class OrbitControls extends Controls {
+
+ /**
+ * Constructs a new controls instance.
+ *
+ * @param {Object3D} object - The object that is managed by the controls.
+ * @param {?HTMLElement} domElement - The HTML element used for event listeners.
+ */
+ constructor( object, domElement = null ) {
+
+ super( object, domElement );
+
+ this.state = _STATE.NONE;
+
+ /**
+ * The focus point of the controls, the `object` orbits around this.
+ * It can be updated manually at any point to change the focus of the controls.
+ *
+ * @type {Vector3}
+ */
+ this.target = new Vector3();
+
+ /**
+ * The focus point of the `minTargetRadius` and `maxTargetRadius` limits.
+ * It can be updated manually at any point to change the center of interest
+ * for the `target`.
+ *
+ * @type {Vector3}
+ */
+ this.cursor = new Vector3();
+
+ /**
+ * How far you can dolly in (perspective camera only).
+ *
+ * @type {number}
+ * @default 0
+ */
+ this.minDistance = 0;
+
+ /**
+ * How far you can dolly out (perspective camera only).
+ *
+ * @type {number}
+ * @default Infinity
+ */
+ this.maxDistance = Infinity;
+
+ /**
+ * How far you can zoom in (orthographic camera only).
+ *
+ * @type {number}
+ * @default 0
+ */
+ this.minZoom = 0;
+
+ /**
+ * How far you can zoom out (orthographic camera only).
+ *
+ * @type {number}
+ * @default Infinity
+ */
+ this.maxZoom = Infinity;
+
+ /**
+ * How close you can get the target to the 3D `cursor`.
+ *
+ * @type {number}
+ * @default 0
+ */
+ this.minTargetRadius = 0;
+
+ /**
+ * How far you can move the target from the 3D `cursor`.
+ *
+ * @type {number}
+ * @default Infinity
+ */
+ this.maxTargetRadius = Infinity;
+
+ /**
+ * How far you can orbit vertically, lower limit. Range is `[0, Math.PI]` radians.
+ *
+ * @type {number}
+ * @default 0
+ */
+ this.minPolarAngle = 0;
+
+ /**
+ * How far you can orbit vertically, upper limit. Range is `[0, Math.PI]` radians.
+ *
+ * @type {number}
+ * @default Math.PI
+ */
+ this.maxPolarAngle = Math.PI;
+
+ /**
+ * How far you can orbit horizontally, lower limit. If set, the interval `[ min, max ]`
+ * must be a sub-interval of `[ - 2 PI, 2 PI ]`, with `( max - min < 2 PI )`.
+ *
+ * @type {number}
+ * @default -Infinity
+ */
+ this.minAzimuthAngle = - Infinity;
+
+ /**
+ * How far you can orbit horizontally, upper limit. If set, the interval `[ min, max ]`
+ * must be a sub-interval of `[ - 2 PI, 2 PI ]`, with `( max - min < 2 PI )`.
+ *
+ * @type {number}
+ * @default -Infinity
+ */
+ this.maxAzimuthAngle = Infinity;
+
+ /**
+ * Set to `true` to enable damping (inertia), which can be used to give a sense of weight
+ * to the controls. Note that if this is enabled, you must call `update()` in your animation
+ * loop.
+ *
+ * @type {boolean}
+ * @default false
+ */
+ this.enableDamping = false;
+
+ /**
+ * The damping inertia used if `enableDamping` is set to `true`.
+ *
+ * Note that for this to work, you must call `update()` in your animation loop.
+ *
+ * @type {number}
+ * @default 0.05
+ */
+ this.dampingFactor = 0.05;
+
+ /**
+ * Enable or disable zooming (dollying) of the camera.
+ *
+ * @type {boolean}
+ * @default true
+ */
+ this.enableZoom = true;
+
+ /**
+ * Speed of zooming / dollying.
+ *
+ * @type {number}
+ * @default 1
+ */
+ this.zoomSpeed = 1.0;
+
+ /**
+ * Enable or disable horizontal and vertical rotation of the camera.
+ *
+ * Note that it is possible to disable a single axis by setting the min and max of the
+ * `minPolarAngle` or `minAzimuthAngle` to the same value, which will cause the vertical
+ * or horizontal rotation to be fixed at that value.
+ *
+ * @type {boolean}
+ * @default true
+ */
+ this.enableRotate = true;
+
+ /**
+ * Speed of rotation.
+ *
+ * @type {number}
+ * @default 1
+ */
+ this.rotateSpeed = 1.0;
+
+ /**
+ * How fast to rotate the camera when the keyboard is used.
+ *
+ * @type {number}
+ * @default 1
+ */
+ this.keyRotateSpeed = 1.0;
+
+ /**
+ * Enable or disable camera panning.
+ *
+ * @type {boolean}
+ * @default true
+ */
+ this.enablePan = true;
+
+ /**
+ * Speed of panning.
+ *
+ * @type {number}
+ * @default 1
+ */
+ this.panSpeed = 1.0;
+
+ /**
+ * Defines how the camera's position is translated when panning. If `true`, the camera pans
+ * in screen space. Otherwise, the camera pans in the plane orthogonal to the camera's up
+ * direction.
+ *
+ * @type {boolean}
+ * @default true
+ */
+ this.screenSpacePanning = true;
+
+ /**
+ * How fast to pan the camera when the keyboard is used in
+ * pixels per keypress.
+ *
+ * @type {number}
+ * @default 7
+ */
+ this.keyPanSpeed = 7.0;
+
+ /**
+ * Setting this property to `true` allows to zoom to the cursor's position.
+ *
+ * @type {boolean}
+ * @default false
+ */
+ this.zoomToCursor = false;
+
+ /**
+ * Set to true to automatically rotate around the target
+ *
+ * Note that if this is enabled, you must call `update()` in your animation loop.
+ * If you want the auto-rotate speed to be independent of the frame rate (the refresh
+ * rate of the display), you must pass the time `deltaTime`, in seconds, to `update()`.
+ *
+ * @type {boolean}
+ * @default false
+ */
+ this.autoRotate = false;
+
+ /**
+ * How fast to rotate around the target if `autoRotate` is `true`. The default equates to 30 seconds
+ * per orbit at 60fps.
+ *
+ * Note that if `autoRotate` is enabled, you must call `update()` in your animation loop.
+ *
+ * @type {number}
+ * @default 2
+ */
+ this.autoRotateSpeed = 2.0;
+
+ /**
+ * This object contains references to the keycodes for controlling camera panning.
+ *
+ * ```js
+ * controls.keys = {
+ * LEFT: 'ArrowLeft', //left arrow
+ * UP: 'ArrowUp', // up arrow
+ * RIGHT: 'ArrowRight', // right arrow
+ * BOTTOM: 'ArrowDown' // down arrow
+ * }
+ * ```
+ * @type {Object}
+ */
+ this.keys = { LEFT: 'ArrowLeft', UP: 'ArrowUp', RIGHT: 'ArrowRight', BOTTOM: 'ArrowDown' };
+
+ /**
+ * This object contains references to the mouse actions used by the controls.
+ *
+ * ```js
+ * controls.mouseButtons = {
+ * LEFT: THREE.MOUSE.ROTATE,
+ * MIDDLE: THREE.MOUSE.DOLLY,
+ * RIGHT: THREE.MOUSE.PAN
+ * }
+ * ```
+ * @type {Object}
+ */
+ this.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN };
+
+ /**
+ * This object contains references to the touch actions used by the controls.
+ *
+ * ```js
+ * controls.mouseButtons = {
+ * ONE: THREE.TOUCH.ROTATE,
+ * TWO: THREE.TOUCH.DOLLY_PAN
+ * }
+ * ```
+ * @type {Object}
+ */
+ this.touches = { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN };
+
+ /**
+ * Used internally by `saveState()` and `reset()`.
+ *
+ * @type {Vector3}
+ */
+ this.target0 = this.target.clone();
+
+ /**
+ * Used internally by `saveState()` and `reset()`.
+ *
+ * @type {Vector3}
+ */
+ this.position0 = this.object.position.clone();
+
+ /**
+ * Used internally by `saveState()` and `reset()`.
+ *
+ * @type {number}
+ */
+ this.zoom0 = this.object.zoom;
+
+ this._cursorStyle = 'auto';
+
+ // the target DOM element for key events
+ this._domElementKeyEvents = null;
+
+ // internals
+
+ this._lastPosition = new Vector3();
+ this._lastQuaternion = new Quaternion();
+ this._lastTargetPosition = new Vector3();
+
+ // so camera.up is the orbit axis
+ this._quat = new Quaternion().setFromUnitVectors( object.up, new Vector3( 0, 1, 0 ) );
+ this._quatInverse = this._quat.clone().invert();
+
+ // current position in spherical coordinates
+ this._spherical = new Spherical();
+ this._sphericalDelta = new Spherical();
+
+ this._scale = 1;
+ this._panOffset = new Vector3();
+
+ this._rotateStart = new Vector2();
+ this._rotateEnd = new Vector2();
+ this._rotateDelta = new Vector2();
+
+ this._panStart = new Vector2();
+ this._panEnd = new Vector2();
+ this._panDelta = new Vector2();
+
+ this._dollyStart = new Vector2();
+ this._dollyEnd = new Vector2();
+ this._dollyDelta = new Vector2();
+
+ this._dollyDirection = new Vector3();
+ this._mouse = new Vector2();
+ this._performCursorZoom = false;
+
+ this._pointers = [];
+ this._pointerPositions = {};
+
+ this._controlActive = false;
+
+ // event listeners
+
+ this._onPointerMove = onPointerMove.bind( this );
+ this._onPointerDown = onPointerDown.bind( this );
+ this._onPointerUp = onPointerUp.bind( this );
+ this._onContextMenu = onContextMenu.bind( this );
+ this._onMouseWheel = onMouseWheel.bind( this );
+ this._onKeyDown = onKeyDown.bind( this );
+
+ this._onTouchStart = onTouchStart.bind( this );
+ this._onTouchMove = onTouchMove.bind( this );
+
+ this._onMouseDown = onMouseDown.bind( this );
+ this._onMouseMove = onMouseMove.bind( this );
+
+ this._interceptControlDown = interceptControlDown.bind( this );
+ this._interceptControlUp = interceptControlUp.bind( this );
+
+ //
+
+ if ( this.domElement !== null ) {
+
+ this.connect( this.domElement );
+
+ }
+
+ this.update();
+
+ }
+
+ /**
+ * Defines the visual representation of the cursor.
+ *
+ * @type {('auto'|'grab')}
+ * @default 'auto'
+ */
+ set cursorStyle( type ) {
+
+ this._cursorStyle = type;
+
+ if ( type === 'grab' ) {
+
+ this.domElement.style.cursor = 'grab';
+
+ } else {
+
+ this.domElement.style.cursor = 'auto';
+
+ }
+
+ }
+
+ get cursorStyle() {
+
+ return this._cursorStyle;
+
+ }
+
+ connect( element ) {
+
+ super.connect( element );
+
+ 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: false } );
+
+ const document = this.domElement.getRootNode(); // offscreen canvas compatibility
+ document.addEventListener( 'keydown', this._interceptControlDown, { passive: true, capture: true } );
+
+ this.domElement.style.touchAction = 'none'; // Disable touch scroll
+
+ }
+
+ 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();
+
+ const document = this.domElement.getRootNode(); // offscreen canvas compatibility
+ document.removeEventListener( 'keydown', this._interceptControlDown, { capture: true } );
+
+ this.domElement.style.touchAction = ''; // Restore touch scroll
+
+ }
+
+ dispose() {
+
+ this.disconnect();
+
+ }
+
+ /**
+ * Get the current vertical rotation, in radians.
+ *
+ * @return {number} The current vertical rotation, in radians.
+ */
+ getPolarAngle() {
+
+ return this._spherical.phi;
+
+ }
+
+ /**
+ * Get the current horizontal rotation, in radians.
+ *
+ * @return {number} The current horizontal rotation, in radians.
+ */
+ getAzimuthalAngle() {
+
+ return this._spherical.theta;
+
+ }
+
+ /**
+ * Returns the distance from the camera to the target.
+ *
+ * @return {number} The distance from the camera to the target.
+ */
+ getDistance() {
+
+ return this.object.position.distanceTo( this.target );
+
+ }
+
+ /**
+ * Adds key event listeners to the given DOM element.
+ * `window` is a recommended argument for using this method.
+ *
+ * @param {HTMLElement} domElement - The DOM element
+ */
+ listenToKeyEvents( domElement ) {
+
+ domElement.addEventListener( 'keydown', this._onKeyDown );
+ this._domElementKeyEvents = domElement;
+
+ }
+
+ /**
+ * Removes the key event listener previously defined with `listenToKeyEvents()`.
+ */
+ stopListenToKeyEvents() {
+
+ if ( this._domElementKeyEvents !== null ) {
+
+ this._domElementKeyEvents.removeEventListener( 'keydown', this._onKeyDown );
+ this._domElementKeyEvents = null;
+
+ }
+
+ }
+
+ /**
+ * Save the current state of the controls. This can later be recovered with `reset()`.
+ */
+ saveState() {
+
+ this.target0.copy( this.target );
+ this.position0.copy( this.object.position );
+ this.zoom0 = this.object.zoom;
+
+ }
+
+ /**
+ * Reset the controls to their state from either the last time the `saveState()`
+ * was called, or the initial state.
+ */
+ reset() {
+
+ this.target.copy( this.target0 );
+ this.object.position.copy( this.position0 );
+ this.object.zoom = this.zoom0;
+
+ this.object.updateProjectionMatrix();
+ this.dispatchEvent( _changeEvent );
+
+ this.update();
+
+ this.state = _STATE.NONE;
+
+ }
+
+ /**
+ * Programmatically pan the camera.
+ *
+ * @param {number} deltaX - The horizontal pan amount in pixels.
+ * @param {number} deltaY - The vertical pan amount in pixels.
+ */
+ pan( deltaX, deltaY ) {
+
+ this._pan( deltaX, deltaY );
+ this.update();
+
+ }
+
+ /**
+ * Programmatically dolly in (zoom in for perspective camera).
+ *
+ * @param {number} dollyScale - The dolly scale factor.
+ */
+ dollyIn( dollyScale ) {
+
+ this._dollyIn( dollyScale );
+ this.update();
+
+ }
+
+ /**
+ * Programmatically dolly out (zoom out for perspective camera).
+ *
+ * @param {number} dollyScale - The dolly scale factor.
+ */
+ dollyOut( dollyScale ) {
+
+ this._dollyOut( dollyScale );
+ this.update();
+
+ }
+
+ /**
+ * Programmatically rotate the camera left (around the vertical axis).
+ *
+ * @param {number} angle - The rotation angle in radians.
+ */
+ rotateLeft( angle ) {
+
+ this._rotateLeft( angle );
+ this.update();
+
+ }
+
+ /**
+ * Programmatically rotate the camera up (around the horizontal axis).
+ *
+ * @param {number} angle - The rotation angle in radians.
+ */
+ rotateUp( angle ) {
+
+ this._rotateUp( angle );
+ this.update();
+
+ }
+
+ update( deltaTime = null ) {
+
+ const position = this.object.position;
+
+ _v.copy( position ).sub( this.target );
+
+ // rotate offset to "y-axis-is-up" space
+ _v.applyQuaternion( this._quat );
+
+ // angle from z-axis around y-axis
+ this._spherical.setFromVector3( _v );
+
+ if ( this.autoRotate && this.state === _STATE.NONE ) {
+
+ this._rotateLeft( this._getAutoRotationAngle( deltaTime ) );
+
+ }
+
+ if ( this.enableDamping ) {
+
+ this._spherical.theta += this._sphericalDelta.theta * this.dampingFactor;
+ this._spherical.phi += this._sphericalDelta.phi * this.dampingFactor;
+
+ } else {
+
+ this._spherical.theta += this._sphericalDelta.theta;
+ this._spherical.phi += this._sphericalDelta.phi;
+
+ }
+
+ // restrict theta to be between desired limits
+
+ let min = this.minAzimuthAngle;
+ let max = this.maxAzimuthAngle;
+
+ if ( isFinite( min ) && isFinite( max ) ) {
+
+ if ( min < - Math.PI ) min += _twoPI; else if ( min > Math.PI ) min -= _twoPI;
+
+ if ( max < - Math.PI ) max += _twoPI; else if ( max > Math.PI ) max -= _twoPI;
+
+ if ( min <= max ) {
+
+ this._spherical.theta = Math.max( min, Math.min( max, this._spherical.theta ) );
+
+ } else {
+
+ this._spherical.theta = ( this._spherical.theta > ( min + max ) / 2 ) ?
+ Math.max( min, this._spherical.theta ) :
+ Math.min( max, this._spherical.theta );
+
+ }
+
+ }
+
+ // restrict phi to be between desired limits
+ this._spherical.phi = Math.max( this.minPolarAngle, Math.min( this.maxPolarAngle, this._spherical.phi ) );
+
+ this._spherical.makeSafe();
+
+
+ // move target to panned location
+
+ if ( this.enableDamping === true ) {
+
+ this.target.addScaledVector( this._panOffset, this.dampingFactor );
+
+ } else {
+
+ this.target.add( this._panOffset );
+
+ }
+
+ // Limit the target distance from the cursor to create a sphere around the center of interest
+ this.target.sub( this.cursor );
+ this.target.clampLength( this.minTargetRadius, this.maxTargetRadius );
+ this.target.add( this.cursor );
+
+ let zoomChanged = false;
+ // adjust the camera position based on zoom only if we're not zooming to the cursor or if it's an ortho camera
+ // we adjust zoom later in these cases
+ if ( this.zoomToCursor && this._performCursorZoom || this.object.isOrthographicCamera ) {
+
+ this._spherical.radius = this._clampDistance( this._spherical.radius );
+
+ } else {
+
+ const prevRadius = this._spherical.radius;
+ this._spherical.radius = this._clampDistance( this._spherical.radius * this._scale );
+ zoomChanged = prevRadius != this._spherical.radius;
+
+ }
+
+ _v.setFromSpherical( this._spherical );
+
+ // rotate offset back to "camera-up-vector-is-up" space
+ _v.applyQuaternion( this._quatInverse );
+
+ position.copy( this.target ).add( _v );
+
+ this.object.lookAt( this.target );
+
+ if ( this.enableDamping === true ) {
+
+ this._sphericalDelta.theta *= ( 1 - this.dampingFactor );
+ this._sphericalDelta.phi *= ( 1 - this.dampingFactor );
+
+ this._panOffset.multiplyScalar( 1 - this.dampingFactor );
+
+ } else {
+
+ this._sphericalDelta.set( 0, 0, 0 );
+
+ this._panOffset.set( 0, 0, 0 );
+
+ }
+
+ // adjust camera position
+ if ( this.zoomToCursor && this._performCursorZoom ) {
+
+ let newRadius = null;
+ if ( this.object.isPerspectiveCamera ) {
+
+ // move the camera down the pointer ray
+ // this method avoids floating point error
+ const prevRadius = _v.length();
+ newRadius = this._clampDistance( prevRadius * this._scale );
+
+ const radiusDelta = prevRadius - newRadius;
+ this.object.position.addScaledVector( this._dollyDirection, radiusDelta );
+ this.object.updateMatrixWorld();
+
+ zoomChanged = !! radiusDelta;
+
+ } else if ( this.object.isOrthographicCamera ) {
+
+ // adjust the ortho camera position based on zoom changes
+ const mouseBefore = new Vector3( this._mouse.x, this._mouse.y, 0 );
+ mouseBefore.unproject( this.object );
+
+ const prevZoom = this.object.zoom;
+ this.object.zoom = Math.max( this.minZoom, Math.min( this.maxZoom, this.object.zoom / this._scale ) );
+ this.object.updateProjectionMatrix();
+
+ zoomChanged = prevZoom !== this.object.zoom;
+
+ const mouseAfter = new Vector3( this._mouse.x, this._mouse.y, 0 );
+ mouseAfter.unproject( this.object );
+
+ this.object.position.sub( mouseAfter ).add( mouseBefore );
+ this.object.updateMatrixWorld();
+
+ newRadius = _v.length();
+
+ } else {
+
+ console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled.' );
+ this.zoomToCursor = false;
+
+ }
+
+ // handle the placement of the target
+ if ( newRadius !== null ) {
+
+ if ( this.screenSpacePanning ) {
+
+ // position the orbit target in front of the new camera position
+ this.target.set( 0, 0, - 1 )
+ .transformDirection( this.object.matrix )
+ .multiplyScalar( newRadius )
+ .add( this.object.position );
+
+ } else {
+
+ // get the ray and translation plane to compute target
+ _ray.origin.copy( this.object.position );
+ _ray.direction.set( 0, 0, - 1 ).transformDirection( this.object.matrix );
+
+ // if the camera is 20 degrees above the horizon then don't adjust the focus target to avoid
+ // extremely large values
+ if ( Math.abs( this.object.up.dot( _ray.direction ) ) < _TILT_LIMIT ) {
+
+ this.object.lookAt( this.target );
+
+ } else {
+
+ _plane.setFromNormalAndCoplanarPoint( this.object.up, this.target );
+ _ray.intersectPlane( _plane, this.target );
+
+ }
+
+ }
+
+ }
+
+ } else if ( this.object.isOrthographicCamera ) {
+
+ const prevZoom = this.object.zoom;
+ this.object.zoom = Math.max( this.minZoom, Math.min( this.maxZoom, this.object.zoom / this._scale ) );
+
+ if ( prevZoom !== this.object.zoom ) {
+
+ this.object.updateProjectionMatrix();
+ zoomChanged = true;
+
+ }
+
+ }
+
+ this._scale = 1;
+ this._performCursorZoom = false;
+
+ // update condition is:
+ // min(camera displacement, camera rotation in radians)^2 > EPS
+ // using small-angle approximation cos(x/2) = 1 - x^2 / 8
+
+ if ( zoomChanged ||
+ this._lastPosition.distanceToSquared( this.object.position ) > _EPS ||
+ 8 * ( 1 - this._lastQuaternion.dot( this.object.quaternion ) ) > _EPS ||
+ this._lastTargetPosition.distanceToSquared( this.target ) > _EPS ) {
+
+ this.dispatchEvent( _changeEvent );
+
+ this._lastPosition.copy( this.object.position );
+ this._lastQuaternion.copy( this.object.quaternion );
+ this._lastTargetPosition.copy( this.target );
+
+ return true;
+
+ }
+
+ return false;
+
+ }
+
+ _getAutoRotationAngle( deltaTime ) {
+
+ if ( deltaTime !== null ) {
+
+ return ( _twoPI / 60 * this.autoRotateSpeed ) * deltaTime;
+
+ } else {
+
+ return _twoPI / 60 / 60 * this.autoRotateSpeed;
+
+ }
+
+ }
+
+ _getZoomScale( delta ) {
+
+ const normalizedDelta = Math.abs( delta * 0.01 );
+ return Math.pow( 0.95, this.zoomSpeed * normalizedDelta );
+
+ }
+
+ _rotateLeft( angle ) {
+
+ this._sphericalDelta.theta -= angle;
+
+ }
+
+ _rotateUp( angle ) {
+
+ this._sphericalDelta.phi -= angle;
+
+ }
+
+ _panLeft( distance, objectMatrix ) {
+
+ _v.setFromMatrixColumn( objectMatrix, 0 ); // get X column of objectMatrix
+ _v.multiplyScalar( - distance );
+
+ this._panOffset.add( _v );
+
+ }
+
+ _panUp( distance, objectMatrix ) {
+
+ if ( this.screenSpacePanning === true ) {
+
+ _v.setFromMatrixColumn( objectMatrix, 1 );
+
+ } else {
+
+ _v.setFromMatrixColumn( objectMatrix, 0 );
+ _v.crossVectors( this.object.up, _v );
+
+ }
+
+ _v.multiplyScalar( distance );
+
+ this._panOffset.add( _v );
+
+ }
+
+ // deltaX and deltaY are in pixels; right and down are positive
+ _pan( deltaX, deltaY ) {
+
+ const element = this.domElement;
+
+ if ( this.object.isPerspectiveCamera ) {
+
+ // perspective
+ const position = this.object.position;
+ _v.copy( position ).sub( this.target );
+ let targetDistance = _v.length();
+
+ // half of the fov is center to top of screen
+ targetDistance *= Math.tan( ( this.object.fov / 2 ) * Math.PI / 180.0 );
+
+ // we use only clientHeight here so aspect ratio does not distort speed
+ this._panLeft( 2 * deltaX * targetDistance / element.clientHeight, this.object.matrix );
+ this._panUp( 2 * deltaY * targetDistance / element.clientHeight, this.object.matrix );
+
+ } else if ( this.object.isOrthographicCamera ) {
+
+ // orthographic
+ this._panLeft( deltaX * ( this.object.right - this.object.left ) / this.object.zoom / element.clientWidth, this.object.matrix );
+ this._panUp( deltaY * ( this.object.top - this.object.bottom ) / this.object.zoom / element.clientHeight, this.object.matrix );
+
+ } else {
+
+ // camera neither orthographic nor perspective
+ console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' );
+ this.enablePan = false;
+
+ }
+
+ }
+
+ _dollyOut( dollyScale ) {
+
+ if ( this.object.isPerspectiveCamera || this.object.isOrthographicCamera ) {
+
+ this._scale /= dollyScale;
+
+ } else {
+
+ console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );
+ this.enableZoom = false;
+
+ }
+
+ }
+
+ _dollyIn( dollyScale ) {
+
+ if ( this.object.isPerspectiveCamera || this.object.isOrthographicCamera ) {
+
+ this._scale *= dollyScale;
+
+ } else {
+
+ console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );
+ this.enableZoom = false;
+
+ }
+
+ }
+
+ _updateZoomParameters( x, y ) {
+
+ if ( ! this.zoomToCursor ) {
+
+ return;
+
+ }
+
+ this._performCursorZoom = true;
+
+ const rect = this.domElement.getBoundingClientRect();
+ const dx = x - rect.left;
+ const dy = y - rect.top;
+ const w = rect.width;
+ const h = rect.height;
+
+ this._mouse.x = ( dx / w ) * 2 - 1;
+ this._mouse.y = - ( dy / h ) * 2 + 1;
+
+ this._dollyDirection.set( this._mouse.x, this._mouse.y, 1 ).unproject( this.object ).sub( this.object.position ).normalize();
+
+ }
+
+ _clampDistance( dist ) {
+
+ return Math.max( this.minDistance, Math.min( this.maxDistance, dist ) );
+
+ }
+
+ //
+ // event callbacks - update the object state
+ //
+
+ _handleMouseDownRotate( event ) {
+
+ this._rotateStart.set( event.clientX, event.clientY );
+
+ }
+
+ _handleMouseDownDolly( event ) {
+
+ this._updateZoomParameters( event.clientX, event.clientX );
+ this._dollyStart.set( event.clientX, event.clientY );
+
+ }
+
+ _handleMouseDownPan( event ) {
+
+ this._panStart.set( event.clientX, event.clientY );
+
+ }
+
+ _handleMouseMoveRotate( event ) {
+
+ this._rotateEnd.set( event.clientX, event.clientY );
+
+ this._rotateDelta.subVectors( this._rotateEnd, this._rotateStart ).multiplyScalar( this.rotateSpeed );
+
+ const element = this.domElement;
+
+ this._rotateLeft( _twoPI * this._rotateDelta.x / element.clientHeight ); // yes, height
+
+ this._rotateUp( _twoPI * this._rotateDelta.y / element.clientHeight );
+
+ this._rotateStart.copy( this._rotateEnd );
+
+ this.update();
+
+ }
+
+ _handleMouseMoveDolly( event ) {
+
+ this._dollyEnd.set( event.clientX, event.clientY );
+
+ this._dollyDelta.subVectors( this._dollyEnd, this._dollyStart );
+
+ if ( this._dollyDelta.y > 0 ) {
+
+ this._dollyOut( this._getZoomScale( this._dollyDelta.y ) );
+
+ } else if ( this._dollyDelta.y < 0 ) {
+
+ this._dollyIn( this._getZoomScale( this._dollyDelta.y ) );
+
+ }
+
+ this._dollyStart.copy( this._dollyEnd );
+
+ this.update();
+
+ }
+
+ _handleMouseMovePan( event ) {
+
+ this._panEnd.set( event.clientX, event.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( event ) {
+
+ this._updateZoomParameters( event.clientX, event.clientY );
+
+ if ( event.deltaY < 0 ) {
+
+ this._dollyIn( this._getZoomScale( event.deltaY ) );
+
+ } else if ( event.deltaY > 0 ) {
+
+ this._dollyOut( this._getZoomScale( event.deltaY ) );
+
+ }
+
+ this.update();
+
+ }
+
+ _handleKeyDown( event ) {
+
+ let needsUpdate = false;
+
+ switch ( event.code ) {
+
+ case this.keys.UP:
+
+ if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
+
+ if ( this.enableRotate ) {
+
+ this._rotateUp( _twoPI * this.keyRotateSpeed / this.domElement.clientHeight );
+
+ }
+
+ } else {
+
+ if ( this.enablePan ) {
+
+ this._pan( 0, this.keyPanSpeed );
+
+ }
+
+ }
+
+ needsUpdate = true;
+ break;
+
+ case this.keys.BOTTOM:
+
+ if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
+
+ if ( this.enableRotate ) {
+
+ this._rotateUp( - _twoPI * this.keyRotateSpeed / this.domElement.clientHeight );
+
+ }
+
+ } else {
+
+ if ( this.enablePan ) {
+
+ this._pan( 0, - this.keyPanSpeed );
+
+ }
+
+ }
+
+ needsUpdate = true;
+ break;
+
+ case this.keys.LEFT:
+
+ if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
+
+ if ( this.enableRotate ) {
+
+ this._rotateLeft( _twoPI * this.keyRotateSpeed / this.domElement.clientHeight );
+
+ }
+
+ } else {
+
+ if ( this.enablePan ) {
+
+ this._pan( this.keyPanSpeed, 0 );
+
+ }
+
+ }
+
+ needsUpdate = true;
+ break;
+
+ case this.keys.RIGHT:
+
+ if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
+
+ if ( this.enableRotate ) {
+
+ this._rotateLeft( - _twoPI * this.keyRotateSpeed / this.domElement.clientHeight );
+
+ }
+
+ } else {
+
+ if ( this.enablePan ) {
+
+ this._pan( - this.keyPanSpeed, 0 );
+
+ }
+
+ }
+
+ needsUpdate = true;
+ break;
+
+ }
+
+ if ( needsUpdate ) {
+
+ // prevent the browser from scrolling on cursor keys
+ event.preventDefault();
+
+ this.update();
+
+ }
+
+
+ }
+
+ _handleTouchStartRotate( event ) {
+
+ if ( this._pointers.length === 1 ) {
+
+ this._rotateStart.set( event.pageX, event.pageY );
+
+ } else {
+
+ const position = this._getSecondPointerPosition( event );
+
+ const x = 0.5 * ( event.pageX + position.x );
+ const y = 0.5 * ( event.pageY + position.y );
+
+ this._rotateStart.set( x, y );
+
+ }
+
+ }
+
+ _handleTouchStartPan( event ) {
+
+ if ( this._pointers.length === 1 ) {
+
+ this._panStart.set( event.pageX, event.pageY );
+
+ } else {
+
+ const position = this._getSecondPointerPosition( event );
+
+ const x = 0.5 * ( event.pageX + position.x );
+ const y = 0.5 * ( event.pageY + position.y );
+
+ this._panStart.set( x, y );
+
+ }
+
+ }
+
+ _handleTouchStartDolly( event ) {
+
+ const position = this._getSecondPointerPosition( event );
+
+ const dx = event.pageX - position.x;
+ const dy = event.pageY - position.y;
+
+ const distance = Math.sqrt( dx * dx + dy * dy );
+
+ this._dollyStart.set( 0, distance );
+
+ }
+
+ _handleTouchStartDollyPan( event ) {
+
+ if ( this.enableZoom ) this._handleTouchStartDolly( event );
+
+ if ( this.enablePan ) this._handleTouchStartPan( event );
+
+ }
+
+ _handleTouchStartDollyRotate( event ) {
+
+ if ( this.enableZoom ) this._handleTouchStartDolly( event );
+
+ if ( this.enableRotate ) this._handleTouchStartRotate( event );
+
+ }
+
+ _handleTouchMoveRotate( event ) {
+
+ if ( this._pointers.length == 1 ) {
+
+ this._rotateEnd.set( event.pageX, event.pageY );
+
+ } else {
+
+ const position = this._getSecondPointerPosition( event );
+
+ const x = 0.5 * ( event.pageX + position.x );
+ const y = 0.5 * ( event.pageY + position.y );
+
+ this._rotateEnd.set( x, y );
+
+ }
+
+ this._rotateDelta.subVectors( this._rotateEnd, this._rotateStart ).multiplyScalar( this.rotateSpeed );
+
+ const element = this.domElement;
+
+ this._rotateLeft( _twoPI * this._rotateDelta.x / element.clientHeight ); // yes, height
+
+ this._rotateUp( _twoPI * this._rotateDelta.y / element.clientHeight );
+
+ this._rotateStart.copy( this._rotateEnd );
+
+ }
+
+ _handleTouchMovePan( event ) {
+
+ if ( this._pointers.length === 1 ) {
+
+ this._panEnd.set( event.pageX, event.pageY );
+
+ } else {
+
+ const position = this._getSecondPointerPosition( event );
+
+ const x = 0.5 * ( event.pageX + position.x );
+ const y = 0.5 * ( event.pageY + position.y );
+
+ this._panEnd.set( x, y );
+
+ }
+
+ this._panDelta.subVectors( this._panEnd, this._panStart ).multiplyScalar( this.panSpeed );
+
+ this._pan( this._panDelta.x, this._panDelta.y );
+
+ this._panStart.copy( this._panEnd );
+
+ }
+
+ _handleTouchMoveDolly( event ) {
+
+ const position = this._getSecondPointerPosition( event );
+
+ const dx = event.pageX - position.x;
+ const dy = event.pageY - position.y;
+
+ const distance = Math.sqrt( dx * dx + dy * dy );
+
+ this._dollyEnd.set( 0, distance );
+
+ this._dollyDelta.set( 0, Math.pow( this._dollyEnd.y / this._dollyStart.y, this.zoomSpeed ) );
+
+ this._dollyOut( this._dollyDelta.y );
+
+ this._dollyStart.copy( this._dollyEnd );
+
+ const centerX = ( event.pageX + position.x ) * 0.5;
+ const centerY = ( event.pageY + position.y ) * 0.5;
+
+ this._updateZoomParameters( centerX, centerY );
+
+ }
+
+ _handleTouchMoveDollyPan( event ) {
+
+ if ( this.enableZoom ) this._handleTouchMoveDolly( event );
+
+ if ( this.enablePan ) this._handleTouchMovePan( event );
+
+ }
+
+ _handleTouchMoveDollyRotate( event ) {
+
+ if ( this.enableZoom ) this._handleTouchMoveDolly( event );
+
+ if ( this.enableRotate ) this._handleTouchMoveRotate( event );
+
+ }
+
+ // pointers
+
+ _addPointer( event ) {
+
+ this._pointers.push( event.pointerId );
+
+ }
+
+ _removePointer( event ) {
+
+ delete this._pointerPositions[ event.pointerId ];
+
+ for ( let i = 0; i < this._pointers.length; i ++ ) {
+
+ if ( this._pointers[ i ] == event.pointerId ) {
+
+ this._pointers.splice( i, 1 );
+ return;
+
+ }
+
+ }
+
+ }
+
+ _isTrackingPointer( event ) {
+
+ for ( let i = 0; i < this._pointers.length; i ++ ) {
+
+ if ( this._pointers[ i ] == event.pointerId ) return true;
+
+ }
+
+ return false;
+
+ }
+
+ _trackPointer( event ) {
+
+ let position = this._pointerPositions[ event.pointerId ];
+
+ if ( position === undefined ) {
+
+ position = new Vector2();
+ this._pointerPositions[ event.pointerId ] = position;
+
+ }
+
+ position.set( event.pageX, event.pageY );
+
+ }
+
+ _getSecondPointerPosition( event ) {
+
+ const pointerId = ( event.pointerId === this._pointers[ 0 ] ) ? this._pointers[ 1 ] : this._pointers[ 0 ];
+
+ return this._pointerPositions[ pointerId ];
+
+ }
+
+ //
+
+ _customWheelEvent( event ) {
+
+ const mode = event.deltaMode;
+
+ // minimal wheel event altered to meet delta-zoom demand
+ const newEvent = {
+ clientX: event.clientX,
+ clientY: event.clientY,
+ deltaY: event.deltaY,
+ };
+
+ switch ( mode ) {
+
+ case 1: // LINE_MODE
+ newEvent.deltaY *= 16;
+ break;
+
+ case 2: // PAGE_MODE
+ newEvent.deltaY *= 100;
+ break;
+
+ }
+
+ // detect if event was triggered by pinching
+ if ( event.ctrlKey && ! this._controlActive ) {
+
+ newEvent.deltaY *= 10;
+
+ }
+
+ return newEvent;
+
+ }
+
+}
+
+function onPointerDown( event ) {
+
+ if ( this.enabled === false ) return;
+
+ if ( this._pointers.length === 0 ) {
+
+ this.domElement.setPointerCapture( event.pointerId );
+
+ this.domElement.ownerDocument.addEventListener( 'pointermove', this._onPointerMove );
+ this.domElement.ownerDocument.addEventListener( 'pointerup', this._onPointerUp );
+
+ }
+
+ //
+
+ if ( this._isTrackingPointer( event ) ) return;
+
+ //
+
+ this._addPointer( event );
+
+ if ( event.pointerType === 'touch' ) {
+
+ this._onTouchStart( event );
+
+ } else {
+
+ this._onMouseDown( event );
+
+ }
+
+ if ( this._cursorStyle === 'grab' ) {
+
+ this.domElement.style.cursor = 'grabbing';
+
+ }
+
+}
+
+function onPointerMove( event ) {
+
+ if ( this.enabled === false ) return;
+
+ if ( event.pointerType === 'touch' ) {
+
+ this._onTouchMove( event );
+
+ } else {
+
+ this._onMouseMove( event );
+
+ }
+
+}
+
+function onPointerUp( event ) {
+
+ this._removePointer( event );
+
+ switch ( this._pointers.length ) {
+
+ case 0:
+
+ this.domElement.releasePointerCapture( event.pointerId );
+
+ this.domElement.ownerDocument.removeEventListener( 'pointermove', this._onPointerMove );
+ this.domElement.ownerDocument.removeEventListener( 'pointerup', this._onPointerUp );
+
+ this.dispatchEvent( _endEvent );
+
+ this.state = _STATE.NONE;
+
+ if ( this._cursorStyle === 'grab' ) {
+
+ this.domElement.style.cursor = 'grab';
+
+ }
+
+ break;
+
+ case 1:
+
+ const pointerId = this._pointers[ 0 ];
+ const position = this._pointerPositions[ pointerId ];
+
+ // minimal placeholder event - allows state correction on pointer-up
+ this._onTouchStart( { pointerId: pointerId, pageX: position.x, pageY: position.y } );
+
+ break;
+
+ }
+
+}
+
+function onMouseDown( event ) {
+
+ let mouseAction;
+
+ switch ( event.button ) {
+
+ case 0:
+
+ mouseAction = this.mouseButtons.LEFT;
+ break;
+
+ case 1:
+
+ mouseAction = this.mouseButtons.MIDDLE;
+ break;
+
+ case 2:
+
+ mouseAction = this.mouseButtons.RIGHT;
+ break;
+
+ default:
+
+ mouseAction = - 1;
+
+ }
+
+ switch ( mouseAction ) {
+
+ case MOUSE.DOLLY:
+
+ if ( this.enableZoom === false ) return;
+
+ this._handleMouseDownDolly( event );
+
+ this.state = _STATE.DOLLY;
+
+ break;
+
+ case MOUSE.ROTATE:
+
+ if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
+
+ if ( this.enablePan === false ) return;
+
+ this._handleMouseDownPan( event );
+
+ this.state = _STATE.PAN;
+
+ } else {
+
+ if ( this.enableRotate === false ) return;
+
+ this._handleMouseDownRotate( event );
+
+ this.state = _STATE.ROTATE;
+
+ }
+
+ break;
+
+ case MOUSE.PAN:
+
+ if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
+
+ if ( this.enableRotate === false ) return;
+
+ this._handleMouseDownRotate( event );
+
+ this.state = _STATE.ROTATE;
+
+ } else {
+
+ if ( this.enablePan === false ) return;
+
+ this._handleMouseDownPan( event );
+
+ this.state = _STATE.PAN;
+
+ }
+
+ break;
+
+ default:
+
+ this.state = _STATE.NONE;
+
+ }
+
+ if ( this.state !== _STATE.NONE ) {
+
+ this.dispatchEvent( _startEvent );
+
+ }
+
+}
+
+function onMouseMove( event ) {
+
+ switch ( this.state ) {
+
+ case _STATE.ROTATE:
+
+ if ( this.enableRotate === false ) return;
+
+ this._handleMouseMoveRotate( event );
+
+ break;
+
+ case _STATE.DOLLY:
+
+ if ( this.enableZoom === false ) return;
+
+ this._handleMouseMoveDolly( event );
+
+ break;
+
+ case _STATE.PAN:
+
+ if ( this.enablePan === false ) return;
+
+ this._handleMouseMovePan( event );
+
+ break;
+
+ }
+
+}
+
+function onMouseWheel( event ) {
+
+ if ( this.enabled === false || this.enableZoom === false || this.state !== _STATE.NONE ) return;
+
+ event.preventDefault();
+
+ this.dispatchEvent( _startEvent );
+
+ this._handleMouseWheel( this._customWheelEvent( event ) );
+
+ this.dispatchEvent( _endEvent );
+
+}
+
+function onKeyDown( event ) {
+
+ if ( this.enabled === false ) return;
+
+ this._handleKeyDown( event );
+
+}
+
+function onTouchStart( event ) {
+
+ this._trackPointer( event );
+
+ switch ( this._pointers.length ) {
+
+ case 1:
+
+ switch ( this.touches.ONE ) {
+
+ case TOUCH.ROTATE:
+
+ if ( this.enableRotate === false ) return;
+
+ this._handleTouchStartRotate( event );
+
+ this.state = _STATE.TOUCH_ROTATE;
+
+ break;
+
+ case TOUCH.PAN:
+
+ if ( this.enablePan === false ) return;
+
+ this._handleTouchStartPan( event );
+
+ this.state = _STATE.TOUCH_PAN;
+
+ break;
+
+ default:
+
+ this.state = _STATE.NONE;
+
+ }
+
+ break;
+
+ case 2:
+
+ switch ( this.touches.TWO ) {
+
+ case TOUCH.DOLLY_PAN:
+
+ if ( this.enableZoom === false && this.enablePan === false ) return;
+
+ this._handleTouchStartDollyPan( event );
+
+ this.state = _STATE.TOUCH_DOLLY_PAN;
+
+ break;
+
+ case TOUCH.DOLLY_ROTATE:
+
+ if ( this.enableZoom === false && this.enableRotate === false ) return;
+
+ this._handleTouchStartDollyRotate( event );
+
+ this.state = _STATE.TOUCH_DOLLY_ROTATE;
+
+ break;
+
+ default:
+
+ this.state = _STATE.NONE;
+
+ }
+
+ break;
+
+ default:
+
+ this.state = _STATE.NONE;
+
+ }
+
+ if ( this.state !== _STATE.NONE ) {
+
+ this.dispatchEvent( _startEvent );
+
+ }
+
+}
+
+function onTouchMove( event ) {
+
+ this._trackPointer( event );
+
+ switch ( this.state ) {
+
+ case _STATE.TOUCH_ROTATE:
+
+ if ( this.enableRotate === false ) return;
+
+ this._handleTouchMoveRotate( event );
+
+ this.update();
+
+ break;
+
+ case _STATE.TOUCH_PAN:
+
+ if ( this.enablePan === false ) return;
+
+ this._handleTouchMovePan( event );
+
+ this.update();
+
+ break;
+
+ case _STATE.TOUCH_DOLLY_PAN:
+
+ if ( this.enableZoom === false && this.enablePan === false ) return;
+
+ this._handleTouchMoveDollyPan( event );
+
+ this.update();
+
+ break;
+
+ case _STATE.TOUCH_DOLLY_ROTATE:
+
+ if ( this.enableZoom === false && this.enableRotate === false ) return;
+
+ this._handleTouchMoveDollyRotate( event );
+
+ this.update();
+
+ break;
+
+ default:
+
+ this.state = _STATE.NONE;
+
+ }
+
+}
+
+function onContextMenu( event ) {
+
+ if ( this.enabled === false ) return;
+
+ event.preventDefault();
+
+}
+
+function interceptControlDown( event ) {
+
+ if ( event.key === 'Control' ) {
+
+ this._controlActive = true;
+
+ const document = this.domElement.getRootNode(); // offscreen canvas compatibility
+
+ document.addEventListener( 'keyup', this._interceptControlUp, { passive: true, capture: true } );
+
+ }
+
+}
+
+function interceptControlUp( event ) {
+
+ if ( event.key === 'Control' ) {
+
+ this._controlActive = false;
+
+ const document = this.domElement.getRootNode(); // offscreen canvas compatibility
+
+ document.removeEventListener( 'keyup', this._interceptControlUp, { passive: true, capture: true } );
+
+ }
+
+}
+
+export { OrbitControls };
diff --git a/web/vendor/THREE-LICENSE.txt b/web/vendor/THREE-LICENSE.txt
new file mode 100644
index 0000000..8ada2a5
--- /dev/null
+++ b/web/vendor/THREE-LICENSE.txt
@@ -0,0 +1,21 @@
+The MIT License
+
+Copyright © 2010-2026 three.js authors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/web/vendor/three.module.min.mjs b/web/vendor/three.module.min.mjs
new file mode 100644
index 0000000..5ae623c
--- /dev/null
+++ b/web/vendor/three.module.min.mjs
@@ -0,0 +1,6 @@
+/**
+ * @license
+ * Copyright 2010-2026 Three.js Authors
+ * SPDX-License-Identifier: MIT
+ */
+import{Matrix3 as e,Vector2 as t,Color as n,Vector3 as i,mergeUniforms as r,CubeUVReflectionMapping as a,Mesh as o,BoxGeometry as s,ShaderMaterial as l,BackSide as c,cloneUniforms as d,Matrix4 as u,ColorManagement as f,SRGBTransfer as p,PlaneGeometry as m,FrontSide as h,getUnlitUniformColorSpace as _,IntType as g,warn as v,HalfFloatType as E,UnsignedByteType as S,FloatType as M,RGBAFormat as T,Plane as x,CubeReflectionMapping as R,CubeRefractionMapping as A,BufferGeometry as b,OrthographicCamera as C,PerspectiveCamera as P,NoToneMapping as L,MeshBasicMaterial as U,error as D,NoBlending as w,WebGLRenderTarget as I,BufferAttribute as N,LinearSRGBColorSpace as y,LinearFilter as O,CubeTexture as F,LinearMipmapLinearFilter as B,CubeCamera as G,EquirectangularReflectionMapping as H,EquirectangularRefractionMapping as V,warnOnce as W,Uint32BufferAttribute as z,Uint16BufferAttribute as k,DataArrayTexture as X,Vector4 as K,DepthTexture as Y,Float32BufferAttribute as q,RawShaderMaterial as j,CustomToneMapping as Z,NeutralToneMapping as $,AgXToneMapping as Q,ACESFilmicToneMapping as J,CineonToneMapping as ee,ReinhardToneMapping as te,LinearToneMapping as ne,Data3DTexture as ie,GreaterEqualCompare as re,LessEqualCompare as ae,Texture as oe,GLSL3 as se,VSMShadowMap as le,PCFShadowMap as ce,AddOperation as de,MixOperation as ue,MultiplyOperation as fe,LinearTransfer as pe,UniformsUtils as me,DoubleSide as he,NormalBlending as _e,TangentSpaceNormalMap as ge,ObjectSpaceNormalMap as ve,Layers as Ee,RGFormat as Se,RG11_EAC_Format as Me,RED_GREEN_RGTC2_Format as Te,MeshDepthMaterial as xe,MeshDistanceMaterial as Re,PCFSoftShadowMap as Ae,DepthFormat as be,NearestFilter as Ce,CubeDepthTexture as Pe,UnsignedIntType as Le,Frustum as Ue,LessEqualDepth as De,ReverseSubtractEquation as we,SubtractEquation as Ie,AddEquation as Ne,OneMinusConstantAlphaFactor as ye,ConstantAlphaFactor as Oe,OneMinusConstantColorFactor as Fe,ConstantColorFactor as Be,OneMinusDstAlphaFactor as Ge,OneMinusDstColorFactor as He,OneMinusSrcAlphaFactor as Ve,OneMinusSrcColorFactor as We,DstAlphaFactor as ze,DstColorFactor as ke,SrcAlphaSaturateFactor as Xe,SrcAlphaFactor as Ke,SrcColorFactor as Ye,OneFactor as qe,ZeroFactor as je,NotEqualDepth as Ze,GreaterDepth as $e,GreaterEqualDepth as Qe,EqualDepth as Je,LessDepth as et,AlwaysDepth as tt,NeverDepth as nt,CullFaceNone as it,CullFaceBack as rt,CullFaceFront as at,CustomBlending as ot,MultiplyBlending as st,SubtractiveBlending as lt,AdditiveBlending as ct,ReversedDepthFuncs as dt,MinEquation as ut,MaxEquation as ft,MirroredRepeatWrapping as pt,ClampToEdgeWrapping as mt,RepeatWrapping as ht,LinearMipmapNearestFilter as _t,NearestMipmapLinearFilter as gt,NearestMipmapNearestFilter as vt,NotEqualCompare as Et,GreaterCompare as St,EqualCompare as Mt,LessCompare as Tt,AlwaysCompare as xt,NeverCompare as Rt,NoColorSpace as At,DepthStencilFormat as bt,getByteLength as Ct,UnsignedInt248Type as Pt,UnsignedShortType as Lt,createElementNS as Ut,UnsignedShort4444Type as Dt,UnsignedShort5551Type as wt,UnsignedInt5999Type as It,UnsignedInt101111Type as Nt,ByteType as yt,ShortType as Ot,AlphaFormat as Ft,RGBFormat as Bt,RedFormat as Gt,RedIntegerFormat as Ht,RGIntegerFormat as Vt,RGBAIntegerFormat as Wt,RGB_S3TC_DXT1_Format as zt,RGBA_S3TC_DXT1_Format as kt,RGBA_S3TC_DXT3_Format as Xt,RGBA_S3TC_DXT5_Format as Kt,RGB_PVRTC_4BPPV1_Format as Yt,RGB_PVRTC_2BPPV1_Format as qt,RGBA_PVRTC_4BPPV1_Format as jt,RGBA_PVRTC_2BPPV1_Format as Zt,RGB_ETC1_Format as $t,RGB_ETC2_Format as Qt,RGBA_ETC2_EAC_Format as Jt,R11_EAC_Format as en,SIGNED_R11_EAC_Format as tn,SIGNED_RG11_EAC_Format as nn,RGBA_ASTC_4x4_Format as rn,RGBA_ASTC_5x4_Format as an,RGBA_ASTC_5x5_Format as on,RGBA_ASTC_6x5_Format as sn,RGBA_ASTC_6x6_Format as ln,RGBA_ASTC_8x5_Format as cn,RGBA_ASTC_8x6_Format as dn,RGBA_ASTC_8x8_Format as un,RGBA_ASTC_10x5_Format as fn,RGBA_ASTC_10x6_Format as pn,RGBA_ASTC_10x8_Format as mn,RGBA_ASTC_10x10_Format as hn,RGBA_ASTC_12x10_Format as _n,RGBA_ASTC_12x12_Format as gn,RGBA_BPTC_Format as vn,RGB_BPTC_SIGNED_Format as En,RGB_BPTC_UNSIGNED_Format as Sn,RED_RGTC1_Format as Mn,SIGNED_RED_RGTC1_Format as Tn,SIGNED_RED_GREEN_RGTC2_Format as xn,ExternalTexture as Rn,EventDispatcher as An,ArrayCamera as bn,WebXRController as Cn,RAD2DEG as Pn,DataTexture as Ln,createCanvasElement as Un,SRGBColorSpace as Dn,REVISION as wn,log as In,WebGLCoordinateSystem as Nn,probeAsync as yn}from"./three.core.min.js";export{AdditiveAnimationBlendMode,AlwaysStencilFunc,AmbientLight,AnimationAction,AnimationClip,AnimationLoader,AnimationMixer,AnimationObjectGroup,AnimationUtils,ArcCurve,ArrowHelper,AttachedBindMode,Audio,AudioAnalyser,AudioContext,AudioListener,AudioLoader,AxesHelper,BasicDepthPacking,BasicShadowMap,BatchedMesh,BezierInterpolant,Bone,BooleanKeyframeTrack,Box2,Box3,Box3Helper,BoxHelper,BufferGeometryLoader,Cache,Camera,CameraHelper,CanvasTexture,CapsuleGeometry,CatmullRomCurve3,CircleGeometry,Clock,ColorKeyframeTrack,Compatibility,CompressedArrayTexture,CompressedCubeTexture,CompressedTexture,CompressedTextureLoader,ConeGeometry,Controls,CubeTextureLoader,CubicBezierCurve,CubicBezierCurve3,CubicInterpolant,CullFaceFrontBack,Curve,CurvePath,CylinderGeometry,Cylindrical,DataTextureLoader,DataUtils,DecrementStencilOp,DecrementWrapStencilOp,DefaultLoadingManager,DetachedBindMode,DirectionalLight,DirectionalLightHelper,DiscreteInterpolant,DodecahedronGeometry,DynamicCopyUsage,DynamicDrawUsage,DynamicReadUsage,EdgesGeometry,EllipseCurve,EqualStencilFunc,Euler,ExtrudeGeometry,FileLoader,Float16BufferAttribute,Fog,FogExp2,FramebufferTexture,FrustumArray,GLBufferAttribute,GLSL1,GreaterEqualStencilFunc,GreaterStencilFunc,GridHelper,Group,HTMLTexture,HemisphereLight,HemisphereLightHelper,IcosahedronGeometry,ImageBitmapLoader,ImageLoader,ImageUtils,IncrementStencilOp,IncrementWrapStencilOp,InstancedBufferAttribute,InstancedBufferGeometry,InstancedInterleavedBuffer,InstancedMesh,Int16BufferAttribute,Int32BufferAttribute,Int8BufferAttribute,InterleavedBuffer,InterleavedBufferAttribute,Interpolant,InterpolateBezier,InterpolateDiscrete,InterpolateLinear,InterpolateSmooth,InterpolationSamplingMode,InterpolationSamplingType,InvertStencilOp,KeepStencilOp,KeyframeTrack,LOD,LatheGeometry,LessEqualStencilFunc,LessStencilFunc,Light,LightProbe,Line,Line3,LineBasicMaterial,LineCurve,LineCurve3,LineDashedMaterial,LineLoop,LineSegments,LinearInterpolant,LinearMipMapLinearFilter,LinearMipMapNearestFilter,Loader,LoaderUtils,LoadingManager,LoopOnce,LoopPingPong,LoopRepeat,MOUSE,Material,MaterialBlending,MaterialLoader,MathUtils,Matrix2,MeshLambertMaterial,MeshMatcapMaterial,MeshNormalMaterial,MeshPhongMaterial,MeshPhysicalMaterial,MeshStandardMaterial,MeshToonMaterial,NearestMipMapLinearFilter,NearestMipMapNearestFilter,NeverStencilFunc,NoNormalPacking,NormalAnimationBlendMode,NormalGAPacking,NormalRGPacking,NotEqualStencilFunc,NumberKeyframeTrack,Object3D,ObjectLoader,OctahedronGeometry,Path,PlaneHelper,PointLight,PointLightHelper,Points,PointsMaterial,PolarGridHelper,PolyhedronGeometry,PositionalAudio,PropertyBinding,PropertyMixer,QuadraticBezierCurve,QuadraticBezierCurve3,Quaternion,QuaternionKeyframeTrack,QuaternionLinearInterpolant,RGBADepthPacking,RGBDepthPacking,RGBIntegerFormat,RGDepthPacking,Ray,Raycaster,RectAreaLight,RenderTarget,RenderTarget3D,ReplaceStencilOp,RingGeometry,Scene,ShadowMaterial,Shape,ShapeGeometry,ShapePath,ShapeUtils,Skeleton,SkeletonHelper,SkinnedMesh,Source,Sphere,SphereGeometry,Spherical,SphericalHarmonics3,SplineCurve,SpotLight,SpotLightHelper,Sprite,SpriteMaterial,StaticCopyUsage,StaticDrawUsage,StaticReadUsage,StereoCamera,StreamCopyUsage,StreamDrawUsage,StreamReadUsage,StringKeyframeTrack,TOUCH,TetrahedronGeometry,TextureLoader,TextureUtils,Timer,TimestampQuery,TorusGeometry,TorusKnotGeometry,Triangle,TriangleFanDrawMode,TriangleStripDrawMode,TrianglesDrawMode,TubeGeometry,UVMapping,Uint8BufferAttribute,Uint8ClampedBufferAttribute,Uniform,UniformsGroup,VectorKeyframeTrack,VideoFrameTexture,VideoTexture,WebGL3DRenderTarget,WebGLArrayRenderTarget,WebGPUCoordinateSystem,WireframeGeometry,WrapAroundEnding,ZeroCurvatureEnding,ZeroSlopeEnding,ZeroStencilOp,getConsoleFunction,setConsoleFunction}from"./three.core.min.js";function On(){let e=null,t=!1,n=null,i=null;function r(t,a){n(t,a),i=e.requestAnimationFrame(r)}return{start:function(){!0!==t&&null!==n&&null!==e&&(i=e.requestAnimationFrame(r),t=!0)},stop:function(){null!==e&&e.cancelAnimationFrame(i),t=!1},setAnimationLoop:function(e){n=e},setContext:function(t){e=t}}}function Fn(e){const t=new WeakMap;return{get:function(e){return e.isInterleavedBufferAttribute&&(e=e.data),t.get(e)},remove:function(n){n.isInterleavedBufferAttribute&&(n=n.data);const i=t.get(n);i&&(e.deleteBuffer(i.buffer),t.delete(n))},update:function(n,i){if(n.isInterleavedBufferAttribute&&(n=n.data),n.isGLBufferAttribute){const e=t.get(n);return void((!e||e.versione.start-t.start);let t=0;for(let e=1;e 0\n\tvec4 plane;\n\t#ifdef ALPHA_TO_COVERAGE\n\t\tfloat distanceToPlane, distanceGradient;\n\t\tfloat clipOpacity = 1.0;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\tclipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\tif ( clipOpacity == 0.0 ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tfloat unionClipOpacity = 1.0;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\t\tunionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tclipOpacity *= 1.0 - unionClipOpacity;\n\t\t#endif\n\t\tdiffuseColor.a *= clipOpacity;\n\t\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tbool clipped = true;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tif ( clipped ) discard;\n\t\t#endif\n\t#endif\n#endif",clipping_planes_pars_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif",clipping_planes_pars_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif",clipping_planes_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif",color_fragment:"#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#endif",color_pars_fragment:"#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#endif",color_pars_vertex:"#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvarying vec4 vColor;\n#endif",color_vertex:"#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvColor = vec4( 1.0 );\n#endif\n#ifdef USE_COLOR_ALPHA\n\tvColor *= color;\n#elif defined( USE_COLOR )\n\tvColor.rgb *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.rgb *= instanceColor.rgb;\n#endif\n#ifdef USE_BATCHING_COLOR\n\tvColor *= getBatchingColor( getIndirectIndex( gl_DrawID ) );\n#endif",common:"#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\n#ifdef USE_ALPHAHASH\n\tvarying vec3 vPosition;\n#endif\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\n#define inverseTransformDirection transformDirectionByInverseViewMatrix\nvec3 transformNormalByInverseViewMatrix( in vec3 normal, in mat4 viewMatrix ) {\n\treturn normalize( ( vec4( normal, 0.0 ) * viewMatrix ).xyz );\n}\nvec3 transformDirectionByInverseViewMatrix( in vec3 dir, in mat4 viewMatrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * viewMatrix ).xyz );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}\nvec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n} // validated",cube_uv_reflection_fragment:"#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\thighp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define cubeUV_r0 1.0\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif",defaultnormal_vertex:"vec3 transformedNormal = objectNormal;\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = objectTangent;\n#endif\n#ifdef USE_BATCHING\n\tmat3 bm = mat3( batchingMatrix );\n\ttransformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );\n\ttransformedNormal = bm * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = bm * transformedTangent;\n\t#endif\n#endif\n#ifdef USE_INSTANCING\n\tmat3 im = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );\n\ttransformedNormal = im * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = im * transformedTangent;\n\t#endif\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\ttransformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;\n#endif",displacementmap_pars_vertex:"#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif",displacementmap_vertex:"#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif",emissivemap_fragment:"#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE_EMISSIVE\n\t\temissiveColor = sRGBTransferEOTF( emissiveColor );\n\t#endif\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif",emissivemap_pars_fragment:"#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif",colorspace_fragment:"gl_FragColor = linearToOutputTexel( gl_FragColor );",colorspace_pars_fragment:"vec4 LinearTransferOETF( in vec4 value ) {\n\treturn value;\n}\nvec4 sRGBTransferEOTF( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 sRGBTransferOETF( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}",envmap_fragment:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = transformNormalByInverseViewMatrix( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, envMapRotation * reflectVec );\n\t\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t\t#endif\n\t#endif\n#endif",envmap_common_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform mat3 envMapRotation;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n#endif",envmap_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif",envmap_pars_vertex:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif",envmap_physical_pars_fragment:"#ifdef USE_ENVMAP\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 worldNormal = transformNormalByInverseViewMatrix( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, pow4( roughness ) ) );\n\t\t\treflectVec = transformDirectionByInverseViewMatrix( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\t#ifdef USE_ANISOTROPY\n\t\tvec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n\t\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\t\tvec3 bentNormal = cross( bitangent, viewDir );\n\t\t\t\tbentNormal = normalize( cross( bentNormal, bitangent ) );\n\t\t\t\tbentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n\t\t\t\treturn getIBLRadiance( viewDir, bentNormal, roughness );\n\t\t\t#else\n\t\t\t\treturn vec3( 0.0 );\n\t\t\t#endif\n\t\t}\n\t#endif\n#endif",envmap_vertex:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = transformNormalByInverseViewMatrix( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif",fog_vertex:"#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif",fog_pars_vertex:"#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif",fog_fragment:"#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif",fog_pars_fragment:"#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif",gradientmap_pars_fragment:"#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\tvec2 fw = fwidth( coord ) * 0.5;\n\t\treturn mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n\t#endif\n}",lightmap_pars_fragment:"#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif",lights_lambert_fragment:"LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;",lights_lambert_pars_fragment:"varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert",lights_pars_begin:"uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\n#if defined( USE_LIGHT_PROBES )\n\tuniform vec3 lightProbe[ 9 ];\n#endif\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = transformNormalByInverseViewMatrix( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif ( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif\n#include ",lights_toon_fragment:"ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;",lights_toon_pars_fragment:"varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon",lights_phong_fragment:"BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;",lights_phong_pars_fragment:"varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong",lights_physical_fragment:"PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.diffuseContribution = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.metalness = metalnessFactor;\nvec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef USE_SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULAR_COLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;\n\t\t#endif\n\t\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor;\n\tmaterial.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = vec3( 0.04 );\n\tmaterial.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_DISPERSION\n\tmaterial.dispersion = dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.0001, 1.0 );\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\t#ifdef USE_ANISOTROPYMAP\n\t\tmat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );\n\t\tvec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;\n\t\tvec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;\n\t#else\n\t\tvec2 anisotropyV = anisotropyVector;\n\t#endif\n\tmaterial.anisotropy = length( anisotropyV );\n\tif( material.anisotropy == 0.0 ) {\n\t\tanisotropyV = vec2( 1.0, 0.0 );\n\t} else {\n\t\tanisotropyV /= material.anisotropy;\n\t\tmaterial.anisotropy = saturate( material.anisotropy );\n\t}\n\tmaterial.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );\n\tmaterial.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;\n\tmaterial.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;\n#endif",lights_physical_pars_fragment:"uniform sampler2D dfgLUT;\nstruct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tvec3 diffuseContribution;\n\tvec3 specularColor;\n\tvec3 specularColorBlended;\n\tfloat roughness;\n\tfloat metalness;\n\tfloat specularF90;\n\tfloat dispersion;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t\tvec3 iridescenceFresnelDielectric;\n\t\tvec3 iridescenceFresnelMetallic;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat anisotropy;\n\t\tfloat alphaT;\n\t\tvec3 anisotropyT;\n\t\tvec3 anisotropyB;\n\t#endif\n};\nvec3 clearcoatSpecularDirect = vec3( 0.0 );\nvec3 clearcoatSpecularIndirect = vec3( 0.0 );\nvec3 sheenSpecularDirect = vec3( 0.0 );\nvec3 sheenSpecularIndirect = vec3(0.0 );\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\n#ifdef USE_ANISOTROPY\n\tfloat V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {\n\t\tfloat gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );\n\t\tfloat gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );\n\t\treturn 0.5 / max( gv + gl, EPSILON );\n\t}\n\tfloat D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {\n\t\tfloat a2 = alphaT * alphaB;\n\t\thighp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );\n\t\thighp float v2 = dot( v, v );\n\t\tfloat w2 = a2 / v2;\n\t\treturn RECIPROCAL_PI * a2 * pow2 ( w2 );\n\t}\n#endif\n#ifdef USE_CLEARCOAT\n\tvec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {\n\t\tvec3 f0 = material.clearcoatF0;\n\t\tfloat f90 = material.clearcoatF90;\n\t\tfloat roughness = material.clearcoatRoughness;\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 f0 = material.specularColorBlended;\n\tfloat f90 = material.specularF90;\n\tfloat roughness = material.roughness;\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t#ifdef USE_IRIDESCENCE\n\t\tF = mix( F, material.iridescenceFresnel, material.iridescence );\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat dotTL = dot( material.anisotropyT, lightDir );\n\t\tfloat dotTV = dot( material.anisotropyT, viewDir );\n\t\tfloat dotTH = dot( material.anisotropyT, halfDir );\n\t\tfloat dotBL = dot( material.anisotropyB, lightDir );\n\t\tfloat dotBV = dot( material.anisotropyB, viewDir );\n\t\tfloat dotBH = dot( material.anisotropyB, halfDir );\n\t\tfloat V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );\n\t\tfloat D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );\n\t#else\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t#endif\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transpose( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat rInv = 1.0 / ( roughness + 0.1 );\n\tfloat a = -1.9362 + 1.0678 * roughness + 0.4573 * r2 - 0.8469 * rInv;\n\tfloat b = -0.6014 + 0.5538 * roughness - 0.4670 * r2 - 0.1255 * rInv;\n\tfloat DG = exp( a * dotNV + b );\n\treturn saturate( DG );\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg;\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg;\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\nvec3 BRDF_GGX_Multiscatter( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 singleScatter = BRDF_GGX( lightDir, viewDir, normal, material );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 dfgV = texture2D( dfgLUT, vec2( material.roughness, dotNV ) ).rg;\n\tvec2 dfgL = texture2D( dfgLUT, vec2( material.roughness, dotNL ) ).rg;\n\tvec3 FssEss_V = material.specularColorBlended * dfgV.x + material.specularF90 * dfgV.y;\n\tvec3 FssEss_L = material.specularColorBlended * dfgL.x + material.specularF90 * dfgL.y;\n\tfloat Ess_V = dfgV.x + dfgV.y;\n\tfloat Ess_L = dfgL.x + dfgL.y;\n\tfloat Ems_V = 1.0 - Ess_V;\n\tfloat Ems_L = 1.0 - Ess_L;\n\tvec3 Favg = material.specularColorBlended + ( 1.0 - material.specularColorBlended ) * 0.047619;\n\tvec3 Fms = FssEss_V * FssEss_L * Favg / ( 1.0 - Ems_V * Ems_L * Favg + EPSILON );\n\tfloat compensationFactor = Ems_V * Ems_L;\n\tvec3 multiScatter = Fms * compensationFactor;\n\treturn singleScatter + multiScatter;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometryNormal;\n\t\tvec3 viewDir = geometryViewDir;\n\t\tvec3 position = geometryPosition;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColorBlended * t2.x + ( material.specularF90 - material.specularColorBlended ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseContribution * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t\t#ifdef USE_CLEARCOAT\n\t\t\tvec3 Ncc = geometryClearcoatNormal;\n\t\t\tvec2 uvClearcoat = LTC_Uv( Ncc, viewDir, material.clearcoatRoughness );\n\t\t\tvec4 t1Clearcoat = texture2D( ltc_1, uvClearcoat );\n\t\t\tvec4 t2Clearcoat = texture2D( ltc_2, uvClearcoat );\n\t\t\tmat3 mInvClearcoat = mat3(\n\t\t\t\tvec3( t1Clearcoat.x, 0, t1Clearcoat.y ),\n\t\t\t\tvec3( 0, 1, 0 ),\n\t\t\t\tvec3( t1Clearcoat.z, 0, t1Clearcoat.w )\n\t\t\t);\n\t\t\tvec3 fresnelClearcoat = material.clearcoatF0 * t2Clearcoat.x + ( material.clearcoatF90 - material.clearcoatF0 ) * t2Clearcoat.y;\n\t\t\tclearcoatSpecularDirect += lightColor * fresnelClearcoat * LTC_Evaluate( Ncc, viewDir, position, mInvClearcoat, rectCoords );\n\t\t#endif\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );\n\t#endif\n\t#ifdef USE_SHEEN\n \n \t\tsheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n \n \t\tfloat sheenAlbedoV = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n \t\tfloat sheenAlbedoL = IBLSheenBRDF( geometryNormal, directLight.direction, material.sheenRoughness );\n \n \t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * max( sheenAlbedoV, sheenAlbedoL );\n \n \t\tirradiance *= sheenEnergyComp;\n \n \t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX_Multiscatter( directLight.direction, geometryViewDir, geometryNormal, material );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseContribution );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 diffuse = irradiance * BRDF_Lambert( material.diffuseContribution );\n\t#ifdef USE_SHEEN\n\t\tfloat sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;\n\t\tdiffuse *= sheenEnergyComp;\n\t#endif\n\treflectedLight.indirectDiffuse += diffuse;\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ) * RECIPROCAL_PI;\n \t#endif\n\tvec3 singleScatteringDielectric = vec3( 0.0 );\n\tvec3 multiScatteringDielectric = vec3( 0.0 );\n\tvec3 singleScatteringMetallic = vec3( 0.0 );\n\tvec3 multiScatteringMetallic = vec3( 0.0 );\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnelDielectric, material.roughness, singleScatteringDielectric, multiScatteringDielectric );\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.iridescence, material.iridescenceFresnelMetallic, material.roughness, singleScatteringMetallic, multiScatteringMetallic );\n\t#else\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScatteringDielectric, multiScatteringDielectric );\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.roughness, singleScatteringMetallic, multiScatteringMetallic );\n\t#endif\n\tvec3 singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, material.metalness );\n\tvec3 multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, material.metalness );\n\tvec3 totalScatteringDielectric = singleScatteringDielectric + multiScatteringDielectric;\n\tvec3 diffuse = material.diffuseContribution * ( 1.0 - totalScatteringDielectric );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tvec3 indirectSpecular = radiance * singleScattering;\n\tindirectSpecular += multiScattering * cosineWeightedIrradiance;\n\tvec3 indirectDiffuse = diffuse * cosineWeightedIrradiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;\n\t\tindirectSpecular *= sheenEnergyComp;\n\t\tindirectDiffuse *= sheenEnergyComp;\n\t#endif\n\treflectedLight.indirectSpecular += indirectSpecular;\n\treflectedLight.indirectDiffuse += indirectDiffuse;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}",lights_fragment_begin:"\nvec3 geometryPosition = - vViewPosition;\nvec3 geometryNormal = normal;\nvec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\nvec3 geometryClearcoatNormal = vec3( 0.0 );\n#ifdef USE_CLEARCOAT\n\tgeometryClearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometryViewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnelDielectric = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceFresnelMetallic = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.diffuseColor );\n\t\tmaterial.iridescenceFresnel = mix( material.iridescenceFresnelDielectric, material.iridescenceFresnelMetallic, material.metalness );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometryPosition, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometryPosition, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#if defined( USE_LIGHT_PROBES )\n\t\tirradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#ifdef USE_LIGHT_PROBES_GRID\n\t\tvec3 probeWorldPos = ( ( vec4( geometryPosition, 1.0 ) - viewMatrix[ 3 ] ) * viewMatrix ).xyz;\n\t\tvec3 probeWorldNormal = transformNormalByInverseViewMatrix( geometryNormal, viewMatrix );\n\t\tirradiance += getLightProbeGridIrradiance( probeWorldPos, probeWorldNormal );\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif",lights_fragment_maps:"#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\t#if defined( STANDARD ) || defined( LAMBERT ) || defined( PHONG )\n\t\t\tiblIrradiance += getIBLIrradiance( geometryNormal );\n\t\t#endif\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\t#ifdef USE_ANISOTROPY\n\t\tradiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );\n\t#else\n\t\tradiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif",lights_fragment_end:"#if defined( RE_IndirectDiffuse )\n\t#if defined( LAMBERT ) || defined( PHONG )\n\t\tirradiance += iblIrradiance;\n\t#endif\n\tRE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif",lightprobes_pars_fragment:"#ifdef USE_LIGHT_PROBES_GRID\nuniform highp sampler3D probesSH;\nuniform vec3 probesMin;\nuniform vec3 probesMax;\nuniform vec3 probesResolution;\nvec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) {\n\tvec3 res = probesResolution;\n\tvec3 gridRange = probesMax - probesMin;\n\tvec3 resMinusOne = res - 1.0;\n\tvec3 probeSpacing = gridRange / resMinusOne;\n\tvec3 samplePos = worldPos + worldNormal * probeSpacing * 0.5;\n\tvec3 uvw = clamp( ( samplePos - probesMin ) / gridRange, 0.0, 1.0 );\n\tuvw = uvw * resMinusOne / res + 0.5 / res;\n\tfloat nz = res.z;\n\tfloat paddedSlices = nz + 2.0;\n\tfloat atlasDepth = 7.0 * paddedSlices;\n\tfloat uvZBase = uvw.z * nz + 1.0;\n\tvec4 s0 = texture( probesSH, vec3( uvw.xy, ( uvZBase ) / atlasDepth ) );\n\tvec4 s1 = texture( probesSH, vec3( uvw.xy, ( uvZBase + paddedSlices ) / atlasDepth ) );\n\tvec4 s2 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 2.0 * paddedSlices ) / atlasDepth ) );\n\tvec4 s3 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 3.0 * paddedSlices ) / atlasDepth ) );\n\tvec4 s4 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 4.0 * paddedSlices ) / atlasDepth ) );\n\tvec4 s5 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 5.0 * paddedSlices ) / atlasDepth ) );\n\tvec4 s6 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 6.0 * paddedSlices ) / atlasDepth ) );\n\tvec3 c0 = s0.xyz;\n\tvec3 c1 = vec3( s0.w, s1.xy );\n\tvec3 c2 = vec3( s1.zw, s2.x );\n\tvec3 c3 = s2.yzw;\n\tvec3 c4 = s3.xyz;\n\tvec3 c5 = vec3( s3.w, s4.xy );\n\tvec3 c6 = vec3( s4.zw, s5.x );\n\tvec3 c7 = s5.yzw;\n\tvec3 c8 = s6.xyz;\n\tfloat x = worldNormal.x, y = worldNormal.y, z = worldNormal.z;\n\tvec3 result = c0 * 0.886227;\n\tresult += c1 * 2.0 * 0.511664 * y;\n\tresult += c2 * 2.0 * 0.511664 * z;\n\tresult += c3 * 2.0 * 0.511664 * x;\n\tresult += c4 * 2.0 * 0.429043 * x * y;\n\tresult += c5 * 2.0 * 0.429043 * y * z;\n\tresult += c6 * ( 0.743125 * z * z - 0.247708 );\n\tresult += c7 * 2.0 * 0.429043 * x * z;\n\tresult += c8 * 0.429043 * ( x * x - y * y );\n\treturn max( result, vec3( 0.0 ) );\n}\n#endif",logdepthbuf_fragment:"#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )\n\tgl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_pars_vertex:"#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif",map_fragment:"#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif",map_pars_fragment:"#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif",map_particle_fragment:"#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t#if defined( USE_POINTS_UV )\n\t\tvec2 uv = vUv;\n\t#else\n\t\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif",map_particle_pars_fragment:"#if defined( USE_POINTS_UV )\n\tvarying vec2 vUv;\n#else\n\t#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t\tuniform mat3 uvTransform;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif",metalnessmap_fragment:"float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif",metalnessmap_pars_fragment:"#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif",morphinstance_vertex:"#ifdef USE_INSTANCING_MORPH\n\tfloat morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\tfloat morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tmorphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;\n\t}\n#endif",morphcolor_vertex:"#if defined( USE_MORPHCOLORS )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif",morphnormal_vertex:"#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif",morphtarget_pars_vertex:"#ifdef USE_MORPHTARGETS\n\t#ifndef USE_INSTANCING_MORPH\n\t\tuniform float morphTargetBaseInfluence;\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t#endif\n\tuniform sampler2DArray morphTargetsTexture;\n\tuniform ivec2 morphTargetsTextureSize;\n\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t}\n#endif",morphtarget_vertex:"#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif",normal_fragment_begin:"float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = dFdx( vViewPosition );\n\tvec3 fdy = dFdy( vViewPosition );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal *= faceDirection;\n\t#endif\n#endif\n#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn = getTangentFrame( - vViewPosition, normal,\n\t\t#if defined( USE_NORMALMAP )\n\t\t\tvNormalMapUv\n\t\t#elif defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tvClearcoatNormalMapUv\n\t\t#else\n\t\t\tvUv\n\t\t#endif\n\t\t);\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\ttbn[0] *= faceDirection;\n\t\ttbn[1] *= faceDirection;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\ttbn2[0] *= faceDirection;\n\t\ttbn2[1] *= faceDirection;\n\t#endif\n#endif\nvec3 nonPerturbedNormal = normal;",normal_fragment_maps:"#ifdef USE_NORMALMAP_OBJECTSPACE\n\tnormal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( USE_NORMALMAP_TANGENTSPACE )\n\tvec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\t#if defined( USE_PACKED_NORMALMAP )\n\t\tmapN = vec3( mapN.xy, sqrt( saturate( 1.0 - dot( mapN.xy, mapN.xy ) ) ) );\n\t#endif\n\tmapN.xy *= normalScale;\n\tnormal = normalize( tbn * mapN );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif",normal_pars_fragment:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_pars_vertex:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_vertex:"#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t\t#ifdef FLIP_SIDED\n\t\t\tvBitangent = - vBitangent;\n\t\t#endif\n\t#endif\n#endif",normalmap_pars_fragment:"#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef USE_NORMALMAP_OBJECTSPACE\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )\n\tmat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( uv.st );\n\t\tvec2 st1 = dFdy( uv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );\n\t\treturn mat3( T * scale, B * scale, N );\n\t}\n#endif",clearcoat_normal_fragment_begin:"#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif",clearcoat_normal_fragment_maps:"#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\tclearcoatNormal = normalize( tbn2 * clearcoatMapN );\n#endif",clearcoat_pars_fragment:"#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif",iridescence_pars_fragment:"#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif",opaque_fragment:"#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );",packing:"vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;\nconst float Inv255 = 1. / 255.;\nconst vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );\nconst vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );\nconst vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );\nconst vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );\nvec4 packDepthToRGBA( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec4( 0., 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec4( 1., 1., 1., 1. );\n\tfloat vuf;\n\tfloat af = modf( v * PackFactors.a, vuf );\n\tfloat bf = modf( vuf * ShiftRight8, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );\n}\nvec3 packDepthToRGB( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec3( 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec3( 1., 1., 1. );\n\tfloat vuf;\n\tfloat bf = modf( v * PackFactors.b, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec3( vuf * Inv255, gf * PackUpscale, bf );\n}\nvec2 packDepthToRG( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec2( 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec2( 1., 1. );\n\tfloat vuf;\n\tfloat gf = modf( v * 256., vuf );\n\treturn vec2( vuf * Inv255, gf );\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors4 );\n}\nfloat unpackRGBToDepth( const in vec3 v ) {\n\treturn dot( v, UnpackFactors3 );\n}\nfloat unpackRGToDepth( const in vec2 v ) {\n\treturn v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;\n}\nvec4 pack2HalfToRGBA( const in vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( const in vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\n\t\treturn depth * ( far - near ) - far;\n\t#else\n\t\treturn depth * ( near - far ) - near;\n\t#endif\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\t\n\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\treturn ( near * far ) / ( ( near - far ) * depth - near );\n\t#else\n\t\treturn ( near * far ) / ( ( far - near ) * depth - far );\n\t#endif\n}",premultiplied_alpha_fragment:"#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif",project_vertex:"vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_BATCHING\n\tmvPosition = batchingMatrix * mvPosition;\n#endif\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;",dithering_fragment:"#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif",dithering_pars_fragment:"#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif",roughnessmap_fragment:"float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif",roughnessmap_pars_fragment:"#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif",shadowmap_pars_fragment:"#if NUM_SPOT_LIGHT_COORDS > 0\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n\tuniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform sampler2DShadow directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\t#else\n\t\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform sampler2DShadow spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\t#else\n\t\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform samplerCubeShadow pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\t#elif defined( SHADOWMAP_TYPE_BASIC )\n\t\t\tuniform samplerCube pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\tfloat interleavedGradientNoise( vec2 position ) {\n\t\t\treturn fract( 52.9829189 * fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) );\n\t\t}\n\t\tvec2 vogelDiskSample( int sampleIndex, int samplesCount, float phi ) {\n\t\t\tconst float goldenAngle = 2.399963229728653;\n\t\t\tfloat r = sqrt( ( float( sampleIndex ) + 0.5 ) / float( samplesCount ) );\n\t\t\tfloat theta = float( sampleIndex ) * goldenAngle + phi;\n\t\t\treturn vec2( cos( theta ), sin( theta ) ) * r;\n\t\t}\n\t#endif\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\tfloat getShadow( sampler2DShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\tshadowCoord.z += shadowBias;\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\t\tfloat radius = shadowRadius * texelSize.x;\n\t\t\t\tfloat phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2;\n\t\t\t\tshadow = (\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 0, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 1, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 2, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 3, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 4, 5, phi ) * radius, shadowCoord.z ) )\n\t\t\t\t) * 0.2;\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tshadowCoord.z -= shadowBias;\n\t\t\t#else\n\t\t\t\tshadowCoord.z += shadowBias;\n\t\t\t#endif\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tvec2 distribution = texture2D( shadowMap, shadowCoord.xy ).rg;\n\t\t\t\tfloat mean = distribution.x;\n\t\t\t\tfloat variance = distribution.y * distribution.y;\n\t\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\t\tfloat hard_shadow = step( mean, shadowCoord.z );\n\t\t\t\t#else\n\t\t\t\t\tfloat hard_shadow = step( shadowCoord.z, mean );\n\t\t\t\t#endif\n\t\t\t\t\n\t\t\t\tif ( hard_shadow == 1.0 ) {\n\t\t\t\t\tshadow = 1.0;\n\t\t\t\t} else {\n\t\t\t\t\tvariance = max( variance, 0.0000001 );\n\t\t\t\t\tfloat d = shadowCoord.z - mean;\n\t\t\t\t\tfloat p_max = variance / ( variance + d * d );\n\t\t\t\t\tp_max = clamp( ( p_max - 0.3 ) / 0.65, 0.0, 1.0 );\n\t\t\t\t\tshadow = max( hard_shadow, p_max );\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#else\n\t\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tshadowCoord.z -= shadowBias;\n\t\t\t#else\n\t\t\t\tshadowCoord.z += shadowBias;\n\t\t\t#endif\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tfloat depth = texture2D( shadowMap, shadowCoord.xy ).r;\n\t\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\t\tshadow = step( depth, shadowCoord.z );\n\t\t\t\t#else\n\t\t\t\t\tshadow = step( shadowCoord.z, depth );\n\t\t\t\t#endif\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\tfloat getPointShadow( samplerCubeShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tvec3 absVec = abs( lightToPosition );\n\t\tfloat viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );\n\t\tif ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tfloat dp = ( shadowCameraNear * ( shadowCameraFar - viewSpaceZ ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\t\tdp -= shadowBias;\n\t\t\t#else\n\t\t\t\tfloat dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\t\tdp += shadowBias;\n\t\t\t#endif\n\t\t\tfloat texelSize = shadowRadius / shadowMapSize.x;\n\t\t\tvec3 absDir = abs( bd3D );\n\t\t\tvec3 tangent = absDir.x > absDir.z ? vec3( 0.0, 1.0, 0.0 ) : vec3( 1.0, 0.0, 0.0 );\n\t\t\ttangent = normalize( cross( bd3D, tangent ) );\n\t\t\tvec3 bitangent = cross( bd3D, tangent );\n\t\t\tfloat phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2;\n\t\t\tvec2 sample0 = vogelDiskSample( 0, 5, phi );\n\t\t\tvec2 sample1 = vogelDiskSample( 1, 5, phi );\n\t\t\tvec2 sample2 = vogelDiskSample( 2, 5, phi );\n\t\t\tvec2 sample3 = vogelDiskSample( 3, 5, phi );\n\t\t\tvec2 sample4 = vogelDiskSample( 4, 5, phi );\n\t\t\tshadow = (\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample0.x + bitangent * sample0.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample1.x + bitangent * sample1.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample2.x + bitangent * sample2.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample3.x + bitangent * sample3.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample4.x + bitangent * sample4.y ) * texelSize, dp ) )\n\t\t\t) * 0.2;\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\t#elif defined( SHADOWMAP_TYPE_BASIC )\n\tfloat getPointShadow( samplerCube shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 absVec = abs( lightToPosition );\n\t\tfloat viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );\n\t\tif ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\tdp += shadowBias;\n\t\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t\tfloat depth = textureCube( shadowMap, bd3D ).r;\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tdepth = 1.0 - depth;\n\t\t\t#endif\n\t\t\tshadow = step( dp, depth );\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\t#endif\n\t#endif\n#endif",shadowmap_pars_vertex:"#if NUM_SPOT_LIGHT_COORDS > 0\n\tuniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif",shadowmap_vertex:"#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\t#ifdef HAS_NORMAL\n\t\tvec3 shadowWorldNormal = transformNormalByInverseViewMatrix( transformedNormal, viewMatrix );\n\t#else\n\t\tvec3 shadowWorldNormal = vec3( 0.0 );\n\t#endif\n\tvec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n#endif",shadowmask_pars_fragment:"float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0 && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}",skinbase_vertex:"#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif",skinning_pars_vertex:"#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tint size = textureSize( boneTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n#endif",skinning_vertex:"#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif",skinnormal_vertex:"#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif",specularmap_fragment:"float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif",specularmap_pars_fragment:"#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif",tonemapping_fragment:"#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif",tonemapping_pars_fragment:"#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn saturate( toneMappingExposure * color );\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 CineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.6605, - 0.1246, - 0.0182 ),\n\tvec3( - 0.5876, 1.1329, - 0.1006 ),\n\tvec3( - 0.0728, - 0.0083, 1.1187 )\n);\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n\tvec3( 0.6274, 0.0691, 0.0164 ),\n\tvec3( 0.3293, 0.9195, 0.0880 ),\n\tvec3( 0.0433, 0.0113, 0.8956 )\n);\nvec3 agxDefaultContrastApprox( vec3 x ) {\n\tvec3 x2 = x * x;\n\tvec3 x4 = x2 * x2;\n\treturn + 15.5 * x4 * x2\n\t\t- 40.14 * x4 * x\n\t\t+ 31.96 * x4\n\t\t- 6.868 * x2 * x\n\t\t+ 0.4298 * x2\n\t\t+ 0.1191 * x\n\t\t- 0.00232;\n}\nvec3 AgXToneMapping( vec3 color ) {\n\tconst mat3 AgXInsetMatrix = mat3(\n\t\tvec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n\t\tvec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n\t\tvec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n\t);\n\tconst mat3 AgXOutsetMatrix = mat3(\n\t\tvec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n\t\tvec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n\t\tvec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n\t);\n\tconst float AgxMinEv = - 12.47393;\tconst float AgxMaxEv = 4.026069;\n\tcolor *= toneMappingExposure;\n\tcolor = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\tcolor = AgXInsetMatrix * color;\n\tcolor = max( color, 1e-10 );\tcolor = log2( color );\n\tcolor = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\tcolor = clamp( color, 0.0, 1.0 );\n\tcolor = agxDefaultContrastApprox( color );\n\tcolor = AgXOutsetMatrix * color;\n\tcolor = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\tcolor = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\tcolor = clamp( color, 0.0, 1.0 );\n\treturn color;\n}\nvec3 NeutralToneMapping( vec3 color ) {\n\tconst float StartCompression = 0.8 - 0.04;\n\tconst float Desaturation = 0.15;\n\tcolor *= toneMappingExposure;\n\tfloat x = min( color.r, min( color.g, color.b ) );\n\tfloat offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n\tcolor -= offset;\n\tfloat peak = max( color.r, max( color.g, color.b ) );\n\tif ( peak < StartCompression ) return color;\n\tfloat d = 1. - StartCompression;\n\tfloat newPeak = 1. - d * d / ( peak + d - StartCompression );\n\tcolor *= newPeak / peak;\n\tfloat g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n\treturn mix( color, vec3( newPeak ), g );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }",transmission_fragment:"#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = transformNormalByInverseViewMatrix( normal, viewMatrix );\n\tvec4 transmitted = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseContribution, material.specularColorBlended, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );\n#endif",transmission_pars_fragment:"#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tfloat w0( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n\t}\n\tfloat w1( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );\n\t}\n\tfloat w2( float a ){\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n\t}\n\tfloat w3( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * a );\n\t}\n\tfloat g0( float a ) {\n\t\treturn w0( a ) + w1( a );\n\t}\n\tfloat g1( float a ) {\n\t\treturn w2( a ) + w3( a );\n\t}\n\tfloat h0( float a ) {\n\t\treturn - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n\t}\n\tfloat h1( float a ) {\n\t\treturn 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n\t}\n\tvec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {\n\t\tuv = uv * texelSize.zw + 0.5;\n\t\tvec2 iuv = floor( uv );\n\t\tvec2 fuv = fract( uv );\n\t\tfloat g0x = g0( fuv.x );\n\t\tfloat g1x = g1( fuv.x );\n\t\tfloat h0x = h0( fuv.x );\n\t\tfloat h1x = h1( fuv.x );\n\t\tfloat h0y = h0( fuv.y );\n\t\tfloat h1y = h1( fuv.y );\n\t\tvec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\treturn g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\n\t\t\tg1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\n\t}\n\tvec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\n\t\tvec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\n\t\tvec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\n\t\tvec2 fLodSizeInv = 1.0 / fLodSize;\n\t\tvec2 cLodSizeInv = 1.0 / cLodSize;\n\t\tvec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );\n\t\tvec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );\n\t\treturn mix( fSample, cSample, fract( lod ) );\n\t}\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\treturn textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );\n\t}\n\tvec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn vec3( 1.0 );\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec4 transmittedLight;\n\t\tvec3 transmittance;\n\t\t#ifdef USE_DISPERSION\n\t\t\tfloat halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;\n\t\t\tvec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );\n\t\t\tfor ( int i = 0; i < 3; i ++ ) {\n\t\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );\n\t\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\t\trefractionCoords += 1.0;\n\t\t\t\trefractionCoords /= 2.0;\n\t\t\t\tvec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );\n\t\t\t\ttransmittedLight[ i ] = transmissionSample[ i ];\n\t\t\t\ttransmittedLight.a += transmissionSample.a;\n\t\t\t\ttransmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];\n\t\t\t}\n\t\t\ttransmittedLight.a /= 3.0;\n\t\t#else\n\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\trefractionCoords += 1.0;\n\t\t\trefractionCoords /= 2.0;\n\t\t\ttransmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\t\ttransmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\t#endif\n\t\tvec3 attenuatedColor = transmittance * transmittedLight.rgb;\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\tfloat transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );\n\t}\n#endif",uv_pars_fragment:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif",uv_pars_vertex:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tuniform mat3 mapTransform;\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform mat3 alphaMapTransform;\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tuniform mat3 lightMapTransform;\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tuniform mat3 aoMapTransform;\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tuniform mat3 bumpMapTransform;\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tuniform mat3 normalMapTransform;\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tuniform mat3 displacementMapTransform;\n\tvarying vec2 vDisplacementMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tuniform mat3 emissiveMapTransform;\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tuniform mat3 metalnessMapTransform;\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tuniform mat3 roughnessMapTransform;\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tuniform mat3 anisotropyMapTransform;\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tuniform mat3 clearcoatMapTransform;\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform mat3 clearcoatNormalMapTransform;\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform mat3 clearcoatRoughnessMapTransform;\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tuniform mat3 sheenColorMapTransform;\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tuniform mat3 sheenRoughnessMapTransform;\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tuniform mat3 iridescenceMapTransform;\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform mat3 iridescenceThicknessMapTransform;\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tuniform mat3 specularMapTransform;\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tuniform mat3 specularColorMapTransform;\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tuniform mat3 specularIntensityMapTransform;\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif",uv_vertex:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvUv = vec3( uv, 1 ).xy;\n#endif\n#ifdef USE_MAP\n\tvMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ALPHAMAP\n\tvAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_LIGHTMAP\n\tvLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_AOMAP\n\tvAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_BUMPMAP\n\tvBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_NORMALMAP\n\tvNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tvDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_METALNESSMAP\n\tvMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULARMAP\n\tvSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tvTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_THICKNESSMAP\n\tvThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;\n#endif",worldpos_vertex:"#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_BATCHING\n\t\tworldPosition = batchingMatrix * worldPosition;\n\t#endif\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif",background_vert:"varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}",background_frag:"uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\ttexColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}",backgroundCube_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}",backgroundCube_frag:"#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nuniform mat3 backgroundRotation;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, backgroundRotation * vWorldDirection );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}",cube_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}",cube_frag:"uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = texColor;\n\tgl_FragColor.a *= opacity;\n\t#include \n\t#include \n}",depth_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvHighPrecisionZW = gl_Position.zw;\n}",depth_frag:"#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\tfloat fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ];\n\t#else\n\t\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5;\n\t#endif\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#elif DEPTH_PACKING == 3202\n\t\tgl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );\n\t#elif DEPTH_PACKING == 3203\n\t\tgl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );\n\t#endif\n}",distance_vert:"#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition.xyz;\n}",distance_frag:"#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = vec4( dist, 0.0, 0.0, 1.0 );\n}",equirect_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}",equirect_frag:"uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include \n\t#include \n}",linedashed_vert:"uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",linedashed_frag:"uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshbasic_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshbasic_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshlambert_vert:"#define LAMBERT\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}",meshlambert_frag:"#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include